Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(chat): Copy button on every code block in the ⌘M chat view (#1217)

Paul Robertsoncb8a0e267d0c
diff --git a/CLAUDE.md b/CLAUDE.md
index 8f8d19648..bda953a83 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3701,6 +3701,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
the legacy and paged paths; absent when the line states none — never a made-up time). One
60-second `now` tick in ChatPanel drives every row's label. No thumbs / read-aloud / retry (no
terminal equivalent). `.term-chat__text` stays the markdown sink the link guard scopes to.
+ **Every code block has the same Copy control in its top-right corner** (`nodes/CodeBlockCopy.tsx`;
+ ONE button component, `ChatCopyButton`, shared with the per-turn Copy so the two cannot drift).
+ The Markdown is an HTML string, so after each new string the hook wraps every `<pre>` in a
+ positioned `.term-chat__code` (never inside the `<pre>`: it scrolls sideways and would carry the
+ button) and portals the button beside it. It copies the block's `<code>` text minus marked's one
+ trailing newline (`lib/codeBlockCopy.ts`) — a pasted command must not run on paste. Hover-revealed,
+ kept visible while it says "Copied". Chat messages, thinking and plan/question cards all render
+ through `MarkdownText`, so all get it; the ⌘M output view and the editor preview do not.
**The composer (2026-09-26, claude.ai-style)** is one rounded box — textarea on top, a toolbar
under it: "+" attach on the left; model label, muted effort label and a mic on the right (pure
decisions in `lib/chatComposer.ts`). Four rules: (1) **attach = paths in the DRAFT, resolved the
diff --git a/src/renderer/lib/codeBlockCopy.test.ts b/src/renderer/lib/codeBlockCopy.test.ts
new file mode 100644
index 000000000..9bf10ae67
--- /dev/null
+++ b/src/renderer/lib/codeBlockCopy.test.ts
@@ -0,0 +1,30 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import { codeBlockText, preText } from './codeBlockCopy'
+
+describe('codeBlockText', () => {
+ it('drops the one trailing newline marked emits before </code>', () => {
+ expect(codeBlockText('let x = 1\n')).toBe('let x = 1')
+ })
+
+ it('keeps a blank last line the author wrote, and everything inside', () => {
+ expect(codeBlockText('a\n b\n\n')).toBe('a\n b\n')
+ expect(codeBlockText('no newline')).toBe('no newline')
+ })
+})
+
+describe('preText', () => {
+ it('reads the <code> inside the block, decoded', () => {
+ const pre = document.createElement('pre')
+ pre.innerHTML = '<code class="language-js">if (a &lt; b) {}\n</code>'
+
+ expect(preText(pre)).toBe('if (a < b) {}')
+ })
+
+ it('falls back to the <pre> itself', () => {
+ const pre = document.createElement('pre')
+ pre.textContent = 'raw\n'
+
+ expect(preText(pre)).toBe('raw')
+ })
+})
diff --git a/src/renderer/lib/codeBlockCopy.ts b/src/renderer/lib/codeBlockCopy.ts
new file mode 100644
index 000000000..21526ebe5
--- /dev/null
+++ b/src/renderer/lib/codeBlockCopy.ts
@@ -0,0 +1,14 @@
+/**
+ * What the code-block Copy button in the ⌘M chat view copies: the block's text exactly as rendered,
+ * minus the one trailing newline marked always emits before `</code>` (it is not part of the code
+ * the agent wrote, and a pasted command line ending in a newline would run on paste).
+ */
+export function codeBlockText(raw: string): string {
+ return raw.endsWith('\n') ? raw.slice(0, -1) : raw
+}
+
+/** The text of a rendered `<pre>`: its `<code>` when there is one (marked always emits one). */
+export function preText(pre: Element): string {
+ const code = pre.querySelector('code')
+ return codeBlockText((code ?? pre).textContent ?? '')
+}
diff --git a/src/renderer/nodes/ChatCopyButton.tsx b/src/renderer/nodes/ChatCopyButton.tsx
new file mode 100644
index 000000000..845a65e89
--- /dev/null
+++ b/src/renderer/nodes/ChatCopyButton.tsx
@@ -0,0 +1,47 @@
+import { useEffect, useState } from 'react'
+import { IconCheck, IconCopy } from '../components/icons'
+
+/**
+ * The ⌘M chat view's one copy control: a quiet icon button that turns into a check + "Copied" for
+ * 1.5 s. Shared by the per-turn Copy (ChatTurnActions) and the code-block Copy (CodeBlockCopy), so
+ * the two look and behave the same.
+ */
+export function ChatCopyButton({
+ text,
+ label,
+ title,
+ className
+}: {
+ /** Read at click time, so a code block's current contents are copied. */
+ text: () => string
+ /** The accessible name ("Copy message", "Copy code"). */
+ label: string
+ /** The tooltip before copying; "Copied" after. */
+ title: string
+ className?: string
+}) {
+ const [copied, setCopied] = useState(false)
+ useEffect(() => {
+ if (!copied) return
+ const t = setTimeout(() => setCopied(false), 1500)
+ return () => clearTimeout(t)
+ }, [copied])
+ return (
+ <button
+ type="button"
+ className={`term-chat__action${className !== undefined ? ` ${className}` : ''}`}
+ aria-label={label}
+ title={copied ? 'Copied' : title}
+ data-copied={copied ? '' : undefined}
+ onClick={() => {
+ // The app's own clipboard channel, not `navigator.clipboard`: it never rejects, and the
+ // Server Edition bridge falls back to execCommand and raises its own banner on failure.
+ window.nodeTerminal.clipboard.writeText(text())
+ setCopied(true)
+ }}
+ >
+ {copied ? <IconCheck /> : <IconCopy />}
+ {copied && <span className="term-chat__action-note">Copied</span>}
+ </button>
+ )
+}
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index d62823c73..1164862d4 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -51,6 +51,7 @@ import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } fr
import type { PermissionAnswer } from '@shared/agents/permission-answer'
import { ChatComposer } from './ChatComposer'
import { ChatTurnActions } from './ChatTurnActions'
+import { useCodeBlockCopy } from './CodeBlockCopy'
import { assistantTurnEnds } from '../lib/chatThread'
import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'
@@ -58,9 +59,17 @@ import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSessi
// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.
// `breaks`: a single newline is a line break, as Claude Code's own TUI renders it — without it a
// multi-line prompt, or a reply quoting one line by line (`> a` / `> b`), collapsed onto one line.
+// Every code block gets a Copy button in its top-right corner (useCodeBlockCopy).
export const MarkdownText = memo(function MarkdownText({ text }: { text: string }) {
const html = useMemo(() => renderMarkdown(text, { breaks: true }), [text])
- return <div className="term-chat__text" dangerouslySetInnerHTML={{ __html: html }} />
+ const ref = useRef<HTMLDivElement>(null)
+ const copyButtons = useCodeBlockCopy(ref, html)
+ return (
+ <>
+ <div ref={ref} className="term-chat__text" dangerouslySetInnerHTML={{ __html: html }} />
+ {copyButtons}
+ </>
+ )
})
interface ChatPanelProps {
diff --git a/src/renderer/nodes/ChatTurnActions.tsx b/src/renderer/nodes/ChatTurnActions.tsx
index 8b0762480..75aae3a75 100644
--- a/src/renderer/nodes/ChatTurnActions.tsx
+++ b/src/renderer/nodes/ChatTurnActions.tsx
@@ -1,6 +1,5 @@
-import { useEffect, useState } from 'react'
-import { IconCheck, IconCopy } from '../components/icons'
import { chatAbsoluteTime, chatRelativeTime } from '../lib/chatThread'
+import { ChatCopyButton } from './ChatCopyButton'
/**
* The quiet row under an assistant turn in the ⌘M thread (claude.ai look): Copy + relative time.
@@ -21,32 +20,10 @@ export function ChatTurnActions({
now: number
latest: boolean
}) {
- const [copied, setCopied] = useState(false)
- useEffect(() => {
- if (!copied) return
- const t = setTimeout(() => setCopied(false), 1500)
- return () => clearTimeout(t)
- }, [copied])
if (!copyText && at === undefined) return null
return (
<div className={`term-chat__actions${latest ? ' term-chat__actions--latest' : ''}`}>
- {copyText && (
- <button
- type="button"
- className="term-chat__action"
- aria-label="Copy message"
- title={copied ? 'Copied' : 'Copy message (markdown)'}
- onClick={() => {
- // The app's own clipboard channel, not `navigator.clipboard`: it never rejects, and the
- // Server Edition bridge falls back to execCommand and raises its own banner on failure.
- window.nodeTerminal.clipboard.writeText(copyText)
- setCopied(true)
- }}
- >
- {copied ? <IconCheck /> : <IconCopy />}
- {copied && <span className="term-chat__action-note">Copied</span>}
- </button>
- )}
+ {copyText && <ChatCopyButton text={() => copyText} label="Copy message" title="Copy message (markdown)" />}
{at !== undefined && (
<time className="term-chat__time" dateTime={new Date(at).toISOString()} title={chatAbsoluteTime(at)}>
{chatRelativeTime(at, now)}
diff --git a/src/renderer/nodes/CodeBlockCopy.test.tsx b/src/renderer/nodes/CodeBlockCopy.test.tsx
new file mode 100644
index 000000000..37f3a6cda
--- /dev/null
+++ b/src/renderer/nodes/CodeBlockCopy.test.tsx
@@ -0,0 +1,80 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+/**
+ * A Copy button in the corner of every code block in the ⌘M chat view: the same control as the
+ * per-turn Copy (ChatCopyButton — app clipboard channel, check + "Copied"), one per fenced block,
+ * none for inline code, and rebuilt when the message text changes.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+vi.mock('../session/session', () => ({ useSession: () => ({ api: {} }) }))
+
+import { MarkdownText } from './ChatPanel'
+
+let host: HTMLDivElement
+let root: Root
+const writeText = vi.fn()
+
+beforeEach(() => {
+ writeText.mockClear()
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { clipboard: { writeText } }
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+})
+
+const TWO_BLOCKS = 'Run `npm test`, then:\n\n```sh\nnpm run build\n```\n\nand\n\n```js\nif (a < b) {}\n```\n'
+
+const buttons = () => Array.from(host.querySelectorAll<HTMLButtonElement>('button[aria-label="Copy code"]'))
+
+describe('code block Copy', () => {
+ it('puts one button on each fenced block and none on inline code', async () => {
+ await act(async () => root.render(<MarkdownText text={TWO_BLOCKS} />))
+
+ expect(buttons()).toHaveLength(2)
+ for (const b of buttons()) expect(b.closest('.term-chat__code')?.querySelector('pre')).not.toBeNull()
+ })
+
+ it('copies that block through the app clipboard channel and says Copied', async () => {
+ await act(async () => root.render(<MarkdownText text={TWO_BLOCKS} />))
+
+ await act(async () => buttons()[1].click())
+
+ expect(writeText).toHaveBeenCalledWith('if (a < b) {}')
+ expect(buttons()[1].textContent).toContain('Copied')
+ expect(buttons()[1].hasAttribute('data-copied')).toBe(true)
+ })
+
+ it('keeps the button out of the code text itself', async () => {
+ await act(async () => root.render(<MarkdownText text={TWO_BLOCKS} />))
+
+ const pre = host.querySelector('pre')!
+
+ expect(pre.querySelector('button')).toBeNull()
+ })
+
+ it('rebuilds the buttons when the message text changes', async () => {
+ await act(async () => root.render(<MarkdownText text={TWO_BLOCKS} />))
+
+ await act(async () => root.render(<MarkdownText text={'```\nonly one\n```\n'} />))
+ await act(async () => buttons()[0].click())
+
+ expect(buttons()).toHaveLength(1)
+ expect(writeText).toHaveBeenCalledWith('only one')
+ })
+
+ it('adds nothing to a message without code blocks', async () => {
+ await act(async () => root.render(<MarkdownText text="plain **text**" />))
+
+ expect(buttons()).toHaveLength(0)
+ expect(host.querySelector('.term-chat__code')).toBeNull()
+ })
+})
diff --git a/src/renderer/nodes/CodeBlockCopy.tsx b/src/renderer/nodes/CodeBlockCopy.tsx
new file mode 100644
index 000000000..2fea50230
--- /dev/null
+++ b/src/renderer/nodes/CodeBlockCopy.tsx
@@ -0,0 +1,60 @@
+import { useLayoutEffect, useState, type RefObject } from 'react'
+import { createPortal } from 'react-dom'
+import { preText } from '../lib/codeBlockCopy'
+import { ChatCopyButton } from './ChatCopyButton'
+
+interface CodeBlock {
+ pre: HTMLPreElement
+ host: HTMLElement
+}
+
+/**
+ * A Copy button in the top-right corner of every code block in a rendered-Markdown container of the
+ * ⌘M chat view — the same control as the per-turn Copy (ChatCopyButton).
+ *
+ * The Markdown arrives as an HTML string set as the container's inner HTML, so the blocks are found in
+ * the DOM after each render of a new string: each `<pre>` is wrapped in a positioned
+ * `.term-chat__code` (the button cannot live inside the `<pre>`, which scrolls sideways and would
+ * carry it along) and the button is portalled into a host beside it. React replaces the container's
+ * children when the HTML string changes, which drops the old wrappers; this runs again for the new
+ * ones. Wrapping is idempotent, so a re-run on the same DOM adds nothing.
+ */
+export function useCodeBlockCopy(container: RefObject<HTMLElement | null>, html: string): React.ReactNode {
+ const [blocks, setBlocks] = useState<CodeBlock[]>([])
+
+ useLayoutEffect(() => {
+ const root = container.current
+ if (root === null) return
+ const found: CodeBlock[] = []
+ for (const pre of Array.from(root.querySelectorAll('pre'))) {
+ let wrap = pre.parentElement
+ if (wrap === null || !wrap.classList.contains('term-chat__code')) {
+ wrap = document.createElement('div')
+ wrap.className = 'term-chat__code'
+ pre.replaceWith(wrap)
+ wrap.appendChild(pre)
+ }
+ let host = wrap.querySelector<HTMLElement>(':scope > .term-chat__code-copy-host')
+ if (host === null) {
+ host = document.createElement('span')
+ host.className = 'term-chat__code-copy-host'
+ wrap.appendChild(host)
+ }
+ found.push({ pre, host })
+ }
+ setBlocks(found)
+ }, [container, html])
+
+ return blocks.map(({ pre, host }, i) =>
+ createPortal(
+ <ChatCopyButton
+ text={() => preText(pre)}
+ label="Copy code"
+ title="Copy code"
+ className="term-chat__code-copy"
+ />,
+ host,
+ String(i)
+ )
+ )
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index ba652f1b8..d356011ab 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3427,6 +3427,41 @@ body,
border-radius: 6px;
overflow-x: auto;
}
+/* A code block with its Copy button (nodes/CodeBlockCopy.tsx): the wrapper is the positioned box,
+ because the <pre> scrolls sideways and would carry the button with it. The wrapper takes the
+ <pre>'s block margin so the thread's first/last-child margin rules still apply. */
+.term-chat__code {
+ position: relative;
+ margin: 1em 0;
+}
+.term-chat__code > pre {
+ margin: 0;
+}
+/* Same control as the per-turn Copy (.term-chat__action), in the block's top-right corner. Hidden
+ until the block is hovered or the button is keyboard-focused, and kept while it says "Copied".
+ A solid backing so the code underneath does not show through it. */
+.term-chat__code-copy {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ font-size: 11px;
+ color: var(--muted);
+ background: var(--bg);
+ border: 1px solid var(--border);
+ opacity: 0;
+ transition: opacity 0.12s ease;
+ user-select: none;
+ -webkit-user-select: none;
+}
+.term-chat__code:hover .term-chat__code-copy,
+.term-chat__code-copy:focus-visible,
+.term-chat__code-copy[data-copied] {
+ opacity: 1;
+}
+.term-chat__code-copy:hover {
+ background: var(--bg);
+ border-color: rgba(var(--tint-rgb), 0.3);
+}
.term-chat__text a {
color: var(--accent);
text-decoration: underline;