Every URL mentioned in the session, floating in a compact band above the prompt: pin it, dismiss it, open it in the browser. Decisions survive exit and resume…

Every link your session mentions, in one row above the prompt. Pin the ones you keep coming back to, dismiss the noise, open any of them in your browser, give one a name — all saved with the session. Nothing is ever fetched, and the model never sees any of it: zero tokens.
In the terminal:

In the Claude desktop app:

claude plugin marketplace add samaphp/session-links
claude plugin install session-links@session-links
Needs Claude Code 2.1.291 or later. To try it without installing: claude --plugin-dir path/to/session-links. To remove it: claude plugin uninstall session-links.
claude plugin update session-links
☆ pins a link (first seat, whole session) · the address opens your browser · × dismisses it (press twice) · ≡ opens /links.dismiss all clears them in two presses; the second answer beside it also opens /links, so you can restore the few you need. Pinned links are never touched./links lists every link in three groups — pinned, floating, dismissed — with open, pin, dismiss, copy, rename and restore. The text box at the top adds an address you paste, pinned. dismiss all is there too, from two links.rename gives a link a name that leads on its chip and in the list; the address stays beneath it. Only in /links, never on the band.ctrl+x then Tab enters the band; Tab and the arrows walk, Enter presses, Esc returns. Mouse: the fullscreen layout (/tui fullscreen) makes every control clickable; in the default layout set FORCE_HYPERLINK=1 and the addresses become hyperlinks your terminal opens on a click.--resume.The controls in full, the colours, what is collected and what is left out, terminal notes and how it works: docs/reference.md.
git clone https://github.com/samaphp/session-links
cd session-links
claude --plugin-dir . # loads from disk, hot-reloads on save
claude plugin validate .
claude plugin test .
npx -y -p typescript tsc -p . # once a load has written .claude-plugin/types/
MIT. See LICENSE.
hooks/register.tsx 934 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderSurface } from 'claude-code'
3
4import type { Link, LinkSource, LinkStatus, SessionRecord } from '../types'
5
6import { bandOrder, byPriority, chipLabels, clip, displayOf, extractUrls, labelOf, mergeMentions } from './links'
7
8const PANE = 'links'
9// `$.store` holds 4 MiB across every session; past this many the oldest records leave.
10const MAX_SESSIONS = 300
11// Making room reads every record to find the oldest. Trimming to the cap
12// exactly would repeat that read at every start once the store is full, so
13// it trims this far below and the read comes once in that many new sessions.
14const SESSION_SLACK = 50
15// One chip is `▎ ☆ domain × `. Each control carries a cell of air on each
16// side inside its own label: the highlight under the pointer or the focus is
17// the label's width, and one bare glyph made a target too tight to see or to
18// hit. A pinned chip is `▎ ★ domain `: a lock has no dismiss beside it, so
19// losing a link the person kept takes an unpin first. Both widths count the
20// gap to the next chip.
21const FLOATING_CELLS = 10
22const PINNED_CELLS = 7
23// A dismissal takes two presses. The first turns the cross into this question
24// on the chip itself, so what is about to go is named where the person is
25// looking; the second, on the same control, dismisses. Left alone, the
26// question goes back to a cross.
27const ARMED_LABEL = ' dismiss? '
28const DISMISS_LABEL = ' × '
29const DISARM_MS = 4000
30// Below this many floating links, one `×` at a time is quick; from it on the
31// band also offers to dismiss them all at once. Pinned links are never touched.
32const BULK_MIN = 5
33// The list offers it sooner: the person who opened it is tidying already.
34const LIST_BULK_MIN = 2
35// The `armed` value that puts the question over every floating link rather
36// than one of them. No normalized address can look like it.
37const ALL = '*'
38// Room kept at a row's end for the control that closes the band, air included:
39// ` +12 more ` on the last row the band may take, ` ≡ ` on an earlier one.
40const BAND_TAIL = 11
41const ROW_TAIL = 3
42// The band grows downward before it hides a link: three rows show a busy
43// session whole, and the person tidies by dismissing what they no longer need.
44const MAX_ROWS = 3
45// xdg-open stays alive for as long as the browser it started does, and
46// `$.process.run` waits on a child's output: so it is detached, its output
47// dropped, and the address rides as an argument, never as script text. An
48// opener with nothing to hand the address to gives up within a moment, so
49// the script watches for that moment: its exit then says whether the
50// address was taken, which is all "sent to your browser" may claim.
51const DETACHED_XDG_OPEN = [
52 'command -v xdg-open >/dev/null || exit 127',
53 'if command -v setsid >/dev/null; then setsid xdg-open "$1" >/dev/null 2>&1 &',
54 'else xdg-open "$1" >/dev/null 2>&1 &',
55 'fi',
56 'opener=$!',
57 'for tick in 1 2 3 4 5 6 7 8 9 10; do',
58 ' kill -0 "$opener" 2>/dev/null || break',
59 ' sleep 0.1',
60 'done',
61 'kill -0 "$opener" 2>/dev/null && exit 0',
62 'wait "$opener"',
63].join('\n')
64
65const sessionId = atom({ plugin: 'session-links', key: 'sessionId' } as const, '')
66const links = atom({ plugin: 'session-links', key: 'links' } as const, [])
67const freshSince = atom({ plugin: 'session-links', key: 'freshSince' } as const, 0)
68const armed = atom({ plugin: 'session-links', key: 'armed' } as const, '')
69const renaming = atom({ plugin: 'session-links', key: 'renaming' } as const, '')
70
71type Engine = EngineInterface
72// `id` is the link's address: it names the link's controls wherever the chip
73// sits, so a key stays with its link when the row reorders or the cap trims.
74type Chip = { link: Link; id: string; label: string; width: number }
75type Kit = Pick<Elements[RenderSurface], 'Box' | 'Button' | 'Link' | 'Text'> & {
76 // The mobile app draws no text field yet: there the list goes without its add box.
77 Input?: Elements['terminal']['Input']
78}
79type Row = {
80 agentId?: string
81 message: { content: readonly { type: string; [field: string]: unknown }[] }
82}
83
84const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
85
86/** A failure of this mod must never cost the conversation a row or a prompt: it goes to the debug log. */
87async function quietly($: Engine, what: string, work: () => Promise<unknown>): Promise<void> {
88 try {
89 await work()
90 } catch (error) {
91 // The engine tags each log line with the plugin's name: the line carries only what happened.
92 $.ui.log(`could not ${what}: ${reasonOf(error)}`, { to: 'debug' })
93 }
94}
95
96const keyOf = (id: string): string => `session:${id}`
97
98const isRecord = (value: unknown): value is SessionRecord =>
99 typeof value === 'object' && value !== null && Array.isArray((value as SessionRecord).links)
100
101/** Once more than `limit` sessions are saved, drops the ones saved longest ago, down to `keep`. */
102async function forget($: Engine, limit: number, keep: number): Promise<void> {
103 const keys = (await $.store.keys()).filter(key => key.startsWith('session:'))
104
105 if (keys.length <= limit) {
106 return
107 }
108
109 const aged: { key: string; savedAt: number }[] = []
110
111 for (const key of keys) {
112 const record = await $.store.get(key)
113 aged.push({ key, savedAt: isRecord(record) ? record.savedAt : 0 })
114 }
115
116 aged.sort((a, b) => a.savedAt - b.savedAt)
117
118 for (const { key } of aged.slice(0, aged.length - keep)) {
119 await $.store.delete(key)
120 }
121}
122
123/**
124 * The store is what a resume reads, so every change of the list is written
125 * through at once: there is no "save on exit" to miss when the terminal dies.
126 */
127async function save($: Engine): Promise<void> {
128 const id = await read($, sessionId)
129
130 if (id === '') {
131 return
132 }
133
134 const record: SessionRecord = { links: await read($, links), savedAt: await $.clock.now() }
135
136 try {
137 await $.store.set(keyOf(id), record)
138 } catch (error) {
139 $.ui.log(`the store refused a save, making room: ${reasonOf(error)}`, { to: 'debug' })
140 await forget($, 0, Math.floor(MAX_SESSIONS / 2))
141
142 try {
143 await $.store.set(keyOf(id), record)
144 } catch (again) {
145 $.ui.toast(`Links were not saved, so a resume will not restore them: ${reasonOf(again)}`)
146 }
147 }
148}
149
150/** A session the mod never saw (it was installed mid-conversation) starts from what its transcript mentions. */
151function fromTranscript(messages: readonly { role: 'user' | 'assistant'; text: string }[]): Link[] {
152 return messages.reduce<Link[]>(
153 (list, message, index) =>
154 mergeMentions(list, extractUrls(message.text), message.role === 'user' ? 'you' : 'claude', index + 1),
155 [],
156 )
157}
158
159async function load($: Engine): Promise<void> {
160 const id = await $.session.id()
161
162 // Also true after a hot reload of this file: the host kept the state.
163 if ((await read($, sessionId)) === id) {
164 return
165 }
166
167 const saved = await $.store.get(keyOf(id))
168 const restored = isRecord(saved) ? saved.links : fromTranscript(await $.session.messages())
169 const now = await $.clock.now()
170
171 await update($, links, () => restored)
172 await update($, armed, () => '')
173 await update($, renaming, () => '')
174 // Nothing restored is news: only what arrives from here on is drawn fresh.
175 await update($, freshSince, () => now)
176 await update($, sessionId, () => id)
177
178 if (!isRecord(saved) && restored.length > 0) {
179 await save($)
180 }
181
182 await forget($, MAX_SESSIONS, MAX_SESSIONS - SESSION_SLACK)
183}
184
185let loading: Promise<void> | undefined
186
187/**
188 * The state always belongs to the session on screen. A /clear and an
189 * in-process /resume go on under another id with no `session.start`, so every
190 * entry point and every drawing passes through here, and a changed id reloads
191 * that session's links.
192 */
193function ensure($: Engine): Promise<void> {
194 loading ??= load($).finally(() => {
195 loading = undefined
196 })
197
198 return loading
199}
200
201/**
202 * A drawing never shows another session's links. An in-process /resume is
203 * announced (`classic.SessionStart`) while the process is still under the
204 * session it leaves, so the announcement alone reloads the wrong one: the
205 * first drawing after the switch is what notices. A render cannot write
206 * state, so the reload runs as a dispatch of its own and redraws when done.
207 */
208async function isCurrent($: Engine): Promise<boolean> {
209 if ((await $.session.id()) === (await read($, sessionId))) {
210 return true
211 }
212
213 $.clock.after(0, () => void quietly($, 'load the links', () => ensure($)))
214
215 return false
216}
217
218async function capture($: Engine, row: Row, source: LinkSource): Promise<void> {
219 // A subagent's conversation is its own; what matters of it reaches the main one.
220 if (row.agentId !== undefined) {
221 return
222 }
223
224 const text = row.message.content
225 .map(block => (block.type === 'text' && typeof block.text === 'string' ? block.text : ''))
226 .join('\n')
227 const urls = extractUrls(text)
228
229 if (urls.length === 0) {
230 return
231 }
232
233 // Before the merge, so a first load never reads this row back from the transcript as well.
234 await ensure($)
235
236 const now = await $.clock.now()
237 await update($, links, list => mergeMentions(list, urls, source, now))
238 await save($)
239}
240
241/** Also seats an address the conversation never mentioned, when the person adds it by hand. */
242async function setStatus($: Engine, url: string, status: LinkStatus): Promise<void> {
243 const now = await $.clock.now()
244
245 await update($, links, list => {
246 const known = list.some(link => link.url === url) ? list : mergeMentions(list, [url], 'you', now)
247
248 return known.map(link => (link.url === url ? { ...link, status } : link))
249 })
250 await save($)
251}
252
253/**
254 * A pin moves its link to the front of the row, while the engine's focus ring
255 * keeps its place in the row: the ring is sent after the link it was on.
256 */
257async function togglePin($: Engine, link: Link, key: string, requestId: string): Promise<void> {
258 await setStatus($, link.url, link.status === 'pinned' ? 'floating' : 'pinned')
259
260 // Answers `{ deny }` when the site does not hold the keyboard (a pointer
261 // press on a surface with no ring): there is no highlight to move then.
262 const moved = await $.ui.focus({ requestId, key })
263
264 if (moved.deny !== undefined) {
265 $.ui.log(`the highlight stayed where it was: ${moved.deny}`, { to: 'debug' })
266 }
267}
268
269/** How a toast names a link: by the name the person gave it, else by its address. */
270async function nameOf($: Engine, url: string, max: number): Promise<string> {
271 const name = (await read($, links)).find(link => link.url === url)?.name
272
273 return name === undefined ? labelOf(url, max) : clip(name, max)
274}
275
276async function dismiss($: Engine, url: string): Promise<void> {
277 const named = await nameOf($, url, 40)
278
279 await setStatus($, url, 'dismissed')
280 // The chip is gone from the band, so the way back is said where they acted.
281 $.ui.toast(`Dismissed ${named} · /links brings it back`)
282}
283
284/**
285 * Opens the name field under a link's row in the list, or closes it when it
286 * is open there. The list is the only place a link is renamed: the band
287 * stays a row of chips. The field is drawn after the add box, which would
288 * otherwise keep the focus, so the ring is sent to the field by name.
289 */
290async function toggleRename($: Engine, url: string, requestId: string): Promise<void> {
291 const isOpen = (await read($, renaming)) === url
292
293 await update($, renaming, () => (isOpen ? '' : url))
294
295 if (!isOpen) {
296 const moved = await $.ui.focus({ requestId, key: 'rename' })
297
298 if (moved.deny !== undefined) {
299 $.ui.log(`the field did not take the focus: ${moved.deny}`, { to: 'debug' })
300 }
301 }
302}
303
304/** What was typed into the name field. Blank clears the name; control characters never reach a label. */
305async function rename($: Engine, url: string, text: string): Promise<void> {
306 const name = text.replace(/\p{Cc}/gu, '').trim().slice(0, 80)
307
308 await update($, renaming, () => '')
309 await update($, links, list =>
310 list.map(link => {
311 if (link.url !== url) {
312 return link
313 }
314
315 const { name: _was, ...bare } = link
316
317 return name === '' ? bare : { ...bare, name }
318 }),
319 )
320 await save($)
321 $.ui.toast(name === '' ? `Cleared the name of ${labelOf(url, 40)}` : `Named ${labelOf(url, 30)} "${clip(name, 30)}"`)
322}
323
324/**
325 * What the person typed or pasted into the list's field. A link added by hand
326 * is one they went out of their way to keep, so it starts locked in. Nothing
327 * of this reaches the model: the field is the mod's, the prompt box is not touched.
328 */
329async function addByHand($: Engine, text: string): Promise<void> {
330 const typed = text.trim()
331 // An address is usually copied without its scheme. A machine on the desk
332 // serves plain http; everything else is assumed to be the secure web.
333 const isLocal = /^(localhost|\d{1,3}(\.\d{1,3}){3})([:/]|$)/i.test(typed)
334 const urls = extractUrls(/https?:\/\//i.test(typed) ? typed : `${isLocal ? 'http' : 'https'}://${typed}`)
335
336 if (urls.length === 0) {
337 // The engine empties the field on Enter, so the reason quotes what was typed.
338 $.ui.toast(typed === '' ? 'Type or paste a web address, then press Enter' : `"${clip(typed, 40)}" is not a web address`)
339
340 return
341 }
342
343 for (const url of urls) {
344 await setStatus($, url, 'pinned')
345 }
346
347 $.ui.toast(urls.length === 1 ? `Pinned ${await nameOf($, urls[0] ?? '', 44)}` : `Pinned ${urls.length} links`)
348}
349
350/** Puts the question on `what` (one address, or ALL). One question stands at a time: asking moves it. */
351async function ask($: Engine, what: string): Promise<void> {
352 await update($, armed, () => what)
353 // A question nobody answers must not wait there to catch a stray press later.
354 $.clock.after(DISARM_MS, () => void quietly($, 'withdraw the question', () => update($, armed, now => (now === what ? '' : now))))
355}
356
357/** The first press on a link's dismiss asks; the second, while the question stands, answers yes. */
358async function pressDismiss($: Engine, url: string): Promise<void> {
359 if ((await read($, armed)) === url) {
360 await update($, armed, () => '')
361 await dismiss($, url)
362
363 return
364 }
365
366 await ask($, url)
367}
368
369/**
370 * The question over every floating link. Arming re-seats the band (the
371 * question is wider than the offer), so the focus ring is sent back to it:
372 * two presses on the same spot dismiss them all, as on a chip.
373 */
374async function askAll($: Engine, key: string, requestId: string): Promise<void> {
375 await ask($, ALL)
376
377 const moved = await $.ui.focus({ requestId, key })
378
379 if (moved.deny !== undefined) {
380 $.ui.log(`the highlight stayed where it was: ${moved.deny}`, { to: 'debug' })
381 }
382}
383
384/**
385 * Every floating link at once, while the question still stands: a press that
386 * lands after it lapsed, on a frame not yet redrawn, must not clear the band.
387 * Pinned links are the person's own and stay; the toast counts both.
388 */
389async function dismissAll($: Engine): Promise<void> {
390 if ((await read($, armed)) !== ALL) {
391 return
392 }
393
394 let gone = 0
395 let kept = 0
396
397 await update($, armed, () => '')
398 await update($, links, list => {
399 gone = list.filter(link => link.status === 'floating').length
400 kept = list.filter(link => link.status === 'pinned').length
401
402 return list.map(link => (link.status === 'floating' ? { ...link, status: 'dismissed' } : link))
403 })
404 await save($)
405 $.ui.toast(`Dismissed ${gone === 1 ? 'one link' : `${gone} links`}${kept === 0 ? '' : `, kept ${kept} pinned`} · /links brings them back`)
406}
407
408async function copyLink($: Engine, url: string, surface: RenderSurface): Promise<void> {
409 const copied = await $.ui.copy({ text: url, surface })
410
411 $.ui.toast(copied.isCopied ? `Copied ${await nameOf($, url, 44)}` : `This surface has no clipboard: ${url}`)
412}
413
414async function openInBrowser($: Engine, url: string, surface: RenderSurface): Promise<void> {
415 const openers = [
416 ['sh', '-c', DETACHED_XDG_OPEN, 'sh', url],
417 ['open', url],
418 ['rundll32', 'url.dll,FileProtocolHandler', url],
419 ]
420 const refusals: string[] = []
421
422 for (const argv of openers) {
423 try {
424 const ran = await $.process.run(argv, { timeoutMs: 10_000 })
425
426 if (ran.exitCode === 0) {
427 // The opener took the address; whether a window then appeared is the desktop's to show.
428 $.ui.toast(`Sent ${await nameOf($, url, 44)} to your browser`)
429
430 return
431 }
432
433 // 127 is the script's own word for "this machine has no xdg-open": nothing gave up, nothing was there.
434 if (ran.exitCode !== 127) {
435 refusals.push(`${argv[0] === 'sh' ? 'xdg-open' : argv[0]} gave up with exit ${ran.exitCode}`)
436 }
437 } catch (error) {
438 // Each opener belongs to one platform; the next one is tried.
439 $.ui.log(`${argv[0]} is not an opener here: ${reasonOf(error)}`, { to: 'debug' })
440 }
441 }
442
443 const copied = await $.ui.copy({ text: url, surface })
444 const why = refusals.length === 0 ? 'No browser opener answered on this machine' : `No browser took the link (${refusals.join(', ')})`
445
446 $.ui.toast(copied.isCopied ? `${why}, so the link is on your clipboard` : `${why}: ${url}`)
447}
448
449/**
450 * The engine seats a pane at any width only when the open answers the
451 * person's own press or command. One that arrives after that press has been
452 * answered counts as the mod's own idea and waits for a 110-column terminal
453 * ("waiting for room"). So every press handler hands its promise back
454 * (`() => openPane($)`, never `() => void openPane($)`), and the press stays
455 * open until the pane is asked for.
456 */
457async function openPane($: Engine): Promise<void> {
458 const opened = await $.ui.open({ id: PANE, title: 'Links', focus: true })
459
460 if (!opened.isPlaced) {
461 $.ui.toast(`The links pane is waiting for room: ${opened.reason}`)
462 }
463}
464
465/**
466 * Whether a Link will be drawn as a real hyperlink. On a terminal the engine
467 * draws one only when it takes the terminal to speak hyperlinks; otherwise it
468 * prints the Link's text followed by the whole URL in dim. It does not say
469 * which it will do, so the mod goes by what the person has declared the
470 * standard way (FORCE_HYPERLINK), and draws no Link on a terminal without it.
471 */
472async function drawsHyperlinks($: Engine, surface: RenderSurface): Promise<boolean> {
473 if (surface !== 'terminal') {
474 return true
475 }
476
477 const declared = await $.env.get('FORCE_HYPERLINK')
478
479 return declared !== undefined && !(declared.length > 0 && parseInt(declared, 10) === 0)
480}
481
482const barOf = (link: Link, since: number): string =>
483 link.status === 'pinned' ? 'claude' : link.lastAt >= since ? 'suggestion' : 'subtle'
484
485/**
486 * What the band offers over every floating link at once, by their count and
487 * whether the question stands: nothing below BULK_MIN, else the offer, else
488 * the question (press it to answer yes) beside the answer that also opens the
489 * list, for the person who clears the band and then restores a few.
490 */
491function bulkLabels(floating: number, isAsked: boolean): string[] {
492 if (floating < BULK_MIN) {
493 return []
494 }
495
496 return isAsked ? [` dismiss ${floating}? `, ` dismiss ${floating} & open the list `] : [' dismiss all ']
497}
498
499/**
500 * Chips fill a row, then the next, up to `maxRows`; what the last row cannot
501 * seat whole is counted, never squeezed. Every row keeps room for the control
502 * that closes the band, since any row may turn out to be its last; the last
503 * one also keeps `tail` cells for the bulk control drawn beside it.
504 */
505function seat(
506 all: readonly Link[],
507 columns: number,
508 maxRows: number,
509 asked: string,
510 tail: number,
511): { rows: Chip[][]; hidden: number } {
512 const ordered = bandOrder(all)
513 const labels = chipLabels(ordered)
514 const rows: Chip[][] = [[]]
515 let used = 0
516 let seated = 0
517
518 for (const link of ordered) {
519 const label = labels.get(link.url) ?? ''
520 const width =
521 label.length +
522 (link.status === 'pinned' ? PINNED_CELLS : FLOATING_CELLS) +
523 (link.url === asked ? ARMED_LABEL.length - DISMISS_LABEL.length : 0)
524 const isLastRow = rows.length >= maxRows
525 const isFull = used > 0 && used + width > columns - (isLastRow ? BAND_TAIL + tail : ROW_TAIL)
526
527 if (isFull && isLastRow) {
528 break
529 }
530
531 if (isFull) {
532 rows.push([])
533 used = 0
534 }
535
536 rows.at(-1)?.push({ link, id: link.url, label, width })
537 used += width
538 seated += 1
539 }
540
541 // The row that turns out last carries the tail too, and it kept room only
542 // for a row's end if the links ran out before the cap. Its closing chip
543 // moves down to a row of its own while there is one; at the cap it gives
544 // way, since a clipped control cannot be pressed and a hidden chip is counted.
545 for (;;) {
546 const last = rows.at(-1) ?? []
547 const lastUsed = last.reduce((cells, chip) => cells + chip.width, 0)
548 // Below the cap nothing is hidden, so the row ends in ` ≡ `, not a count.
549 const end = rows.length >= maxRows ? BAND_TAIL : ROW_TAIL
550
551 if (lastUsed <= columns - (end + tail)) {
552 break
553 }
554
555 const moved = last.pop()
556
557 if (moved === undefined) {
558 break
559 }
560
561 if (rows.length >= maxRows) {
562 seated -= 1
563 } else if (last.length > 0) {
564 rows.push([moved])
565 } else {
566 // A lone chip too wide to share its row with the tail keeps the row; the tail takes the next.
567 last.push(moved)
568 rows.push([])
569 break
570 }
571 }
572
573 return { rows, hidden: ordered.length - seated }
574}
575
576function listView(
577 $: Engine,
578 kit: Kit,
579 all: readonly Link[],
580 columns: number,
581 since: number,
582 isLinked: boolean,
583 asked: string,
584 editing: string,
585) {
586 const { Box, Button, Link, Text } = kit
587 const Field = kit.Input
588 const run = (what: string, work: () => Promise<unknown>) => () => quietly($, what, work)
589 // A row's keys carry its link's address: unique across the sections, and
590 // unmoved when a link changes section or the cap trims the list.
591 const pinned = all.filter(link => link.status === 'pinned').sort(byPriority)
592 const floating = all.filter(link => link.status === 'floating').sort(byPriority)
593 const dismissed = all.filter(link => link.status === 'dismissed')
594 const width = Math.max(8, columns - 4)
595
596 const row = (link: Link) => (
597 <Box key={`row:${link.url}`} flexDirection="column" marginBottom={1}>
598 <Box flexDirection="row">
599 <Text color={link.url === asked ? 'error' : barOf(link, since)}>▎</Text>
600 {link.name !== undefined && <Text bold>{` ${clip(link.name, width)}`}</Text>}
601 {link.name === undefined && isLinked && <Link href={link.url} label={` ${displayOf(link.url, width)} `} />}
602 {link.name === undefined && !isLinked && (
603 // Without hyperlinks the whole address is written once, as plain
604 // text: that is what such a terminal can open on a click.
605 <Text>{` ${link.url}`}</Text>
606 )}
607 </Box>
608 {link.name !== undefined && isLinked && <Link href={link.url} label={` ${displayOf(link.url, width - 1)} `} />}
609 {link.name !== undefined && !isLinked && <Text dimColor>{` ${link.url}`}</Text>}
610 {Field !== undefined && link.url === editing && (
611 <Box paddingLeft={1}>
612 <Field
613 key="rename"
614 label="name "
615 value={link.name ?? ''}
616 placeholder="a name for this link; leave empty to clear it"
617 submitLabel="save"
618 autoFocus
619 onSubmit={value => quietly($, 'name the link', () => rename($, link.url, value))}
620 />
621 </Box>
622 )}
623 <Box flexDirection="row" paddingLeft={1}>
624 <Button
625 key={`open:${link.url}`}
626 plain
627 dimColor
628 label=" open "
629 onPress={press => quietly($, 'open the browser', () => openInBrowser($, link.url, press.surface))}
630 />
631 <Button
632 key={`pin:${link.url}`}
633 plain
634 dimColor
635 label={link.status === 'pinned' ? ' unpin ' : ' pin '}
636 onPress={press => quietly($, 'pin', () => togglePin($, link, `pin:${link.url}`, press.requestId))}
637 />
638 {link.status !== 'pinned' && (
639 <Button
640 key={`drop:${link.url}`}
641 plain
642 dimColor={link.url !== asked}
643 label={link.url === asked ? ' dismiss? ' : ' dismiss '}
644 onPress={run('dismiss', () => pressDismiss($, link.url))}
645 />
646 )}
647 <Button
648 key={`copy:${link.url}`}
649 plain
650 dimColor
651 label=" copy "
652 onPress={press => quietly($, 'copy', () => copyLink($, link.url, press.surface))}
653 />
654 {Field !== undefined && (
655 <Button
656 key={`rename:${link.url}`}
657 plain
658 dimColor={link.url !== editing}
659 label={link.url === editing ? ' cancel ' : ' rename '}
660 onPress={press => quietly($, 'rename', () => toggleRename($, link.url, press.requestId))}
661 />
662 )}
663 {columns >= 60 && <Text dimColor>{` ${link.source === 'you' ? 'you' : 'Claude'} · ${link.mentions}×`}</Text>}
664 </Box>
665 </Box>
666 )
667
668 return (
669 <Box flexDirection="column">
670 <Box flexDirection="row">
671 <Text bold>Links</Text>
672 <Text dimColor>{` ${pinned.length} pinned · ${floating.length} floating · ${dismissed.length} dismissed`}</Text>
673 </Box>
674 {Field !== undefined && (
675 <Box marginBottom={1}>
676 <Field
677 key="add"
678 label="add "
679 placeholder="type or paste an address"
680 submitLabel="pin it"
681 // Of several fields the first drawn takes the focus: while a name is being typed, this one yields.
682 {...(editing === '' ? { autoFocus: true as const } : {})}
683 onSubmit={value => quietly($, 'add the link', () => addByHand($, value))}
684 />
685 </Box>
686 )}
687 {all.length === 0 && <Text dimColor>Every URL you or Claude mention lands here and floats above the prompt.</Text>}
688 {pinned.length > 0 && (
689 <Text bold color="claude">
690 ★ PINNED
691 </Text>
692 )}
693 {pinned.map(row)}
694 {floating.length > 0 && (
695 <Box key="floating" flexDirection="row">
696 <Text bold color="suggestion">
697 ☆ FLOATING
698 </Text>
699 {floating.length >= LIST_BULK_MIN && asked !== ALL && (
700 <Button
701 key="bulk"
702 plain
703 dimColor
704 label=" dismiss all "
705 hover={{ color: 'error' }}
706 onPress={press => quietly($, 'ask about every link', () => askAll($, 'bulk', press.requestId))}
707 />
708 )}
709 {floating.length >= LIST_BULK_MIN && asked === ALL && (
710 <Button key="bulk" plain label={` dismiss ${floating.length}? `} hover={{ color: 'error' }} onPress={run('dismiss every link', () => dismissAll($))} />
711 )}
712 </Box>
713 )}
714 {floating.map(row)}
715 {dismissed.length > 0 && (
716 <Text bold dimColor>
717 × DISMISSED
718 </Text>
719 )}
720 {dismissed.map(link => (
721 <Box key={`row:${link.url}`} flexDirection="row">
722 <Text dimColor>{' '}</Text>
723 <Text dimColor strikethrough>
724 {displayOf(link.url, Math.max(8, width - 12))}
725 </Text>
726 <Button key={`restore:${link.url}`} plain label=" restore " onPress={run('restore', () => setStatus($, link.url, 'floating'))} />
727 </Box>
728 ))}
729 {all.length > 0 && (
730 <Box marginTop={1}>
731 <Text dimColor>★ locks a link in for the whole session · × hides it · both survive exit and resume</Text>
732 </Box>
733 )}
734 </Box>
735 )
736}
737
738export const register: Register = on => {
739 on('session.start', async ($, e, next) => {
740 const started = await next(e)
741
742 await $.command.register({
743 name: 'links',
744 description: 'Every link of this session in a pane: pinned, floating and dismissed',
745 })
746 await quietly($, 'load the links', () => ensure($))
747
748 return started
749 })
750
751 // Fires where `session.start` does not: a /clear lands here already under its new id.
752 on('classic.SessionStart', async ($, e, next) => {
753 const started = await next(e)
754
755 await quietly($, 'load the links', () => ensure($))
756
757 return started
758 })
759
760 on('prompt.submit', async ($, e, next) => {
761 await quietly($, 'mark the turn', async () => {
762 await ensure($)
763
764 const now = await $.clock.now()
765 await update($, freshSince, () => now)
766 })
767
768 return next(e)
769 })
770
771 // What the person typed, what a command they ran said, and what Claude
772 // answered, each read as it arrives. Tool output stays out: one search
773 // result or lockfile would bury the links the conversation is about.
774 on('session.append', { door: 'prompt' }, async ($, e, next) => {
775 await quietly($, 'collect links', () => capture($, e, 'you'))
776
777 return next(e)
778 })
779
780 on('session.append', { door: 'command' }, async ($, e, next) => {
781 await quietly($, 'collect links', () => capture($, e, 'you'))
782
783 return next(e)
784 })
785
786 on('session.append', { door: 'response' }, async ($, e, next) => {
787 await quietly($, 'collect links', () => capture($, e, 'claude'))
788
789 return next(e)
790 })
791
792 on('command.run', { command: 'links' }, async $ => {
793 await quietly($, 'load the links', () => ensure($))
794 await openPane($)
795
796 return {}
797 })
798
799 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
800 // Asked first, and of every drawing: an empty band is exactly what a session just left looks like.
801 const isMine = await isCurrent($)
802 const all = await read($, links)
803 const shown = all.filter(link => link.status !== 'dismissed').length
804
805 if (e.props.hasSurvey || shown === 0 || !isMine) {
806 return next(e)
807 }
808
809 const since = await read($, freshSince)
810 const { Box, Button, Link, Text } = $.ui.resolve(e)
811 const asked = await read($, armed)
812 const floating = all.filter(link => link.status === 'floating').length
813 const bulk = bulkLabels(floating, asked === ALL)
814 const tail = bulk.reduce((cells, label) => cells + label.length, 0)
815 const { rows, hidden } = seat(all, e.props.bodyColumns, Math.max(1, Math.min(MAX_ROWS, e.props.maxRows)), asked, tail)
816 // A click reaches a Button only where the surface reports clicks: the
817 // fullscreen terminal. On the main screen only the terminal's own
818 // hyperlink answers a click, so the label is a Link there when one will
819 // be drawn as a hyperlink, and a Button the keyboard presses otherwise.
820 const hasClicks = e.surface === 'terminal' && e.viewport?.isFullscreen === true
821 const isPressed = hasClicks || !(await drawsHyperlinks($, e.surface))
822 const run = (what: string, work: () => Promise<unknown>) => () => quietly($, what, work)
823
824 const chip = ({ link, id, label }: Chip) => {
825 const isPinned = link.status === 'pinned'
826 const isAsked = link.url === asked
827 // The bar names what the standing question would take: this link, or every floating one.
828 const isMarked = isAsked || (asked === ALL && !isPinned)
829
830 return (
831 <Box key={`chip:${id}`} flexDirection="row" flexShrink={0} marginRight={1}>
832 <Text color={isMarked ? 'error' : barOf(link, since)}>▎</Text>
833 <Button
834 key={`pin:${id}`}
835 plain
836 dimColor={!isPinned}
837 label={isPinned ? ' ★ ' : ' ☆ '}
838 hover={{ color: 'warning' }}
839 onPress={press => quietly($, 'pin', () => togglePin($, link, `pin:${id}`, press.requestId))}
840 />
841 {isPressed ? (
842 <Button
843 key={`open:${id}`}
844 plain
845 label={` ${label} `}
846 hover={{ underline: true }}
847 onPress={press => quietly($, 'open the browser', () => openInBrowser($, link.url, press.surface))}
848 />
849 ) : (
850 <Link href={link.url} label={` ${label} `} />
851 )}
852 {!isPinned && (
853 <Button
854 key={`drop:${id}`}
855 plain
856 dimColor={!isAsked}
857 label={isAsked ? ARMED_LABEL : DISMISS_LABEL}
858 hover={{ color: 'error' }}
859 onPress={run('dismiss', () => pressDismiss($, link.url))}
860 />
861 )}
862 </Box>
863 )
864 }
865
866 const own = (
867 <Box flexDirection="column">
868 {rows.map((row, at) => (
869 <Box key={`row:${at}`} flexDirection="row">
870 {row.map(chip)}
871 {at === rows.length - 1 && bulk.length === 1 && (
872 <Button
873 key="bulk"
874 plain
875 dimColor
876 label={bulk[0]}
877 hover={{ color: 'error' }}
878 onPress={press => quietly($, 'ask about every link', () => askAll($, 'bulk', press.requestId))}
879 />
880 )}
881 {at === rows.length - 1 && bulk.length === 2 && (
882 <Button key="bulk" plain label={bulk[0]} hover={{ color: 'error' }} onPress={run('dismiss every link', () => dismissAll($))} />
883 )}
884 {at === rows.length - 1 && bulk.length === 2 && (
885 <Button
886 key="bulk:list"
887 plain
888 label={bulk[1]}
889 hover={{ color: 'error' }}
890 onPress={run('dismiss every link and open the list', async () => {
891 await dismissAll($)
892 await openPane($)
893 })}
894 />
895 )}
896 {at === rows.length - 1 && (
897 <Button
898 key="all"
899 plain
900 dimColor
901 label={hidden > 0 ? ` +${hidden} more ` : ' ≡ '}
902 onPress={run('open the list', () => openPane($))}
903 />
904 )}
905 </Box>
906 ))}
907 </Box>
908 )
909
910 // Other mods draw in this band too (status rows, confirmation controls):
911 // the links stack over whatever the rest of the chain drew instead of replacing it.
912 return (
913 <Box flexDirection="column">
914 {own}
915 {await next(e)}
916 </Box>
917 )
918 })
919
920 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
921 const all = (await isCurrent($)) ? await read($, links) : []
922 const since = await read($, freshSince)
923 const kit = $.ui.resolve(e)
924 const columns = Math.max(24, e.props.bodyColumns)
925
926 const isLinked = await drawsHyperlinks($, e.surface)
927
928 const asked = await read($, armed)
929 const editing = await read($, renaming)
930
931 return listView($, kit, all, columns, since, isLinked, asked, editing)
932 })
933}
934hooks/links.ts 251 lines1import type { Link, LinkSource } from '../types'
2
3/**
4 * Unnamed floating links per session. Past it the oldest of them leaves. A
5 * pinned, dismissed or named link never does: those are the person's decisions,
6 * and the list promises that a dismissed link stays dismissed when mentioned again.
7 */
8export const MAX_LINKS = 300
9
10const CANDIDATE = /https?:\/\/[^\s<>"'`\\^{}|]+/gi
11// Prose punctuation that ends a sentence, Arabic and CJK marks included.
12const TRAILING = '.,;:!?*_~،؛؟。,'
13const CLOSERS: Record<string, string> = { ')': '(', ']': '[' }
14const NAMED_HOST =
15 /^(localhost|(\d{1,3}\.){3}\d{1,3}|\[[0-9a-f:.]+\]|([a-z0-9-]+\.)+([a-z]{2,}|xn--[a-z0-9-]+))$/i
16// `http://web:3000` between containers is a real address; a bare `http://word` is prose.
17const SINGLE_LABEL = /^[a-z0-9-]+$/i
18
19const count = (text: string, mark: string): number => text.split(mark).length - 1
20
21/** `text` cut to `max` cells, the cut marked. The one place a label is shortened. */
22export const clip = (text: string, max: number): string =>
23 text.length <= max ? text : `${text.slice(0, Math.max(1, max - 1))}…`
24
25/**
26 * Injected context (instruction files, reminders) is not the conversation:
27 * what sits between its tags is left out. One walk through the text, so a row
28 * full of opening tags with no end costs one search, not one per tag.
29 */
30function withoutReminders(text: string): string {
31 const open = '<system-reminder>'
32 const close = '</system-reminder>'
33 let kept = ''
34 let at = 0
35
36 for (;;) {
37 const start = text.indexOf(open, at)
38 const end = start === -1 ? -1 : text.indexOf(close, start)
39
40 if (end === -1) {
41 return kept + text.slice(at)
42 }
43
44 kept += `${text.slice(at, start)} `
45 at = end + close.length
46 }
47}
48
49function trimTail(raw: string): string {
50 let url = raw
51
52 while (url !== '') {
53 const last = url.at(-1) ?? ''
54 const opener = CLOSERS[last]
55 // `(see https://host/a)` closes the sentence; `/wiki/Foo_(bar)` closes its own.
56 const isLoose = opener !== undefined && count(url, last) > count(url, opener)
57
58 if (!TRAILING.includes(last) && !isLoose) {
59 break
60 }
61
62 url = url.slice(0, -1)
63 }
64
65 return url
66}
67
68function normalize(raw: string): string | null {
69 if (!URL.canParse(raw)) {
70 return null
71 }
72
73 const url = new URL(raw)
74 const isAddress =
75 NAMED_HOST.test(url.hostname) || (SINGLE_LABEL.test(url.hostname) && url.port !== '')
76
77 return isAddress ? url.href : null
78}
79
80/** The http(s) links a text mentions: normalized, each once, in reading order. */
81export function extractUrls(text: string): string[] {
82 const found = new Set<string>()
83
84 for (const match of withoutReminders(text).matchAll(CANDIDATE)) {
85 // An address written with an ellipsis (`https://host/blog/…`) was shortened
86 // by its writer: what is left opens nothing, so it is no link to collect.
87 if (match[0].includes('…')) {
88 continue
89 }
90
91 const url = normalize(trimTail(match[0]))
92
93 if (url !== null) {
94 found.add(url)
95 }
96 }
97
98 return [...found]
99}
100
101function trim(list: Link[]): Link[] {
102 const floating = list.filter(link => link.status === 'floating' && link.name === undefined).sort((a, b) => a.lastAt - b.lastAt)
103 const gone = new Set(floating.slice(0, Math.max(0, floating.length - MAX_LINKS)))
104
105 return gone.size === 0 ? list : list.filter(link => !gone.has(link))
106}
107
108/**
109 * A mention never changes a decision: a dismissed link mentioned again stays
110 * dismissed, a pinned one stays pinned.
111 */
112export function mergeMentions(
113 list: readonly Link[],
114 urls: readonly string[],
115 source: LinkSource,
116 at: number,
117): Link[] {
118 const merged = [...list]
119
120 for (const url of urls) {
121 const index = merged.findIndex(link => link.url === url)
122 const seen = merged[index]
123
124 if (seen === undefined) {
125 merged.push({ url, source, status: 'floating', mentions: 1, firstAt: at, lastAt: at })
126 } else {
127 merged[index] = { ...seen, mentions: seen.mentions + 1, lastAt: at }
128 }
129 }
130
131 return trim(merged)
132}
133
134/** The link the conversation keeps coming back to leads; between equals, the one mentioned last. */
135export const byPriority = (a: Link, b: Link): number => b.mentions - a.mentions || b.lastAt - a.lastAt
136
137/** What the band seats, in order: the pinned links, then the floating ones, each group by priority. */
138export function bandOrder(list: readonly Link[]): Link[] {
139 const pinned = list.filter(link => link.status === 'pinned').sort(byPriority)
140 const floating = list.filter(link => link.status === 'floating').sort(byPriority)
141
142 return [...pinned, ...floating]
143}
144
145const MAX_DOMAIN = 28
146const MAX_HINT = 16
147
148const siteOf = (url: string): string => new URL(url).host.replace(/^www\./, '')
149
150const closing = (segments: readonly string[], count: number): string => segments.slice(-count).join('/')
151
152/**
153 * What tells apart the links that share a site: the closing run of each
154 * one's path, as short as still differs from the others'. A last segment that
155 * is only a number or a few letters brings the one before it (`pull/12`).
156 */
157function hintsFor(paths: readonly (readonly string[])[]): string[] {
158 return paths.map((segments, index) => {
159 const start = /^(\d+|.{1,3})$/.test(segments.at(-1) ?? '') ? 2 : 1
160
161 for (let count = start; count <= segments.length; count += 1) {
162 const tail = closing(segments, count)
163
164 if (paths.every((other, at) => at === index || closing(other, count) !== tail)) {
165 return tail
166 }
167 }
168
169 return segments.join('/')
170 })
171}
172
173/**
174 * What each chip writes, by link: the name the person gave it in the list,
175 * else the site alone, so that one row seats many links, and beside it a
176 * short hint of the path only for links that share their site with another
177 * unnamed one on the band.
178 */
179export function chipLabels(links: readonly Link[]): Map<string, string> {
180 const bySite = new Map<string, Link[]>()
181 const labels = new Map<string, string>()
182
183 for (const link of links) {
184 if (link.name !== undefined) {
185 labels.set(link.url, clip(link.name, MAX_DOMAIN))
186 continue
187 }
188
189 const site = siteOf(link.url)
190 bySite.set(site, [...(bySite.get(site) ?? []), link])
191 }
192
193 for (const [site, group] of bySite) {
194 const hints =
195 group.length === 1
196 ? ['']
197 : hintsFor(group.map(link => new URL(link.url).pathname.split('/').filter(Boolean)))
198
199 group.forEach((link, index) => {
200 const hint = hints[index] ?? ''
201
202 labels.set(link.url, clip(site, MAX_DOMAIN) + (hint === '' ? '' : `/${clip(hint, MAX_HINT)}`))
203 })
204 }
205
206 return labels
207}
208
209/**
210 * Host and path, sized to `max` cells: how a toast names the one link it is
211 * about. The query string is never drawn: that is where tokens and signatures ride.
212 */
213export function labelOf(url: string, max: number): string {
214 const { host, pathname } = new URL(url)
215 const site = host.replace(/^www\./, '')
216 const segments = pathname.split('/').filter(Boolean)
217 const full = [site, ...segments].join('/')
218
219 if (full.length <= max || segments.length < 2) {
220 return clip(full, max)
221 }
222
223 // The end of a path names the page, the middle is the way there: the
224 // middle folds first, and as many closing segments stay as the room holds.
225 let tail = ''
226
227 for (const segment of [...segments].reverse()) {
228 const longer = `/${segment}${tail}`
229
230 if (site.length + 2 + longer.length > max) {
231 break
232 }
233
234 tail = longer
235 }
236
237 return clip(`${site}/…${tail === '' ? `/${segments.at(-1)}` : tail}`, max)
238}
239
240/**
241 * The address as the pane labels a hyperlink: the query folded to `?…`, the
242 * fragment kept. Where the terminal has no hyperlinks the pane writes the
243 * address whole instead, since only a complete one can be opened on a click.
244 */
245export function displayOf(url: string, max: number): string {
246 const { host, pathname, search, hash } = new URL(url)
247 const full = host + pathname.replace(/\/$/, '') + (search === '' ? '' : '?…') + hash
248
249 return clip(full, max)
250}
251types/index.d.ts 44 lines1/** Who brought the link into the conversation first. */
2export type LinkSource = 'you' | 'claude'
3
4/**
5 * `floating`: shown while it is recent, pushed off the band by newer links.
6 * `pinned`: the person locked it; it keeps its seat for the whole session.
7 * `dismissed`: the person hid it; it stays hidden even when mentioned again.
8 */
9export type LinkStatus = 'floating' | 'pinned' | 'dismissed'
10
11export type Link = {
12 /** Normalized href; the link's identity. */
13 url: string
14 source: LinkSource
15 status: LinkStatus
16 mentions: number
17 /**
18 * Milliseconds since the epoch. A link recovered from a transcript that
19 * predates the mod carries its message's position instead (a small number),
20 * which keeps the order and claims no time.
21 */
22 firstAt: number
23 lastAt: number
24 /** The person's own name for the link, given in the list; it leads on the chip and in the list. */
25 name?: string
26}
27
28/** What `$.store` keeps under `session:<id>`, so a resume restores the band exactly. */
29export type SessionRecord = { links: Link[]; savedAt: number }
30
31declare module 'claude-code' {
32 interface PluginState {
33 'session-links': {
34 sessionId: string
35 links: Link[]
36 freshSince: number
37 /** The url whose name is being edited in the list; '' when none is. */
38 renaming: string
39 /** The url whose dismiss was pressed once and waits for the second press, `*` when the question stands over every floating link; '' when none does. */
40 armed: string
41 }
42 }
43}
44