Pin tables, artifact links and answers into a side pane; re-pinning under the same title replaces the pin, so changing figures stay one current version (/pin…

A Claude Code mod that keeps tables, artifact links and answers in a Pins side pane, so the figures you are working through stay in view instead of scrolling away.
Forked from Young-in/pinboard. The difference: a pin has a name, and pinning under that name again replaces it. When figures change mid-investigation Claude re-pins the table under the same title, so the pane holds the current version and never a trail of stale ones.
claude plugin install pinboard@vise-tools
pin tool asks Claude to pin figures you are working through over several turns without being asked, and to re-pin under the same title when they change. You can also just say "pin this table"./pin saves the mouse selection, or else the last answer's tables and artifact links. /pin <title> does the same under a title, replacing a pin of that title.A new pin replaces an existing one only when all of these hold:
title, or /pin <title>), not derived from the content;The replaced pin keeps its id and moves to the top with the new content and time. Identical content is never pinned twice. Pins live in the mod's store across sessions and projects; the pane's This project and This session tabs narrow them.
| Command | Does | ||
|---|---|---|---|
/pin [title] | Pin the selection, else the last answer's tables and links (else the whole answer) | ||
/pin all [title] | Pin the whole last answer | ||
/pin tables \ | links | Pin only the last answer's tables \ | links |
| `/pin rm <n\ | last>, /unpin <n>` | Remove pin n (the pane's number) or the latest | |
/pin undo | Undo the last remove or clear | ||
/pin show <n> | Print pin n into the conversation, where Claude reads it too | ||
/pin clear | Remove all, after confirming | ||
/pin export | Write every pin to ~/.claude/pins/pins-<date>.md | ||
| `/pin auto on\ | off` | Open the pane on session start and when new candidates appear (off until turned on) | |
/pins | Open or close the pane |
In the pane (focus it with ctrl+x tab): 1–9 select, a s d g h pin a candidate, c copy, p insert into the prompt, x remove, u undo, f next filter.
Claude's tools: pin (markdown, title, kind), unpin (id, index or title), list.
/pin can't read a mouse selection.--plugin-dir working copy don't see each other.claude plugin validate plugins/pinboard
claude plugin test plugins/pinboard
claude --plugin-dir plugins/pinboard # a session with this working copy loaded
Code that uses $ stays in hooks/register.tsx, because the engine follows $ only through functions in the hooks module itself; extract.ts and format.ts hold the pure functions.
MIT. Original work © 2026 Young-in; see LICENSE.
hooks/register.tsx 1100 lines1// pinboard: pin tables, artifact links and answers from the conversation into a side pane.
2//
3// One module on purpose: the engine follows `$` only into functions declared in the file that
4// registers the hooks, never across an import, so everything that touches `$` lives here, in
5// sections. The markdown extraction is pure and lives in extract.ts.
6//
7// Entry points: /pin, /pins, /unpin; the model's pin/unpin/list tools; every reply scanned for
8// tables and artifact links (candidates); the Pane the person opens.
9import { atom, read, update } from 'claude-code'
10import type { EngineInterface, Register, RenderInputOf, RenderSurface } from 'claude-code'
11
12import type { PinboardCandidate, PinboardFilter, PinboardKind, PinboardPin } from '../types'
13import {
14 bodyKey,
15 classify,
16 cleanTitle,
17 extractAll,
18 extractLinks,
19 extractTables,
20 firstLineTitle,
21 isKind,
22 projectName,
23} from './extract'
24import { fitWidth, KIND_LABEL, localStamp, shortAge, textWidth } from './format'
25
26// ────────────────────────────────────────────────────────────────────────────
27// State, store and shared operations
28// ────────────────────────────────────────────────────────────────────────────
29
30type Dollar = EngineInterface
31/** Which agent an item came from: a subagent's or teammate's id and the name it is shown by. */
32type AgentTag = { agentId?: string; agentLabel?: string }
33/**
34 * `isNamed`: the title was chosen, by the person or by Claude, rather than derived from the content. A
35 * named item replaces the pin of the same name, so a figure that keeps changing stays one current pin.
36 */
37type PinInput = { kind: PinboardKind; title: string; body: string; sourceUuid?: string; isNamed?: boolean } & AgentTag
38type SavedPin = { pin: PinboardPin; isReplacement: boolean }
39
40const PANE = 'pins'
41const PIN_TOOL = 'mcp__pinboard__pin'
42const PANE_TITLE = 'Pins'
43const STORE_PINS = 'pins'
44const STORE_BACKUP = 'pins.backup'
45const STORE_AUTO_OPEN = 'autoOpen'
46const MAX_PINS = 200
47const MAX_BODY = 20_000
48const MAX_CANDIDATES = 8
49/** How often a session re-reads the shared store to show what other sessions pinned or removed. */
50const REFRESH_MS = 3_000
51
52const STORE_FILTER = 'filter'
53
54const FILTERS: PinboardFilter[] = ['all', 'session', 'project', 'table', 'artifact', 'link']
55const FILTER_LABEL: Record<PinboardFilter, string> = {
56 all: 'All',
57 session: 'This session',
58 table: 'Tables',
59 artifact: 'Artifacts',
60 link: 'Links',
61 project: 'This project',
62}
63const GLYPH: Record<PinboardKind, string> = { table: '▤', artifact: '◈', link: '⇗', text: '¶' }
64
65const pins = atom({ plugin: 'pinboard', key: 'pins' } as const, [])
66const selectedId = atom({ plugin: 'pinboard', key: 'selectedId' } as const, null)
67const filter = atom({ plugin: 'pinboard', key: 'filter' } as const, 'all')
68const candidates = atom({ plugin: 'pinboard', key: 'candidates' } as const, [])
69const lastRemoved = atom({ plugin: 'pinboard', key: 'lastRemoved' } as const, null)
70const confirmDeleteId = atom({ plugin: 'pinboard', key: 'confirmDeleteId' } as const, null)
71const autoOpenSuppressed = atom({ plugin: 'pinboard', key: 'autoOpenSuppressed' } as const, false)
72
73function newId(seed: number): string {
74 return `${seed.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
75}
76
77/**
78 * The agent whose transcript the person last had in view beside the pane, as the pane's last drawing saw it;
79 * undefined for the main conversation. Commands read it, since only a drawing is told which view is on screen.
80 * A module variable on purpose: a hint about the screen, fine to lose on a reload.
81 */
82let viewedAgentId: string | undefined
83
84/** Where the pane is looked at from: the session's folder and id, and the agent in view if any. */
85type Scope = { cwd: string; sessionId: string; agentId?: string }
86
87async function currentScope($: Dollar, agentId = viewedAgentId): Promise<Scope> {
88 const [cwd, sessionId] = await Promise.all([$.session.cwd(), $.session.id()])
89 return agentId ? { cwd, sessionId, agentId } : { cwd, sessionId }
90}
91
92function isFilter(value: unknown): value is PinboardFilter {
93 return typeof value === 'string' && (FILTERS as string[]).includes(value)
94}
95
96/** The pins of the view: one agent's while its transcript is in view, else every pin. */
97function inView(list: PinboardPin[], scope: Scope): PinboardPin[] {
98 return scope.agentId ? list.filter(p => p.agentId === scope.agentId) : list
99}
100
101function visible(list: PinboardPin[], f: PinboardFilter, scope: Scope): PinboardPin[] {
102 const base = inView(list, scope)
103 if (f === 'all') return base
104 if (f === 'session') return base.filter(p => p.sessionId === scope.sessionId)
105 if (f === 'project') return base.filter(p => p.cwd === scope.cwd)
106 return base.filter(p => p.kind === f)
107}
108
109/** The name an agent is shown by: its SendMessage name, its task description, or its type. */
110async function agentLabelOf($: Dollar, agentId: string): Promise<string> {
111 try {
112 const agent = (await $.agent.list()).find(a => a.id === agentId)
113 const label = agent?.name || agent?.description || agent?.type
114 if (label) return label
115 } catch {
116 // the roster is a nicety; fall back to the id
117 }
118 return `agent ${agentId.slice(0, 6)}`
119}
120
121async function agentTag($: Dollar, agentId: string | undefined): Promise<AgentTag> {
122 return agentId ? { agentId, agentLabel: await agentLabelOf($, agentId) } : {}
123}
124
125type PinGroup = { sessionId: string; isCurrent: boolean; label: string; pins: PinboardPin[] }
126
127/** Pins grouped by the session that saved them: this session first, then the others, most recent first. */
128function groupBySession(list: PinboardPin[], scope: Scope): PinGroup[] {
129 const bySession = new Map<string, PinboardPin[]>()
130 for (const p of [...list].sort((a, b) => b.createdAt - a.createdAt)) {
131 const group = bySession.get(p.sessionId)
132 if (group) group.push(p)
133 else bySession.set(p.sessionId, [p])
134 }
135 const groups = [...bySession].map(([sessionId, group]) => {
136 const isCurrent = sessionId === scope.sessionId
137 const oldest = group[group.length - 1]!
138 const label = isCurrent
139 ? 'This session'
140 : `Other session · ${localStamp(oldest.createdAt).slice(5)} · ${projectName(oldest.cwd)}`
141 return { sessionId, isCurrent, label, pins: group }
142 })
143 return groups.sort((a, b) => Number(b.isCurrent) - Number(a.isCurrent) || b.pins[0]!.createdAt - a.pins[0]!.createdAt)
144}
145
146/** The pins a filter shows, in the order the pane numbers them. */
147function displayOrder(list: PinboardPin[], f: PinboardFilter, scope: Scope): PinboardPin[] {
148 return groupBySession(visible(list, f, scope), scope).flatMap(g => g.pins)
149}
150
151function describe(p: PinboardPin): string {
152 return `${GLYPH[p.kind]} ${p.title}`
153}
154
155// Every session of one installed copy shares one list in `$.store`. The store is the truth: each change
156// reads it right before writing, and `refreshPins` mirrors it into session state, where the pane reads it.
157
158/** The pins as the store holds them now. */
159async function loadPins($: Dollar): Promise<PinboardPin[]> {
160 const stored = await $.store.get(STORE_PINS)
161 return Array.isArray(stored) ? (stored as PinboardPin[]) : []
162}
163
164function signature(list: readonly PinboardPin[]): string {
165 return list.map(p => p.id).join(',')
166}
167
168/** Mirrors the store into session state when another session changed it, so the pane redraws. */
169async function refreshPins($: Dollar): Promise<PinboardPin[]> {
170 const fresh = await loadPins($)
171 const mirrored = await read($, pins)
172 if (signature(fresh) !== signature(mirrored)) await update($, pins, () => fresh)
173 return fresh
174}
175
176/**
177 * Changes the shared list: reads the store fresh, applies `change`, writes the result back and mirrors it.
178 * Reading right before writing keeps what other sessions saved meanwhile. `change` returning its input
179 * unchanged writes nothing.
180 */
181async function mutatePins($: Dollar, change: (list: PinboardPin[]) => PinboardPin[]): Promise<PinboardPin[]> {
182 const list = await loadPins($)
183 const next = change(list)
184 if (next !== list) await $.store.set(STORE_PINS, next.slice(0, MAX_PINS))
185 await update($, pins, () => next.slice(0, MAX_PINS))
186 return next
187}
188
189/**
190 * Adds the items not already pinned (same body, whitespace aside), newest first; returns what was saved.
191 * A named item takes the place of the pin with the same name in this project, keeping its id.
192 */
193async function addPins($: Dollar, items: PinInput[]): Promise<SavedPin[]> {
194 const [now, sessionId, cwd] = await Promise.all([$.clock.now(), $.session.id(), $.session.cwd()])
195 const saved: SavedPin[] = []
196 await mutatePins($, current => {
197 let kept = current
198 const known = new Set(current.map(p => bodyKey(p.body)))
199 for (const it of items) {
200 const body = it.body.length > MAX_BODY ? `${it.body.slice(0, MAX_BODY)}\n\n…(truncated)` : it.body
201 const key = bodyKey(body)
202 if (!key || known.has(key)) continue
203 known.add(key)
204 const replaced = it.isNamed ? kept.find(p => isSameNamedPin(p, it, cwd)) : undefined
205 if (replaced) kept = kept.filter(p => p.id !== replaced.id)
206 const pin: PinboardPin = {
207 id: replaced?.id ?? newId(now + saved.length),
208 createdAt: now,
209 sessionId,
210 cwd,
211 kind: it.kind,
212 title: it.title || firstLineTitle(body),
213 body,
214 }
215 if (it.sourceUuid) pin.sourceUuid = it.sourceUuid
216 if (it.isNamed) pin.isNamed = true
217 if (it.agentId) pin.agentId = it.agentId
218 if (it.agentLabel) pin.agentLabel = it.agentLabel
219 saved.push({ pin, isReplacement: Boolean(replaced) })
220 }
221 return saved.length > 0 ? [...saved.map(s => s.pin), ...kept] : current
222 })
223 if (saved.length === 0) return []
224 const savedKeys = new Set(saved.map(s => bodyKey(s.pin.body)))
225 await update($, selectedId, () => saved[0]?.pin.id ?? null)
226 await update($, confirmDeleteId, () => null)
227 await update($, candidates, list => list.filter(c => !savedKeys.has(bodyKey(c.body))))
228 return saved
229}
230
231/** A named pin with the same name, case and spacing aside, in the same project and from the same agent. */
232function isSameNamedPin(p: PinboardPin, it: PinInput, cwd: string): boolean {
233 return p.isNamed === true && p.cwd === cwd && p.agentId === it.agentId && nameKey(p.title) === nameKey(it.title)
234}
235
236function nameKey(title: string): string {
237 return title.trim().replace(/\s+/g, ' ').toLowerCase()
238}
239
240/** Removes one pin and keeps it as `lastRemoved` for undo. */
241async function removePin($: Dollar, id: string): Promise<PinboardPin | undefined> {
242 let target: PinboardPin | undefined
243 await mutatePins($, current => {
244 target = current.find(p => p.id === id)
245 return target ? current.filter(p => p.id !== id) : current
246 })
247 if (!target) return undefined
248 const removed = target
249 await update($, lastRemoved, () => removed)
250 await update($, confirmDeleteId, () => null)
251 await update($, selectedId, cur => (cur === id ? null : cur))
252 return removed
253}
254
255/** Restores the last removed pin, or the backup `/pin clear` left. */
256async function undo($: Dollar): Promise<string> {
257 const removed = await read($, lastRemoved)
258 if (removed) {
259 await mutatePins($, current =>
260 current.some(p => p.id === removed.id)
261 ? current
262 : [removed, ...current].sort((a, b) => b.createdAt - a.createdAt),
263 )
264 await update($, lastRemoved, () => null)
265 await update($, selectedId, () => removed.id)
266 return `↩ Restored: ${describe(removed)}`
267 }
268 const backup = await $.store.get(STORE_BACKUP)
269 if (Array.isArray(backup) && backup.length > 0) {
270 let restored = 0
271 await mutatePins($, current => {
272 const ids = new Set(current.map(p => p.id))
273 const back = (backup as PinboardPin[]).filter(p => !ids.has(p.id))
274 restored = back.length
275 return [...current, ...back].sort((a, b) => b.createdAt - a.createdAt)
276 })
277 await $.store.delete(STORE_BACKUP)
278 return `↩ Restored ${restored} pins`
279 }
280 return 'Nothing to undo.'
281}
282
283async function isPaneOpen($: Dollar): Promise<boolean> {
284 return (await $.ui.panes()).some(p => p.id === PANE)
285}
286
287/**
288 * Opens the pane. `asked` means the person did something (a command, a press): it seats at any width and
289 * lifts the suppression their close set. Unasked opens respect `/pin auto off` and a close this session.
290 */
291async function openPane($: Dollar, options: { asked: boolean; focus?: boolean }): Promise<boolean> {
292 if (options.asked) {
293 await update($, autoOpenSuppressed, () => false)
294 } else {
295 const auto = (await $.store.get(STORE_AUTO_OPEN)) === true
296 if (!auto || (await read($, autoOpenSuppressed))) return false
297 }
298 const opened = await $.ui.open(
299 options.focus ? { id: PANE, title: PANE_TITLE, focus: true } : { id: PANE, title: PANE_TITLE },
300 )
301 return opened.isPlaced
302}
303
304/** A pin by its number in the pane (filtered, newest first), `last`, its id, or a title substring. */
305async function resolvePin($: Dollar, token: string): Promise<PinboardPin | undefined> {
306 const list = await refreshPins($)
307 const t = token.trim()
308 if (!t || t === 'last') return list[0]
309 const n = Number(t)
310 if (Number.isInteger(n) && n >= 1) {
311 const shown = displayOrder(list, await read($, filter), await currentScope($))
312 if (n <= shown.length) return shown[n - 1]
313 }
314 const lower = t.toLowerCase()
315 return list.find(p => p.id === t) ?? list.find(p => p.title.toLowerCase().includes(lower))
316}
317
318/** The newest assistant message with text in the main conversation, or in one agent's; undefined before any. */
319async function lastAnswer($: Dollar, agentId?: string): Promise<string | undefined> {
320 const messages = agentId ? await $.session.messages({ agentId }) : await $.session.messages()
321 if (!Array.isArray(messages)) return undefined
322 for (let i = messages.length - 1; i >= 0; i--) {
323 const m = messages[i]
324 if (m && m.role === 'assistant' && m.text.trim()) return m.text
325 }
326 return undefined
327}
328
329// ────────────────────────────────────────────────────────────────────────────
330// Slash commands: /pin, /unpin, /pins
331// ────────────────────────────────────────────────────────────────────────────
332
333const HELP = [
334 "/pin save the mouse selection, else the last answer's tables and artifact links (else the whole answer)",
335 '/pin [title] as above, under a title; an existing pin with that title is replaced',
336 '/pin all [title] save the whole last answer',
337 "/pin tables|links save only the last answer's tables | links",
338 '/pin rm <n|last> remove pin n (pane number) or the latest (same as /unpin <n>)',
339 '/pin undo undo the last remove (or clear)',
340 '/pin show <n> print pin n into the conversation (the model reads it too)',
341 '/pin clear remove all (after confirming)',
342 '/pin export export to ~/.claude/pins/pins-<date>.md',
343 '/pin auto on|off open the pane on session start and when new candidates appear (default off)',
344 '/pins open/close the pane',
345 'Sessions: "All" groups pins by session · the "This session" tab shows only this session\'s pins',
346 'Agents: while viewing an agent (pane open), the pane and /pin work on that agent',
347 'Pane keys (focus with ctrl+x tab): 1-9 select · a/s/d/g/h save candidate · c copy · p insert into prompt · x remove · u undo · f filter',
348].join('\n')
349
350function report(saved: SavedPin[], tag: AgentTag = {}): string {
351 const from = tag.agentLabel ? ` (agent ${tag.agentLabel})` : ''
352 if (saved.length === 0) return 'Already pinned.'
353 if (saved.length === 1) return `📌 ${savedVerb(saved[0]!)}${from}: ${describe(saved[0]!.pin)}`
354 return `📌 Pinned ${saved.length}${from}:\n${saved.map(s => ` ${describe(s.pin)}${s.isReplacement ? ' (updated)' : ''}`).join('\n')}`
355}
356
357function savedVerb(s: SavedPin): string {
358 return s.isReplacement ? 'Updated' : 'Pinned'
359}
360
361/**
362 * Pins from the last answer of the transcript in view: the main conversation's, or the agent's whose
363 * transcript the pane last showed beside it.
364 */
365async function pinFromAnswer($: Dollar, mode: 'auto' | 'all' | 'links' | 'tables', title: string): Promise<string> {
366 const tag = await agentTag($, viewedAgentId)
367 const text = await lastAnswer($, tag.agentId)
368 if (!text) return tag.agentId ? 'No answer from this agent to pin.' : 'No answer to pin.'
369 let items: PinInput[]
370 if (mode === 'all') items = [{ kind: classify(text), title: title || firstLineTitle(text), body: text.trim() }]
371 else if (mode === 'links') items = extractLinks(text, false)
372 else if (mode === 'tables') items = extractTables(text)
373 else items = extractAll(text)
374 if (items.length === 0) {
375 if (mode === 'links') return 'The last answer has no links.'
376 if (mode === 'tables') return 'The last answer has no tables.'
377 items = [{ kind: 'text', title: title || firstLineTitle(text), body: text.trim() }]
378 } else if (title && mode !== 'all') {
379 const n = items.length
380 items = items.map((it, i) => ({ ...it, title: n > 1 ? `${title} (${i + 1}/${n})` : title }))
381 }
382 const added = await addPins(
383 $,
384 items.map(it => ({ ...it, ...tag, isNamed: Boolean(title) })),
385 )
386 await openPane($, { asked: true })
387 return report(added, tag)
388}
389
390/** `/pin [title]`: the mouse selection when there is one, else the last answer's tables and artifact links. */
391async function pinDefault($: Dollar, title: string): Promise<string> {
392 let selected: { text: string; requestId?: string } | undefined
393 try {
394 selected = await $.ui.selection()
395 } catch {
396 selected = undefined
397 }
398 const text = selected?.text.trim() ?? ''
399 if (text) {
400 const tag = await agentTag($, viewedAgentId)
401 const item: PinInput = {
402 kind: classify(text),
403 title: title || firstLineTitle(text),
404 body: text,
405 isNamed: Boolean(title),
406 ...tag,
407 }
408 if (selected?.requestId) item.sourceUuid = selected.requestId
409 const added = await addPins($, [item])
410 await openPane($, { asked: true })
411 return report(added, tag)
412 }
413 return pinFromAnswer($, 'auto', title)
414}
415
416async function runRemove($: Dollar, token: string): Promise<string> {
417 const target = await resolvePin($, token)
418 if (!target) return `No such pin: ${token.trim() || '(none)'}`
419 await removePin($, target.id)
420 return `🗑 Removed: ${describe(target)} (/pin undo to restore)`
421}
422
423async function runShow($: Dollar, token: string): Promise<string> {
424 const target = await resolvePin($, token)
425 if (!target) return `No such pin: ${token.trim() || '(none)'}`
426 await update($, selectedId, () => target.id)
427 await openPane($, { asked: true })
428 return `${describe(target)}\n\n${target.body}`
429}
430
431async function runClear($: Dollar, rest: string): Promise<string> {
432 const list = await refreshPins($)
433 if (list.length === 0) return 'No pins.'
434 let ok = rest.trim() === '--yes'
435 if (!ok) {
436 try {
437 ok = (await $.ui.ask(`Remove all ${list.length} pins?`, ['Remove', 'Cancel'])) === 'Remove'
438 } catch {
439 return 'Cancelled (non-interactive: /pin clear --yes)'
440 }
441 }
442 if (!ok) return 'Cancelled'
443 let cleared: PinboardPin[] = []
444 await mutatePins($, current => {
445 cleared = current
446 return []
447 })
448 await $.store.set(STORE_BACKUP, cleared)
449 await update($, selectedId, () => null)
450 await update($, lastRemoved, () => null)
451 return `🗑 Removed ${cleared.length} pins (/pin undo to restore)`
452}
453
454async function runExport($: Dollar): Promise<string> {
455 const list = await refreshPins($)
456 if (list.length === 0) return 'No pins to export.'
457 const home = (await $.env.get('HOME')) ?? '.'
458 const date = localStamp(await $.clock.now()).slice(0, 10)
459 const path = `${home}/.claude/pins/pins-${date}.md`
460 const sections = list.map(p => {
461 const meta = `${KIND_LABEL[p.kind]} · ${projectName(p.cwd)} · ${localStamp(p.createdAt)}`
462 return `## ${GLYPH[p.kind]} ${p.title}\n\n_${meta}_\n\n${p.body}\n`
463 })
464 try {
465 await $.fs.write(path, [`# Pins (${list.length}) · ${date}`, '', ...sections].join('\n'))
466 } catch (err) {
467 return `Export failed: ${String(err)}`
468 }
469 return `📄 Exported: ${path}`
470}
471
472async function runAuto($: Dollar, rest: string): Promise<string> {
473 const v = rest.trim().toLowerCase()
474 if (v !== 'on' && v !== 'off') {
475 const cur = await $.store.get(STORE_AUTO_OPEN)
476 return `Auto-open: ${cur === true ? 'on' : 'off'} (/pin auto on|off)`
477 }
478 await $.store.set(STORE_AUTO_OPEN, v === 'on')
479 return `Auto-open: ${v}`
480}
481
482/** `/pin ...`: the first word picks a subcommand; anything else is a title for the default save. */
483async function runPin($: Dollar, rawArgs: string): Promise<string> {
484 const args = rawArgs.trim()
485 const [head = '', ...tail] = args.split(/\s+/)
486 const rest = tail.join(' ').trim()
487 switch (head.toLowerCase()) {
488 case 'help':
489 case '?':
490 return HELP
491 case 'rm':
492 case 'remove':
493 case 'del':
494 case 'delete':
495 return runRemove($, rest)
496 case 'undo':
497 return undo($)
498 case 'show':
499 case 'cat':
500 return runShow($, rest)
501 case 'clear':
502 return runClear($, rest)
503 case 'export':
504 return runExport($)
505 case 'auto':
506 return runAuto($, rest)
507 case 'all':
508 return pinFromAnswer($, 'all', rest)
509 case 'links':
510 case 'link':
511 return pinFromAnswer($, 'links', rest)
512 case 'tables':
513 case 'table':
514 return pinFromAnswer($, 'tables', rest)
515 default:
516 return pinDefault($, args)
517 }
518}
519
520/** `/pins`: closes the pane when open, else opens it with the keyboard. */
521async function togglePane($: Dollar): Promise<string> {
522 if (await isPaneOpen($)) {
523 await $.ui.close({ id: PANE })
524 return 'Pins pane closed'
525 }
526 const placed = await openPane($, { asked: true, focus: true })
527 return placed
528 ? 'Pins pane opened (ctrl+x tab: focus pane · Esc: back to prompt · /pin help: help)'
529 : 'Pins pane opened but not shown yet (widen the terminal to see it)'
530}
531
532// ────────────────────────────────────────────────────────────────────────────
533// The Pins pane
534// ────────────────────────────────────────────────────────────────────────────
535
536const MAX_ROWS = 30
537const CANDIDATE_HOTKEYS = ['a', 's', 'd', 'g', 'h']
538// Theme keys, so the colors follow the person's light or dark theme.
539const ACCENT = 'claude'
540const KIND_COLOR: Record<PinboardKind, string> = {
541 table: 'suggestion',
542 artifact: 'merged',
543 link: 'ide',
544 text: 'subtle',
545}
546
547async function renderPane($: Dollar, e: RenderInputOf<'Pane', RenderSurface>) {
548 const { Box, Text, Button, Markdown, Link } = $.ui.resolve(e)
549 // Only a drawing is told which transcript is on screen; remember it for /pin and /unpin.
550 const viewAgent = e.props.view.agentId
551 viewedAgentId = viewAgent
552 const [list, f, sel, allCands, removed, confirm, now, scope, viewLabel] = await Promise.all([
553 read($, pins),
554 read($, filter),
555 read($, selectedId),
556 read($, candidates),
557 read($, lastRemoved),
558 read($, confirmDeleteId),
559 $.clock.now(),
560 currentScope($, viewAgent),
561 viewAgent ? agentLabelOf($, viewAgent) : Promise.resolve(undefined),
562 ])
563 const base = inView(list, scope)
564 const groups = groupBySession(visible(list, f, scope), scope)
565 const shown = groups.flatMap(g => g.pins)
566 const selected = shown.find(p => p.id === sel) ?? null
567 // The main view offers the main conversation's candidates; an agent's view offers that agent's.
568 const cands = allCands.filter(c => c.agentId === viewAgent)
569 const width = Math.max(20, e.props.bodyColumns)
570
571 const select = (id: string) => {
572 void update($, confirmDeleteId, () => null)
573 void update($, selectedId, cur => (cur === id ? null : id))
574 }
575 const setFilter = (next: PinboardFilter) => {
576 void update($, selectedId, () => null)
577 void update($, filter, () => next)
578 void $.store.set(STORE_FILTER, next)
579 }
580 const cycleFilter = () => setFilter(FILTERS[(FILTERS.indexOf(f) + 1) % FILTERS.length] ?? 'all')
581 const counts: Record<PinboardFilter, number> = {
582 all: base.length,
583 session: base.filter(p => p.sessionId === scope.sessionId).length,
584 project: base.filter(p => p.cwd === scope.cwd).length,
585 table: base.filter(p => p.kind === 'table').length,
586 artifact: base.filter(p => p.kind === 'artifact').length,
587 link: base.filter(p => p.kind === 'link').length,
588 }
589 const rule = '─'.repeat(width)
590
591 const pinRow = (p: PinboardPin, i: number) => {
592 const isSelected = p.id === sel
593 const hotkey = i < 9 ? String(i + 1) : undefined
594 const age = shortAge(now, p.createdAt)
595 // In the main view a pin an agent saved names the agent beside its age.
596 const badge = !viewAgent && p.agentLabel ? fitWidth(`@${p.agentLabel}`, 14) : ''
597 // marker 2 + "1: " 3 + gap 2 + glyph and age on the right (+ the badge)
598 const room = width - 2 - 3 - 2 - (2 + textWidth(age)) - (badge ? textWidth(badge) + 1 : 0)
599 const title = fitWidth(hotkey ? p.title : `${i + 1}. ${p.title}`, room)
600 return (
601 <Box key={`row:${p.id}`} justifyContent="space-between">
602 <Box>
603 <Text color={ACCENT}>{isSelected ? '▍ ' : ' '}</Text>
604 <Button
605 key={`sel:${p.id}`}
606 {...(hotkey ? { hotkey } : {})}
607 plain
608 dimColor={!isSelected}
609 hover={{ dimColor: false }}
610 label={title}
611 onPress={() => select(p.id)}
612 />
613 </Box>
614 <Text>
615 {badge ? <Text dimColor>{badge} </Text> : null}
616 <Text color={KIND_COLOR[p.kind]}>{GLYPH[p.kind]}</Text> <Text dimColor>{age}</Text>
617 </Text>
618 </Box>
619 )
620 }
621
622 // Rows in display order, with a header per session when more than one session's pins are shown.
623 const rows: ReturnType<typeof pinRow>[] = []
624 let index = 0
625 for (const g of groups) {
626 if (index >= MAX_ROWS) break
627 if (groups.length > 1) {
628 rows.push(
629 <Box key={`group:${g.sessionId}`} marginTop={index === 0 ? 0 : 1}>
630 {g.isCurrent ? (
631 <Text color={ACCENT} bold>
632 {fitWidth(g.label, width)}
633 </Text>
634 ) : (
635 <Text dimColor>{fitWidth(g.label, width)}</Text>
636 )}
637 </Box>,
638 )
639 }
640 for (const p of g.pins) {
641 if (index >= MAX_ROWS) break
642 rows.push(pinRow(p, index))
643 index++
644 }
645 }
646
647 return (
648 <Box flexDirection="column">
649 <Box justifyContent="space-between">
650 <Text bold>
651 Pins <Text dimColor>{base.length}</Text>
652 </Text>
653 <Button key="filter" hotkey="f" plain dimColor label="next filter" onPress={cycleFilter} />
654 </Box>
655 {viewLabel ? (
656 <Text wrap="truncate-end">
657 <Text color={ACCENT} bold>
658 ↳ {viewLabel}
659 </Text>
660 <Text dimColor>: showing only this agent's pins and candidates</Text>
661 </Text>
662 ) : null}
663 <Box flexWrap="wrap" columnGap={2}>
664 {FILTERS.map(name =>
665 name === f ? (
666 <Text color="claude" bold underline>
667 {FILTER_LABEL[name]} {counts[name]}
668 </Text>
669 ) : (
670 <Button
671 key={`tab:${name}`}
672 plain
673 dimColor
674 label={`${FILTER_LABEL[name]} ${counts[name]}`}
675 onPress={() => setFilter(name)}
676 />
677 ),
678 )}
679 </Box>
680 <Text dimColor>{rule}</Text>
681
682 {base.length === 0 && (
683 <Box flexDirection="column" paddingX={2} marginY={1}>
684 <Text bold>{viewAgent ? 'No pins from this agent yet' : 'No pins yet'}</Text>
685 {EMPTY_HINTS.map(([how, what]) => (
686 <Text>
687 <Text color={ACCENT}>{padCells(how, 16)}</Text>
688 <Text dimColor>{what}</Text>
689 </Text>
690 ))}
691 </Box>
692 )}
693 {base.length > 0 && shown.length === 0 && (
694 <Box paddingX={2} marginY={1}>
695 <Text dimColor>No pins match this filter · f for the next filter</Text>
696 </Box>
697 )}
698
699 {rows}
700 {shown.length > MAX_ROWS && (
701 <Text dimColor>
702 {' '}… {shown.length - MAX_ROWS} more · f to filter
703 </Text>
704 )}
705
706 {selected && (
707 <Box
708 flexDirection="column"
709 marginTop={1}
710 paddingX={1}
711 borderStyle="round"
712 borderColor={KIND_COLOR[selected.kind]}
713 >
714 <Text bold>
715 <Text color={KIND_COLOR[selected.kind]}>{GLYPH[selected.kind]}</Text> {fitWidth(selected.title, width - 6)}
716 </Text>
717 <Text dimColor wrap="truncate-end">
718 {KIND_LABEL[selected.kind]} · {projectName(selected.cwd)} · {localStamp(selected.createdAt)}
719 {selected.agentLabel ? ` · agent ${selected.agentLabel}` : ''}
720 </Text>
721 <Box marginY={1} flexDirection="column">
722 {selected.kind === 'link' || selected.kind === 'artifact' ? (
723 <Link href={selected.body} label={fitWidth(selected.body, width - 4)} />
724 ) : (
725 <Markdown text={selected.body} />
726 )}
727 </Box>
728 {confirm === selected.id ? (
729 <Box columnGap={2} flexWrap="wrap">
730 <Text color="error" bold>
731 Remove this pin?
732 </Text>
733 <Button
734 key="delete-yes"
735 hotkey="x"
736 plain
737 label="remove"
738 onPress={() => {
739 void removePin($, selected.id)
740 }}
741 />
742 <Button
743 key="delete-no"
744 hotkey="o"
745 plain
746 label="cancel"
747 onPress={() => void update($, confirmDeleteId, () => null)}
748 />
749 </Box>
750 ) : (
751 <Box columnGap={2} flexWrap="wrap">
752 <Button
753 key="copy"
754 hotkey="c"
755 plain
756 label="copy"
757 onPress={press => {
758 void $.ui
759 .copy({ text: selected.body, surface: press.surface })
760 .then(r => $.ui.toast(r.isCopied ? 'Copied' : `Copy failed: ${r.reason}`))
761 }}
762 />
763 <Button
764 key="prompt"
765 hotkey="p"
766 plain
767 label="insert into prompt"
768 onPress={() => {
769 void $.prompt.fill({ text: `${selected.body}\n`, mode: 'insert' })
770 }}
771 />
772 <Button
773 key="delete"
774 hotkey="x"
775 plain
776 dimColor
777 label="remove"
778 onPress={() => void update($, confirmDeleteId, () => selected.id)}
779 />
780 </Box>
781 )}
782 </Box>
783 )}
784
785 {removed && (
786 <Box marginTop={1}>
787 <Text color="warning">↩ </Text>
788 <Button
789 key="undo"
790 hotkey="u"
791 plain
792 label="undo"
793 onPress={() => {
794 void undo($)
795 }}
796 />
797 <Text dimColor> {fitWidth(removed.title, width - 16)}</Text>
798 </Box>
799 )}
800
801 {cands.length > 0 && (
802 <Box flexDirection="column" marginTop={1}>
803 <Text dimColor>
804 {labelledRule(viewAgent ? 'Candidates from this agent · press to pin' : 'Candidates from this session · press to pin', width)}
805 </Text>
806 {cands.map((c, i) => {
807 const hotkey = CANDIDATE_HOTKEYS[i]
808 const age = shortAge(now, c.seenAt)
809 const room = width - 2 - 3 - 2 - (2 + textWidth(age))
810 return (
811 <Box key={`cand:${c.id}`} justifyContent="space-between">
812 <Box>
813 <Text color={ACCENT}>+ </Text>
814 <Button
815 key={`save:${c.id}`}
816 {...(hotkey ? { hotkey } : {})}
817 plain
818 dimColor
819 hover={{ dimColor: false }}
820 label={fitWidth(c.title, room)}
821 onPress={() => {
822 const tag: AgentTag = c.agentId ? { agentId: c.agentId, agentLabel: c.agentLabel ?? '' } : {}
823 void addPins($, [
824 { kind: c.kind, title: c.title, body: c.body, sourceUuid: c.sourceUuid, ...tag },
825 ])
826 }}
827 />
828 </Box>
829 <Text>
830 <Text color={KIND_COLOR[c.kind]}>{GLYPH[c.kind]}</Text> <Text dimColor>{age}</Text>
831 </Text>
832 </Box>
833 )
834 })}
835 </Box>
836 )}
837
838 <Box flexDirection="column" marginTop={1}>
839 <Text dimColor>{rule}</Text>
840 <Text dimColor wrap="truncate-end">
841 {e.props.isFocused ? 'Esc back to prompt · /pin help' : 'ctrl+x tab to use the pane · /pin help'}
842 </Text>
843 </Box>
844 </Box>
845 )
846}
847
848const EMPTY_HINTS: [string, string][] = [
849 ['/pin', "pin the last answer's tables and links"],
850 ['"pin this table"', 'ask Claude to pin it'],
851 ['a s d g h', 'pin a candidate below'],
852]
853
854/** `text` followed by spaces up to `cells` cells (at least one). */
855function padCells(text: string, cells: number): string {
856 return text + ' '.repeat(Math.max(1, cells - textWidth(text)))
857}
858
859/** A rule with a label at its start: `─ label ─────`, `width` cells long. */
860function labelledRule(label: string, width: number): string {
861 const head = `─ ${label} `
862 return head + '─'.repeat(Math.max(0, width - textWidth(head)))
863}
864
865// ────────────────────────────────────────────────────────────────────────────
866// Hooks
867// ────────────────────────────────────────────────────────────────────────────
868
869/** Keeps at most `cap` candidates for each agent (and for the main conversation), newest first. */
870function capPerAgent(list: PinboardCandidate[], cap: number): PinboardCandidate[] {
871 const seen = new Map<string, number>()
872 return list.filter(c => {
873 const key = c.agentId ?? ''
874 const n = (seen.get(key) ?? 0) + 1
875 seen.set(key, n)
876 return n <= cap
877 })
878}
879
880/** The pin tool's result row: what was saved, and a button that opens the pane on demand. */
881function renderPinResult($: Dollar, e: RenderInputOf<'ToolResult', RenderSurface>) {
882 const { Box, Text, Button } = $.ui.resolve(e)
883 const text = resultText(e.props.output)
884 return (
885 <Box flexDirection="row" gap={1}>
886 <Text dimColor>{text}</Text>
887 <Button
888 key="open-pins"
889 variant="primary"
890 label="Open pins"
891 onPress={() => {
892 void openPane($, { asked: true })
893 }}
894 />
895 </Box>
896 )
897}
898
899/** The tool's reply line, whichever shape the surface hands over: the text, `{ result }`, or MCP content. */
900function resultText(output: unknown): string {
901 if (typeof output === 'string') return output
902 if (typeof output !== 'object' || output === null) return ''
903 const { result, content } = output as { result?: unknown; content?: unknown }
904 if (typeof result === 'string') return result
905 if (!Array.isArray(content)) return ''
906 return content
907 .map(block => (typeof block?.text === 'string' ? block.text : ''))
908 .join('')
909}
910
911/** A plugin tool answers with a string (or an array of content blocks); an object is refused. */
912function toolText(text: string) {
913 return { result: text }
914}
915
916export const register: Register = on => {
917 on('session.start', async ($, e, next) => {
918 try {
919 await Promise.all([
920 $.command.register({
921 name: 'pin',
922 description: "Pin the last answer's tables and artifact links (or the mouse selection) to the Pins pane",
923 argumentHint:
924 '[title] | all | tables | links | rm <n> | undo | show <n> | clear | export | auto on|off | help',
925 }),
926 $.command.register({ name: 'pins', description: 'Open/close the Pins pane' }),
927 $.command.register({ name: 'unpin', description: 'Remove a pin (same as /pin rm)', argumentHint: '<n|last|title>' }),
928 $.tool.register({
929 name: 'pin',
930 description:
931 "Save an item from this conversation into the user's Pins side pane so they can reopen it any time. " +
932 "Use when the user asks to pin, save, keep or bookmark a table, link, artifact or answer, and also, unasked, " +
933 'for a table or set of figures the user is working through over several turns, so they need not ask for it again. ' +
934 'Pass the exact markdown of the item: a whole markdown table, a URL, or the text itself. ' +
935 'Pinning again under the same title replaces that pin: when figures you pinned change, re-pin under the same ' +
936 'title rather than a new one, so the pane holds only the current version.',
937 inputSchema: {
938 type: 'object',
939 properties: {
940 markdown: {
941 type: 'string',
942 description: 'The item to save, verbatim markdown (a full table, a URL, or text).',
943 },
944 title: {
945 type: 'string',
946 description:
947 'Short title (<= 60 chars), stable across updates. A pin with this title in this project is replaced. Derived from the content when omitted, and then nothing is replaced.',
948 },
949 kind: {
950 type: 'string',
951 enum: ['table', 'artifact', 'link', 'text'],
952 description: 'Derived from the content when omitted.',
953 },
954 },
955 required: ['markdown'],
956 },
957 }),
958 $.tool.register({
959 name: 'unpin',
960 description:
961 "Remove a pin from the user's Pins pane. Identify it by id, by its 1-based index as `list` shows, or by a title substring. Call `list` first when unsure.",
962 inputSchema: {
963 type: 'object',
964 properties: {
965 id: { type: 'string' },
966 index: { type: 'integer', minimum: 1 },
967 title: { type: 'string', description: 'A substring of the pin title.' },
968 },
969 },
970 }),
971 $.tool.register({
972 name: 'list',
973 description: "List the user's saved pins: index, kind, title, project and id.",
974 }),
975 ])
976 } catch (err) {
977 $.ui.log(`pinboard: registration failed: ${String(err)}`, { to: 'debug' })
978 }
979
980 // The store is the truth; session state mirrors it so the pane redraws on every change. The timer
981 // picks up what other sessions pin or remove while this one runs.
982 const list = await refreshPins($)
983 const savedFilter = await $.store.get(STORE_FILTER)
984 if (isFilter(savedFilter)) await update($, filter, () => savedFilter)
985 $.clock.every(REFRESH_MS, () => {
986 void refreshPins($).catch(() => undefined)
987 })
988 if (e.isInteractive && list.length > 0) await openPane($, { asked: false })
989
990 return next(e)
991 })
992
993 on('command.run', { command: 'pin' }, async ($, e) => ({ text: await runPin($, e.args) }))
994 on('command.run', { command: 'unpin' }, async ($, e) => ({ text: await runRemove($, e.args) }))
995 on('command.run', { command: 'pins' }, async $ => ({ text: await togglePane($) }))
996
997 on('tool.call', { tool: PIN_TOOL }, async ($, e) => {
998 const input = e as unknown as Record<string, unknown>
999 const markdown = typeof input.markdown === 'string' ? input.markdown.trim() : ''
1000 if (!markdown) return toolText('error: markdown is empty')
1001 const title = typeof input.title === 'string' ? cleanTitle(input.title) : ''
1002 const kind = isKind(input.kind) ? input.kind : classify(markdown)
1003 // A subagent or teammate calling the tool runs in its own loop: the pin remembers which.
1004 const tag = await agentTag($, typeof input.agentId === 'string' ? input.agentId : undefined)
1005 // The pane stays shut: the result row offers to open it, so a pin never takes the screen unasked.
1006 const added = await addPins($, [{ kind, title, body: markdown, isNamed: Boolean(title), ...tag }])
1007 const first = added[0]
1008 return toolText(
1009 first
1010 ? `${savedVerb(first).toLowerCase()}: ${describe(first.pin)} (id ${first.pin.id})`
1011 : 'already pinned (identical content exists)',
1012 )
1013 }).catch(() => ({ deny: 'pinboard: pin failed' }))
1014
1015 on('tool.call', { tool: 'mcp__pinboard__unpin' }, async ($, e) => {
1016 const input = e as unknown as Record<string, unknown>
1017 const token =
1018 typeof input.id === 'string'
1019 ? input.id
1020 : typeof input.index === 'number'
1021 ? String(input.index)
1022 : typeof input.title === 'string'
1023 ? input.title
1024 : ''
1025 if (!token) return toolText('error: give id, index or title')
1026 const target = await resolvePin($, token)
1027 if (!target) return toolText(`error: no pin matches "${token}"`)
1028 await removePin($, target.id)
1029 return toolText(`unpinned: ${describe(target)} (the user can restore it with /pin undo)`)
1030 }).catch(() => ({ deny: 'pinboard: unpin failed' }))
1031
1032 on('tool.call', { tool: 'mcp__pinboard__list' }, async $ => {
1033 const list = await refreshPins($)
1034 if (list.length === 0) return toolText('no pins')
1035 return toolText(
1036 list
1037 .map((p, i) => {
1038 const agent = p.agentLabel ? ` · agent ${p.agentLabel}` : ''
1039 return `${i + 1}. [${p.kind}] ${p.title} · ${projectName(p.cwd)}${agent} · id ${p.id}`
1040 })
1041 .join('\n'),
1042 )
1043 }).catch(() => ({ deny: 'pinboard: list failed' }))
1044
1045 // Every block of a reply, the main conversation's and each agent's: its tables and artifact links become
1046 // one-press candidates, tagged with the agent. The pane offers each view its own.
1047 on('session.append', { door: 'response' }, async ($, e, next) => {
1048 const stored = await next(e)
1049 try {
1050 if (e.message.role === 'assistant') {
1051 const texts: string[] = []
1052 for (const block of e.message.content) {
1053 if (block.type === 'text' && typeof block.text === 'string') texts.push(block.text)
1054 }
1055 const found = texts.flatMap(t => extractAll(t))
1056 if (found.length > 0) {
1057 const now = await $.clock.now()
1058 const pinned = new Set((await refreshPins($)).map(p => bodyKey(p.body)))
1059 const fresh = found.filter(f => !pinned.has(bodyKey(f.body)))
1060 if (fresh.length > 0) {
1061 const tag = await agentTag($, e.agentId)
1062 await update($, candidates, list => {
1063 const have = new Set(list.map(c => bodyKey(c.body)))
1064 const incoming: PinboardCandidate[] = fresh
1065 .filter(f => !have.has(bodyKey(f.body)))
1066 .map((f, i) => ({
1067 id: newId(now + i),
1068 kind: f.kind,
1069 title: f.title,
1070 body: f.body,
1071 sourceUuid: e.uuid,
1072 seenAt: now,
1073 ...tag,
1074 }))
1075 return capPerAgent([...incoming, ...list], MAX_CANDIDATES)
1076 })
1077 // Only the main conversation opens the pane unasked: agents can be many and busy.
1078 // Awaited: work a hook leaves running is dropped when its dispatch ends.
1079 if (e.agentId === undefined && !(await isPaneOpen($))) await openPane($, { asked: false })
1080 }
1081 }
1082 }
1083 } catch {
1084 // candidates are best effort; the row is already stored
1085 }
1086 return stored
1087 })
1088
1089 // The person closed the pane: no unasked reopen until they ask for it again.
1090 on('ui.close', { id: PANE }, async ($, e, next) => {
1091 if (e.origin.kind === 'person') await update($, autoOpenSuppressed, () => true)
1092 return next(e)
1093 })
1094
1095 on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => renderPane($, e))
1096 on('ui.render', { component: 'ToolResult' }, ($, e, next) =>
1097 e.props.tool === PIN_TOOL && !e.props.isErrored ? renderPinResult($, e) : next(e),
1098 )
1099}
1100hooks/extract.ts 119 lines1// Pure helpers: find markdown tables and links in a reply, name them, classify text.
2import type { PinboardKind } from '../types'
3
4export type Extracted = { kind: PinboardKind; title: string; body: string }
5
6export const MAX_TITLE = 60
7
8const SEPARATOR = /^\s*\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)*\|?\s*$/
9const URL = /https?:\/\/[^\s<>()[\]'"`]+/g
10const MD_LINK = /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g
11const ARTIFACT = /claude\.ai\/(?:code\/)?artifact\//
12
13export function cleanTitle(line: string): string {
14 return line
15 .replace(/^[#>\-*\d.)\s]+/, '')
16 .replace(/[*_`]/g, '')
17 .replace(/[::]\s*$/, '')
18 .trim()
19 .slice(0, MAX_TITLE)
20}
21
22function isTableLine(line: string): boolean {
23 const t = line.trim()
24 return t.length > 0 && t.includes('|')
25}
26
27export function headerCells(line: string): string[] {
28 return line
29 .trim()
30 .replace(/^\|/, '')
31 .replace(/\|$/, '')
32 .split('|')
33 .map(c => c.trim())
34 .filter(Boolean)
35}
36
37export function extractTables(text: string): Extracted[] {
38 const lines = text.split('\n')
39 const out: Extracted[] = []
40 let i = 0
41 while (i < lines.length - 1) {
42 const header = lines[i] ?? ''
43 const sep = lines[i + 1] ?? ''
44 if (isTableLine(header) && SEPARATOR.test(sep)) {
45 let end = i + 2
46 while (end < lines.length && isTableLine(lines[end] ?? '')) end++
47 const body = lines.slice(i, end).join('\n').trim()
48 let title = ''
49 for (let j = i - 1; j >= 0; j--) {
50 const above = (lines[j] ?? '').trim()
51 if (!above) continue
52 if (isTableLine(above) || SEPARATOR.test(above)) break
53 // A heading, a short label or a line ending in a colon names the table; a long sentence does not.
54 if (above.length <= 48 || /^#/.test(above) || /[::]$/.test(above)) title = cleanTitle(above)
55 break
56 }
57 if (!title) title = headerCells(header).join(' | ').slice(0, MAX_TITLE)
58 out.push({ kind: 'table', title: title || 'Table', body })
59 i = end
60 } else {
61 i++
62 }
63 }
64 return out
65}
66
67export function extractLinks(text: string, onlyArtifacts: boolean): Extracted[] {
68 const labels = new Map<string, string>()
69 for (const m of text.matchAll(MD_LINK)) labels.set(m[2] ?? '', m[1] ?? '')
70 const out: Extracted[] = []
71 const seen = new Set<string>()
72 for (const m of text.matchAll(URL)) {
73 const url = (m[0] ?? '').replace(/[.,;:!?*]+$/, '')
74 if (!url || seen.has(url)) continue
75 seen.add(url)
76 const isArtifact = ARTIFACT.test(url)
77 if (onlyArtifacts && !isArtifact) continue
78 const label = cleanTitle(labels.get(url) ?? '')
79 const fallback = isArtifact
80 ? `artifact ${url.split('/').filter(Boolean).pop() ?? ''}`
81 : url.replace(/^https?:\/\//, '')
82 out.push({ kind: isArtifact ? 'artifact' : 'link', title: (label || fallback).slice(0, MAX_TITLE), body: url })
83 }
84 return out
85}
86
87/** Tables and artifact links: what /pin and the candidate list pick up by default. */
88export function extractAll(text: string): Extracted[] {
89 return [...extractTables(text), ...extractLinks(text, true)]
90}
91
92export function firstLineTitle(text: string, fallback = 'Note'): string {
93 for (const line of text.split('\n')) {
94 const t = cleanTitle(line)
95 if (t) return t
96 }
97 return fallback
98}
99
100export function classify(text: string): PinboardKind {
101 const t = text.trim()
102 if (/^https?:\/\/\S+$/.test(t)) return ARTIFACT.test(t) ? 'artifact' : 'link'
103 if (extractTables(t).length > 0) return 'table'
104 return 'text'
105}
106
107export function isKind(value: unknown): value is PinboardKind {
108 return value === 'table' || value === 'artifact' || value === 'link' || value === 'text'
109}
110
111export function projectName(cwd: string): string {
112 return cwd.split('/').filter(Boolean).pop() ?? cwd
113}
114
115/** Whitespace-insensitive identity of a body, for de-duplication. */
116export function bodyKey(body: string): string {
117 return body.replace(/\s+/g, ' ').trim()
118}
119hooks/format.ts 84 lines1// Pure display helpers for the pane: terminal cell widths, truncation, short times.
2import type { PinboardKind } from '../types'
3
4/** Cells a code point takes in a terminal: 2 for wide East Asian characters and emoji, 0 for combining marks. */
5export function cellWidth(codePoint: number): number {
6 if (codePoint < 32 || (codePoint >= 0x7f && codePoint < 0xa0)) return 0
7 if (
8 (codePoint >= 0x0300 && codePoint <= 0x036f) ||
9 (codePoint >= 0x200b && codePoint <= 0x200f) ||
10 (codePoint >= 0xfe00 && codePoint <= 0xfe0f)
11 )
12 return 0
13 if (
14 (codePoint >= 0x1100 && codePoint <= 0x115f) ||
15 (codePoint >= 0x2e80 && codePoint <= 0x303e) ||
16 (codePoint >= 0x3041 && codePoint <= 0x33ff) ||
17 (codePoint >= 0x3400 && codePoint <= 0x4dbf) ||
18 (codePoint >= 0x4e00 && codePoint <= 0x9fff) ||
19 (codePoint >= 0xa960 && codePoint <= 0xa97f) ||
20 (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
21 (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
22 (codePoint >= 0xfe30 && codePoint <= 0xfe4f) ||
23 (codePoint >= 0xff00 && codePoint <= 0xff60) ||
24 (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
25 (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||
26 (codePoint >= 0x20000 && codePoint <= 0x3fffd)
27 )
28 return 2
29 return 1
30}
31
32/** Cells a string takes in a terminal. */
33export function textWidth(text: string): number {
34 let w = 0
35 for (const ch of text) w += cellWidth(ch.codePointAt(0) ?? 0)
36 return w
37}
38
39/** Cuts `text` to at most `cells` cells, ending in `…` when it was cut. */
40export function fitWidth(text: string, cells: number): string {
41 if (cells <= 0) return ''
42 if (textWidth(text) <= cells) return text
43 let out = ''
44 let w = 0
45 for (const ch of text) {
46 const cw = cellWidth(ch.codePointAt(0) ?? 0)
47 if (w + cw > cells - 1) break
48 out += ch
49 w += cw
50 }
51 return `${out.trimEnd()}…`
52}
53
54/** A compact age for a list column: now, 5m, 3h, 2d, or the date as MM-DD. */
55export function shortAge(now: number, then: number): string {
56 const s = Math.max(0, Math.round((now - then) / 1000))
57 if (s < 60) return 'now'
58 const m = Math.floor(s / 60)
59 if (m < 60) return `${m}m`
60 const h = Math.floor(m / 60)
61 if (h < 24) return `${h}h`
62 const d = Math.floor(h / 24)
63 if (d < 7) return `${d}d`
64 const date = new Date(then)
65 return `${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
66}
67
68/** Local date and time as YYYY-MM-DD HH:MM. */
69export function localStamp(then: number): string {
70 const d = new Date(then)
71 return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
72}
73
74function pad2(n: number): string {
75 return n < 10 ? `0${n}` : String(n)
76}
77
78export const KIND_LABEL: Record<PinboardKind, string> = {
79 table: 'table',
80 artifact: 'artifact',
81 link: 'link',
82 text: 'note',
83}
84types/index.d.ts 50 lines1export type PinboardKind = 'table' | 'artifact' | 'link' | 'text'
2
3/** One saved item. Kept in `$.store` across sessions. */
4export type PinboardPin = {
5 id: string
6 createdAt: number
7 sessionId: string
8 cwd: string
9 kind: PinboardKind
10 title: string
11 body: string
12 sourceUuid?: string
13 /** The title was chosen rather than derived from the content; only such a pin is replaced by name. */
14 isNamed?: boolean
15 /** The subagent or teammate it came from; absent for the main conversation. */
16 agentId?: string
17 /** That agent's name as shown when it was pinned, kept since the agent is gone in later sessions. */
18 agentLabel?: string
19}
20
21/** A table or artifact link seen in a reply this session, one press away from being a pin. */
22export type PinboardCandidate = {
23 id: string
24 kind: PinboardKind
25 title: string
26 body: string
27 sourceUuid: string
28 seenAt: number
29 /** The subagent or teammate whose reply it was in; absent for the main conversation. */
30 agentId?: string
31 agentLabel?: string
32}
33
34export type PinboardFilter = 'all' | 'session' | 'project' | 'table' | 'artifact' | 'link'
35
36declare module 'claude-code' {
37 interface PluginState {
38 pinboard: {
39 pins: PinboardPin[]
40 selectedId: string | null
41 filter: PinboardFilter
42 candidates: PinboardCandidate[]
43 lastRemoved: PinboardPin | null
44 confirmDeleteId: string | null
45 /** True once the person closed the pane this session: no unasked reopen until they open it again. */
46 autoOpenSuppressed: boolean
47 }
48 }
49}
50