diff --git a/apps/host/src/lib/clipboard.ts b/apps/host/src/lib/clipboard.ts new file mode 100644 index 00000000..7a51f061 --- /dev/null +++ b/apps/host/src/lib/clipboard.ts @@ -0,0 +1,35 @@ +/** + * Copy text for the person. The browser clipboard call can be refused (the desktop web view asks for permission, or has no clipboard + * object); the older copy command through a hidden field still works there. The answer is always a toast: "Copied", or one plain + * sentence and what to do next (#3731). + */ +export interface ClipboardDeps { + clipboard?: { writeText(text: string): Promise } | null; + legacyCopy?: (text: string) => boolean; + toast: (tone: 'success' | 'warn', title: string, body?: string) => void; +} + +function legacyCopy(text: string): boolean { + if (typeof document === 'undefined') return false; + const field = document.createElement('textarea'); + field.value = text; + field.setAttribute('readonly', ''); + field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none'; + document.body.appendChild(field); + const active = document.activeElement as HTMLElement | null; + try { + field.select(); + return document.execCommand('copy'); + } catch { return false; } + finally { field.remove(); active?.focus?.(); } +} + +export async function copyText(text: string, label: string, deps: ClipboardDeps): Promise { + const clipboard = deps.clipboard === undefined ? (typeof navigator === 'undefined' ? null : navigator.clipboard) : deps.clipboard; + let done = false; + try { if (clipboard) { await clipboard.writeText(text); done = true; } } catch { /* the fallback is next */ } + if (!done) { try { done = (deps.legacyCopy ?? legacyCopy)(text); } catch { done = false; } } + if (done) deps.toast('success', 'Copied', label); + else deps.toast('warn', 'Couldn’t copy', 'Select the text and copy it with Ctrl+C.'); + return done; +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 286fb723..97dc34f2 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -39,6 +39,7 @@ import { Btn, Icon, IconBtn, ErrorNotice, type IconName } from '../components/ui import { composerCap, scrollBehavior } from '../lib/responsive'; import { relTime, cx, duration, tokens, tps } from '../lib/format'; import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store'; +import { copyText } from '../lib/clipboard'; import { getSlashCommands } from '../lib/commands'; import { useLocation } from '../lib/router'; import { composerSends } from '../lib/shortcut-bindings'; @@ -616,11 +617,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp const [sentTime, setSentTime] = useState(() => relTime(m.at)); if (m.role === 'user') { return (
setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}> -
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
+
{tr(m.photos?.length ? : null)}{m.markdown ? : {m.content}}
- void navigator.clipboard.writeText(m.content)}/> + void copyText(m.content, 'Message', { toast: pushToast })}/> { const prompt = rewindTo(m.id); if (prompt !== null) @@ -659,11 +660,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp {tr(!m.streaming && !m.timeSkipId && (m.content || m.error) ? (
{tr(isLast ? <> - void navigator.clipboard.writeText(m.content)}/> + void copyText(m.content, 'Response', { toast: pushToast })}/> void retryLast(m.id)}/> : null)} - {tr(!isLast ? <> : null)} + {tr(!isLast ? <> : null)} {tr(isLast ? : null)} {tr(m.tokens || m.tps || m.durationMs ?

{tr(m.tokens ? `${tokens(m.tokens)} tokens` : '')}{tr(m.tps ? ` · ${tps(m.tps)} tok/s` : '')}{tr(m.durationMs ? ` · ${duration(m.durationMs)}` : '')}{tr(m.demo ? ' · Example' : '')}

: null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index bb27e246..977ecbd5 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7517,3 +7517,6 @@ textarea { .md-math-block .md-math--display { margin: 0; } .md-math .katex { font-size: 1.08em; } .md-math .katex-display { margin: 0; } + +/* A message the person typed keeps its line breaks (#3720). */ +.st-bubble__text { white-space: pre-wrap; overflow-wrap: anywhere; } diff --git a/apps/host/tests/clipboard-copy.test.mjs b/apps/host/tests/clipboard-copy.test.mjs new file mode 100644 index 00000000..0ed7787a --- /dev/null +++ b/apps/host/tests/clipboard-copy.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; + +const { code } = await transform(await readFile(new URL('../src/lib/clipboard.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); +const { copyText } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const toasts = () => { const list = []; return { list, toast: (...a) => list.push(a) }; }; + +test('Copy says Copied when the clipboard takes the text (#3731)', async () => { + const t = toasts(); let got = ''; + assert.equal(await copyText('hello', 'Response', { clipboard: { writeText: async v => { got = v; } }, toast: t.toast }), true); + assert.equal(got, 'hello'); assert.equal(t.list[0][0], 'success'); +}); +test('a refused clipboard falls back to the older copy command', async () => { + const t = toasts(); let got = ''; + assert.equal(await copyText('x', 'Response', { clipboard: { writeText: async () => { throw new Error('denied'); } }, legacyCopy: v => { got = v; return true; }, toast: t.toast }), true); + assert.equal(got, 'x'); assert.equal(t.list[0][0], 'success'); +}); +test('when nothing works the person is told, never left with a silent click', async () => { + const t = toasts(); + assert.equal(await copyText('x', 'Response', { clipboard: null, legacyCopy: () => false, toast: t.toast }), false); + assert.equal(t.list.length, 1); assert.equal(t.list[0][0], 'warn'); assert.match(t.list[0][2], /Ctrl\+C/); +}); +test('the typed message keeps its line breaks (#3720) and the chat uses the shared copy', async () => { + const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8'); + assert.match(css, /\.st-bubble__text\s*\{[^}]*white-space:\s*pre-wrap/); + const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8'); + assert.doesNotMatch(chat, /void navigator\.clipboard\.writeText/); +});