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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(clipboard): enhance paste handling for images and text in browser
Dat Tran82e10946c299
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex 12d21c851..442dc26e0 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -10,7 +10,7 @@ import { useSession } from '../../session/session'import { useSettings } from '../../state/settings'import { useTerminalSearch } from '../../terminal/useTerminalSearch'import { LocalTransport } from '../../terminal/local-transport'-import { droppedPaths, pastedFiles } from '../../terminal/file-drop'+import { clipboardImages, droppedPaths, pasteHasText, pastedFiles } from '../../terminal/file-drop'import { parseOsc52 } from '../../terminal/osc52'import {attachReplay,@@ -345,10 +345,17 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda// Capture phase, because xterm's own paste listener sits on the textarea below this wrapper.const onPaste = (e: React.ClipboardEvent) => {const files = pastedFiles(e.clipboardData)- if (!files.length) return- e.preventDefault()- e.stopPropagation()- void insertFiles(files, { raiseWindow: false })+ if (files.length) {+ e.preventDefault()+ e.stopPropagation()+ void insertFiles(files, { raiseWindow: false })+ return+ }+ // Files nor text — the filtered image-only clipboard. Same fallback as the canvas node.+ if (pasteHasText(e.clipboardData)) return+ void clipboardImages().then((images) => {+ if (images.length) void insertFiles(images, { raiseWindow: false })+ })}return (diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 6990db620..9ab362455 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -17,7 +17,7 @@ import { WebglAddon } from '@xterm/addon-webgl'// one-frame spinner in that slot reads as a glitch.const ChatPanel = lazy(() => import('./ChatPanel').then((m) => ({ default: m.ChatPanel })))import { LocalTransport } from '../terminal/local-transport'-import { droppedPaths, pastedFiles } from '../terminal/file-drop'+import { clipboardImages, droppedPaths, pasteHasText, pastedFiles } from '../terminal/file-drop'import type { TerminalTransport } from '../terminal/transport'import { patchTerminalScale } from '../terminal/scale-fix'import { parseOsc52 } from '../terminal/osc52'@@ -1714,10 +1714,21 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// keep it from also pasting whatever text the clipboard happened to carry alongside the file.const onBodyPaste = (e: React.ClipboardEvent) => {const files = pastedFiles(e.clipboardData)- if (!files.length) return- e.preventDefault()- e.stopPropagation()- void insertFiles(files, { raiseWindow: false })+ if (files.length) {+ e.preventDefault()+ e.stopPropagation()+ void insertFiles(files, { raiseWindow: false })+ return+ }+ // Neither files NOR text: an image-only clipboard that Chromium filtered down to nothing on+ // its way to xterm's textarea (see clipboardImages). Ask the async API, which isn't filtered.+ // Deliberately NOT prevented/stopped — there is no text for xterm to paste either way, so a+ // clipboard that turns out to hold no image is left exactly as the no-op it already was, and+ // an ordinary text paste never reaches this branch at all.+ if (pasteHasText(e.clipboardData)) return+ void clipboardImages().then((images) => {+ if (images.length) void insertFiles(images, { raiseWindow: false })+ })}// A rename-capable agent's session name follows the node title: push `/rename <name>` intodiff --git a/src/renderer/terminal/file-drop.test.ts b/src/renderer/terminal/file-drop.test.tsindex fabd48632..008353410 100644--- a/src/renderer/terminal/file-drop.test.ts+++ b/src/renderer/terminal/file-drop.test.ts@@ -1,5 +1,11 @@-import { describe, it, expect } from 'vitest'-import { escapeDroppedPath, pastedFiles, uploadNameFor } from './file-drop'+import { describe, it, expect, afterEach, vi } from 'vitest'+import {+ clipboardImages,+ escapeDroppedPath,+ pasteHasText,+ pastedFiles,+ uploadNameFor+} from './file-drop'describe('escapeDroppedPath', () => {it('escapes what a shell would otherwise interpret', () => {@@ -29,12 +35,13 @@ describe('uploadNameFor', () => {})})-/** Minimal stand-in for the two shapes Chromium actually hands a paste. */-const clipboard = (opts: { files?: File[]; items?: File[] }): DataTransfer =>+/** Minimal stand-in for the shapes Chromium actually hands a paste. */+const clipboard = (opts: { files?: File[]; items?: File[]; text?: string }): DataTransfer =>({files: (opts.files ?? []) as unknown as FileList,items: (opts.items ?? []).map((f) => ({ kind: 'file', getAsFile: () => f })) as unknown as- DataTransferItemList+ DataTransferItemList,+ getData: (type: string) => (type === 'text/plain' ? (opts.text ?? '') : '')}) as DataTransferdescribe('pastedFiles', () => {@@ -53,3 +60,49 @@ describe('pastedFiles', () => {expect(pastedFiles(null)).toEqual([])})})++describe('pasteHasText', () => {+ it('separates an ordinary text paste from one that carried nothing at all', () => {+ expect(pasteHasText(clipboard({ text: 'hello' }))).toBe(true)+ // The filtered image-only clipboard: Chromium hands over no files AND no text.+ expect(pasteHasText(clipboard({}))).toBe(false)+ expect(pasteHasText(null)).toBe(false)+ })+})++describe('clipboardImages', () => {+ afterEach(() => vi.unstubAllGlobals())++ /** Stand-in for the async Clipboard API — `read()` is the only member touched. */+ const stubClipboard = (read: () => Promise<unknown[]>): void => {+ vi.stubGlobal('navigator', { clipboard: { read } })+ }++ const item = (types: string[]): unknown => ({+ types,+ getType: (t: string) => Promise.resolve(new Blob(['bytes'], { type: t }))+ })++ it('reads the screenshot the paste event filtered out, and names it', async () => {+ stubClipboard(async () => [item(['image/png'])])+ const [file] = await clipboardImages()+ expect(file.type).toBe('image/png')+ // A bare Blob has no name; without one the upload overlay and the agent both see nothing.+ expect(file.name).toMatch(/^pasted-\d{8}-\d{6}\.png$/)+ })++ it('ignores clipboard entries that hold no image', async () => {+ stubClipboard(async () => [item(['text/html', 'text/plain'])])+ expect(await clipboardImages()).toEqual([])+ })++ it('answers empty where the API is absent — an insecure context, or an older browser', async () => {+ vi.stubGlobal('navigator', {})+ expect(await clipboardImages()).toEqual([])+ })++ it('answers empty when the read is refused, leaving the paste the no-op it already was', async () => {+ stubClipboard(() => Promise.reject(new DOMException('denied', 'NotAllowedError')))+ expect(await clipboardImages()).toEqual([])+ })+})diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.tsindex c641e7dd0..af7c7b81e 100644--- a/src/renderer/terminal/file-drop.ts+++ b/src/renderer/terminal/file-drop.ts@@ -24,7 +24,7 @@ const EXT_BY_TYPE: Record<string, string> = {/** The name to store a file under. Clipboard bytes usually have none, so one is generated from* the MIME type + a timestamp — recognizable in a prompt and unique enough to read back. */-export function uploadNameFor(file: File): string {+export function uploadNameFor(file: { name: string; type: string }): string {if (file.name) return file.nameconst ext = EXT_BY_TYPE[file.type] ?? (file.type.split('/')[1] || 'bin')const stamp = new Date()@@ -48,6 +48,46 @@ export function pastedFiles(dt: DataTransfer | null): File[] {.filter((f): f is File => !!f)}+/** True when the paste carried text. That text is xterm's to handle — and its ABSENCE, on a paste+ * that carried no files either, is the signature of the filtered clipboard `clipboardImages`+ * exists for. */+export function pasteHasText(dt: DataTransfer | null): boolean {+ return !!dt && !!dt.getData('text/plain')+}++/**+ * Images that are ON the clipboard but that the paste event refused to hand over.+ *+ * Chromium fills `clipboardData` only with formats the paste TARGET can hold, and the element+ * holding focus inside a terminal node is xterm's helper `<textarea>` — text, and nothing else. A+ * clipboard carrying just a screenshot has no text flavour to survive that filter, so the handler+ * is handed an EMPTY `clipboardData` (files 0, items []) and the paste looks like it did nothing.+ * Observed on Chrome/Windows against the Server Edition; it is why apps that accept pasted images+ * focus a `contenteditable` rather than a textarea.+ *+ * The async Clipboard API is not filtered by the focused element, so ask it directly. It needs a+ * secure context and the `clipboard-read` permission (granted once per origin, prompted on first+ * use); a browser without either, or a user who declines, resolves to [] and the paste stays the+ * no-op it already was. Never throws — same fail-open contract as the rest of this module.+ */+export async function clipboardImages(): Promise<File[]> {+ try {+ if (!navigator.clipboard?.read) return []+ const out: File[] = []+ for (const item of await navigator.clipboard.read()) {+ const type = item.types.find((t) => t.startsWith('image/'))+ if (!type) continue+ const blob = await item.getType(type)+ // Named here rather than left to `localPathFor`: the upload overlay prints this name, and+ // the clipboard hands over a bare Blob with none.+ out.push(new File([blob], uploadNameFor({ name: '', type }), { type }))+ }+ return out+ } catch {+ return []+ }+}+const readAsBase64 = (file: File): Promise<string | null> =>new Promise((resolve) => {const reader = new FileReader()