Ctrl+click copy link on every code block in Claude's replies (normal mode; WSL + Windows Terminal, Linux desktops, nothing to install)

Ctrl+click to copy any code block in Claude Code. One click, exact text, straight to your clipboard. Works in WSL with Windows Terminal, and on Linux desktops (X11 and Wayland) with nothing extra to install.

Normal mode only (Claude Code's default renderer, not fullscreen). You Ctrl+click the link. Runs in WSL + Windows Terminal and on Linux desktops; anywhere else it stays out of the way. See Where it works.
Copying a code block out of Claude Code in the terminal is annoying:
/copy copies the last reply (or lets you pick from it), so for a block further up you have to count back with /copy N.With this mod every code block gets a small box with a ⧉ copy link in the corner. Ctrl+click it and the block is on your clipboard, exactly as written, no matter how far up it is.
In Claude Code (terminal):
/plugin install copy-button --marketplace GeckoKing9/claude-code-copy-button
Answer y to add the marketplace and pick the user scope. That's it, it is active right away. Needs Claude Code 2.1.287 or later (the version that added mods).
Nothing else to install, on Linux either. If you have wl-copy, xclip or xsel it uses that; if not, it copies with its own small helper, which only needs the Python and X11 library every Linux desktop already ships.
If Claude Code opens fullscreen for you (newer installs can), switch to normal mode with /tui default. In fullscreen the mod steps aside.
| Setup | Status |
|---|---|
| WSL 2 + Windows Terminal, normal mode | Yes. Tested. |
| Linux, X11 (tested: Xubuntu 24.04, xfce4-terminal) | Yes. Tested with a real Ctrl+click, with xclip and with no clipboard tool at all. |
| Linux, Wayland | Yes. Tested in a Weston session, with wl-copy and with no clipboard tool at all. GNOME and KDE on Wayland not tested yet. |
| Other Linux terminals (GNOME Terminal, Konsole, kitty...) | Should work if the terminal opens file: links on Ctrl+click. Only xfce4-terminal is tested. |
| Bare window managers (i3, sway...) | Probably not: there xdg-open guesses the file type from its content, so the click opens the block in a text editor. |
SSH sessions, including ssh -X | No, on purpose: the links would point at the remote machine. |
| Fullscreen renderer | No. The mod steps aside and the reply is drawn as usual. |
| VS Code terminal, other Windows terminals | No. They open file: links their own way. |
| macOS | Not yet. The mod draws nothing and runs nothing. |
macOS would need its own click handler (a file type that runs pbcopy). Happy to take a PR from someone who can test it on a real Mac.
⧉ copy shows but Ctrl+click does nothingClaude Code only makes links clickable when it recognises the terminal. In WSL it looks for WT_SESSION, which Windows Terminal sets but which doesn't always reach WSL, for example when WSL was started from the Start menu. Then the link is drawn as plain text: it looks right and does nothing.
Tell Claude Code your terminal handles links, then start a new session:
echo 'export FORCE_HYPERLINK=1' >> ~/.bashrc
Use ~/.zshrc if your shell is zsh. To check the current window: echo "$WT_SESSION" prints nothing when it is missing.
Normal mode has no click events. The one click you get is the terminal's own Ctrl+click on a link. So:
.ccopy file..ccopy file type for your user (no admin, no sudo) whose handler puts the file's text on the clipboard.| WSL | Linux | |
|---|---|---|
| Files | %LOCALAPPDATA%\claude-copy | ~/.local/share/claude-copy ($XDG_DATA_HOME) |
| File type | HKCU\Software\Classes\.ccopy | shared-mime type application/x-claude-copy + a hidden .desktop entry, set as its default app |
| Handler | windows/copy.vbs (Windows clip) | linux/copy.sh: wl-copy, xclip or xsel when installed, otherwise linux/clip.py |
On Linux a click fills both places Linux pastes from: the clipboard (Ctrl+V, or Ctrl+Shift+V in a terminal) and the primary selection (middle-click, Shift+Insert). Whichever way you paste, you get the block.
clip.py does what xclip does, through the X11 library directly: it holds the copied text in a small background process until you copy something else, then exits. On Wayland desktops it goes through their X11 layer (Xwayland), whose clipboard is shared with Wayland apps.
Why a custom extension instead of linking a script: Windows Terminal warns before opening anything in PATHEXT (.vbs, .cmd...). .ccopy isn't in it, so the click is silent.
Session folders are deleted two days after the session was last used.
Read this before installing anything that runs scripts, including this.
WSL
%LOCALAPPDATA%\claude-copy (your code blocks, one folder per session, and a copy of copy.vbs).HKCU\Software\Classes\.ccopy and HKCU\Software\Classes\ClaudeCopy (current user only, no admin).cmd.exe once to find %LOCALAPPDATA%, wslpath, reg.exe to check the file type each session (and add it when missing), rm to prune old session folders.Linux
~/.local/share/claude-copy (code blocks, copy.sh, clip.py), ~/.local/share/mime/packages/claude-copy.xml, ~/.local/share/applications/claude-copy.desktop, and one line in ~/.config/mimeapps.list (written by xdg-mime).uname, xdg-mime, update-mime-database, update-desktop-database, chmod on its own script, sh to check what can copy, rm to prune old session folders. On a click: your clipboard tool, or python3 clip.py.Both
The handler (windows/copy.vbs, linux/copy.sh) only copies .ccopy files from its own folder, so a stray .ccopy file from a download or a web page can't replace your clipboard. Errors go to the Claude Code debug log (claude --debug).
Heads up for Windows: Microsoft is phasing VBScript out. If it gets removed on your machine the click stops working until the script is replaced.
/plugin uninstall copy-buttonWSL:
reg.exe delete 'HKCU\Software\Classes\.ccopy' /f
reg.exe delete 'HKCU\Software\Classes\ClaudeCopy' /f
rm -rf "$(wslpath "$(cmd.exe /c 'echo %LOCALAPPDATA%' 2>/dev/null | tr -d '\r')")/claude-copy"
Linux:
d=${XDG_DATA_HOME:-$HOME/.local/share}
rm -rf "$d/claude-copy" "$d/applications/claude-copy.desktop" "$d/mime/packages/claude-copy.xml"
update-mime-database "$d/mime"
sed -i '/x-claude-copy/d' "${XDG_CONFIG_HOME:-$HOME/.config}/mimeapps.list"
git clone https://github.com/GeckoKing9/claude-code-copy-button
claude --plugin-dir ./claude-code-copy-button
claude plugin test ./claude-code-copy-button
sh ./claude-code-copy-button/tests/copy.sh.test.sh
MIT license.
hooks/register.tsx 555 lines1import type { EngineInterface, Register } from 'claude-code'
2
3// A boxed "⧉ copy" link on every fenced code block in Claude's replies, for
4// Claude Code in the classic renderer: in WSL shown in Windows Terminal, or on
5// a Linux desktop. See ../README.md for the moving parts and how to uninstall.
6//
7// The classic renderer has no click events; the one click there is the
8// terminal's own Ctrl+click on a link. Each block is saved to a .ccopy file
9// and linked, and the .ccopy file type copies the file's text:
10// - WSL: %LOCALAPPDATA%\claude-copy\<session>\<hash>.ccopy; the file type
11// (HKCU) runs copy.vbs silently. .ccopy, unlike .vbs, is not in PATHEXT, so
12// Windows Terminal opens it without its "unsafe link" dialog.
13// - Linux: $XDG_DATA_HOME/claude-copy/<session>/<hash>.ccopy; a shared-mime
14// type and a hidden .desktop entry run copy.sh (wl-copy, xclip or xsel).
15//
16// The engine still draws the prose (bullet, indent, markdown); this hook only
17// cuts the reply at its code blocks and draws a box around each one. Classic
18// Claude Code prints a file: link's URL after it, so the link sits in a 6x1
19// box with overflow hidden and only "⧉ copy" shows.
20//
21// Drawing never runs anything: the engine refuses side effects there. All
22// work (finding the Windows folder, the file type, writing blocks, pruning)
23// runs in a background queue, one task at a time, each failure on its own.
24// A reply drawn while the folder is being looked up waits for it (up to
25// LOOKUP_WAIT_MS): the classic renderer cannot redraw a finished reply. Anywhere else (no Windows side and no Linux
26// display: macOS, a plain SSH session) nothing is drawn or run.
27
28const KEEP_MS = 2 * 86_400_000
29const STAMP_EVERY_MS = 10 * 60_000
30const PRUNE_EVERY_MS = 60 * 60_000
31const RETRY_MS = 5 * 60_000
32const LOOKUP_WAIT_MS = 2_000
33const MOVE_WAIT_MS = 5_000
34const MOVE_POLL_MS = 50
35const STORE_KEY = 'home.v3'
36const MIME = 'application/x-claude-copy'
37const DESKTOP = 'claude-copy.desktop'
38const CLASSES = 'HKCU\\Software\\Classes'
39const LINK_WIDTH = 6
40// The link's icon: Windows Terminal's fonts have ⧉; Linux's default monospace
41// (DejaVu Sans Mono) has ❐ but not ⧉, which it draws as an empty box.
42const ICON = { wsl: '⧉', linux: '❐' } as const
43const GUTTER = 2
44
45type Host = Pick<EngineInterface, 'clock' | 'env' | 'fs' | 'plugin' | 'process' | 'session' | 'store' | 'ui'>
46
47type Code = { kind: 'code'; lang: string; body: string; raw: string }
48type Segment = { kind: 'prose'; text: string } | Code
49
50// ---- Parsing ---------------------------------------------------------------
51
52const OPEN = /^([ \t]*)(`{3,}|~{3,})(.*)$/
53
54const columns = (lead: string) => [...lead].reduce((col, c) => (c === '\t' ? col + 4 - (col % 4) : col + 1), 0)
55
56// Removes `indent` columns of leading whitespace, tabs stopping every 4
57// columns; a tab that straddles the edge leaves its extra columns as spaces,
58// as CommonMark strips a fenced block's body.
59function dedent(line: string, indent: number): string {
60 let col = 0
61 let i = 0
62 while (i < line.length && col < indent) {
63 const c = line[i]
64 if (c === ' ') col++
65 else if (c === '\t') col += 4 - (col % 4)
66 else break
67 i++
68 }
69 return ' '.repeat(Math.max(0, col - indent)) + line.slice(i)
70}
71
72// CommonMark-ish fences: any indent (list items), closed by the same char at
73// >= the opening length, indented at most 3 columns past the opening fence.
74// An unclosed fence (still streaming) stays prose.
75function split(text: string): Segment[] {
76 const lines = text.replace(/\r\n?/g, '\n').split('\n')
77 const out: Segment[] = []
78 let prose: string[] = []
79 let i = 0
80 while (i < lines.length) {
81 const line = lines[i] ?? ''
82 const m = OPEN.exec(line)
83 const [, lead = '', fence = '', info = ''] = m ?? []
84 if (!m || (fence.startsWith('`') && info.includes('`'))) {
85 prose.push(line)
86 i++
87 continue
88 }
89 const indent = columns(lead)
90 const close = new RegExp(`^([ \\t]*)${fence[0] === '`' ? '`' : '~'}{${fence.length},}[ \\t]*$`)
91 const closes = (l: string) => {
92 const c = close.exec(l)
93 return c !== null && columns(c[1] ?? '') <= indent + 3
94 }
95 let j = i + 1
96 while (j < lines.length && !closes(lines[j] ?? '')) j++
97 if (j >= lines.length) {
98 prose.push(...lines.slice(i))
99 break
100 }
101 const body = lines.slice(i + 1, j).map(l => dedent(l, indent))
102 if (prose.length) out.push({ kind: 'prose', text: prose.join('\n') })
103 prose = []
104 out.push({ kind: 'code', lang: info.trim().split(/\s+/)[0] ?? '', body: body.join('\n'), raw: [line.slice(lead.length), ...body, fence].join('\n') })
105 i = j + 1
106 }
107 if (prose.length) out.push({ kind: 'prose', text: prose.join('\n') })
108 return out
109}
110
111// A code block with something in it; an empty one is drawn as the engine draws it.
112const copyable = (s: Segment): Code | undefined => (s.kind === 'code' && s.body.trim() !== '' ? s : undefined)
113
114// 53-bit hash (cyrb53): a file per distinct block, collisions out of reach.
115function hash(s: string): string {
116 let h1 = 0xdeadbeef
117 let h2 = 0x41c6ce57
118 for (let i = 0; i < s.length; i++) {
119 const c = s.charCodeAt(i)
120 h1 = Math.imul(h1 ^ c, 2654435761)
121 h2 = Math.imul(h2 ^ c, 1597334677)
122 }
123 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
124 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
125 return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0')
126}
127
128const textOf = (content: unknown): string =>
129 Array.isArray(content)
130 ? content
131 .map(b => (b && typeof b === 'object' && (b as { type?: string }).type === 'text' ? String((b as { text?: unknown }).text ?? '') : ''))
132 .join('\n')
133 : typeof content === 'string'
134 ? content
135 : ''
136
137// ---- Where the files live --------------------------------------------------
138
139// WSL: %LOCALAPPDATA%\claude-copy as a Linux path (to write), a Windows path
140// (for the registry) and a file: URL (to link), plus %SystemRoot%.
141// Linux: $XDG_DATA_HOME/claude-copy and its file: URL.
142type Home = { kind: 'wsl'; dir: string; win: string; url: string; systemRoot: string } | { kind: 'linux'; dir: string; url: string; dataHome: string }
143
144// A file: URL path segment that is also a valid markdown link destination.
145// Windows decodes %XX in file: URLs with the ANSI code page, so a UTF-8
146// escape of "é" names a different folder there: only ASCII that would break
147// the URL or the markdown is escaped and non-ASCII stays literal. Linux reads
148// %XX as UTF-8, so everything outside unreserved ASCII is escaped.
149const escape = (c: string) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`
150const winSegment = (s: string) => s.replace(/[\x00-\x20"#%'()<>?[\\\]^`{|}\x7f]/g, escape)
151const linuxSegment = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, escape)
152const winUrl = (win: string) => {
153 const [drive = '', ...rest] = win.split('\\')
154 return `file:///${drive}/${rest.map(winSegment).join('/')}`
155}
156const linuxUrl = (dir: string) => `file://${dir.split('/').map(linuxSegment).join('/')}`
157const urlSegment = (h: Home, s: string) => (h.kind === 'wsl' ? winSegment(s) : linuxSegment(s))
158
159async function locateWsl($: Host): Promise<Home> {
160 const kept = (await $.store.get(STORE_KEY)) as Home | undefined
161 if (kept?.kind === 'wsl' && kept.dir && kept.systemRoot) return kept
162 // chcp 65001: the paths come back as UTF-8 whatever the user's name is.
163 const r = await $.process.run(['cmd.exe', '/d', '/c', 'chcp 65001 >nul & echo %LOCALAPPDATA%& echo %SystemRoot%'], { cwd: '/mnt/c' })
164 const [local = '', systemRoot = ''] = r.stdout.split(/\r?\n/).map(l => l.trim())
165 if (!/^[A-Za-z]:\\/.test(local) || !/^[A-Za-z]:\\/.test(systemRoot)) throw new Error(`no %LOCALAPPDATA%: ${JSON.stringify(r.stdout)} ${r.stderr}`)
166 const win = `${local}\\claude-copy`
167 const w = await $.process.run(['wslpath', '-u', win])
168 const dir = w.stdout.trim()
169 if (w.exitCode !== 0 || !dir.startsWith('/')) throw new Error(`wslpath ${win}: ${w.stderr}`)
170 const home: Home = { kind: 'wsl', dir, win, url: winUrl(win), systemRoot }
171 await $.store.set(STORE_KEY, home)
172 return home
173}
174
175async function locateLinux($: Host): Promise<Home | null> {
176 const kept = (await $.store.get(STORE_KEY)) as Home | undefined
177 if (kept?.kind === 'linux' && kept.dir) return kept
178 const r = await $.process.run(['uname', '-s'])
179 if (r.stdout.trim() !== 'Linux') return null // macOS and others: not yet
180 const user = await $.env.get('HOME')
181 if (!user?.startsWith('/')) return null
182 // The XDG spec: a relative XDG_DATA_HOME is invalid and ignored.
183 const xdg = (await $.env.get('XDG_DATA_HOME'))?.replace(/\/+$/, '')
184 const dataHome = xdg?.startsWith('/') ? xdg : `${user}/.local/share`
185 const dir = `${dataHome}/claude-copy`
186 const home: Home = { kind: 'linux', dir, url: linuxUrl(dir), dataHome }
187 await $.store.set(STORE_KEY, home)
188 return home
189}
190
191// Which side this session copies through, from the environment alone, so
192// drawing may ask too. A forwarded display (ssh -X, a container) is not
193// the screen the user clicks on: the links would name the remote machine.
194async function platformOf($: Host): Promise<Home['kind'] | null> {
195 if ((await $.env.get('WSL_DISTRO_NAME')) || (await $.env.get('WSL_INTEROP'))) return 'wsl'
196 if ((await $.env.get('SSH_CONNECTION')) || (await $.env.get('SSH_TTY'))) return null
197 if (!(await $.env.get('DISPLAY')) && !(await $.env.get('WAYLAND_DISPLAY'))) return null
198 return 'linux'
199}
200
201async function locate($: Host): Promise<Home | null> {
202 const platform = await platformOf($)
203 if (platform === 'wsl') return locateWsl($)
204 if (platform === 'linux') return locateLinux($)
205 return null
206}
207
208// What drawing reads: undefined until looked up, null where the mod stays out;
209// `lookup` is the lookup in flight, which drawing may wait on but never starts.
210// Before that, drawing falls back on the folder a past session kept.
211let known: Home | null | undefined
212let lookup: Promise<Home | null> | undefined
213let failedAt = 0
214
215async function getHome($: Host): Promise<Home | null> {
216 if (known !== undefined) return known
217 // On WSL a failed lookup (interop off, cmd.exe missing) is retried, not
218 // hammered: once per RETRY_MS at most.
219 if (Date.now() - failedAt < RETRY_MS) return null
220 lookup ??= locate($)
221 .then(
222 h => {
223 known = h
224 if (h) $.ui.invalidate('ui.render')
225 return h
226 },
227 err => {
228 failedAt = Date.now()
229 throw err
230 },
231 )
232 .finally(() => {
233 lookup = undefined
234 })
235 return lookup
236}
237
238// For a reply drawn before the folder is known: wait on the lookup in flight
239// (up to LOOKUP_WAIT_MS), or, before one has started (a resumed session draws
240// early), take the folder a past session kept. Reads only: drawing runs nothing.
241async function homeWhileDrawing($: Host, signal: AbortSignal): Promise<Home | null> {
242 if (lookup) return Promise.race([lookup.catch(() => null), $.clock.sleep(LOOKUP_WAIT_MS, { signal }).then(() => null, () => null)])
243 const kept = (await $.store.get(STORE_KEY).catch(() => undefined)) as Home | undefined
244 return kept && kept.kind === (await platformOf($)) ? kept : null
245}
246
247const log = ($: Host, what: string, err: unknown) => $.ui.log(`copy-button: ${what}: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
248
249// ---- Background work, one task at a time ----------------------------------
250
251let queue: Promise<void> = Promise.resolve()
252const later = ($: Host, what: string, task: (h: Home) => Promise<void>) => {
253 queue = queue
254 .then(async () => {
255 const h = await getHome($)
256 if (h) await task(h)
257 })
258 .catch(err => log($, what, err))
259}
260
261// Windows programs run from /mnt/c: a Linux working directory makes cmd.exe
262// and reg.exe warn about UNC paths.
263const run = async ($: Host, argv: string[], cwd?: string) => {
264 const r = await $.process.run(argv, cwd ? { cwd } : {})
265 if (r.exitCode !== 0) throw new Error(`${argv.slice(0, 3).join(' ')}: exit ${r.exitCode} ${r.stderr.trim()}`)
266 return r.stdout
267}
268
269// Puts copy.vbs and the .ccopy file type in place, checked against what is
270// actually there each session, so a removed or stale entry heals itself. The
271// check reads an ASCII signature of the command, never the command itself:
272// reg.exe prints in the console code page, which mangles non-ASCII paths.
273async function installWsl($: Host, h: Extract<Home, { kind: 'wsl' }>): Promise<void> {
274 const vbs = await $.fs.read(`${$.plugin.root}/windows/copy.vbs`)
275 if ((await $.fs.read(`${h.dir}/copy.vbs`).catch(() => '')) !== vbs) await $.fs.write(`${h.dir}/copy.vbs`, vbs)
276 // %L: the long path, so copy.vbs compares like with like.
277 const command = `"${h.systemRoot}\\System32\\wscript.exe" //B //Nologo "${h.win}\\copy.vbs" "%L"`
278 const signature = hash(command)
279 const query = (key: string, value: string[]) => $.process.run(['reg.exe', 'query', key, ...value], { cwd: '/mnt/c' }).then(r => r.stdout, () => '')
280 const [ext, sig] = await Promise.all([query(`${CLASSES}\\.ccopy`, ['/ve']), query(`${CLASSES}\\ClaudeCopy`, ['/v', 'Signature'])])
281 if (ext.includes('ClaudeCopy') && sig.includes(signature)) return
282 // Arguments, not a .reg file: WSL hands them to reg.exe as UTF-16, so a
283 // non-ASCII user name survives.
284 await run($, ['reg.exe', 'add', `${CLASSES}\\ClaudeCopy\\shell\\open\\command`, '/ve', '/d', command, '/f'], '/mnt/c')
285 await run($, ['reg.exe', 'add', `${CLASSES}\\ClaudeCopy`, '/ve', '/d', 'Claude Code block', '/f'], '/mnt/c')
286 await run($, ['reg.exe', 'add', `${CLASSES}\\.ccopy`, '/ve', '/d', 'ClaudeCopy', '/f'], '/mnt/c')
287 await run($, ['reg.exe', 'add', `${CLASSES}\\ClaudeCopy`, '/v', 'Signature', '/d', signature, '/f'], '/mnt/c')
288}
289
290// A path in a .desktop Exec line: double-quoted, with the characters the
291// spec reserves escaped, and % doubled.
292const execArg = (path: string) =>
293 `"${path.replace(/["`$\\]/g, c => `\\${c}`)}"`
294 // then the key-file string escape over the whole value: \ is written \\
295 .replace(/\\/g, '\\\\')
296 .replace(/%/g, '%%')
297
298// The freedesktop way: a shared-mime type for *.ccopy, a hidden .desktop entry
299// that runs copy.sh on the file, and that entry as the type's default app,
300// all under the user's own data and config folders. Checked each session
301// like the Windows side: a file that differs, or another default, is redone.
302async function installLinux($: Host, h: Extract<Home, { kind: 'linux' }>): Promise<void> {
303 const script = `${h.dir}/copy.sh`
304 const want = new Map([
305 [script, await $.fs.read(`${$.plugin.root}/linux/copy.sh`)],
306 [`${h.dir}/clip.py`, await $.fs.read(`${$.plugin.root}/linux/clip.py`)],
307 [
308 `${h.dataHome}/mime/packages/claude-copy.xml`,
309 `<?xml version="1.0" encoding="UTF-8"?>
310<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
311 <mime-type type="${MIME}">
312 <comment>Claude Code block</comment>
313 <glob pattern="*.ccopy" weight="90"/>
314 </mime-type>
315</mime-info>
316`,
317 ],
318 [
319 `${h.dataHome}/applications/${DESKTOP}`,
320 // sh runs the script so that its path is an argument, not argv[0]: GLib
321 // checks that argv[0] exists before it unescapes %%, so a % in the path
322 // would make the entry unloadable and every click do nothing. It also
323 // spares the exec bit.
324 `[Desktop Entry]
325Type=Application
326Name=Claude Code copy button
327Comment=Copies a Claude Code block to the clipboard
328Exec=sh ${execArg(script)} %f
329MimeType=${MIME};
330NoDisplay=true
331Terminal=false
332`,
333 ],
334 ])
335 const stale: string[] = []
336 for (const [path, text] of want) if ((await $.fs.read(path).catch(() => '')) !== text) stale.push(path)
337 const current = await $.process.run(['xdg-mime', 'query', 'default', MIME]).then(r => r.stdout.trim(), () => '')
338 const runnable = await $.process.run(['test', '-x', script]).then(r => r.exitCode === 0, () => false)
339 if (stale.length || current !== DESKTOP || !runnable) {
340 for (const path of stale) await $.fs.write(path, want.get(path) ?? '')
341 await run($, ['chmod', '755', script])
342 await run($, ['update-mime-database', `${h.dataHome}/mime`])
343 await $.process.run(['update-desktop-database', `${h.dataHome}/applications`]).catch(() => undefined)
344 await run($, ['xdg-mime', 'default', DESKTOP, MIME])
345 }
346}
347
348// The package that gives a click something to copy with: wl-clipboard on a
349// Wayland session with no X11 layer, xclip otherwise.
350const INSTALL: Record<string, (pkg: string) => string> = {
351 'apt-get': pkg => `sudo apt install ${pkg}`,
352 dnf: pkg => `sudo dnf install ${pkg}`,
353 pacman: pkg => `sudo pacman -S ${pkg}`,
354 zypper: pkg => `sudo zypper install ${pkg}`,
355}
356const FIRST_INSTALLER = `for t in ${Object.keys(INSTALL).join(' ')}; do command -v "$t" >/dev/null 2>&1 && { echo "$t"; break; }; done`
357const WARNED_KEY = 'warned-session'
358
359// The one notice this mod ever shows: a click would copy nothing. copy.sh
360// answers that itself (--check runs the exact choice a click makes), so the
361// notice and the click cannot disagree. Only its own answer counts: exit 3.
362// Any other failure (the script missing, unreadable) is an install problem,
363// and advice to install a tool would not fix it. Once per session, reloads
364// included.
365async function warnIfNothingCopies($: Host, h: Extract<Home, { kind: 'linux' }>): Promise<void> {
366 const check = await $.process.run(['sh', `${h.dir}/copy.sh`, '--check'])
367 if (check.exitCode === 0) return
368 if (check.exitCode !== 3) throw new Error(`copy.sh --check: exit ${check.exitCode} ${check.stderr.trim()}`)
369 const session = await $.session.id()
370 if ((await $.store.get(WARNED_KEY)) === session) return
371 await $.store.set(WARNED_KEY, session)
372 const pkg = (await $.env.get('WAYLAND_DISPLAY')) && !(await $.env.get('DISPLAY')) ? 'wl-clipboard' : 'xclip'
373 const installer = (await $.process.run(['sh', '-c', FIRST_INSTALLER])).stdout.trim()
374 const how = INSTALL[installer]?.(pkg) ?? `install ${pkg}`
375 $.ui.log(`copy-button: nothing on this system can copy to the clipboard; to make the copy links work, run: ${how}`)
376}
377
378const install = ($: Host, h: Home) => (h.kind === 'wsl' ? installWsl($, h) : installLinux($, h))
379
380const written = new Set<string>()
381
382// Writes each block of a reply; a block that fails is logged and left for the
383// next save to retry, the others are still written.
384async function saveBlocks($: Host, h: Home, text: string): Promise<void> {
385 const folder = `${h.dir}/${await $.session.id()}`
386 for (const s of split(text)) {
387 const code = copyable(s)
388 if (!code) continue
389 const path = `${folder}/${hash(code.body)}.ccopy`
390 if (written.has(path)) continue
391 try {
392 await $.fs.write(path, h.kind === 'wsl' ? code.body.replace(/\n/g, '\r\n') : code.body)
393 written.add(path)
394 } catch (err) {
395 log($, `save ${path}`, err)
396 }
397 }
398}
399
400// Every reply of the conversation: at start, after /resume or /clear, and
401// when this session's folder has gone missing.
402let savedFor: string | undefined
403async function saveAll($: Host, h: Home): Promise<void> {
404 const id = await $.session.id()
405 for (const m of await $.session.messages()) if (m.role === 'assistant' && m.text) await saveBlocks($, h, m.text)
406 savedFor = id
407}
408
409// Marks this session's folder as in use. If it is gone (pruned by another
410// session after two idle days), every block is written again; so is every
411// reply of a conversation /resume, /clear or /branch moved to, which comes
412// with no session.start.
413let lastStamp = 0
414async function stamp($: Host, h: Home): Promise<void> {
415 const now = Date.now()
416 const id = await $.session.id()
417 const isMoved = savedFor !== undefined && id !== savedFor
418 if (!isMoved && now - lastStamp < STAMP_EVERY_MS) return
419 lastStamp = now
420 const folder = `${h.dir}/${id}`
421 if (isMoved || (written.size && !(await $.fs.exists(folder)))) {
422 written.clear()
423 await saveAll($, h)
424 }
425 await $.fs.write(`${folder}/.last`, String(now))
426}
427
428// /resume, /clear and /branch end the session, then go on under another id.
429// Resolves once the id has moved or after MOVE_WAIT_MS; a move missed here is
430// saved by the next turn's stamp.
431async function moved($: Host, ending: string): Promise<void> {
432 for (let waited = 0; waited < MOVE_WAIT_MS && (await $.session.id()) === ending; waited += MOVE_POLL_MS) await $.clock.sleep(MOVE_POLL_MS)
433}
434
435// Deletes session folders unused for KEEP_MS, temp files copy.vbs left behind
436// after a failed click, and files older versions wrote.
437const LITTER = /^(rad[0-9a-f]+\.tmp|clip\.u16|\.installed)$/i
438let lastPrune = 0
439async function prune($: Host, h: Home): Promise<void> {
440 const now = Date.now()
441 if (now - lastPrune < PRUNE_EVERY_MS) return
442 lastPrune = now
443 const mine = await $.session.id()
444 const expired: string[] = []
445 for (const e of await $.fs.list(h.dir)) {
446 const path = `${h.dir}/${e.name}`
447 if (e.kind === 'file' && LITTER.test(e.name)) {
448 expired.push(path)
449 continue
450 }
451 if (e.kind !== 'dir' || e.name === mine) continue
452 const used = await $.fs
453 .stat(`${path}/.last`)
454 .catch(() => $.fs.stat(path))
455 .then(s => s.mtimeMs, () => now)
456 if (now - used > KEEP_MS) expired.push(path)
457 }
458 if (expired.length) await run($, ['rm', '-rf', '--', ...expired])
459}
460
461// ---- Hooks -----------------------------------------------------------------
462
463export const register: Register = on => {
464 // Once per process and per reload of this module.
465 on('session.start', async ($, e, next) => {
466 const r = await next(e)
467 later($, 'install', h => install($, h))
468 later($, 'clipboard check', h => (h.kind === 'linux' ? warnIfNothingCopies($, h) : Promise.resolve()))
469 later($, 'stamp', h => stamp($, h))
470 later($, 'prune', h => prune($, h))
471 later($, 'save', h => saveAll($, h))
472 return r
473 })
474
475 // Not classic.SessionStart: in a Team or Enterprise organization the
476 // built-in cc-plugin-sec-default sends classic events past every plugin a
477 // person installs. /branch ends the session as 'resume'. The wait stays out
478 // of the queue, so saves behind it are not held up.
479 on('session.end', async ($, e, next) => {
480 const r = await next(e)
481 if (e.reason === 'resume' || e.reason === 'clear') {
482 void moved($, e.sessionId).then(
483 () => later($, 'stamp', h => stamp($, h)),
484 err => log($, 'move', err),
485 )
486 }
487 return r
488 })
489
490 on('session.append', { door: 'response' }, async ($, e, next) => {
491 const stored = await next(e)
492 // The row as stored, after any plugin beneath rewrote it.
493 if (!e.agentId && stored.deny === undefined) {
494 const text = textOf(stored.message.content)
495 later($, 'save', h => saveBlocks($, h, text))
496 }
497 return stored
498 })
499
500 on('turn.complete', async ($, e, next) => {
501 const r = await next(e)
502 if (e.agentId === undefined) {
503 later($, 'stamp', h => stamp($, h))
504 later($, 'prune', h => prune($, h))
505 }
506 return r
507 })
508
509 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
510 // Classic terminal only: the fullscreen renderer, desktop and IDE surfaces
511 // have mouse handling of their own; a summary row is not the saved text.
512 if (e.surface !== 'terminal' || e.viewport?.isFullscreen || e.props.isSummary) return next(e)
513 const segments = split(e.props.text)
514 if (!segments.some(copyable)) return next(e)
515 const where = known ?? (await homeWhileDrawing($, next.signal)) // (not named h: JSX compiles to the global h)
516 if (!where) return next(e)
517
518 const { Box, Text, Markdown } = $.ui.resolve(e)
519 const base = `${where.url}/${urlSegment(where, await $.session.id())}`
520 // Laid out as the engine lays out a reply: the bullet on the first piece,
521 // every other piece under it (GUTTER), a blank line between pieces. The
522 // engine's own drawing of a piece brings its blank line; a box adds one.
523 const parts = []
524 let isFirst = e.props.isFirstOfReply
525 for (const [i, s] of segments.entries()) {
526 const code = copyable(s)
527 if (!code) {
528 const text = (s.kind === 'prose' ? s.text : s.raw).replace(/^\n+|\n+$/g, '')
529 if (!text.trim()) continue
530 const drawn = await next({ ...e, props: { ...e.props, text, isFirstOfReply: isFirst } })
531 parts.push(
532 <Box key={`p${i}`} marginLeft={isFirst ? 0 : GUTTER}>
533 {drawn}
534 </Box>,
535 )
536 isFirst = false
537 continue
538 }
539 parts.push(
540 <Box key={`c${i}`} flexDirection="column" borderStyle="round" borderDimColor paddingX={1} marginTop={1} marginLeft={GUTTER}>
541 <Box flexDirection="row" justifyContent="space-between">
542 <Text dimColor>{code.lang || 'text'}</Text>
543 <Box width={LINK_WIDTH} height={1} overflow="hidden">
544 <Markdown text={`[${ICON[where.kind]} copy](${base}/${hash(code.body)}.ccopy)`} />
545 </Box>
546 </Box>
547 <Markdown text={code.raw} />
548 </Box>,
549 )
550 isFirst = false
551 }
552 return <Box flexDirection="column">{parts}</Box>
553 })
554}
555