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(terminal): paste a file into a terminal, not just drop it

enesce63a3283e66
diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.ts
index 0ad899f04..a61b50bae 100644
--- a/src/core/fs-handlers.ts
+++ b/src/core/fs-handlers.ts
@@ -1,5 +1,6 @@
import type { CorePlatform } from './platform'
import * as fsOps from './fs-ops'
+import { saveUpload } from './uploads'
import { IPC } from '../shared/ipc'
import type { DownloadTicket } from '../shared/types'
@@ -32,6 +33,11 @@ export function registerFsHandlers(
platform.handle(IPC.fsMkdir, (dirPath: string) => fsOps.makeDir(dirPath))
platform.handle(IPC.fsExists, (p: string) => fsOps.pathExists(p))
platform.handle(IPC.filesQuickOpen, (cwd: string) => fsOps.listQuickOpenFiles(cwd))
+ // Bytes with no path on this machine (a clipboard paste, or a browser client's file) land in
+ // the managed uploads dir so the terminal has something to name. See core/uploads.ts.
+ platform.handle(IPC.filesSaveUpload, (name: string, dataBase64: string) =>
+ saveUpload(platform.userDataDir, name, dataBase64)
+ )
platform.handle(IPC.filesDownloadTicket, (p: string) =>
deps.issueDownloadTicket ? deps.issueDownloadTicket(p) : Promise.resolve(null)
)
diff --git a/src/core/uploads.test.ts b/src/core/uploads.test.ts
new file mode 100644
index 000000000..172a8d52f
--- /dev/null
+++ b/src/core/uploads.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { saveUpload, safeUploadName, uploadsRoot, UPLOAD_MAX_BYTES } from './uploads'
+
+describe('safeUploadName', () => {
+ it('strips any directory part — the name is a renderer string, never a write target', () => {
+ expect(safeUploadName('../../../.bashrc')).toBe('.bashrc')
+ expect(safeUploadName('/etc/passwd')).toBe('passwd')
+ // A POSIX-looking name must not steer a Windows write either (basename only knows one sep).
+ expect(safeUploadName('a\\b\\c.png')).not.toContain('\\')
+ })
+
+ it('falls back to a generated name for what basename still lets through', () => {
+ for (const bad of ['', '..', '.', ' ']) {
+ expect(safeUploadName(bad)).toMatch(/^upload-/)
+ }
+ })
+
+ it('keeps an ordinary name — the user recognizes it in the prompt', () => {
+ expect(safeUploadName('Bishop Drew order.xlsx')).toBe('Bishop Drew order.xlsx')
+ })
+})
+
+describe('saveUpload', () => {
+ let dir: string
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uploads-'))
+ })
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('writes the bytes under the uploads root and answers an absolute path', async () => {
+ const p = await saveUpload(dir, 'shot.png', Buffer.from('hello').toString('base64'))
+ expect(p).toBeTruthy()
+ expect(p!.startsWith(uploadsRoot(dir))).toBe(true)
+ expect(path.basename(p!)).toBe('shot.png')
+ expect(fs.readFileSync(p!, 'utf-8')).toBe('hello')
+ })
+
+ it('gives each save its own directory, so two pastes of one name never collide', async () => {
+ const data = Buffer.from('x').toString('base64')
+ const a = await saveUpload(dir, 'image.png', data)
+ const b = await saveUpload(dir, 'image.png', data)
+ expect(a).not.toBe(b)
+ expect(fs.existsSync(a!)).toBe(true)
+ expect(fs.existsSync(b!)).toBe(true)
+ })
+
+ it('escapes nothing into the parent of the uploads root', async () => {
+ const p = await saveUpload(dir, '../../escaped.txt', Buffer.from('x').toString('base64'))
+ expect(p!.startsWith(uploadsRoot(dir))).toBe(true)
+ expect(fs.existsSync(path.join(dir, 'escaped.txt'))).toBe(false)
+ })
+
+ it('refuses empty and oversized payloads instead of writing them', async () => {
+ expect(await saveUpload(dir, 'empty.bin', '')).toBeNull()
+ // Guarded on the ENCODED length: decoding a hostile string to measure it is the allocation
+ // the limit exists to prevent.
+ expect(await saveUpload(dir, 'huge.bin', 'A'.repeat(Math.ceil(UPLOAD_MAX_BYTES * 1.5)))).toBeNull()
+ })
+
+ it('never throws on an unwritable root — a failed save drops the file, like a failed drop', async () => {
+ // A FILE where the data dir should be: mkdir under it fails (ENOTDIR) the way a read-only or
+ // full disk would, and the caller must get null rather than an exception.
+ const asFile = path.join(dir, 'not-a-dir')
+ fs.writeFileSync(asFile, 'x')
+ expect(await saveUpload(asFile, 'x.png', Buffer.from('x').toString('base64'))).toBeNull()
+ })
+})
diff --git a/src/core/uploads.ts b/src/core/uploads.ts
new file mode 100644
index 000000000..4bcede468
--- /dev/null
+++ b/src/core/uploads.ts
@@ -0,0 +1,88 @@
+// Landing area for file bytes that reach us WITHOUT a path on the machine the terminals run on.
+//
+// A drag-drop hands the renderer an OS file, and Electron can name its real path — so a desktop
+// drop pastes that path and nothing is copied. Two cases have no such path:
+// • a CLIPBOARD paste of raw bytes (a screenshot, an image copied out of a browser). There is no
+// file anywhere yet; something has to write one before a path can be pasted.
+// • the Server Edition / a relay tab, where the bytes are in a BROWSER on another machine and the
+// terminal runs here — the client's own path, if it even had one, names a stranger's disk.
+//
+// Both resolve the same way: write the bytes under `<userData>/uploads/<token>/<name>` on the
+// machine that owns the terminal, and hand back that absolute path. `<token>` per save, so two
+// pastes of `image.png` never collide and the name the user recognizes is kept.
+
+import { promises as fs } from 'fs'
+import { basename, join } from 'path'
+
+/** Anything bigger is refused rather than marshalled through the RPC layer as base64 (which is
+ * itself ~4/3 of the bytes). Clipboard images and dropped documents sit far below this. */
+export const UPLOAD_MAX_BYTES = 64 * 1024 * 1024
+
+/** Uploads older than this are swept on the next save — the directory is a staging area for a
+ * paste, not storage the user manages, and nothing is coming back to clean it up otherwise. */
+export const UPLOAD_TTL_MS = 7 * 24 * 60 * 60 * 1000
+
+let seq = 0
+
+/** `<userData>/uploads` — exported so a caller can name the directory in a message/test. */
+export const uploadsRoot = (userDataDir: string): string => join(userDataDir, 'uploads')
+
+/**
+ * A filename that is safe to JOIN — never to trust as given. `basename` strips any directory part
+ * (`../../.bashrc` becomes `.bashrc`), and the leftovers that basename still allows through on
+ * their own (`.`, `..`, empty) fall back to a generated name. Separators that are not this
+ * platform's are stripped too, so a POSIX-looking name can't steer a Windows write.
+ */
+export function safeUploadName(name: string): string {
+ const base = basename(String(name ?? '')).replace(/[/\\]/g, '')
+ const clean = base.replace(/^\.+$/, '').trim()
+ return clean || `upload-${Date.now().toString(36)}`
+}
+
+/** Delete upload folders older than the TTL. Best-effort: a sweep that fails changes nothing. */
+async function sweep(root: string): Promise<void> {
+ try {
+ const now = Date.now()
+ for (const entry of await fs.readdir(root, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue
+ const dir = join(root, entry.name)
+ try {
+ const st = await fs.stat(dir)
+ if (now - st.mtimeMs > UPLOAD_TTL_MS) await fs.rm(dir, { recursive: true, force: true })
+ } catch {
+ /* a directory that vanished mid-sweep needs no removing */
+ }
+ }
+ } catch {
+ /* no uploads dir yet */
+ }
+}
+
+/**
+ * Write base64 `data` as `<userData>/uploads/<token>/<name>` and resolve its ABSOLUTE path, or
+ * null when it could not be written (too large, undecodable, unwritable disk). Never throws — the
+ * caller pastes what it got and silently drops what it didn't, exactly like a failed drop.
+ */
+export async function saveUpload(
+ userDataDir: string,
+ name: string,
+ dataBase64: string
+): Promise<string | null> {
+ try {
+ // Guard on the ENCODED length first: decoding a hostile 2 GB string to measure it is the
+ // allocation this limit exists to prevent.
+ if (typeof dataBase64 !== 'string' || dataBase64.length > UPLOAD_MAX_BYTES * 1.4) return null
+ const buf = Buffer.from(dataBase64, 'base64')
+ if (!buf.length || buf.length > UPLOAD_MAX_BYTES) return null
+ const root = uploadsRoot(userDataDir)
+ void sweep(root)
+ const token = `${Date.now().toString(36)}${(seq++).toString(36)}`
+ const dir = join(root, token)
+ await fs.mkdir(dir, { recursive: true })
+ const target = join(dir, safeUploadName(name))
+ await fs.writeFile(target, buf)
+ return target
+ } catch {
+ return null
+ }
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 26145e76c..91e376bb7 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -275,7 +275,9 @@ const api: NodeTerminalApi = {
// Desktop has no HTTP surface to redeem a ticket on — the core handler answers null here, and
// the Explorer reads that as "this shell downloads over scp instead" (SSH) or "the file is
// already on this machine" (local project).
- downloadTicket: (p: string) => ipcRenderer.invoke(IPC.filesDownloadTicket, p)
+ downloadTicket: (p: string) => ipcRenderer.invoke(IPC.filesDownloadTicket, p),
+ saveUpload: (name: string, dataBase64: string) =>
+ ipcRenderer.invoke(IPC.filesSaveUpload, name, dataBase64)
},
updates: {
onAvailable: (listener) => {
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 2b10095a9..a4431c883 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -388,7 +388,11 @@ export function buildFilesApi(
// A REAL implementation, not a stub: this is the browser's only way to get a file off the
// server, and it deliberately does not stream through this socket — it mints a ticket the
// browser redeems with a plain GET (src/server/download.ts).
- downloadTicket: (p) => client.request(IPC.filesDownloadTicket, p) as Promise<DownloadTicket | null>
+ downloadTicket: (p) => client.request(IPC.filesDownloadTicket, p) as Promise<DownloadTicket | null>,
+ // Also real, and the direction that matters here: the browser holds the bytes, the terminal
+ // runs on the server, so a pasted image only becomes nameable once the server has written it.
+ saveUpload: (name, dataBase64) =>
+ client.request(IPC.filesSaveUpload, name, dataBase64) as Promise<string | null>
}
const context: ContextApi = {
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index dd85adf2c..26f23f79f 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 } from '../../terminal/file-drop'
+import { droppedPaths, pastedFiles } from '../../terminal/file-drop'
import { parseOsc52 } from '../../terminal/osc52'
import {
attachReplay,
@@ -267,14 +267,13 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
const rt = e.relatedTarget as Node | null
if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
}
- const onDrop = async (e: React.DragEvent) => {
- const files = Array.from(e.dataTransfer.files)
- setDropping(false)
- if (!files.length) return
- e.preventDefault()
- e.stopPropagation()
+ /** Drop and paste share one path — same rule as the canvas node (see TerminalNode.insertFiles):
+ * files become paths in the terminal, and only the window-raise differs. */
+ const insertFiles = async (files: File[], opts: { raiseWindow: boolean }) => {
const term = termRef.current
- if (!term) return
+ if (!term || !files.length) return
+ // Clipboard bytes must be written before they have a path, which is not instant either.
+ const needsWrite = files.some((f) => !window.nodeTerminal.getPathForFile(f))
let paths: string[]
if (spawn.sshRemoteTmux) {
const projectId = useProjects.getState().activeProjectId
@@ -284,6 +283,13 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
} finally {
setUploading(false)
}
+ } else if (needsWrite) {
+ setUploading(true)
+ try {
+ paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '' })
+ } finally {
+ setUploading(false)
+ }
} else {
paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '' })
}
@@ -291,17 +297,38 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
// A drag-drop from another OS app doesn't bring our window forward (esp. macOS), so the
// drag-source keeps keyboard focus — the user's next keystrokes would land in the wrong app.
// Raise our window FIRST, then focus the terminal, so typing after the drop reaches it.
- window.nodeTerminal.focusWindow()
+ // A paste came from this window, which already has focus.
+ if (opts.raiseWindow) window.nodeTerminal.focusWindow()
term.focus()
term.paste(paths.join(' ') + ' ')
}
+ const onDrop = async (e: React.DragEvent) => {
+ const files = Array.from(e.dataTransfer.files)
+ setDropping(false)
+ if (!files.length) return
+ e.preventDefault()
+ e.stopPropagation()
+ await insertFiles(files, { raiseWindow: true })
+ }
+
+ // Cmd/Ctrl+V of a file or of raw image bytes; a text paste falls through to xterm untouched.
+ // 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 })
+ }
+
return (
<div
className={`kanban-modal__termwrap${dropping ? ' kanban-modal__termwrap--drop' : ''}`}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
+ onPasteCapture={onPaste}
>
{uploading && <div className="kanban-modal__upload">Uploading…</div>}
{searchOpen && (
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index b4632598d..14b93e28d 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -14,7 +14,7 @@ import { WebglAddon } from '@xterm/addon-webgl'
import { renderMarkdown } from '../lib/markdown'
import { ChatPanel } from './ChatPanel'
import { LocalTransport } from '../terminal/local-transport'
-import { droppedPaths } from '../terminal/file-drop'
+import { droppedPaths, pastedFiles } from '../terminal/file-drop'
import type { TerminalTransport } from '../terminal/transport'
import { patchTerminalScale } from '../terminal/scale-fix'
import { parseOsc52 } from '../terminal/osc52'
@@ -1497,14 +1497,19 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
const rt = e.relatedTarget as Node | null
if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
}
- const onBodyDrop = async (e: React.DragEvent) => {
- const files = Array.from(e.dataTransfer.files)
- setDropping(false)
- if (!files.length) return
- e.preventDefault()
- e.stopPropagation()
+ /**
+ * Files arriving by DROP or by PASTE become paths in the terminal — what a native terminal does
+ * on a drop, and the only thing a shell (or an agent reading its prompt) can act on. Shared so
+ * Cmd/Ctrl+V behaves exactly like the drag, upload overlay included: the events differ only in
+ * how the files got here, and in whether our window needs raising afterwards.
+ */
+ const insertFiles = async (files: File[], opts: { raiseWindow: boolean }) => {
const term = termRef.current
- if (!term) return
+ if (!term || !files.length) return
+ // Clipboard bytes (a screenshot) have never been a file anywhere, so something has to write
+ // one before there is a path to paste — worth the same "this is going somewhere" overlay the
+ // SSH upload gets, since neither is instant and both paste nothing until they finish.
+ const needsWrite = files.some((f) => !window.nodeTerminal.getPathForFile(f))
let paths: string[]
if (data.sshRemoteTmux) {
@@ -1525,6 +1530,18 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
setUploadNote({ text: 'Upload failed', failed: true })
uploadNoteTimer.current = setTimeout(() => setUploadNote(null), 2500)
}
+ } else if (needsWrite) {
+ if (uploadNoteTimer.current) clearTimeout(uploadNoteTimer.current)
+ setUploadNote({ text: 'Saving pasted file…' })
+ try {
+ paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '' })
+ } finally {
+ setUploadNote(null)
+ }
+ if (!paths.length) {
+ setUploadNote({ text: 'Could not save the pasted file', failed: true })
+ uploadNoteTimer.current = setTimeout(() => setUploadNote(null), 2500)
+ }
} else {
paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '' })
}
@@ -1534,13 +1551,35 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
setArmed(false)
// A drag-drop from another OS app doesn't bring our window forward (esp. macOS), so raise it
// FIRST — otherwise the drag-source keeps keyboard focus and the user types into the wrong app.
- window.nodeTerminal.focusWindow()
+ // A paste came from THIS window, which already has it.
+ if (opts.raiseWindow) window.nodeTerminal.focusWindow()
term.focus()
term.paste(paths.join(' ') + ' ')
useAgentStatus.getState().setActive(id, true)
presence.reportFocus(id)
}
+ const onBodyDrop = async (e: React.DragEvent) => {
+ const files = Array.from(e.dataTransfer.files)
+ setDropping(false)
+ if (!files.length) return
+ e.preventDefault()
+ e.stopPropagation()
+ await insertFiles(files, { raiseWindow: true })
+ }
+
+ // Cmd/Ctrl+V of a FILE (copied in Finder/Explorer) or of raw image bytes (a screenshot). A paste
+ // carrying neither is ordinary text and belongs to xterm — hence the early return, and hence the
+ // CAPTURE phase: xterm listens on its own textarea below us, so stopping here is the only way to
+ // 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 })
+ }
+
// A rename-capable agent's session name follows the node title: push `/rename <name>` into
// the live session (tmux send-keys, like Branch's /branch). No-op for other agents/shells.
const pushSessionRename = (name: string) => {
@@ -2016,6 +2055,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
onDragOver={onBodyDragOver}
onDragLeave={onBodyDragLeave}
onDrop={onBodyDrop}
+ onPasteCapture={onBodyPaste}
>
<div
className={`term-node__xterm nodrag nowheel${co.letterbox ? ' letterboxed' : ''}`}
diff --git a/src/renderer/terminal/file-drop.test.ts b/src/renderer/terminal/file-drop.test.ts
new file mode 100644
index 000000000..fabd48632
--- /dev/null
+++ b/src/renderer/terminal/file-drop.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect } from 'vitest'
+import { escapeDroppedPath, pastedFiles, uploadNameFor } from './file-drop'
+
+describe('escapeDroppedPath', () => {
+ it('escapes what a shell would otherwise interpret', () => {
+ expect(escapeDroppedPath('/tmp/Bishop Drew order.xlsx')).toBe('/tmp/Bishop\\ Drew\\ order.xlsx')
+ expect(escapeDroppedPath("/tmp/a'b$c")).toBe("/tmp/a\\'b\\$c")
+ })
+})
+
+describe('uploadNameFor', () => {
+ it('keeps the file s own name when it has one', () => {
+ expect(uploadNameFor(new File(['x'], 'report.pdf', { type: 'application/pdf' }))).toBe(
+ 'report.pdf'
+ )
+ })
+
+ it('names clipboard bytes by their type — an agent should not have to guess', () => {
+ // A screenshot arrives as image/png with an EMPTY name; a suffix-less `pasted-<ts>` tells
+ // whatever reads the prompt nothing about what it is holding.
+ const name = uploadNameFor(new File(['x'], '', { type: 'image/png' }))
+ expect(name).toMatch(/^pasted-\d{8}-\d{6}\.png$/)
+ expect(uploadNameFor(new File(['x'], '', { type: 'image/jpeg' }))).toMatch(/\.jpg$/)
+ })
+
+ it('falls back to the subtype, then to .bin, for a type it has no table entry for', () => {
+ expect(uploadNameFor(new File(['x'], '', { type: 'audio/ogg' }))).toMatch(/\.ogg$/)
+ expect(uploadNameFor(new File(['x'], '', { type: '' }))).toMatch(/\.bin$/)
+ })
+})
+
+/** Minimal stand-in for the two shapes Chromium actually hands a paste. */
+const clipboard = (opts: { files?: File[]; items?: File[] }): DataTransfer =>
+ ({
+ files: (opts.files ?? []) as unknown as FileList,
+ items: (opts.items ?? []).map((f) => ({ kind: 'file', getAsFile: () => f })) as unknown as
+ DataTransferItemList
+ }) as DataTransfer
+
+describe('pastedFiles', () => {
+ const png = new File(['x'], 'a.png', { type: 'image/png' })
+
+ it('reads an OS file-manager copy off `files`', () => {
+ expect(pastedFiles(clipboard({ files: [png] }))).toEqual([png])
+ })
+
+ it('reads raw clipboard bytes off `items` — a screenshot never reaches `files`', () => {
+ expect(pastedFiles(clipboard({ items: [png] }))).toEqual([png])
+ })
+
+ it('answers empty for a text paste, which is xterm s to handle', () => {
+ expect(pastedFiles(clipboard({}))).toEqual([])
+ expect(pastedFiles(null)).toEqual([])
+ })
+})
diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.ts
index e7ea6d336..c641e7dd0 100644
--- a/src/renderer/terminal/file-drop.ts
+++ b/src/renderer/terminal/file-drop.ts
@@ -1,34 +1,102 @@
-// Shared terminal file-drop logic — used by both the canvas TerminalNode and the kanban card
-// modal's co-attach terminal (ModalTerminal), so a file dropped onto either pastes the same way.
+// Shared terminal file-drop/paste logic — used by both the canvas TerminalNode and the kanban card
+// modal's co-attach terminal (ModalTerminal), so a file dropped onto or pasted into either becomes
+// a path the same way.
/** Backslash-escape shell-special characters, like a native terminal does on file drop. */
export function escapeDroppedPath(p: string): string {
return p.replace(/([ \t"'`\\()&;|<>$!*?[\]{}#~])/g, '\\$1')
}
+/** Extension for a clipboard blob that arrives with no filename, keyed off its MIME type. A
+ * screenshot is `image/png` with an empty `name`, and an agent asked to look at `pasted-<ts>`
+ * with no suffix has to guess what it is holding. */
+const EXT_BY_TYPE: Record<string, string> = {
+ 'image/png': 'png',
+ 'image/jpeg': 'jpg',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/svg+xml': 'svg',
+ 'image/bmp': 'bmp',
+ 'image/tiff': 'tiff',
+ 'application/pdf': 'pdf',
+ 'text/plain': 'txt'
+}
+
+/** 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 {
+ if (file.name) return file.name
+ const ext = EXT_BY_TYPE[file.type] ?? (file.type.split('/')[1] || 'bin')
+ const stamp = new Date()
+ .toISOString()
+ .replace(/[-:]/g, '')
+ .replace(/\..+$/, '')
+ .replace('T', '-')
+ return `pasted-${stamp}.${ext}`
+}
+
+/** Files carried by a paste. Chromium exposes an OS file-manager copy on `files`, and raw
+ * clipboard bytes (a screenshot) as an `items` entry of kind 'file' — read both, since a paste
+ * that carries neither must fall through to xterm as ordinary text. */
+export function pastedFiles(dt: DataTransfer | null): File[] {
+ if (!dt) return []
+ const files = Array.from(dt.files)
+ if (files.length) return files
+ return Array.from(dt.items)
+ .filter((it) => it.kind === 'file')
+ .map((it) => it.getAsFile())
+ .filter((f): f is File => !!f)
+}
+
+const readAsBase64 = (file: File): Promise<string | null> =>
+ new Promise((resolve) => {
+ const reader = new FileReader()
+ reader.onerror = () => resolve(null)
+ reader.onload = () => {
+ const res = typeof reader.result === 'string' ? reader.result : ''
+ const comma = res.indexOf(',')
+ resolve(comma >= 0 ? res.slice(comma + 1) : null)
+ }
+ reader.readAsDataURL(file)
+ })
+
+/**
+ * The file's path ON THE MACHINE THE TERMINAL RUNS ON.
+ *
+ * A desktop drag-drop already has one (Electron can name the OS file), and using it copies
+ * nothing. Everything else has bytes and no usable path — clipboard images have never been a file
+ * anywhere, and a browser client's file lives on a different machine entirely — so the bytes are
+ * written into the managed uploads dir over there and THAT path is what the terminal gets.
+ */
+async function localPathFor(file: File): Promise<string | null> {
+ const direct = window.nodeTerminal.getPathForFile(file)
+ if (direct) return direct
+ const data = await readAsBase64(file)
+ if (!data) return null
+ return window.nodeTerminal.files.saveUpload(uploadNameFor(file), data).catch(() => null)
+}
+
/**
- * Resolve dropped files to terminal-pasteable paths. For an SSH-project terminal a local path is
- * useless on the host, so each file is uploaded over the project's ControlMaster and its REMOTE
- * absolute path is returned; for a local terminal the local path is used. Fail-open: files that
- * can't be resolved/uploaded are dropped from the result (never throws).
+ * Resolve dropped/pasted files to terminal-pasteable paths. For an SSH-project terminal a local
+ * path is useless on the host, so each file is uploaded over the project's ControlMaster and its
+ * REMOTE absolute path is returned; for a local terminal the local path is used. Fail-open: files
+ * that can't be resolved/uploaded are dropped from the result (never throws).
*/
export async function droppedPaths(
files: File[],
opts: { sshRemoteTmux: boolean; projectId: string }
): Promise<string[]> {
- if (opts.sshRemoteTmux) {
- const uploaded = await Promise.all(
- files.map((f) => {
- const lp = window.nodeTerminal.getPathForFile(f)
- return lp
- ? window.nodeTerminal.sshProject.uploadFile(opts.projectId, lp, f.name).catch(() => null)
- : Promise.resolve(null)
- })
+ const local = await Promise.all(files.map((f) => localPathFor(f).catch(() => null)))
+ const pairs = files
+ .map((f, i) => ({ file: f, path: local[i] }))
+ .filter((p): p is { file: File; path: string } => !!p.path)
+ if (!opts.sshRemoteTmux) return pairs.map((p) => escapeDroppedPath(p.path))
+ const uploaded = await Promise.all(
+ pairs.map((p) =>
+ window.nodeTerminal.sshProject
+ .uploadFile(opts.projectId, p.path, uploadNameFor(p.file))
+ .catch(() => null)
)
- return uploaded.filter((p): p is string => !!p).map(escapeDroppedPath)
- }
- return files
- .map((f) => window.nodeTerminal.getPathForFile(f))
- .filter((p): p is string => !!p)
- .map(escapeDroppedPath)
+ )
+ return uploaded.filter((p): p is string => !!p).map(escapeDroppedPath)
}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 3c1d47aaf..ca881271b 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -176,6 +176,8 @@ export const IPC = {
filesQuickOpen: 'files:quick-open',
/** Mint a one-shot HTTP download ticket (Server Edition only; every other shell answers null). */
filesDownloadTicket: 'files:download-ticket',
+ /** Persist pasted/dropped bytes that have no path here, and answer their absolute path. */
+ filesSaveUpload: 'files:save-upload',
settingsLoad: 'settings:load',
settingsSave: 'settings:save',
sshList: 'ssh:list',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ea8c4dcc2..50c9f147c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -573,6 +573,13 @@ export interface FilesApi {
* affordance rather than erroring.
*/
downloadTicket(path: string): Promise<DownloadTicket | null>
+ /**
+ * Persist raw bytes (base64) as a file on the machine the terminals run on, and resolve its
+ * ABSOLUTE path — what a clipboard paste of an image has instead of a path, and what a browser
+ * client's dropped file has instead of a usable one. Resolves null when it could not be written
+ * (too large, unwritable); callers drop that file the way a failed drop does.
+ */
+ saveUpload(name: string, dataBase64: string): Promise<string | null>
}
export interface MediaApi {