Browse the current repo's Forgejo or Gitea issues in a pane

Small Claude Code mods: plugins of function hooks that change what Claude Code shows or does, in the terminal and in the desktop app's Code tab.
In a terminal Claude Code session:
/plugin install <mod> --marketplace enhki/claude-mods
Answer y to add the marketplace, then pick the user scope so the mod loads in every session, desktop ones included.
| Mod | What it does |
|---|---|
statusline-desktop | Draws your terminal status line above the prompt in the desktop app |
forgejo-issues | Browse, search and manage the current repo's Forgejo or Gitea issues in a pane |
work-session | Kicks off and wraps up working sessions with your own start and end commands, and titles each session |
walkthrough | A checklist pane for testing by hand: mark each step, add notes, send the results back in one message |
The desktop app doesn't run your statusLine command. This mod does: it picks the command the way Claude Code does (project .claude/settings.local.json, then .claude/settings.json, then ~/.claude/settings.json), pipes it the same JSON the terminal would (model, cwd, cost, context window, rate limits), and draws the first line it prints in the band above the prompt.
config-file) sets one; otherwise they map to the app's own theme colours.current_usage reads slightly lower than in the terminal (output tokens come through as 0)./issues opens a pane on the issues of the repo the session runs in. The forge and repo come from git remote get-url origin (ssh or https), so it works for any Forgejo or Gitea host, Codeberg included.
kind/bug sit under their scope, exclusive scopes pick one); a milestone picker.label:bug, -label:wontfix, label:kind/, milestone:"Some name", is:closed. Enter opens the top match.#N mentions as chips that open in the pane..claude/forgejo-issues.json in the folder you start Claude in, as {"repos": ["owner/repo"]} on the same forge. The pane then shows a button per repo (a picker past five), and /issues <repo> jumps to one by name or prefix. The last repo picked is remembered for that project.Token. The mod needs an API token with issue read/write and repository read. Put it in ~/.config/claude-mods/secrets/forgejo.env (folder 700, file 600), keyed by host so a token only ever goes to its own forge:
FORGEJO_TOKEN_CODEBERG_ORG=...
FORGEJO_TOKEN_GIT_EXAMPLE_COM=...
Without one, it falls back to fgj's config for that host. The mod also stops Claude's own file and shell tools from reading that secrets folder.
Settings (the plugin's options):
| Setting | Default | What it does |
|---|---|---|
apiUrl | empty | The API base when it isn't https://<remote host>/api/v1 |
requireCommentOnClose | on | Closing needs a comment, posted before the close |
requireMilestone | off | New issues need a milestone |
requireLabelFrom | empty | New issues need one of these comma-separated labels |
editorCommand | empty | Adds Open in editor: e.g. ghostty --gtk-single-instance=false --class=popup.editor -e nvim {file} |
Desktop notes. The desktop app currently drops Button and Markdown-link presses from plugin panes, so every control here is a small Client that posts a message instead; and it passes no paste into a Client, so for long or pasted text use Open in editor. The editor command must wait until you close the file; one that returns at once (a launcher that forks) leaves a Use editor text button to pull the file back by hand. Ghostty needs --gtk-single-instance=false for this, or it may hand the window to a running instance and return at once.
For projects where you start and end each working session with your own slash commands (a "continue working session" and an "end working session", say /cws and /ews), this mod offers them at the right moments and gives each session a title you can tell apart in the session list.
/clear, not a resume) in a project that has the start command, a band above the prompt offers it: press 1 to run it, 2 to skip, or just type something else. Set Kickoff to auto to run it straight away, or off.set_session_title tool and a line of context asking it to title the session once its focus is clear: <Project> S<n> · <focus> when the project numbers its sessions, else <Project> · <focus>. The title shows from your next message on. A /rename of your own wins: the mod stops setting it.Projects without the start command see nothing. In the desktop app the band draws above the desktop status line rather than in place of it.
Settings (the plugin's options):
| Setting | Default | What it does |
|---|---|---|
startCommand | cws | The command that kicks a session off, without the slash |
endCommand | ews | The command that wraps one up |
kickoff | band | band offers it, auto runs it at start, off never |
wrapAtPercent | 75 | Context fullness that brings up the wrap offer; 0 turns it off |
When Claude asks you to check something by hand (run a demo, resize a window, try a key), it publishes the steps to a Walkthrough pane instead of a list in chat, and you send the results back from there.
publish_walkthrough tool refuses a step that doesn't say what to expect. Publishing again replaces the list./walkthrough. The step you're on is drawn open: its command with Copy, what to expect, Pass / Fail / Skip and a note. Marking it opens the next one; done steps fold to one line you can click to reopen. Pressing a mark again takes it back.p pass, f fail, s skip, c copy, r send.Screenshots don't go through the pane: paste them in the prompt as usual. No settings.
A mod is a plugin of function hooks: a plugin.json, a hooks/hooks.json naming one TypeScript module, and that module's register(on, options). In a Claude Code session, the bundled plugin-authoring skill holds the full API (types, examples, the test kit); load it before writing one.
| Kind | Where | Loads |
|---|---|---|
| General, shareable | here, mods/<name>/ + an entry in .claude-plugin/marketplace.json | everywhere, once installed at user scope |
| Tied to one project, or naming private hosts | that project's .claude/skills/<name>/ | in that project's sessions only, watched for edits |
| Just for you, everywhere, private | ~/.claude/skills/<name>/ | every session, watched for edits |
Anything that names a private host, a person or a machine stays out of this public repo: make it a project mod, or read the value from a setting.
plugin-authoring skill gives a mods folder that hot-reloads when each turn ends: the quickest loop.mods/<name>/, list it in the marketplace file, and install it from this clone (below). From then on, edits are live after /reload-plugins.claude plugin validate mods/<name>, claude plugin test mods/<name>, and a type-check. Bump version in the mod's plugin.json when behaviour changes, so GitHub installs update.claude plugin test runs *.test.ts(x) against the engine itself; a test stands in for engine calls with on('<event>', () => ({ value: … })).userConfig (shown in the plugin's options); nothing personal is hard-coded.~/.config/claude-mods/secrets/<service>.env (folder 700, file 600), keyed by host where a token belongs to a host. A mod that reads one also keeps Claude's own tools out of that folder (see forgejo-issues/hooks/guard.ts).$.state) outlives reloads and upgrades: read and update it through helpers that fill in defaults, or a field a new version adds arrives undefined.ui_press not handled in ~/.config/Claude/logs/claude.ai-web.log). Input, Select and Client messages do. Make each pressable control its own small Client that posts a message (forgejo-issues/hooks/pill.tsx).Client's pointer and key listeners once, on its first draw. Each set is a message to the page, and many Clients re-setting them on every redraw get unmounted for flooding it.Client per clickable item makes hit-testing unnecessary.Client, and the native Input is one line at a fixed width. For long text, hand off to an external editor (forgejo-issues's Open in editor).<mod>: <event> hook skipped: threw … names the handler that did.Clone, then add the clone itself as your marketplace so edits are live after /reload-plugins with no reinstall:
claude plugin marketplace add ~/repos/claude-mods
claude plugin install <mod>@claude-mods --scope user
Check a mod before committing:
claude plugin validate mods/<mod>
claude plugin test mods/<mod>hooks/register.tsx 640 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as $, Register } from 'claude-code'
3
4import type { Data, Detail, Format, RepoInfo, Ui } from '../types'
5import { parseRemote, pickToken, tokenKey, toComments, toIssues, toLabels, toMilestones } from './forge'
6import { touchesSecrets } from './guard'
7import { labelIds, milestoneId, newIssueProblem, parseLabelList, toggleScoped } from './triage'
8import { editorArgv } from './editing'
9import type { TriageRules } from './triage'
10import { filterIssues } from './search'
11import { REPOS_FILE, matchRepo, parseRepoList, repoChoices, repoKey } from './repos'
12import { detailView, listView, newIssueView } from './views'
13
14const PANE = 'forgejo-issues'
15const GUARDED = new Set(['Read', 'Write', 'Edit', 'Grep', 'Glob', 'Bash'])
16// Forgejo's default page cap; a smaller one only means more requests.
17const PAGE = 50
18const MAX_PAGES = 40
19
20const DARK_BORDER = '#3a3a3a'
21const LIGHT_BORDER = '#d0d0d0'
22const DARK_RAISED = '#232323'
23const LIGHT_RAISED = '#f4f4f4'
24const EMPTY_DATA: Data = { status: 'idle', repo: null, choices: [], issues: [], labels: [], milestones: [], message: null, tokenSource: null, fetchedAt: 0, border: DARK_BORDER, raised: DARK_RAISED }
25const EMPTY_UI: Ui = {
26 query: '',
27 chips: [],
28 milestone: '',
29 state: 'open',
30 grouped: true,
31 open: null,
32 draft: '',
33 armed: null,
34 busy: false,
35 notice: null,
36 editingLabels: null,
37 creating: null,
38 sync: {},
39 fmt: {},
40 preview: {},
41 external: null,
42}
43const data = atom({ plugin: 'forgejo-issues', key: 'data' } as const, EMPTY_DATA)
44const ui = atom({ plugin: 'forgejo-issues', key: 'ui' } as const, EMPTY_UI)
45const detail = atom({ plugin: 'forgejo-issues', key: 'detail' } as const, null as Detail | null)
46
47let apiUrl = ''
48let requireCommentOnClose = true
49let triageRules: TriageRules = { requireMilestone: false, requireLabelFrom: [] }
50let editorCommand = ''
51let home = ''
52let configHome = ''
53// Held in the module, never in $.state: the token stays out of anything drawn or logged.
54let auth: { apiBase: string; token: string; repo: RepoInfo; source: 'secrets' | 'fgj' } | null = null
55
56// State saved by an older version of the mod lacks newer fields: fill in the
57// defaults on every read so a missing field never reaches the drawing.
58async function readUi($: $): Promise<Ui> {
59 return { ...EMPTY_UI, ...(await read($, ui)) }
60}
61
62async function readData($: $): Promise<Data> {
63 return { ...EMPTY_DATA, ...(await read($, data)) }
64}
65
66// Updates get the same defaults: the value handed to an update is the raw
67// saved one, so without this a field newer than the save reaches the code.
68function updateUi($: $, fn: (u: Ui) => Ui) {
69 return update($, ui, (x): Ui => fn({ ...EMPTY_UI, ...x }))
70}
71
72function updateData($: $, fn: (d: Data) => Data) {
73 return update($, data, (x): Data => fn({ ...EMPTY_DATA, ...x }))
74}
75
76async function readOrNull($: $, path: string): Promise<string | null> {
77 try {
78 return await $.fs.read(path)
79 } catch {
80 return null
81 }
82}
83
84async function paths($: $): Promise<void> {
85 if (home) return
86 home = (await $.env.get('HOME')) ?? ''
87 configHome = (await $.env.get('XDG_CONFIG_HOME')) || `${home}/.config`
88}
89
90function secretsDir(): string {
91 return `${configHome}/claude-mods/secrets`
92}
93
94/** The store key holding the repo last picked for a session repo. */
95function pickedKey(launch: RepoInfo): string {
96 return `picked:${launch.host}/${repoKey(launch)}`
97}
98
99/**
100 * Finds the repos and the token; a string is why it could not. The repo is
101 * the one last picked for this session's repo, or `arg` (`/issues <repo>`).
102 */
103async function resolveAuth($: $, arg = ''): Promise<string | null> {
104 await paths($)
105 const cwd = await $.session.cwd()
106 const remote = await $.process.run(['git', 'remote', 'get-url', 'origin'], { cwd, timeoutMs: 5_000 })
107 if (remote.exitCode !== 0) return 'This folder has no git remote named origin.'
108 const ref = parseRemote(remote.stdout, apiUrl)
109 if (!ref) return `Could not read the remote: ${remote.stdout.trim()}`
110 const launch = { host: ref.host, owner: ref.owner, repo: ref.repo, webBase: ref.webBase }
111 const choices = repoChoices(launch, parseRepoList(await readOrNull($, `${cwd}/${REPOS_FILE}`)))
112 if (arg.trim()) {
113 const hit = matchRepo(choices, arg)
114 if (!hit) {
115 await updateData($, (d): Data => ({ ...d, choices }))
116 return choices.length > 1
117 ? `No repo matches "${arg.trim()}". This pane switches between ${choices.map(repoKey).join(', ')}.`
118 : `This project lists no other repos. Add them to ${REPOS_FILE} as {"repos": ["owner/repo"]}.`
119 }
120 await $.store.set(pickedKey(launch), repoKey(hit))
121 }
122 const picked = await $.store.get(pickedKey(launch))
123 const repo = choices.find(r => repoKey(r) === picked) ?? launch
124 await updateData($, (d): Data => ({ ...d, repo, choices }))
125 const found = pickToken(
126 ref.host,
127 await readOrNull($, `${secretsDir()}/forgejo.env`),
128 await readOrNull($, `${home}/.config/fgj/config.yaml`),
129 )
130 if (!found) return `No token for ${ref.host}. Add ${tokenKey(ref.host)}=<token> to ${secretsDir()}/forgejo.env`
131 auth = { apiBase: ref.apiBase, token: found.token, repo, source: found.source }
132 return null
133}
134
135/** Calls the API; a string is the failure, worded for the pane. */
136async function request(
137 $: $,
138 method: 'GET' | 'POST' | 'PATCH' | 'PUT',
139 path: string,
140 body?: unknown,
141): Promise<{ text: string; total: number | null } | string> {
142 if (!auth) return 'Not connected.'
143 let res
144 try {
145 res = await $.http.fetch(`${auth.apiBase}${path}`, {
146 method,
147 headers: {
148 Authorization: `token ${auth.token}`,
149 Accept: 'application/json',
150 ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
151 },
152 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
153 })
154 } catch (err) {
155 return `Could not reach ${auth.repo.host}: ${err instanceof Error ? err.message : String(err)}`
156 }
157 const from = auth.source === 'secrets' ? tokenKey(auth.repo.host) : 'fgj'
158 if (res.status === 401) return `${auth.repo.host} refused the token from ${from} (401).`
159 if (res.status === 403) {
160 return method === 'GET'
161 ? `${auth.repo.host} refused the token from ${from} (403).`
162 : `${auth.repo.host} refused the change (403): the token from ${from} may lack write access to issues.`
163 }
164 if (res.status === 404) return `${auth.repo.owner}/${auth.repo.repo} is not on ${auth.repo.host}, or is not a Forgejo/Gitea repo.`
165 if (!res.ok) return `${auth.repo.host} answered ${res.status}.`
166 const header = Object.entries(res.headers).find(([k]) => k.toLowerCase() === 'x-total-count')?.[1]
167 return { text: res.text, total: header ? Number(header) : null }
168}
169
170function get($: $, path: string) {
171 return request($, 'GET', path)
172}
173
174/** Every page of a list endpoint, parsed and joined. */
175async function getAll<T>($: $, path: string, parse: (json: string) => T[]): Promise<T[] | string> {
176 const out: T[] = []
177 const sep = path.includes('?') ? '&' : '?'
178 for (let page = 1; page <= MAX_PAGES; page++) {
179 const res = await get($, `${path}${sep}limit=${PAGE}&page=${page}`)
180 if (typeof res === 'string') return res
181 const items = parse(res.text)
182 out.push(...items)
183 if (items.length < PAGE || (res.total !== null && out.length >= res.total)) break
184 }
185 return out
186}
187
188async function fail($: $, message: string): Promise<void> {
189 await updateData($, (d): Data => ({ ...d, status: 'error', message }))
190}
191
192/** Drops what belonged to the repo the pane showed before: its filters, open issue and lists. */
193async function forgetRepo($: $): Promise<void> {
194 await updateUi($, (u): Ui => ({ ...u, query: '', chips: [], milestone: '', open: null, draft: '', armed: null, notice: null, editingLabels: null, creating: null }))
195 await update($, detail, (): Detail | null => null)
196 await updateData($, (d): Data => ({ ...d, issues: [], labels: [], milestones: [] }))
197}
198
199async function load($: $, arg = ''): Promise<void> {
200 const before = (await readData($)).repo
201 await updateData($, (d): Data => ({ ...d, status: 'loading', message: null }))
202 const why = await resolveAuth($, arg)
203 if (why) return fail($, why)
204 if (before && repoKey(before) !== repoKey(auth!.repo)) await forgetRepo($)
205 const base = `/repos/${auth!.repo.owner}/${auth!.repo.repo}`
206 try {
207 const [issues, labels, milestones] = await Promise.all([
208 getAll($, `${base}/issues?state=all&type=issues`, toIssues),
209 getAll($, `${base}/labels`, toLabels),
210 getAll($, `${base}/milestones?state=all`, toMilestones),
211 ])
212 if (typeof issues === 'string') return fail($, issues)
213 if (typeof labels === 'string') return fail($, labels)
214 if (typeof milestones === 'string') return fail($, milestones)
215 const fetchedAt = await $.clock.now()
216 const tokenSource = auth!.source
217 // The theme names light ones as such (light, light-daltonized, ...); anything else draws dark.
218 const theme = String((await $.config.list()).find(row => row.key === 'theme')?.value ?? '')
219 const isLight = theme.includes('light')
220 const border = isLight ? LIGHT_BORDER : DARK_BORDER
221 const raised = isLight ? LIGHT_RAISED : DARK_RAISED
222 await updateData($, (d): Data => ({ ...d, status: 'ready', message: null, issues, labels, milestones, tokenSource, fetchedAt, border, raised }))
223 } catch (err) {
224 await fail($, `Unexpected answer from ${auth!.repo.host}: ${err instanceof Error ? err.message : String(err)}`)
225 }
226}
227
228async function openIssue($: $, n: number): Promise<void> {
229 await updateUi($, (u): Ui => bump({ ...u, open: n, draft: '', armed: null, notice: null }, 'comment'))
230 const d = await readData($)
231 if (!d.issues.some(i => i.number === n)) return
232 await update($, detail, (): Detail => ({ number: n, status: 'loading', comments: [], message: null }))
233 if (!auth) {
234 const why = await resolveAuth($)
235 if (why) {
236 await update($, detail, (): Detail => ({ number: n, status: 'error', comments: [], message: why }))
237 return
238 }
239 }
240 const res = await getAll($, `/repos/${auth!.repo.owner}/${auth!.repo.repo}/issues/${n}/comments`, toComments)
241 await update($, detail, (cur): Detail | null =>
242 cur?.number !== n
243 ? cur
244 : typeof res === 'string'
245 ? { number: n, status: 'error', comments: [], message: res }
246 : { number: n, status: 'ready', comments: res, message: null },
247 )
248}
249
250async function openFirst($: $): Promise<void> {
251 const [d, u] = await Promise.all([readData($), readUi($)])
252 const top = filterIssues(d.issues, u)[0]
253 if (top) await openIssue($, top.issue.number)
254}
255
256async function toggleChip($: $, name: string): Promise<void> {
257 const d = await readData($)
258 await updateUi($, (u): Ui => ({ ...u, chips: toggleScoped(u.chips, name, d.labels) }))
259}
260
261async function notify($: $, tone: 'ok' | 'error', text: string): Promise<void> {
262 await updateUi($, (u): Ui => ({ ...u, notice: { tone, text }, armed: null }))
263}
264
265/** Swaps in the issue the API answered for a write, so the list and the detail view agree. */
266async function replaceIssue($: $, json: string): Promise<void> {
267 const fresh = toIssues(`[${json}]`)[0]
268 if (fresh) await updateData($, (d): Data => ({ ...d, issues: d.issues.map(i => (i.number === fresh.number ? fresh : i)) }))
269}
270
271/** Posts the draft as a comment on issue `n`; false when it did not land. */
272async function postComment($: $, n: number, text: string): Promise<boolean> {
273 const res = await request($, 'POST', `/repos/${auth!.repo.owner}/${auth!.repo.repo}/issues/${n}/comments`, { body: text })
274 if (typeof res === 'string') {
275 await notify($, 'error', res)
276 return false
277 }
278 const posted = toComments(`[${res.text}]`)
279 await update($, detail, (cur): Detail | null =>
280 cur?.number === n ? { ...cur, comments: [...cur.comments, ...posted] } : cur,
281 )
282 await updateData($, (d): Data => ({
283 ...d,
284 issues: d.issues.map(i => (i.number === n ? { ...i, comments: i.comments + 1 } : i)),
285 }))
286 await updateUi($, (u): Ui => bump({ ...u, draft: '' }, 'comment'))
287 return true
288}
289
290/** Runs one write with the pane marked busy, so a second press waits for it. */
291async function write($: $, run: () => Promise<void>): Promise<void> {
292 const u = await readUi($)
293 if (u.busy) return
294 await updateUi($, (x): Ui => ({ ...x, busy: true, notice: null }))
295 try {
296 if (!auth) {
297 const why = await resolveAuth($)
298 if (why) return notify($, 'error', why)
299 }
300 await run()
301 } finally {
302 await updateUi($, (x): Ui => ({ ...x, busy: false }))
303 }
304}
305
306async function comment($: $): Promise<void> {
307 const u = await readUi($)
308 const n = u.open
309 const text = u.draft.trim()
310 if (n === null || !text) return
311 await write($, async () => {
312 if (await postComment($, n, text)) await notify($, 'ok', `Commented on #${n}.`)
313 })
314}
315
316/** Close or reopen: the first press arms it (and checks the comment rule), Confirm runs it. */
317async function arm($: $, action: 'close' | 'reopen'): Promise<void> {
318 const u = await readUi($)
319 if (action === 'close' && requireCommentOnClose && !u.draft.trim()) {
320 return notify($, 'error', 'Write a comment first: closing posts it, then closes, so the issue says why.')
321 }
322 await updateUi($, (x): Ui => ({ ...x, armed: action, notice: null }))
323}
324
325async function confirm($: $): Promise<void> {
326 const u = await readUi($)
327 const n = u.open
328 const action = u.armed
329 if (n === null || (action !== 'close' && action !== 'reopen')) return
330 const text = u.draft.trim()
331 await write($, async () => {
332 if (text && !(await postComment($, n, text))) return
333 const res = await request($, 'PATCH', `/repos/${auth!.repo.owner}/${auth!.repo.repo}/issues/${n}`, {
334 state: action === 'close' ? 'closed' : 'open',
335 })
336 if (typeof res === 'string') return notify($, 'error', res)
337 await replaceIssue($, res.text)
338 await notify($, 'ok', `${action === 'close' ? 'Closed' : 'Reopened'} #${n}${text ? ' with a comment' : ''}.`)
339 })
340}
341
342function repoPath(): string {
343 return `/repos/${auth!.repo.owner}/${auth!.repo.repo}`
344}
345
346/** Re-reads one issue after a write whose answer is not the issue itself. */
347async function refetchIssue($: $, n: number): Promise<string | null> {
348 const res = await get($, `${repoPath()}/issues/${n}`)
349 if (typeof res === 'string') return res
350 await replaceIssue($, res.text)
351 return null
352}
353
354async function saveLabels($: $): Promise<void> {
355 const [d, u] = await Promise.all([readData($), readUi($)])
356 const n = u.open
357 const names = u.editingLabels
358 if (n === null || names === null) return
359 await write($, async () => {
360 const res = await request($, 'PUT', `${repoPath()}/issues/${n}/labels`, { labels: labelIds(names, d.labels) })
361 if (typeof res === 'string') return notify($, 'error', res)
362 const why = await refetchIssue($, n)
363 if (why) return notify($, 'error', why)
364 await updateUi($, (x): Ui => ({ ...x, editingLabels: null }))
365 await notify($, 'ok', `Labels saved on #${n}.`)
366 })
367}
368
369async function setMilestone($: $, title: string): Promise<void> {
370 const [d, u] = await Promise.all([readData($), readUi($)])
371 const n = u.open
372 if (n === null) return
373 await write($, async () => {
374 const res = await request($, 'PATCH', `${repoPath()}/issues/${n}`, { milestone: milestoneId(title || null, d.milestones) })
375 if (typeof res === 'string') return notify($, 'error', res)
376 await replaceIssue($, res.text)
377 await notify($, 'ok', title ? `#${n} moved to ${title}.` : `#${n} has no milestone now.`)
378 })
379}
380
381async function createIssue($: $): Promise<void> {
382 const [d, u] = await Promise.all([readData($), readUi($)])
383 const draft = u.creating
384 if (!draft) return
385 const problem = newIssueProblem(draft, triageRules)
386 if (problem) return notify($, 'error', problem)
387 await write($, async () => {
388 const res = await request($, 'POST', `${repoPath()}/issues`, {
389 title: draft.title.trim(),
390 body: draft.body.trim(),
391 labels: labelIds(draft.labels, d.labels),
392 ...(draft.milestone ? { milestone: milestoneId(draft.milestone, d.milestones) } : {}),
393 })
394 if (typeof res === 'string') return notify($, 'error', res)
395 const created = toIssues(`[${res.text}]`)[0]
396 if (!created) return notify($, 'error', 'The forge answered without the new issue.')
397 await updateData($, (x): Data => ({ ...x, issues: [created, ...x.issues] }))
398 await updateUi($, (x): Ui => ({ ...x, creating: null }))
399 await openIssue($, created.number)
400 await notify($, 'ok', `Filed #${created.number}.`)
401 })
402}
403
404/** The text behind an editor id: the comment draft, or a field of the new-issue form. */
405function getField(u: Ui, id: string): string {
406 if (id === 'comment') return u.draft
407 if (id === 'new-title') return u.creating?.title ?? ''
408 if (id === 'new-body') return u.creating?.body ?? ''
409 return ''
410}
411
412function setField(u: Ui, id: string, text: string): Ui {
413 if (id === 'comment') return { ...u, draft: text, armed: null }
414 if (id === 'new-title' && u.creating) return { ...u, creating: { ...u.creating, title: text } }
415 if (id === 'new-body' && u.creating) return { ...u, creating: { ...u.creating, body: text } }
416 return u
417}
418
419/** Marks an editor's text as replaced from here, so the editor adopts it. */
420function bump(u: Ui, id: string): Ui {
421 return { ...u, sync: { ...u.sync, [id]: (u.sync[id] ?? 0) + 1 } }
422}
423
424function isFormat(f: string | undefined): f is Format {
425 return f === 'bold' || f === 'italic' || f === 'code' || f === 'link' || f === 'heading' || f === 'list' || f === 'quote'
426}
427
428/**
429 * Hands an editor's text to the external editor: writes it to a file, runs
430 * the configured command, and takes the file back when the command exits. A
431 * command that returns at once (a launcher that forks) leaves the session
432 * open; the "Use editor text" pill takes the file back by hand.
433 */
434async function openExternal($: $, id: string): Promise<void> {
435 if (!editorCommand) return notify($, 'error', 'Set the External editor command in the mod settings first.')
436 const u = await readUi($)
437 const dir = (await $.env.get('XDG_RUNTIME_DIR')) || '/tmp'
438 const file = `${dir}/claude-mods-forgejo-${id}.md`
439 await $.fs.write(file, getField(u, id))
440 await updateUi($, (x): Ui => ({ ...x, external: { id, file }, notice: { tone: 'ok', text: 'Editing in your editor: save and quit to bring the text back.' } }))
441 const started = await $.clock.now()
442 try {
443 const stream = $.process.spawn({ argv: editorArgv(editorCommand, file) })
444 for await (const _ of stream) {
445 // The editor's own output is not used; reading it keeps the process ours.
446 }
447 const done = await stream.result
448 if (done.code !== 0 && done.code !== null) return notify($, 'error', `The editor command exited with ${done.code}.`)
449 } catch (err) {
450 return notify($, 'error', `Could not start the editor: ${err instanceof Error ? err.message : String(err)}`)
451 }
452 if ((await $.clock.now()) - started < 1500) {
453 return notify($, 'ok', 'The editor command returned straight away. When you are done, press Use editor text.')
454 }
455 await pullExternal($)
456}
457
458async function pullExternal($: $): Promise<void> {
459 const u = await readUi($)
460 if (!u.external) return
461 const { id, file } = u.external
462 let text: string
463 try {
464 text = await $.fs.read(file)
465 } catch {
466 return notify($, 'error', 'The editor file is gone; nothing to bring back.')
467 }
468 await updateUi($, (x): Ui => bump({ ...setField(x, id, text.replace(/\n$/, '')), external: null }, id))
469 await $.process.run(['rm', '-f', file])
470 await notify($, 'ok', 'Brought the text back from your editor.')
471}
472
473/** A pill's id, as pill.tsx posts it: `state:open`, `chip:<label>`, `open:<n>`, `back`, ... */
474async function press($: $, id: string): Promise<void> {
475 const [kind, ...rest] = id.split(':')
476 const arg = rest.join(':')
477 if (kind === 'state' && (arg === 'open' || arg === 'closed' || arg === 'all')) {
478 await updateUi($, (x): Ui => ({ ...x, state: arg }))
479 } else if (kind === 'grouped') {
480 await updateUi($, (x): Ui => ({ ...x, grouped: !x.grouped }))
481 } else if (kind === 'refresh') {
482 await load($)
483 } else if (kind === 'repo') {
484 await switchRepo($, arg)
485 } else if (kind === 'chip') {
486 await toggleChip($, arg)
487 } else if (kind === 'back') {
488 await updateUi($, (x): Ui => ({ ...x, open: null }))
489 } else if (kind === 'open' && /^\d+$/.test(arg)) {
490 await openIssue($, Number(arg))
491 } else if (kind === 'comment') {
492 await comment($)
493 } else if (kind === 'close' || kind === 'reopen') {
494 await arm($, kind)
495 } else if (kind === 'confirm') {
496 await confirm($)
497 } else if (kind === 'cancel') {
498 await updateUi($, (x): Ui => ({ ...x, armed: null }))
499 } else if (kind === 'labels') {
500 await pressLabels($, arg)
501 } else if (kind === 'new') {
502 await pressNew($, arg)
503 } else if (kind === 'fmt') {
504 const [id, format] = arg.split(':')
505 if (id && isFormat(format)) {
506 await updateUi($, (x): Ui => ({ ...x, fmt: { ...x.fmt, [id]: { seq: (x.fmt[id]?.seq ?? 0) + 1, format } } }))
507 }
508 } else if (kind === 'preview') {
509 await updateUi($, (x): Ui => ({ ...x, preview: { ...x.preview, [arg]: !x.preview[arg] } }))
510 } else if (kind === 'editor') {
511 // Not awaited: an editing session outlasts any hook's time budget.
512 void openExternal($, arg)
513 } else if (kind === 'editor-pull') {
514 await pullExternal($)
515 }
516}
517
518/** Shows another of the project's repos: remembered for this session's repo, then loaded. */
519async function switchRepo($: $, key: string): Promise<void> {
520 const d = await readData($)
521 const launch = d.choices[0]
522 if (!launch || !d.choices.some(r => repoKey(r) === key) || (d.repo && repoKey(d.repo) === key)) return
523 await $.store.set(pickedKey(launch), key)
524 await load($)
525}
526
527/** `labels:edit`, `labels:save`, `labels:cancel`, `labels:toggle:<name>` in the detail view. */
528async function pressLabels($: $, arg: string): Promise<void> {
529 const d = await readData($)
530 if (arg === 'edit') {
531 const u = await readUi($)
532 const issue = d.issues.find(i => i.number === u.open)
533 if (issue) await updateUi($, (x): Ui => ({ ...x, editingLabels: issue.labels.map(l => l.name), notice: null }))
534 } else if (arg === 'save') {
535 await saveLabels($)
536 } else if (arg === 'cancel') {
537 await updateUi($, (x): Ui => ({ ...x, editingLabels: null }))
538 } else if (arg.startsWith('toggle:')) {
539 const name = arg.slice('toggle:'.length)
540 await updateUi($, (x): Ui => (x.editingLabels ? { ...x, editingLabels: toggleScoped(x.editingLabels, name, d.labels) } : x))
541 }
542}
543
544/** `new:start`, `new:create`, `new:cancel`, `new:toggle:<name>` for the new-issue form. */
545async function pressNew($: $, arg: string): Promise<void> {
546 const d = await readData($)
547 if (arg === 'start') {
548 await updateUi($, (x): Ui =>
549 bump(bump({ ...x, open: null, notice: null, creating: { title: '', body: '', labels: [], milestone: '' } }, 'new-title'), 'new-body'),
550 )
551 } else if (arg === 'create') {
552 await createIssue($)
553 } else if (arg === 'cancel' || arg === 'back') {
554 await updateUi($, (x): Ui => ({ ...x, creating: null, notice: null }))
555 } else if (arg.startsWith('toggle:')) {
556 const name = arg.slice('toggle:'.length)
557 await updateUi($, (x): Ui =>
558 x.creating ? { ...x, creating: { ...x.creating, labels: toggleScoped(x.creating.labels, name, d.labels) } } : x,
559 )
560 }
561}
562
563async function guard($: $, tool: string, input: Record<string, unknown>): Promise<string | null> {
564 await paths($)
565 if (!configHome || !touchesSecrets(tool, input, secretsDir(), home)) return null
566 return `${$.plugin.name}: ${secretsDir()} holds tokens for claude-mods and is kept from the model. Ask the user if something there needs checking.`
567}
568
569export const register: Register = (on, options) => {
570 apiUrl = typeof options?.apiUrl === 'string' ? options.apiUrl : ''
571 requireCommentOnClose = options?.requireCommentOnClose !== false
572 editorCommand = typeof options?.editorCommand === 'string' ? options.editorCommand.trim() : ''
573 triageRules = {
574 requireMilestone: options?.requireMilestone === true,
575 requireLabelFrom: parseLabelList(typeof options?.requireLabelFrom === 'string' ? options.requireLabelFrom : ''),
576 }
577
578 on('session.start', async ($, e, next) => {
579 await $.command.register({ name: 'issues', description: "Show this repo's Forgejo issues in a pane; /issues <repo> switches to another the project lists" })
580 return next(e)
581 })
582
583 on('command.run', { command: 'issues' }, async ($, e) => {
584 await $.ui.open({ id: PANE, title: 'Issues' })
585 void load($, e.args)
586 return { text: 'Issues pane opened.' }
587 })
588
589 // One hook for every tool: builds differ in which file tools they have
590 // (some search with Grep/Glob, some only through Bash).
591 on('tool.call', async ($, e, next) => {
592 if (!GUARDED.has(e.tool)) return next(e)
593 const deny = await guard($, e.tool, e as unknown as Record<string, unknown>)
594 return deny ? { deny } : next(e)
595 })
596
597 // Every pressable control is a Client (cards, pills) posting a message.
598 on('ui.message', { component: 'Pane', requestId: PANE }, async ($, e) => {
599 const msg = e.data as { open?: unknown; press?: unknown; edit?: unknown; text?: unknown; submit?: unknown } | null
600 if (typeof msg?.edit === 'string' && typeof msg.text === 'string') {
601 const id = msg.edit
602 const text = msg.text
603 await updateUi($, (x): Ui => setField(x, id, text))
604 }
605 if (msg?.submit === 'comment') await comment($)
606 if (msg?.submit === 'new-title' || msg?.submit === 'new-body') await createIssue($)
607 if (typeof msg?.open === 'number') await openIssue($, msg.open)
608 if (typeof msg?.press === 'string') await press($, msg.press)
609 return {}
610 })
611
612 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
613 if (e.surface !== 'terminal' && e.surface !== 'desktop') {
614 const { Text } = $.ui.resolve(e)
615 return <Text>The issues pane draws in the terminal and the desktop app.</Text>
616 }
617 const el = $.ui.resolve(e)
618 const [d, u, dt] = await Promise.all([readData($), readUi($), read($, detail)])
619 // Ages count from the fetch: drawing stays a pure function of state.
620 const now = d.fetchedAt
621 const issue = u.open === null ? undefined : d.issues.find(i => i.number === u.open)
622 if (u.creating) {
623 return newIssueView(el, d, u, u.creating, triageRules, editorCommand !== '', {
624 milestone: value => updateUi($, (x): Ui => (x.creating ? { ...x, creating: { ...x.creating, milestone: value } } : x)),
625 })
626 }
627 if (issue) {
628 return detailView(el, d, issue, dt, u, now, editorCommand !== '', {
629 milestone: value => setMilestone($, value),
630 })
631 }
632 return listView(el, d, u, now, e.surface === 'desktop', {
633 query: text => updateUi($, (x): Ui => ({ ...x, query: text })),
634 openFirst: () => openFirst($),
635 milestone: value => updateUi($, (x): Ui => ({ ...x, milestone: value })),
636 repo: key => switchRepo($, key),
637 })
638 })
639}
640hooks/forge.ts 195 lines1import type { Comment, Issue, Label, Milestone } from '../types'
2
3/** Where a repository lives on a Forgejo/Gitea host. */
4export type RepoRef = {
5 host: string
6 owner: string
7 repo: string
8 webBase: string
9 apiBase: string
10}
11
12/**
13 * Reads a git remote URL in any of its spellings: scp-like
14 * (`git@host:owner/repo.git`), `ssh://`, `https://` (with or without a port or
15 * credentials). The API is assumed on https at the same host; `apiOverride`
16 * replaces it where the SSH host is not the web host.
17 */
18export function parseRemote(url: string, apiOverride = ''): RepoRef | null {
19 const trimmed = url.trim()
20 let host: string | undefined
21 let path: string | undefined
22 const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/.exec(trimmed)
23 const full = /^(?:ssh|https?|git):\/\/(?:[^@/\s]+@)?([^/:\s]+)(?::\d+)?\/(.+)$/.exec(trimmed)
24 if (full) [, host, path] = full
25 else if (scp) [, host, path] = scp
26 if (!host || !path) return null
27 const parts = path.replace(/\.git\/?$/, '').replace(/\/$/, '').split('/')
28 const repo = parts.pop()
29 const owner = parts.pop()
30 if (!owner || !repo) return null
31 const webBase = `https://${host}`
32 const apiBase = apiOverride ? apiOverride.replace(/\/+$/, '') : `${webBase}/api/v1`
33 return { host, owner, repo, webBase, apiBase }
34}
35
36/** The secrets-file key holding the token for `host`: `FORGEJO_TOKEN_GIT_EXAMPLE_ORG`. */
37export function tokenKey(host: string): string {
38 return `FORGEJO_TOKEN_${host.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`
39}
40
41/** Parses `KEY=value` lines (comments, blank lines, `export`, quotes allowed). */
42export function parseEnv(text: string): Map<string, string> {
43 const out = new Map<string, string>()
44 for (const line of text.split('\n')) {
45 const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line)
46 if (!m || !m[1]) continue
47 let value = m[2] ?? ''
48 if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1)
49 out.set(m[1], value)
50 }
51 return out
52}
53
54/**
55 * The token fgj keeps for `host` in its config.yaml
56 * (`hosts: { <host>: { token } }`), read without a YAML library.
57 */
58export function fgjToken(yaml: string, host: string): string | undefined {
59 let inHost = false
60 let hostIndent = -1
61 for (const line of yaml.split('\n')) {
62 if (!line.trim() || line.trim().startsWith('#')) continue
63 const indent = line.length - line.trimStart().length
64 const key = /^\s*([^:\s]+):\s*(.*)$/.exec(line)
65 if (!key) continue
66 if (inHost && indent <= hostIndent) inHost = false
67 if (key[1] === host && !key[2]) {
68 inHost = true
69 hostIndent = indent
70 } else if (inHost && key[1] === 'token' && key[2]) {
71 return key[2].replace(/^(['"])(.*)\1$/, '$2')
72 }
73 }
74 return undefined
75}
76
77/** Where a token was found, for the pane to say (never the token itself). */
78export type TokenSource = 'secrets' | 'fgj'
79
80/**
81 * The token for `host`, first match wins: the claude-mods secrets file's
82 * host-bound key, then fgj's entry for that host. Never a token keyed to
83 * another host, so a repo on one forge cannot leak another forge's token.
84 */
85export function pickToken(
86 host: string,
87 secretsText: string | null,
88 fgjYaml: string | null,
89): { token: string; source: TokenSource } | null {
90 const fromSecrets = secretsText ? parseEnv(secretsText).get(tokenKey(host)) : undefined
91 if (fromSecrets) return { token: fromSecrets, source: 'secrets' }
92 const fromFgj = fgjYaml ? fgjToken(fgjYaml, host) : undefined
93 if (fromFgj) return { token: fromFgj, source: 'fgj' }
94 return null
95}
96
97type ApiIssue = {
98 number: number
99 title: string
100 body?: string
101 state: string
102 comments: number
103 updated_at: string
104 html_url: string
105 user?: { login?: string }
106 labels?: { name: string; color: string }[]
107 milestone?: { title?: string } | null
108 pull_request?: unknown
109}
110
111function list<T>(json: string, what: string): T[] {
112 const raw = JSON.parse(json) as unknown
113 if (!Array.isArray(raw)) throw new Error(`${what} is not a list`)
114 return raw as T[]
115}
116
117const hex = (c: string) => `#${c.replace(/^#/, '')}`
118
119/** Narrows the API's issue list to what the pane draws; pull requests are left out. */
120export function toIssues(json: string): Issue[] {
121 return list<ApiIssue>(json, 'issue list')
122 .filter(i => !i.pull_request)
123 .map(i => ({
124 number: i.number,
125 title: i.title,
126 body: i.body ?? '',
127 state: i.state === 'closed' ? 'closed' : 'open',
128 comments: i.comments,
129 updatedAt: i.updated_at,
130 url: i.html_url,
131 author: i.user?.login ?? '',
132 labels: (i.labels ?? []).map(l => ({ name: l.name, color: hex(l.color) })),
133 milestone: i.milestone?.title ?? null,
134 }))
135}
136
137export function toLabels(json: string): Label[] {
138 return list<{ id: number; name: string; color: string; exclusive?: boolean; description?: string }>(json, 'label list').map(
139 l => ({ id: l.id, name: l.name, color: hex(l.color), exclusive: Boolean(l.exclusive), description: l.description ?? '' }),
140 )
141}
142
143export function toMilestones(json: string): Milestone[] {
144 return list<{ id: number; title: string; state?: string; open_issues?: number; closed_issues?: number }>(json, 'milestone list').map(m => ({
145 id: m.id,
146 title: m.title,
147 state: m.state === 'closed' ? 'closed' : 'open',
148 open: m.open_issues ?? 0,
149 closed: m.closed_issues ?? 0,
150 }))
151}
152
153export function toComments(json: string): Comment[] {
154 return list<{ user?: { login?: string }; body?: string; created_at: string }>(json, 'comment list').map(c => ({
155 author: c.user?.login ?? '',
156 body: c.body ?? '',
157 createdAt: c.created_at,
158 }))
159}
160
161/** Splits a scoped label (`kind/bug`, `area/ui/menu`) at its last slash, as Forgejo does. */
162export function scopeOf(name: string): { scope: string | null; leaf: string } {
163 const at = name.lastIndexOf('/')
164 return at > 0 && at < name.length - 1 ? { scope: name.slice(0, at), leaf: name.slice(at + 1) } : { scope: null, leaf: name }
165}
166
167/**
168 * Turns bare `#123` references into links to the issue page, outside code
169 * spans and fences, so the pane can catch a press on one and open it in place.
170 */
171export function linkifyRefs(markdown: string, issueBase: string): string {
172 return markdown
173 .split(/(```[\s\S]*?(?:```|$))/)
174 .map((block, i) =>
175 i % 2 === 1
176 ? block
177 : block
178 .split(/(`[^`\n]*`)/)
179 .map((part, j) =>
180 j % 2 === 1 ? part : part.replace(/(^|[^\w&#\[\/])#(\d+)\b/g, (_, pre: string, n: string) => `${pre}[#${n}](${issueBase}/${n})`),
181 )
182 .join(''),
183 )
184 .join('')
185}
186
187/** "3d", "5h", "just now": how long ago `iso` was, from `now` (ms). */
188export function ago(iso: string, now: number): string {
189 const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000))
190 if (s < 60) return 'now'
191 const units: [number, string][] = [[31_536_000, 'y'], [2_592_000, 'mo'], [86_400, 'd'], [3_600, 'h'], [60, 'm']]
192 for (const [size, unit] of units) if (s >= size) return `${Math.floor(s / size)}${unit}`
193 return 'now'
194}
195hooks/guard.ts 68 lines1/**
2 * Whether a tool call by the model reaches into the claude-mods secrets
3 * folder. A mod reads that folder itself; the model has no reason to, and a
4 * stray `cat` or `grep -r ~/.config` would put a token in the transcript.
5 *
6 * Bash is matched on the command text, so a determined command can get past
7 * it; it is there to stop the accidental reads.
8 */
9export function touchesSecrets(
10 tool: string,
11 input: Record<string, unknown>,
12 secretsDir: string,
13 home: string,
14): boolean {
15 const dir = secretsDir.replace(/\/+$/, '')
16 const spellings = [dir]
17 if (home && dir.startsWith(`${home}/`)) {
18 const rest = dir.slice(home.length)
19 spellings.push(`~${rest}`, `$HOME${rest}`, `\${HOME}${rest}`)
20 }
21 // The folder itself or anything in it: the spelling ends at a path end, a
22 // slash, or a character no path segment holds (a quote, space, `;`, `|`, ...).
23 const pattern = new RegExp(`(?:${spellings.map(escape).join('|')})(?=$|[/\\s'"\`;|&)<>])`)
24 const hits = (text: unknown) => typeof text === 'string' && pattern.test(text)
25
26 switch (tool) {
27 case 'Read':
28 case 'Write':
29 case 'Edit':
30 return hits(input.file_path)
31 case 'Grep':
32 case 'Glob':
33 // A search rooted above the folder is let through: blocking those would
34 // stop every search of ~/.config. Only a search aimed at it is refused.
35 return hits(input.path) || hits(input.pattern)
36 case 'Bash': {
37 // A heredoc's body is text on its way somewhere (a file, a commit
38 // message), not a path being opened; only the command itself counts.
39 const command = stripHeredocs(String(input.command ?? ''))
40 const relative = home && dir.startsWith(`${home}/`) ? dir.slice(home.length + 1) : null
41 return hits(command) || (relative !== null && new RegExp(`(^|[\\s'"=])${escape(relative)}\\b`).test(command))
42 }
43 default:
44 return false
45 }
46}
47
48/** The command with every heredoc body (`<<EOF` … `EOF`, any quoting or `<<-`) taken out. */
49export function stripHeredocs(command: string): string {
50 const lines = command.split('\n')
51 const out: string[] = []
52 const pending: string[] = []
53 for (const line of lines) {
54 if (pending.length > 0) {
55 if (line.replace(/^\t+/, '') === pending[0]) pending.shift()
56 continue
57 }
58 out.push(line)
59 for (const m of line.matchAll(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/g)) pending.push(m[2]!)
60 }
61 return out.join('\n')
62}
63
64function escape(text: string): string {
65 return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
66}
67
68hooks/triage.ts 51 lines1import type { Label, Milestone, NewIssue } from '../types'
2
3/**
4 * `selected` with `name` toggled. Turning on a label from an exclusive scope
5 * (`kind/bug` where `kind/` is exclusive) turns its siblings off, as Forgejo
6 * itself only keeps one per such scope.
7 */
8export function toggleScoped(selected: string[], name: string, labels: Label[]): string[] {
9 if (selected.includes(name)) return selected.filter(s => s !== name)
10 const at = name.lastIndexOf('/')
11 const scope = at > 0 ? name.slice(0, at + 1) : null
12 const exclusive = scope !== null && labels.some(l => l.exclusive && l.name.startsWith(scope))
13 const kept = exclusive && scope ? selected.filter(s => !s.startsWith(scope)) : selected
14 return [...kept, name]
15}
16
17/** The ids of the labels named, in the repo's label list; unknown names are skipped. */
18export function labelIds(names: string[], labels: Label[]): number[] {
19 const byName = new Map(labels.map(l => [l.name, l.id]))
20 return names.map(n => byName.get(n)).filter((id): id is number => id !== undefined)
21}
22
23/** The id of the milestone titled `title`, 0 for none (what the API takes to clear it). */
24export function milestoneId(title: string | null, milestones: Milestone[]): number {
25 return title ? (milestones.find(m => m.title === title)?.id ?? 0) : 0
26}
27
28export type TriageRules = {
29 requireMilestone: boolean
30 /** One of these labels must be set; empty for no such rule. */
31 requireLabelFrom: string[]
32}
33
34/** Parses the comma-separated `requireLabelFrom` setting. */
35export function parseLabelList(text: string): string[] {
36 return text
37 .split(',')
38 .map(s => s.trim())
39 .filter(Boolean)
40}
41
42/** Why `draft` cannot be filed yet, worded for the form, or null when it can. */
43export function newIssueProblem(draft: NewIssue, rules: TriageRules): string | null {
44 if (!draft.title.trim()) return 'Give the issue a title.'
45 if (rules.requireMilestone && !draft.milestone) return 'Pick a milestone: every issue needs one here.'
46 if (rules.requireLabelFrom.length > 0 && !draft.labels.some(l => rules.requireLabelFrom.includes(l))) {
47 return `Pick one of: ${rules.requireLabelFrom.join(', ')}.`
48 }
49 return null
50}
51hooks/editing.ts 125 lines1import type { Format } from '../types'
2
3/** Pure text editing for the editor Client: a text and a caret (an index into it). */
4export type Buffer = { text: string; caret: number }
5
6function lineStart(text: string, at: number): number {
7 return text.lastIndexOf('\n', at - 1) + 1
8}
9
10function lineEnd(text: string, at: number): number {
11 const end = text.indexOf('\n', at)
12 return end === -1 ? text.length : end
13}
14
15export function insert(b: Buffer, s: string): Buffer {
16 return { text: b.text.slice(0, b.caret) + s + b.text.slice(b.caret), caret: b.caret + s.length }
17}
18
19function wordStart(text: string, at: number): number {
20 let i = at
21 while (i > 0 && /\s/.test(text[i - 1]!)) i--
22 while (i > 0 && !/\s/.test(text[i - 1]!)) i--
23 return i
24}
25
26function wordEnd(text: string, at: number): number {
27 let i = at
28 while (i < text.length && /\s/.test(text[i]!)) i++
29 while (i < text.length && !/\s/.test(text[i]!)) i++
30 return i
31}
32
33/** Applies one key the Client received; null when the key is not an edit (submit, focus moves). */
34export function applyKey(b: Buffer, key: string, mods: { ctrl?: boolean; meta?: boolean }, multiline: boolean): Buffer | null {
35 const { text, caret } = b
36 const word = Boolean(mods.ctrl || mods.meta)
37 switch (key) {
38 case 'left':
39 return { text, caret: word ? wordStart(text, caret) : Math.max(0, caret - 1) }
40 case 'right':
41 return { text, caret: word ? wordEnd(text, caret) : Math.min(text.length, caret + 1) }
42 case 'home':
43 return { text, caret: lineStart(text, caret) }
44 case 'end':
45 return { text, caret: lineEnd(text, caret) }
46 case 'up':
47 case 'down': {
48 const start = lineStart(text, caret)
49 const col = caret - start
50 if (key === 'up') {
51 if (start === 0) return { text, caret: 0 }
52 const prev = lineStart(text, start - 1)
53 return { text, caret: Math.min(prev + col, start - 1) }
54 }
55 const end = lineEnd(text, caret)
56 if (end === text.length) return { text, caret: text.length }
57 const nextEnd = lineEnd(text, end + 1)
58 return { text, caret: Math.min(end + 1 + col, nextEnd) }
59 }
60 case 'backspace': {
61 if (caret === 0) return b
62 const from = word ? wordStart(text, caret) : caret - 1
63 return { text: text.slice(0, from) + text.slice(caret), caret: from }
64 }
65 case 'delete': {
66 if (caret === text.length) return b
67 const to = word ? wordEnd(text, caret) : caret + 1
68 return { text: text.slice(0, caret) + text.slice(to), caret }
69 }
70 case 'return':
71 return multiline && !word ? insert(b, '\n') : null
72 case 'tab':
73 return multiline ? insert(b, ' ') : null
74 case 'space':
75 return insert(b, ' ')
76 default:
77 // A printable character arrives as itself; any other named key is ignored.
78 if ([...key].length === 1 && !mods.ctrl && !mods.meta) return insert(b, key)
79 return null
80 }
81}
82
83/** Inserts Markdown syntax at the caret: inline marks wrap the caret, line marks prefix the line. */
84export function applyFormat(b: Buffer, f: Format): Buffer {
85 const { text, caret } = b
86 const wrap = (open: string, close: string) => ({ text: text.slice(0, caret) + open + close + text.slice(caret), caret: caret + open.length })
87 const prefix = (p: string) => {
88 const start = lineStart(text, caret)
89 if (text.startsWith(p, start)) return b
90 return { text: text.slice(0, start) + p + text.slice(start), caret: caret + p.length }
91 }
92 switch (f) {
93 case 'bold':
94 return wrap('**', '**')
95 case 'italic':
96 return wrap('_', '_')
97 case 'code':
98 return wrap('`', '`')
99 case 'link':
100 return wrap('[', '](url)')
101 case 'heading':
102 return prefix('## ')
103 case 'list':
104 return prefix('- ')
105 case 'quote':
106 return prefix('> ')
107 }
108}
109
110/** The caret's line and column, for drawing it. */
111export function caretPosition(b: Buffer): { line: number; col: number } {
112 const before = b.text.slice(0, b.caret)
113 const line = before.split('\n').length - 1
114 return { line, col: b.caret - lineStart(b.text, b.caret) }
115}
116
117/** Splits a command setting into argv, honouring quotes, with `{file}` replaced (appended when absent). */
118export function editorArgv(command: string, file: string): string[] {
119 const args: string[] = []
120 for (const m of command.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)) args.push(m[1] ?? m[2] ?? m[3] ?? '')
121 const hasFile = args.some(a => a.includes('{file}'))
122 const out = args.map(a => a.replaceAll('{file}', file))
123 return hasFile ? out : [...out, file]
124}
125hooks/search.ts 152 lines1import type { Issue, Milestone, StateFilter, Ui } from '../types'
2
3export type Query = {
4 /** Fuzzy terms; each must match (fzf's extended-mode AND). */
5 terms: string[]
6 labels: string[]
7 notLabels: string[]
8 milestones: string[]
9 state: StateFilter | null
10}
11
12/**
13 * Reads the search box: bare words are fuzzy terms; `label:x`, `-label:x`,
14 * `milestone:x` and `is:open|closed|all` filter. Values may be quoted
15 * (`milestone:"Theming System"`). `l:` and `m:` are short forms.
16 */
17export function parseQuery(text: string): Query {
18 const q: Query = { terms: [], labels: [], notLabels: [], milestones: [], state: null }
19 const re = /(-?)([a-z]+):("[^"]*"?|\S*)|"([^"]*)"?|(\S+)/gi
20 for (const m of text.matchAll(re)) {
21 const [, neg, key, raw, quoted, word] = m
22 if (key !== undefined) {
23 const value = (raw ?? '').replace(/^"|"$/g, '').toLowerCase()
24 const k = key.toLowerCase()
25 if (!value) continue
26 if (k === 'label' || k === 'l') (neg ? q.notLabels : q.labels).push(value)
27 else if (k === 'milestone' || k === 'm') q.milestones.push(value)
28 else if (k === 'is' && (value === 'open' || value === 'closed' || value === 'all')) q.state = value
29 else q.terms.push(`${neg}${key}:${value}`.toLowerCase())
30 } else {
31 const t = (quoted ?? word ?? '').toLowerCase()
32 if (t) q.terms.push(t)
33 }
34 }
35 return q
36}
37
38export type Match = { score: number; positions: number[] }
39
40const isWord = (c: string | undefined) => c !== undefined && /[\p{L}\p{N}]/u.test(c)
41
42/**
43 * fzf-style fuzzy match: `pattern`'s characters in order, not necessarily
44 * adjacent. Finds the shortest window holding them (forward, then backward
45 * from where the forward scan ended) and scores it: points per character,
46 * more at word starts and in runs, less for gaps. Case-insensitive.
47 */
48export function fuzzy(text: string, pattern: string): Match | null {
49 if (!pattern) return { score: 0, positions: [] }
50 const t = text.toLowerCase()
51 const p = pattern.toLowerCase()
52 let pi = 0
53 let end = -1
54 for (let i = 0; i < t.length; i++) {
55 if (t[i] === p[pi] && ++pi === p.length) {
56 end = i
57 break
58 }
59 }
60 if (end < 0) return null
61 let start = end
62 for (let i = end, back = p.length - 1; i >= 0; i--) {
63 if (t[i] === p[back]) {
64 start = i
65 if (--back < 0) break
66 }
67 }
68 const positions: number[] = []
69 let score = 0
70 let prev = -2
71 for (let i = start, k = 0; i <= end && k < p.length; i++) {
72 if (t[i] !== p[k]) continue
73 let s = 16
74 if (!isWord(text[i - 1])) s += 10
75 else if (text[i] !== t[i] && text[i - 1] === t[i - 1]) s += 8
76 // A run is worth as much as a word start (fzf's rule); a gap costs more
77 // the longer it is, so a tight match beats letters scattered at word starts.
78 if (i === prev + 1) s += 10
79 else if (prev >= 0) s -= Math.min(12, 3 + (i - prev - 2))
80 score += s
81 positions.push(i)
82 prev = i
83 k++
84 }
85 return { score: score - start * 0.1, positions }
86}
87
88function labelHit(names: string[], want: string): boolean {
89 return names.some(n => {
90 const name = n.toLowerCase()
91 if (want.endsWith('/')) return name.startsWith(want)
92 return name === want || name.endsWith(`/${want}`) || name.startsWith(`${want}/`)
93 })
94}
95
96export type Row = { issue: Issue; positions: number[] }
97
98/** The issues the box and the chips let through, best fuzzy match first, else most recently updated. */
99export function filterIssues(issues: Issue[], ui: Pick<Ui, 'query' | 'chips' | 'milestone' | 'state'>): Row[] {
100 const q = parseQuery(ui.query)
101 const state = q.state ?? ui.state
102 const rows: (Row & { score: number })[] = []
103 for (const issue of issues) {
104 if (state !== 'all' && issue.state !== state) continue
105 const names = issue.labels.map(l => l.name)
106 if (!ui.chips.every(c => names.includes(c))) continue
107 if (!q.labels.every(l => labelHit(names, l))) continue
108 if (q.notLabels.some(l => labelHit(names, l))) continue
109 if (ui.milestone === '-' ? issue.milestone !== null : ui.milestone && issue.milestone !== ui.milestone) continue
110 const ms = (issue.milestone ?? '').toLowerCase()
111 if (!q.milestones.every(m => (m === 'none' ? !issue.milestone : ms.includes(m)))) continue
112
113 const haystack = `#${issue.number} ${issue.title}`
114 let score = 0
115 const positions = new Set<number>()
116 let ok = true
117 for (const term of q.terms) {
118 const m = fuzzy(haystack, term)
119 if (!m) {
120 ok = false
121 break
122 }
123 score += m.score
124 m.positions.forEach(p => positions.add(p))
125 }
126 if (!ok) continue
127 // Positions are reported against the title alone.
128 const offset = haystack.length - issue.title.length
129 rows.push({
130 issue,
131 score,
132 positions: [...positions].filter(p => p >= offset).map(p => p - offset).sort((a, b) => a - b),
133 })
134 }
135 const byDate = (a: Row, b: Row) => b.issue.updatedAt.localeCompare(a.issue.updatedAt)
136 rows.sort((a, b) => (q.terms.length && b.score !== a.score ? b.score - a.score : byDate(a, b)))
137 return rows.map(({ issue, positions }) => ({ issue, positions }))
138}
139
140/** Rows under their milestones, in the repo's milestone order, those without one last. */
141export function groupRows(rows: Row[], milestones: Milestone[]): { title: string; rows: Row[] }[] {
142 const order = new Map(milestones.map((m, i) => [m.title, i]))
143 const groups = new Map<string, Row[]>()
144 for (const r of rows) {
145 const key = r.issue.milestone ?? ''
146 groups.set(key, [...(groups.get(key) ?? []), r])
147 }
148 return [...groups.entries()]
149 .sort(([a], [b]) => (a === '' ? 1 : b === '' ? -1 : (order.get(a) ?? 1e9) - (order.get(b) ?? 1e9) || a.localeCompare(b)))
150 .map(([title, rows]) => ({ title: title || 'No milestone', rows }))
151}
152hooks/repos.ts 65 lines1import type { RepoInfo } from '../types'
2
3/** The project file listing the other repos the pane can switch to, relative to the session folder. */
4export const REPOS_FILE = '.claude/forgejo-issues.json'
5
6/** `owner/repo` as the switcher, the store and `/issues <repo>` name it. */
7export function repoKey(r: Pick<RepoInfo, 'owner' | 'repo'>): string {
8 return `${r.owner}/${r.repo}`
9}
10
11/**
12 * The `owner/repo` names in a project's repos file (`{ "repos": [...] }`):
13 * entries that are not `owner/repo` are dropped, a trailing `.git` is
14 * trimmed, and a repeat is kept once. A missing or unreadable file is none.
15 */
16export function parseRepoList(json: string | null): string[] {
17 if (!json) return []
18 let parsed: unknown
19 try {
20 parsed = JSON.parse(json)
21 } catch {
22 return []
23 }
24 const list = (parsed as { repos?: unknown } | null)?.repos
25 if (!Array.isArray(list)) return []
26 const out: string[] = []
27 for (const entry of list) {
28 if (typeof entry !== 'string') continue
29 const name = entry.trim().replace(/\.git$/, '')
30 if (!/^[\w.-]+\/[\w.-]+$/.test(name)) continue
31 if (!out.some(x => x.toLowerCase() === name.toLowerCase())) out.push(name)
32 }
33 return out
34}
35
36/** The repos to switch between: the session's own first, then the listed ones on its host. */
37export function repoChoices(launch: RepoInfo, listed: string[]): RepoInfo[] {
38 const out = [launch]
39 for (const name of listed) {
40 const [owner, repo] = name.split('/') as [string, string]
41 if (out.some(r => repoKey(r).toLowerCase() === name.toLowerCase())) continue
42 out.push({ ...launch, owner, repo })
43 }
44 return out
45}
46
47/** What the switcher calls a repo: its name, or `owner/repo` where two choices share the name. */
48export function repoLabel(r: RepoInfo, choices: RepoInfo[]): string {
49 const same = choices.filter(c => c.repo.toLowerCase() === r.repo.toLowerCase())
50 return same.length > 1 ? repoKey(r) : r.repo
51}
52
53/**
54 * The choice `/issues <arg>` names: `owner/repo` or a repo name, matched
55 * without case, exact first, then a prefix only one choice starts with.
56 */
57export function matchRepo(choices: RepoInfo[], arg: string): RepoInfo | undefined {
58 const want = arg.trim().toLowerCase()
59 if (!want) return undefined
60 const exact = choices.find(r => repoKey(r).toLowerCase() === want || r.repo.toLowerCase() === want)
61 if (exact) return exact
62 const prefix = choices.filter(r => r.repo.toLowerCase().startsWith(want) || repoKey(r).toLowerCase().startsWith(want))
63 return prefix.length === 1 ? prefix[0] : undefined
64}
65hooks/views.tsx 426 lines1import type { Elements } from 'claude-code'
2
3import type { Data, Detail, Issue, NewIssue, Ui } from '../types'
4import { ago, linkifyRefs, scopeOf } from './forge'
5import type { CardProps } from './card'
6import type { PillProps } from './pill'
7import { filterIssues, groupRows } from './search'
8import { repoKey, repoLabel } from './repos'
9import type { TriageRules } from './triage'
10import type { EditorProps } from './editor'
11import type { Format } from '../types'
12
13/** The elements both drawing surfaces with a pane share. */
14export type El = Pick<Elements['desktop'], 'Box' | 'Text' | 'Button' | 'Input' | 'Select' | 'Link' | 'Markdown' | 'Client'>
15
16/** What the native controls (Input, Select) call; every pressable control is a pill posting its id. */
17export type ListActions = {
18 query: (text: string) => void
19 openFirst: () => void
20 milestone: (value: string) => void
21 repo: (key: string) => void
22}
23
24/** What the detail view's composer calls. */
25export type DetailActions = { milestone: (title: string) => void }
26
27/** What the new-issue form's native controls call. */
28export type NewIssueActions = { milestone: (title: string) => void }
29
30/** A pressable control: a Client posting `{ press: id }` (see pill.tsx for why not a Button). */
31function pill(el: El, props: PillProps) {
32 const { Client } = el
33 return <Client key={`p-${props.id}`} module="./pill.tsx" props={props} />
34}
35
36const SEARCH_HINT = 'Search · label: · milestone: · is:'
37
38export function repoUrl(data: Data): string {
39 return data.repo ? `${data.repo.webBase}/${data.repo.owner}/${data.repo.repo}` : ''
40}
41
42function header(el: El, data: Data, ui: Ui, shown: number) {
43 const { Box, Text, Link } = el
44 const total = data.issues.filter(i => ui.state === 'all' || i.state === ui.state).length
45 return (
46 <Box key="head" flexDirection="row" justifyContent="space-between" flexWrap="wrap" alignItems="center">
47 <Box flexDirection="row">
48 {data.repo ? <Link href={repoUrl(data)} label={`${data.repo.owner}/${data.repo.repo}`} /> : <Text bold>Issues</Text>}
49 <Text dimColor>
50 {data.status === 'ready' ? ` · ${shown === total ? total : `${shown} of ${total}`} ${ui.state === 'all' ? '' : ui.state}` : ''}
51 </Text>
52 </Box>
53 <Box flexDirection="row" gap={1}>
54 {(['open', 'closed', 'all'] as const).map(st =>
55 pill(el, { id: `state:${st}`, kind: 'button', label: st[0]!.toUpperCase() + st.slice(1), active: ui.state === st, border: data.border }),
56 )}
57 {pill(el, { id: 'grouped', kind: 'button', label: 'Grouped', active: ui.grouped, border: data.border })}
58 {pill(el, { id: 'refresh', kind: 'button', label: data.status === 'loading' ? 'Loading…' : 'Refresh', border: data.border })}
59 {pill(el, { id: 'new:start', kind: 'button', label: 'New issue', border: data.border })}
60 </Box>
61 </Box>
62 )
63}
64
65/** Label chips with counts over the issues in the current state; scoped labels sit under their scope. */
66function chips(el: El, data: Data, ui: Ui) {
67 const { Box, Text } = el
68 const counts = new Map<string, number>()
69 for (const i of data.issues) {
70 if (ui.state !== 'all' && i.state !== ui.state) continue
71 for (const l of i.labels) counts.set(l.name, (counts.get(l.name) ?? 0) + 1)
72 }
73 const known = new Map(data.labels.map(l => [l.name, l]))
74 for (const name of counts.keys()) if (!known.has(name)) known.set(name, { id: -1, name, color: '#888888', exclusive: false, description: '' })
75 const shown = [...known.values()].filter(l => counts.has(l.name) || ui.chips.includes(l.name))
76 const scopes = new Map<string, typeof shown>()
77 for (const l of shown) {
78 const scope = scopeOf(l.name).scope ?? ''
79 scopes.set(scope, [...(scopes.get(scope) ?? []), l])
80 }
81 const order = [...scopes.keys()].sort((a, b) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)))
82 return (
83 <Box key="chips" flexDirection="column">
84 {order.map(scope => (
85 <Box key={`scope-${scope}`} flexDirection="row" flexWrap="wrap" columnGap={2}>
86 {scope && <Text dimColor>{scope}/</Text>}
87 {scopes.get(scope)!.sort((a, b) => a.name.localeCompare(b.name)).map(l => {
88 return pill(el, {
89 id: `chip:${l.name}`,
90 kind: 'chip',
91 label: scopeOf(l.name).leaf,
92 dot: l.color,
93 count: counts.get(l.name) ?? 0,
94 active: ui.chips.includes(l.name),
95 })
96 })}
97 </Box>
98 ))}
99 </Box>
100 )
101}
102
103/**
104 * The project's repos as buttons, the shown one lit; a Select past five.
105 * Nothing when the project lists no other repo.
106 */
107function repoSwitcher(el: El, data: Data, act: ListActions) {
108 const { Box, Text, Select } = el
109 if (!data.repo || data.choices.length < 2) return null
110 const current = repoKey(data.repo)
111 if (data.choices.length > 5) {
112 const options = data.choices.map(r => ({ value: repoKey(r), label: repoLabel(r, data.choices) }))
113 return <Select key="repo" options={options} value={current} onSelect={act.repo} />
114 }
115 return (
116 <Box key="repos" flexDirection="row" gap={1} flexWrap="wrap" alignItems="center">
117 <Text dimColor>Repo</Text>
118 {data.choices.map(r =>
119 pill(el, { id: `repo:${repoKey(r)}`, kind: 'button', label: repoLabel(r, data.choices), active: repoKey(r) === current, border: data.border }),
120 )}
121 </Box>
122 )
123}
124
125function milestonePicker(el: El, data: Data, ui: Ui, act: ListActions) {
126 const { Select } = el
127 const options = [
128 { value: '', label: 'Any milestone' },
129 { value: '-', label: 'No milestone' },
130 ...data.milestones.map(m => ({ value: m.title, label: `${m.title} (${ui.state === 'closed' ? m.closed : ui.state === 'all' ? m.open + m.closed : m.open})` })),
131 ]
132 return <Select key="milestone" options={options} value={ui.milestone} onSelect={act.milestone} />
133}
134
135export function listView(el: El, data: Data, ui: Ui, now: number, proportional: boolean, act: ListActions) {
136 const { Box, Text, Input, Client } = el
137 const rows = filterIssues(data.issues, ui)
138 const numberWidth = Math.max(2, ...data.issues.map(i => String(i.number).length))
139 // Desktop text is proportional, about a fifth narrower than its cell grid.
140 const textScale = proportional ? 1.2 : 1
141 const card = (r: (typeof rows)[number]) => {
142 const props: CardProps = {
143 number: r.issue.number,
144 title: r.issue.title,
145 positions: r.positions,
146 labels: r.issue.labels,
147 age: ago(r.issue.updatedAt, now),
148 comments: r.issue.comments,
149 closed: r.issue.state === 'closed',
150 numberWidth,
151 textScale,
152 border: data.border,
153 }
154 return <Client key={`card-${r.issue.number}`} module="./card.tsx" props={props} width="100%" />
155 }
156 // A search ranks by match, so it reads best flat; groups return when it clears.
157 const groups = ui.grouped && !ui.query.trim() ? groupRows(rows, data.milestones) : [{ title: '', rows }]
158 const list = (
159 <Box key="list" flexDirection="column" gap={2}>
160 {groups.map(g => (
161 <Box key={`g-${g.title}`} flexDirection="column" gap={1}>
162 {g.title && (
163 <Box flexDirection="row">
164 <Text bold>{g.title}</Text>
165 <Text dimColor> {g.rows.length}</Text>
166 </Box>
167 )}
168 {g.rows.map(card)}
169 </Box>
170 ))}
171 </Box>
172 )
173
174 return (
175 <Box flexDirection="column" gap={1}>
176 {repoSwitcher(el, data, act)}
177 {header(el, data, ui, rows.length)}
178 <Box key="search-row" flexDirection="row">
179 <Box flexGrow={1} flexDirection="column">
180 <Input key="search" placeholder={SEARCH_HINT} value={ui.query} onInput={act.query} onSubmit={act.openFirst} />
181 </Box>
182 </Box>
183 {data.status === 'ready' && chips(el, data, ui)}
184 {data.status === 'ready' && milestonePicker(el, data, ui, act)}
185 {data.status === 'loading' && <Text dimColor>Loading issues…</Text>}
186 {data.status === 'idle' && <Text dimColor>Run /issues to load this repo's issues.</Text>}
187 {data.message && <Text color="error">{data.message}</Text>}
188 {data.status === 'ready' && rows.length === 0 && <Text dimColor>No issues match. Clear a filter to see more.</Text>}
189 {rows.length > 0 && list}
190 </Box>
191 )
192}
193
194/** Issues `text` mentions as `#N`, outside code, that exist here, in order of first mention. */
195function mentions(texts: string[], data: Data, self: number): number[] {
196 const known = new Set(data.issues.map(i => i.number))
197 const seen: number[] = []
198 for (const t of texts) {
199 const plain = t.replace(/```[\s\S]*?(```|$)/g, '').replace(/`[^`\n]*`/g, '')
200 for (const m of plain.matchAll(/(?:^|[^\w&#/])#(\d+)\b/g)) {
201 const n = Number(m[1])
202 if (n !== self && known.has(n) && !seen.includes(n)) seen.push(n)
203 }
204 }
205 return seen
206}
207
208export function detailView(el: El, data: Data, issue: Issue, detail: Detail | null, ui: Ui, now: number, hasEditor: boolean, act: DetailActions) {
209 const { Box, Text, Link, Markdown, Select } = el
210 const base = `${repoUrl(data)}/issues`
211 const comments = detail?.number === issue.number ? detail : null
212 const refs = mentions([issue.body, ...(comments?.comments ?? []).map(c => c.body)], data, issue.number)
213 const titleOf = (n: number) => data.issues.find(i => i.number === n)?.title ?? ''
214
215 return (
216 <Box flexDirection="column" gap={1}>
217 <Box key="top" flexDirection="row" justifyContent="space-between" alignItems="center">
218 {pill(el, { id: 'back', kind: 'button', label: '← Issues', border: data.border })}
219 <Link href={issue.url} label="Open on web" />
220 </Box>
221 <Box key="title" flexDirection="row" flexWrap="wrap">
222 <Text bold>{issue.title}</Text>
223 <Text dimColor> #{issue.number}</Text>
224 </Box>
225 <Box key="meta" flexDirection="row" flexWrap="wrap" columnGap={2}>
226 <Text color={issue.state === 'open' ? 'success' : 'merged'}>{issue.state === 'open' ? '● Open' : '● Closed'}</Text>
227 {issue.labels.map(l => (
228 <Box key={`ml-${l.name}`} flexDirection="row">
229 <Text color={l.color}>● </Text>
230 <Text dimColor>{l.name}</Text>
231 </Box>
232 ))}
233 <Text dimColor>
234 {issue.author} · updated {ago(issue.updatedAt, now)} ago
235 </Text>
236 </Box>
237 <Box key="triage" flexDirection="row" flexWrap="wrap" gap={1} alignItems="center">
238 <Select
239 key="issue-milestone"
240 options={milestoneOptions(data, issue.milestone)}
241 value={issue.milestone ?? ''}
242 onSelect={act.milestone}
243 />
244 {ui.editingLabels === null && pill(el, { id: 'labels:edit', kind: 'button', label: 'Edit labels', border: data.border })}
245 </Box>
246 {ui.editingLabels !== null && (
247 <Box key="label-editor" flexDirection="column" gap={1} borderStyle="round" borderColor={data.border} paddingX={1}>
248 {labelPicker(el, data, ui.editingLabels, 'labels:toggle:')}
249 <Box flexDirection="row" gap={1}>
250 {pill(el, { id: 'labels:save', kind: 'button', label: ui.busy ? 'Saving…' : 'Save labels', active: true, border: data.border })}
251 {pill(el, { id: 'labels:cancel', kind: 'button', label: 'Cancel', border: data.border })}
252 </Box>
253 </Box>
254 )}
255 {refs.length > 0 && (
256 <Box key="refs" flexDirection="row" flexWrap="wrap" columnGap={2}>
257 <Text dimColor>Mentions</Text>
258 {refs.map(n => pill(el, { id: `open:${n}`, kind: 'chip', label: `#${n} ${titleOf(n).slice(0, 40)}${titleOf(n).length > 40 ? '…' : ''}` }))}
259 </Box>
260 )}
261 {/* The issue itself on a raised panel, so it reads apart from the thread below. */}
262 <Box
263 key="body"
264 flexDirection="column"
265 borderStyle="round"
266 borderColor={data.border}
267 backgroundColor={data.raised}
268 paddingX={2}
269 paddingY={1}
270 >
271 <Markdown key="body-md" text={linkifyRefs(issue.body.trim() || '_No description._', base)} />
272 </Box>
273 <Box key="c-head" flexDirection="row" marginTop={1}>
274 <Text bold>{issue.comments === 1 ? '1 comment' : `${issue.comments} comments`}</Text>
275 </Box>
276 {comments?.status === 'loading' && <Text dimColor>Loading comments…</Text>}
277 {comments?.message && <Text color="error">{comments.message}</Text>}
278 {(comments?.comments ?? []).map((c, i) => (
279 <Box key={`cm${i}`} flexDirection="column" borderStyle="round" borderColor={data.border} paddingX={1}>
280 <Box flexDirection="row">
281 <Text bold>{c.author}</Text>
282 <Text dimColor> · {ago(c.createdAt, now)} ago</Text>
283 </Box>
284 <Markdown key={`cb${i}`} text={linkifyRefs(c.body, base)} />
285 </Box>
286 ))}
287 {composer(el, data, issue, ui, hasEditor)}
288 </Box>
289 )
290}
291
292/** The comment field and the write actions: comment, then close or reopen behind a Confirm. */
293function composer(el: El, data: Data, issue: Issue, ui: Ui, hasEditor: boolean) {
294 const { Box, Text, Input } = el
295 const hasDraft = ui.draft.trim().length > 0
296 const isOpen = issue.state === 'open'
297 const closeLabel = hasDraft ? 'Comment and close' : 'Close issue'
298 const b = data.border
299 return (
300 <Box key="composer" flexDirection="column" gap={1} marginTop={1}>
301 {editor(el, data, ui, 'comment', 'Leave a comment · Ctrl+Enter posts it', true, 3)}
302 {editorTools(el, data, ui, 'comment', hasEditor)}
303 {ui.armed ? (
304 <Box key="confirm" flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
305 <Text>
306 {ui.armed === 'close' ? `Close #${issue.number}${hasDraft ? ' with this comment' : ''}?` : `Reopen #${issue.number}${hasDraft ? ' with this comment' : ''}?`}
307 </Text>
308 {pill(el, { id: 'confirm', kind: 'button', label: ui.busy ? 'Working…' : 'Confirm', active: true, border: b })}
309 {pill(el, { id: 'cancel', kind: 'button', label: 'Cancel', border: b })}
310 </Box>
311 ) : (
312 <Box key="actions" flexDirection="row" gap={1} flexWrap="wrap">
313 {pill(el, { id: 'comment', kind: 'button', label: ui.busy ? 'Working…' : 'Comment', border: b })}
314 {isOpen
315 ? pill(el, { id: 'close', kind: 'button', label: closeLabel, border: b })
316 : pill(el, { id: 'reopen', kind: 'button', label: hasDraft ? 'Comment and reopen' : 'Reopen issue', border: b })}
317 </Box>
318 )}
319 {ui.notice && <Text color={ui.notice.tone === 'ok' ? 'success' : 'error'}>{ui.notice.text}</Text>}
320 </Box>
321 )
322}
323
324/** The milestone picker's options: none, then the open milestones (and the current one if closed). */
325function milestoneOptions(data: Data, current: string | null) {
326 const shown = data.milestones.filter(m => m.state === 'open' || m.title === current)
327 return [{ value: '', label: 'No milestone' }, ...shown.map(m => ({ value: m.title, label: m.title }))]
328}
329
330/** Every repo label as a toggle chip, scoped ones under their scope; each posts `<idPrefix><name>`. */
331function labelPicker(el: El, data: Data, selected: string[], idPrefix: string) {
332 const { Box, Text } = el
333 const scopes = new Map<string, typeof data.labels>()
334 for (const l of data.labels) {
335 const scope = scopeOf(l.name).scope ?? ''
336 scopes.set(scope, [...(scopes.get(scope) ?? []), l])
337 }
338 const order = [...scopes.keys()].sort((a, b) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)))
339 return (
340 <Box key="picker" flexDirection="column">
341 {order.map(scope => (
342 <Box key={`pk-${scope}`} flexDirection="row" flexWrap="wrap" columnGap={2}>
343 {scope && <Text dimColor>{scope}/</Text>}
344 {scopes
345 .get(scope)!
346 .sort((a, b) => a.name.localeCompare(b.name))
347 .map(l =>
348 pill(el, { id: `${idPrefix}${l.name}`, kind: 'chip', label: scopeOf(l.name).leaf, dot: l.color, active: selected.includes(l.name) }),
349 )}
350 </Box>
351 ))}
352 </Box>
353 )
354}
355
356/** The new-issue form: title, a one-line body, labels and a milestone. */
357export function newIssueView(el: El, data: Data, ui: Ui, draft: NewIssue, rules: TriageRules, hasEditor: boolean, act: NewIssueActions) {
358 const { Box, Text, Input, Select } = el
359 const need = [rules.requireMilestone ? 'a milestone' : '', rules.requireLabelFrom.length ? `one of ${rules.requireLabelFrom.join(', ')}` : '']
360 .filter(Boolean)
361 .join(' and ')
362 return (
363 <Box flexDirection="column" gap={1}>
364 <Box key="top" flexDirection="row" justifyContent="space-between" alignItems="center">
365 {pill(el, { id: 'new:back', kind: 'button', label: '← Issues', border: data.border })}
366 <Text bold>New issue{data.repo ? ` in ${data.repo.owner}/${data.repo.repo}` : ''}</Text>
367 </Box>
368 {editor(el, data, ui, 'new-title', 'Title · Enter files the issue', false, 1)}
369 {editor(el, data, ui, 'new-body', 'Description in Markdown · Ctrl+Enter files the issue', true, 6)}
370 {editorTools(el, data, ui, 'new-body', hasEditor)}
371 <Text dimColor>Labels</Text>
372 {labelPicker(el, data, draft.labels, 'new:toggle:')}
373 <Select key="new-milestone" options={milestoneOptions(data, null)} value={draft.milestone} onSelect={act.milestone} />
374 {need && <Text dimColor>This repo's issues need {need}.</Text>}
375 <Box key="actions" flexDirection="row" gap={1}>
376 {pill(el, { id: 'new:create', kind: 'button', label: ui.busy ? 'Filing…' : 'Create issue', active: true, border: data.border })}
377 {pill(el, { id: 'new:cancel', kind: 'button', label: 'Cancel', border: data.border })}
378 </Box>
379 {ui.notice && <Text color={ui.notice.tone === 'ok' ? 'success' : 'error'}>{ui.notice.text}</Text>}
380 </Box>
381 )
382}
383
384/** One editor Client: its text comes from the field behind `id`; see editor.tsx. */
385function editor(el: El, data: Data, ui: Ui, id: string, placeholder: string, multiline: boolean, minRows: number) {
386 const { Client } = el
387 const value = id === 'comment' ? ui.draft : id === 'new-title' ? (ui.creating?.title ?? '') : (ui.creating?.body ?? '')
388 const props: EditorProps = {
389 id,
390 value,
391 sync: ui.sync[id] ?? 0,
392 placeholder,
393 multiline,
394 preview: ui.preview[id] === true,
395 minRows,
396 border: data.border,
397 cmd: ui.fmt[id] ?? null,
398 }
399 return <Client key={`ed-${id}`} module="./editor.tsx" props={props} width="100%" />
400}
401
402const FORMATS: [Format, string][] = [
403 ['bold', 'Bold'],
404 ['italic', 'Italic'],
405 ['code', 'Code'],
406 ['link', 'Link'],
407 ['heading', 'Heading'],
408 ['list', 'List'],
409 ['quote', 'Quote'],
410]
411
412/** The toolbar under a multi-line editor: Markdown marks, Write/Preview, and the external editor. */
413function editorTools(el: El, data: Data, ui: Ui, id: string, hasEditor: boolean) {
414 const { Box } = el
415 const previewing = ui.preview[id] === true
416 const out = ui.external?.id === id
417 return (
418 <Box key={`tools-${id}`} flexDirection="row" flexWrap="wrap" columnGap={2} alignItems="center">
419 {!previewing && FORMATS.map(([f, label]) => pill(el, { id: `fmt:${id}:${f}`, kind: 'chip', label }))}
420 {pill(el, { id: `preview:${id}`, kind: 'chip', label: previewing ? 'Write' : 'Preview', active: previewing })}
421 {hasEditor && !out && pill(el, { id: `editor:${id}`, kind: 'chip', label: 'Open in editor' })}
422 {out && pill(el, { id: 'editor-pull', kind: 'chip', label: 'Use editor text', active: true })}
423 </Box>
424 )
425}
426hooks/card.tsx 125 lines1import type { ClientModule } from 'claude-code'
2
3import { packLabels, wrapTitle } from './cards'
4
5export type CardProps = {
6 number: number
7 title: string
8 /** Title characters the search matched, drawn highlighted. */
9 positions: number[]
10 labels: { name: string; color: string }[]
11 age: string
12 comments: number
13 closed: boolean
14 numberWidth: number
15 /** Border colour at rest. */
16 border: string
17 /** Characters per cell: above 1 where the surface draws a proportional font (the desktop). */
18 textScale: number
19}
20
21type Local = { hover: boolean }
22
23const AGE_COLS = 5
24// The card's border and one-cell padding, each side.
25const FRAME_COLS = 4
26
27function segments(text: string, start: number, hits: Set<number>): { t: string; hi: boolean }[] {
28 const out: { t: string; hi: boolean }[] = []
29 ;[...text].forEach((ch, i) => {
30 const hi = hits.has(start + i)
31 const last = out[out.length - 1]
32 if (last && last.hi === hi) last.t += ch
33 else out.push({ t: ch, hi })
34 })
35 return out
36}
37
38/**
39 * One issue as a card. Each card is its own Client, so a hover or a click
40 * belongs to the card under the pointer whatever the surface makes of
41 * borders and spacing (on the desktop a border is a thin line, not a row).
42 */
43const Card: ClientModule<CardProps, Local> = (props, surface) => {
44 const { Box, Text } = surface.elements
45 const state = surface.state ?? { hover: false }
46 // Listeners are set once, on the first draw: each set is a message to the
47 // page, and a list of a hundred cards re-setting them on every redraw gets
48 // its Clients unmounted for flooding it. A card's key is its issue number,
49 // so the number the listeners close over never changes.
50 if (surface.state === undefined) {
51 const number = props.number
52 surface.onPointer(e => {
53 const cur = surface.state ?? { hover: false }
54 if (e.type === 'leave') {
55 if (cur.hover) surface.setState({ hover: false })
56 } else if (!cur.hover) {
57 surface.setState({ hover: true })
58 }
59 if (e.type === 'down' && (e.button ?? 'left') === 'left') surface.post({ open: number })
60 })
61 surface.onKey(e => {
62 if (e.key === 'return') surface.post({ open: number })
63 })
64 surface.setState(state)
65 }
66
67 const inner = Math.max(20, (surface.columns || 80) - FRAME_COLS)
68 const numberCols = props.numberWidth + 2
69 const titleCols = Math.max(10, inner - numberCols - AGE_COLS)
70 const titleLines = wrapTitle(props.title, Math.floor(titleCols * props.textScale))
71 const labelLines = packLabels(props.labels, props.comments, Math.floor((inner - numberCols) * props.textScale))
72 const hits = new Set(props.positions)
73 const lit = state.hover
74
75 return (
76 <Box flexDirection="column" borderStyle="round" borderColor={lit ? 'suggestion' : props.border} paddingX={1}>
77 {titleLines.map((line, li) => (
78 <Box key={`t${li}`} flexDirection="row">
79 <Box width={numberCols} flexShrink={0}>
80 <Text dimColor>{li === 0 ? `#${props.number}` : ''}</Text>
81 </Box>
82 <Box width={titleCols} flexShrink={0} flexDirection="row" overflow="hidden">
83 {segments(line.text, line.start, hits).map((s, j) => (
84 <Text
85 key={`s${j}`}
86 bold={s.hi || lit}
87 color={s.hi ? 'warning' : undefined}
88 dimColor={props.closed && !s.hi}
89 strikethrough={props.closed}
90 wrap="truncate-end"
91 >
92 {s.t}
93 </Text>
94 ))}
95 </Box>
96 <Box width={AGE_COLS} flexShrink={0} justifyContent="flex-end">
97 <Text dimColor>{li === 0 ? props.age : ''}</Text>
98 </Box>
99 </Box>
100 ))}
101 {labelLines.map((line, li) => (
102 <Box key={`l${li}`} flexDirection="row" paddingLeft={numberCols} overflow="hidden">
103 {line.map(item =>
104 item.kind === 'label' ? (
105 <Box key={`lb${item.name}`} flexDirection="row" marginRight={2}>
106 <Text color={item.color}>● </Text>
107 {item.scope && <Text dimColor>{item.scope}</Text>}
108 <Text dimColor wrap="truncate-end">
109 {item.leaf}
110 </Text>
111 </Box>
112 ) : (
113 <Text key="cm" dimColor>
114 {item.text}
115 </Text>
116 ),
117 )}
118 </Box>
119 ))}
120 </Box>
121 )
122}
123
124export default Card
125hooks/pill.tsx 77 lines1import type { ClientModule } from 'claude-code'
2
3/**
4 * A pressable control drawn as a Client: a click posts `{ press: id }` to the
5 * hooks module. Used in place of Button because the desktop app drops Button
6 * presses for plugin panes (`ui_press not handled`), while Client messages
7 * arrive; each control is its own Client so a click needs no hit-testing.
8 */
9export type PillProps = {
10 id: string
11 label: string
12 /** `button`: a bordered control; `chip`: a coloured dot and text. */
13 kind: 'button' | 'chip'
14 active?: boolean
15 /** A label colour, drawn as the chip's dot. */
16 dot?: string
17 /** A count drawn dim after the label. */
18 count?: number
19 /** Border colour at rest (buttons). */
20 border?: string
21}
22
23type Local = { hover: boolean }
24
25const Pill: ClientModule<PillProps, Local> = (props, surface) => {
26 const { Box, Text } = surface.elements
27 const state = surface.state ?? { hover: false }
28 // Set once on the first draw (each set is a message to the page; see
29 // card.tsx). The id is the Client's key, so it never changes under them.
30 if (surface.state === undefined) {
31 const id = props.id
32 surface.onPointer(e => {
33 const cur = surface.state ?? { hover: false }
34 if (e.type === 'leave') {
35 if (cur.hover) surface.setState({ hover: false })
36 } else if (!cur.hover) {
37 surface.setState({ hover: true })
38 }
39 if (e.type === 'down' && (e.button ?? 'left') === 'left') surface.post({ press: id })
40 })
41 surface.onKey(e => {
42 if (e.key === 'return' || e.key === ' ') surface.post({ press: id })
43 })
44 surface.setState(state)
45 }
46
47 const lit = state.hover
48 const count = props.count === undefined ? null : <Text dimColor> {props.count}</Text>
49
50 if (props.kind === 'chip') {
51 return (
52 <Box flexDirection="row">
53 {props.dot && <Text color={props.dot}>● </Text>}
54 <Text bold={props.active} underline={lit} dimColor={!props.active && !lit}>
55 {props.active ? `✓ ${props.label}` : props.label}
56 </Text>
57 {count}
58 </Box>
59 )
60 }
61 return (
62 <Box
63 flexDirection="row"
64 borderStyle="round"
65 borderColor={props.active || lit ? 'suggestion' : (props.border ?? 'subtle')}
66 paddingX={1}
67 >
68 <Text bold={props.active} color={props.active ? 'suggestion' : undefined}>
69 {props.label}
70 </Text>
71 {count}
72 </Box>
73 )
74}
75
76export default Pill
77hooks/editor.tsx 106 lines1import type { ClientModule } from 'claude-code'
2
3import { applyFormat, applyKey, caretPosition } from './editing'
4import type { Format } from '../types'
5
6/**
7 * A full-width text editor drawn as a Client: the desktop's Input is one
8 * line at a fixed width. It keeps its text locally and posts `{ edit, text }`
9 * (batched every FLUSH_MS) and `{ submit }` on Ctrl+Enter (Enter in a
10 * one-line editor). The desktop passes no paste to a Client: long or pasted
11 * text goes through the external editor instead.
12 */
13export type EditorProps = {
14 id: string
15 value: string
16 /** Bumped by the hooks module when it replaces the text (cleared, imported); the editor then adopts `value`. */
17 sync: number
18 placeholder: string
19 multiline: boolean
20 preview: boolean
21 minRows: number
22 border: string
23 /** A Markdown format to apply at the caret, run once per `seq`. */
24 cmd: { seq: number; format: Format } | null
25}
26
27type Local = { text: string; caret: number; sync: number; cmdSeq: number; dirty: boolean }
28
29const FLUSH_MS = 150
30
31const Editor: ClientModule<EditorProps, Local> = (props, surface) => {
32 const { Box, Text, Markdown } = surface.elements
33 let st: Local = surface.state ?? { text: props.value, caret: props.value.length, sync: props.sync, cmdSeq: props.cmd?.seq ?? 0, dirty: false }
34
35 if (surface.state === undefined) {
36 // Set once (each set is a message to the page). The id and multiline-ness
37 // belong to the editor's key, so the closures may keep them.
38 const id = props.id
39 const multiline = props.multiline
40 const flush = () => {
41 const cur = surface.state
42 if (!cur?.dirty) return
43 surface.setState({ ...cur, dirty: false })
44 surface.post({ edit: id, text: cur.text })
45 }
46 surface.every(FLUSH_MS, flush)
47 surface.onKey(e => {
48 const cur = surface.state ?? st
49 const submits = e.key === 'return' && (Boolean(e.ctrl || e.meta) || !multiline)
50 if (submits) {
51 flush()
52 surface.post({ submit: id })
53 return
54 }
55 const next = applyKey(cur, e.key, { ctrl: e.ctrl, meta: e.meta }, multiline)
56 if (next && (next.text !== cur.text || next.caret !== cur.caret)) {
57 surface.setState({ ...cur, ...next, dirty: cur.dirty || next.text !== cur.text })
58 }
59 })
60 surface.setState(st)
61 }
62
63 // The hooks module replaced the text (a clear after posting, an import from the external editor).
64 if (props.sync !== st.sync) {
65 st = { ...st, text: props.value, caret: props.value.length, sync: props.sync, dirty: false }
66 surface.setState(st)
67 }
68 // A toolbar press: apply the format at the caret, once.
69 if (props.cmd && props.cmd.seq !== st.cmdSeq) {
70 const next = applyFormat(st, props.cmd.format)
71 st = { ...st, ...next, cmdSeq: props.cmd.seq, dirty: true }
72 surface.setState(st)
73 }
74
75 const frame = (children: unknown) => (
76 <Box flexDirection="column" borderStyle="round" borderColor={props.border} paddingX={1} minHeight={props.minRows + 2}>
77 {children as never}
78 </Box>
79 )
80
81 if (props.preview) {
82 return frame(st.text.trim() ? <Markdown text={st.text} /> : <Text dimColor>Nothing to preview yet.</Text>)
83 }
84
85 const lines = st.text.split('\n')
86 const at = caretPosition(st)
87 return frame(
88 lines.map((line, i) => {
89 if (i !== at.line) return <Text key={`l${i}`}>{line || ' '}</Text>
90 const before = line.slice(0, at.col)
91 const under = line.slice(at.col, at.col + 1)
92 const after = line.slice(at.col + 1)
93 return (
94 <Box key={`l${i}`} flexDirection="row" flexWrap="wrap">
95 {before && <Text>{before}</Text>}
96 <Text inverse>{under || ' '}</Text>
97 {after && <Text>{after}</Text>}
98 {!st.text && <Text dimColor> {props.placeholder}</Text>}
99 </Box>
100 )
101 }),
102 )
103}
104
105export default Editor
106hooks/cards.ts 54 lines1export type LabelItem =
2 | { kind: 'label'; name: string; color: string; scope: string | null; leaf: string }
3 | { kind: 'comments'; text: string }
4
5const MAX_TITLE_LINES = 3
6
7/** Word-wraps `text` to lines of at most `width` characters, the last one cut with an ellipsis. */
8export function wrapTitle(text: string, width: number, maxLines = MAX_TITLE_LINES): { text: string; start: number }[] {
9 const lines: { text: string; start: number }[] = []
10 let start = 0
11 while (start < text.length && lines.length < maxLines) {
12 while (text[start] === ' ') start++
13 const rest = text.length - start
14 if (rest <= width) {
15 lines.push({ text: text.slice(start), start })
16 return lines
17 }
18 if (lines.length === maxLines - 1) {
19 lines.push({ text: `${text.slice(start, start + width - 1).trimEnd()}…`, start })
20 return lines
21 }
22 const space = text.lastIndexOf(' ', start + width)
23 const end = space > start ? space : start + width
24 lines.push({ text: text.slice(start, end), start })
25 start = end
26 }
27 return lines
28}
29
30/** Packs labels, then the comment count, into lines of at most `width` characters. */
31export function packLabels(labels: { name: string; color: string }[], comments: number, width: number): LabelItem[][] {
32 const items: LabelItem[] = labels.map(l => {
33 const at = l.name.lastIndexOf('/')
34 return at > 0
35 ? { kind: 'label', name: l.name, color: l.color, scope: l.name.slice(0, at + 1), leaf: l.name.slice(at + 1) }
36 : { kind: 'label', name: l.name, color: l.color, scope: null, leaf: l.name }
37 })
38 if (comments > 0) items.push({ kind: 'comments', text: comments === 1 ? '1 comment' : `${comments} comments` })
39 const lines: LabelItem[][] = []
40 let used = 0
41 for (const item of items) {
42 // "● name" plus the two-cell gap after it.
43 const w = item.kind === 'label' ? item.name.length + 4 : item.text.length
44 if (lines.length === 0 || used + w > width) {
45 lines.push([item])
46 used = w
47 } else {
48 lines[lines.length - 1]!.push(item)
49 used += w
50 }
51 }
52 return lines
53}
54