Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: introduce terminal pasteFile binary type to handle dropped file uploads and path injection

0xken15fbcd303584dd
diff --git a/cli/src/lib/pasteDropFiles.ts b/cli/src/lib/pasteDropFiles.ts
new file mode 100644
index 000000000..6a34e5912
--- /dev/null
+++ b/cli/src/lib/pasteDropFiles.ts
@@ -0,0 +1,69 @@
+/**
+ * Where bytes from a client-side paste/drop land on disk on THIS machine, and how long they stick
+ * around. Two callers share this one directory and one prune sweep:
+ *
+ * - `pasteImage()`'s no-native-clipboard fallback (osClipboard.ts returned 'unavailable') — needs
+ * the file only long enough for the OS to ingest it on a successful clipboard write, but on the
+ * fallback path the path itself is what gets pasted, so it has to keep resolving afterwards.
+ * - `pasteFile()` (a dropped non-image file) — ALWAYS just writes and pastes the path; there is no
+ * clipboard step to skip.
+ *
+ * Both need the same thing: a durable-enough file and a bound on how much accumulates over time.
+ */
+import { randomUUID } from 'node:crypto'
+import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+
+const PASTE_DROPS_DIR = join(env.ADAPTER_DATA_DIR, 'paste-drops')
+const RETENTION_MS = 24 * 60 * 60 * 1000
+
+/** Best-effort: a prune failure must never block a paste/drop that is otherwise fine. */
+async function pruneStale(): Promise<void> {
+ try {
+ const now = Date.now()
+ const entries = await readdir(PASTE_DROPS_DIR)
+ await Promise.all(entries.map(async (name) => {
+ const path = join(PASTE_DROPS_DIR, name)
+ try {
+ const info = await stat(path)
+ if (now - info.mtimeMs > RETENTION_MS) await rm(path, { force: true })
+ } catch { /* raced with something else touching the same file — ignore */ }
+ }))
+ } catch { /* directory not there yet, or unreadable — nothing to prune */ }
+}
+
+async function ensureDir(): Promise<void> {
+ await mkdir(PASTE_DROPS_DIR, { recursive: true })
+ await pruneStale()
+}
+
+/** Strips anything that could escape the drops directory or corrupt a path (separators, null
+ * bytes), caps length, and falls back to a generic name if nothing usable survives — this name is
+ * attacker/careless-client controlled (it travels over the wire as-is) and only ever used as ONE
+ * path segment, appended after a random prefix, never interpreted as a path itself. */
+function sanitizeFilename(name: string): string {
+ const stripped = name.replaceAll(/[/\\\0]/g, '_').trim().slice(-120)
+ return stripped.length > 0 ? stripped : 'file'
+}
+
+/** Writes `bytes` to a freshly named PNG file under the harness data dir, pruning anything older
+ * than a day from the same directory first, and returns its absolute path. Used only by
+ * `pasteImage()`'s fallback path — the name is opaque (a PNG needs no recognizable name) and does
+ * not carry a client-supplied filename. */
+export async function writePasteImageFile(bytes: Uint8Array): Promise<string> {
+ await ensureDir()
+ const path = join(PASTE_DROPS_DIR, `${randomUUID()}.png`)
+ await writeFile(path, bytes)
+ return path
+}
+
+/** Writes `bytes` under a name derived from `originalFilename` (sanitized, prefixed with a short
+ * random id to avoid collisions) so the path pasted into the pane stays recognizable — e.g.
+ * `.../a1b2c3d4-report.pdf` rather than an opaque id. Used by `pasteFile()` for a dropped file. */
+export async function writePasteDropFile(originalFilename: string, bytes: Uint8Array): Promise<string> {
+ await ensureDir()
+ const path = join(PASTE_DROPS_DIR, `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalFilename)}`)
+ await writeFile(path, bytes)
+ return path
+}
diff --git a/cli/src/lib/pasteImageFiles.ts b/cli/src/lib/pasteImageFiles.ts
deleted file mode 100644
index ef10c33ad..000000000
--- a/cli/src/lib/pasteImageFiles.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Where an image paste's PNG bytes land on disk on THIS machine, and how long they stick around.
- *
- * A successful native-clipboard write (osClipboard.ts) only needs the file for the instant the OS
- * takes to ingest it — the OS clipboard owns the bytes after that. The file-path fallback (when no
- * native clipboard is reachable) is different: the path itself is what gets pasted into the pane,
- * so the file has to keep resolving after this call returns. Both cases share one directory so a
- * single prune sweep bounds both.
- */
-import { randomUUID } from 'node:crypto'
-import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'
-import { join } from 'node:path'
-import { env } from '../config/env.js'
-
-const PASTE_IMAGES_DIR = join(env.ADAPTER_DATA_DIR, 'paste-images')
-const RETENTION_MS = 24 * 60 * 60 * 1000
-
-/** Best-effort: a prune failure must never block an image paste that is otherwise fine. */
-async function pruneStale(): Promise<void> {
- try {
- const now = Date.now()
- const entries = await readdir(PASTE_IMAGES_DIR)
- await Promise.all(entries.map(async (name) => {
- const path = join(PASTE_IMAGES_DIR, name)
- try {
- const info = await stat(path)
- if (now - info.mtimeMs > RETENTION_MS) await rm(path, { force: true })
- } catch { /* raced with something else touching the same file — ignore */ }
- }))
- } catch { /* directory not there yet, or unreadable — nothing to prune */ }
-}
-
-/** Writes `bytes` to a freshly named PNG file under the harness data dir, pruning anything older
- * than a day from the same directory first, and returns its absolute path. */
-export async function writePasteImageFile(bytes: Uint8Array): Promise<string> {
- await mkdir(PASTE_IMAGES_DIR, { recursive: true })
- await pruneStale()
- const path = join(PASTE_IMAGES_DIR, `${randomUUID()}.png`)
- await writeFile(path, bytes)
- return path
-}
diff --git a/cli/src/lib/terminalBinary.spec.ts b/cli/src/lib/terminalBinary.spec.ts
index 61998e30d..dbbeb1a37 100644
--- a/cli/src/lib/terminalBinary.spec.ts
+++ b/cli/src/lib/terminalBinary.spec.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest'
import {
deriveTerminalBinaryKey,
+ decodePasteFilePayload,
decodeTerminalLocal,
+ encodePasteFilePayload,
encodeTerminalLocal,
openTerminalBinary,
parseTerminalBinaryEnvelope,
@@ -9,8 +11,10 @@ import {
TerminalBinaryKind,
TERMINAL_BINARY_IMAGE_PASTE_MAX_CIPHERTEXT_BYTES,
TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES,
+ TERMINAL_BINARY_PASTE_FILE_MAX_CIPHERTEXT_BYTES,
TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES,
TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES,
+ TERMINAL_LOCAL_PASTE_FILE_MAX_PAYLOAD_BYTES,
} from './terminalBinary.js'
const key = Uint8Array.from({ length: 32 }, (_, index) => index)
@@ -162,6 +166,41 @@ describe('terminal binary protocol v3', () => {
})).toBeNull()
})
+ it('round-trips a pasteFile payload (filename + content) at its own ceiling', () => {
+ const payload = encodePasteFilePayload('report.pdf', Uint8Array.of(0x25, 0x50, 0x44, 0x46))!
+ expect(payload).not.toBeNull()
+
+ const sealed = sealTerminalBinary(key, 30, {
+ kind: TerminalBinaryKind.pasteFile,
+ streamId,
+ seq: 0,
+ bytes: payload,
+ compressed: false,
+ })!
+ expect(sealed).not.toBeNull()
+ expect(openTerminalBinary(key, sealed)?.frame).toEqual({
+ kind: TerminalBinaryKind.pasteFile,
+ streamId,
+ seq: 0,
+ bytes: payload,
+ compressed: false,
+ })
+
+ // Its own ceiling, independent of paste/imagePaste.
+ const tooBig = new Uint8Array(TERMINAL_BINARY_PASTE_FILE_MAX_CIPHERTEXT_BYTES + 1)
+ expect(sealTerminalBinary(key, 31, { kind: TerminalBinaryKind.pasteFile, streamId, seq: 0, bytes: tooBig, compressed: false })).toBeNull()
+ })
+
+ it('rejects a compressed pasteFile, same reason as paste/imagePaste', () => {
+ expect(sealTerminalBinary(key, 32, {
+ kind: TerminalBinaryKind.pasteFile,
+ streamId,
+ seq: 0,
+ bytes: Uint8Array.of(1, 2, 3),
+ compressed: true,
+ })).toBeNull()
+ })
+
it('rejects tamper, truncation and unsupported flags', () => {
const sealed = sealTerminalBinary(key, 1, {
kind: TerminalBinaryKind.output,
@@ -276,4 +315,51 @@ describe('authenticated loopback terminal framing v1', () => {
compressed: false,
})).toBeNull()
})
+
+ it('carries a pasteFile well past the ordinary local frame ceiling, independent of paste/imagePaste', () => {
+ const content = new Uint8Array(2 * 1024 * 1024).fill(0xcd)
+ const payload = encodePasteFilePayload('archive.zip', content)!
+ const encoded = encodeTerminalLocal({
+ kind: TerminalBinaryKind.pasteFile,
+ streamId,
+ seq: 0,
+ bytes: payload,
+ compressed: false,
+ })
+ expect(encoded).not.toBeNull()
+ const decoded = decodeTerminalLocal(encoded!)
+ expect(decoded?.kind).toBe(TerminalBinaryKind.pasteFile)
+ expect(decodePasteFilePayload(decoded!.bytes)).toEqual({ filename: 'archive.zip', content })
+
+ const tooBig = new Uint8Array(TERMINAL_LOCAL_PASTE_FILE_MAX_PAYLOAD_BYTES + 1)
+ expect(encodeTerminalLocal({
+ kind: TerminalBinaryKind.pasteFile,
+ streamId,
+ seq: 0,
+ bytes: tooBig,
+ compressed: false,
+ })).toBeNull()
+ })
+})
+
+describe('pasteFile payload sub-format', () => {
+ it('round-trips filename + content', () => {
+ const content = Uint8Array.of(1, 2, 3, 4, 5)
+ const payload = encodePasteFilePayload('xin chào.txt', content)!
+ expect(payload).not.toBeNull()
+ expect(decodePasteFilePayload(payload)).toEqual({ filename: 'xin chào.txt', content })
+ })
+
+ it('rejects an empty filename', () => {
+ expect(encodePasteFilePayload('', Uint8Array.of(1))).toBeNull()
+ })
+
+ it('rejects malformed/truncated payloads', () => {
+ expect(decodePasteFilePayload(new Uint8Array(0))).toBeNull()
+ expect(decodePasteFilePayload(Uint8Array.of(0, 0))).toBeNull() // zero-length filename
+ // Claims a 10-byte filename but supplies none.
+ const truncated = new Uint8Array(2)
+ new DataView(truncated.buffer).setUint16(0, 10, false)
+ expect(decodePasteFilePayload(truncated)).toBeNull()
+ })
})
diff --git a/cli/src/lib/terminalBinary.ts b/cli/src/lib/terminalBinary.ts
index 2fd2aafbf..071a9e0ac 100644
--- a/cli/src/lib/terminalBinary.ts
+++ b/cli/src/lib/terminalBinary.ts
@@ -23,6 +23,12 @@ export const TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES = 6 * 1024 * 1024
// terminalLocalImagePasteMaxPayloadBytes — keep the two in step.
export const TERMINAL_BINARY_IMAGE_PASTE_MAX_CIPHERTEXT_BYTES = 4 * 1024 * 1024
export const TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024
+// A dropped (non-image) file, delivered whole so its path can be pasted on the far side — see
+// terminalStreamManager.ts's pasteFile(). Ordinary files run larger than a screenshot, hence its
+// own, more generous ceiling; this is a modest atomic-frame limit, not a general file-transfer
+// feature. Mirrors terminal_binary.dart's terminalLocalPasteFileMaxPayloadBytes — keep in step.
+export const TERMINAL_BINARY_PASTE_FILE_MAX_CIPHERTEXT_BYTES = 10 * 1024 * 1024
+export const TERMINAL_LOCAL_PASTE_FILE_MAX_PAYLOAD_BYTES = 10 * 1024 * 1024
export const enum TerminalBinaryKind {
input = 1,
@@ -38,6 +44,12 @@ export const enum TerminalBinaryKind {
* See `terminalStreamManager.ts`'s `pasteImage()`. Upload (client→CLI) only; nothing ever sends
* this back down. */
imagePaste = 6,
+ /** A dropped (non-image) FILE — carries the original filename plus its bytes (see
+ * `pasteFile()`'s payload layout), so the daemon can write it to disk on its own machine and
+ * paste that path as text. Never touches the OS clipboard and never replays a keystroke, unlike
+ * `imagePaste` — the goal here is only "the pane gets a valid path". Upload (client→CLI) only;
+ * nothing ever sends this back down. */
+ pasteFile = 7,
}
export interface TerminalBinaryClear {
@@ -92,6 +104,7 @@ function validKind(value: number): value is TerminalBinaryKind {
|| value === TerminalBinaryKind.sync
|| value === TerminalBinaryKind.paste
|| value === TerminalBinaryKind.imagePaste
+ || value === TerminalBinaryKind.pasteFile
}
export function terminalBinaryType(kind: TerminalBinaryKind): string {
@@ -100,21 +113,24 @@ export function terminalBinaryType(kind: TerminalBinaryKind): string {
if (kind === TerminalBinaryKind.keyframe) return 'terminal_keyframe'
if (kind === TerminalBinaryKind.paste) return 'terminal_paste'
if (kind === TerminalBinaryKind.imagePaste) return 'terminal_paste_image'
+ if (kind === TerminalBinaryKind.pasteFile) return 'terminal_paste_file'
return 'terminal_sync'
}
-/** The seal/parse/encode/decode size ceiling for [kind] — paste and imagePaste get a much larger
- * one each; see TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES /
- * TERMINAL_BINARY_IMAGE_PASTE_MAX_CIPHERTEXT_BYTES. */
+/** The seal/parse/encode/decode size ceiling for [kind] — paste, imagePaste and pasteFile each get
+ * a much larger one; see TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES /
+ * TERMINAL_BINARY_IMAGE_PASTE_MAX_CIPHERTEXT_BYTES / TERMINAL_BINARY_PASTE_FILE_MAX_CIPHERTEXT_BYTES. */
function maxCiphertextBytesFor(kind: TerminalBinaryKind): number {
if (kind === TerminalBinaryKind.paste) return TERMINAL_BINARY_PASTE_MAX_CIPHERTEXT_BYTES
if (kind === TerminalBinaryKind.imagePaste) return TERMINAL_BINARY_IMAGE_PASTE_MAX_CIPHERTEXT_BYTES
+ if (kind === TerminalBinaryKind.pasteFile) return TERMINAL_BINARY_PASTE_FILE_MAX_CIPHERTEXT_BYTES
return TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES
}
function maxLocalPayloadBytesFor(kind: TerminalBinaryKind): number {
if (kind === TerminalBinaryKind.paste) return TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES
if (kind === TerminalBinaryKind.imagePaste) return TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES
+ if (kind === TerminalBinaryKind.pasteFile) return TERMINAL_LOCAL_PASTE_FILE_MAX_PAYLOAD_BYTES
return TERMINAL_LOCAL_MAX_PAYLOAD_BYTES
}
@@ -125,7 +141,8 @@ export function encodeTerminalPlain(frame: TerminalBinaryClear): Uint8Array | nu
// to inflate. Nothing on this side inflates an incoming frame, so a client-compressed kind (input,
// sync, and — for now — paste too) would silently hand tmux a compressed blob instead of text.
if ((frame.kind === TerminalBinaryKind.input || frame.kind === TerminalBinaryKind.sync
- || frame.kind === TerminalBinaryKind.paste || frame.kind === TerminalBinaryKind.imagePaste)
+ || frame.kind === TerminalBinaryKind.paste || frame.kind === TerminalBinaryKind.imagePaste
+ || frame.kind === TerminalBinaryKind.pasteFile)
&& frame.compressed) return null
if (frame.kind === TerminalBinaryKind.sync && frame.bytes.length !== 0) return null
const metaBytes = frame.kind === TerminalBinaryKind.keyframe ? 28 : 24
@@ -146,7 +163,8 @@ export function encodeTerminalPlain(frame: TerminalBinaryClear): Uint8Array | nu
export function decodeTerminalPlain(kind: TerminalBinaryKind, flags: number, plaintext: Uint8Array): TerminalBinaryClear | null {
if ((flags & ~FLAG_ZLIB) !== 0
|| ((kind === TerminalBinaryKind.input || kind === TerminalBinaryKind.sync
- || kind === TerminalBinaryKind.paste || kind === TerminalBinaryKind.imagePaste) && flags !== 0)) return null
+ || kind === TerminalBinaryKind.paste || kind === TerminalBinaryKind.imagePaste
+ || kind === TerminalBinaryKind.pasteFile) && flags !== 0)) return null
const metaBytes = kind === TerminalBinaryKind.keyframe ? 28 : 24
if (plaintext.length < metaBytes || (kind === TerminalBinaryKind.sync && plaintext.length !== metaBytes)) return null
const view = new DataView(plaintext.buffer, plaintext.byteOffset, plaintext.byteLength)
@@ -243,6 +261,34 @@ export function decodeTerminalLocal(raw: Uint8Array): TerminalBinaryClear | null
return decodeTerminalPlain(kind, flags, bytes.slice(TERMINAL_LOCAL_HEADER_BYTES))
}
+/** `pasteFile`'s payload (the frame's opaque `bytes`) is itself a tiny sub-format: a 2-byte
+ * big-endian filename length, the UTF-8 filename, then the file's own content — one small header
+ * inside the existing opaque `bytes` field, so the outer frame format needs no changes for this. */
+export function encodePasteFilePayload(filename: string, content: Uint8Array): Uint8Array | null {
+ const nameBytes = utf8(filename)
+ if (nameBytes.length === 0 || nameBytes.length > 0xffff) return null
+ const out = new Uint8Array(2 + nameBytes.length + content.length)
+ const view = new DataView(out.buffer)
+ view.setUint16(0, nameBytes.length, false)
+ out.set(nameBytes, 2)
+ out.set(content, 2 + nameBytes.length)
+ return out
+}
+
+export function decodePasteFilePayload(payload: Uint8Array): { filename: string; content: Uint8Array } | null {
+ if (payload.length < 2) return null
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)
+ const nameLength = view.getUint16(0, false)
+ if (nameLength === 0 || payload.length < 2 + nameLength) return null
+ let filename: string
+ try {
+ filename = new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(2, 2 + nameLength))
+ } catch {
+ return null
+ }
+ return { filename, content: payload.subarray(2 + nameLength) }
+}
+
export const enum TerminalHopDirection {
down = 1,
up = 2,
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index a4a7a142b..d61a0b401 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -4,12 +4,12 @@ import type { RegisteredSession } from './registry.js'
import { TerminalStreamManager, terminalEngineCapabilities } from './terminalStreamManager.js'
import { TERMINAL_ACTION_SUCCEEDED, type TerminalStreamHandle, type TerminalStreamSink } from './terminalTypes.js'
import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'
-import { TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'
+import { encodePasteFilePayload, TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'
import { writeImageToOsClipboard, type OsClipboardImageResult } from './osClipboard.js'
-import { writePasteImageFile } from './pasteImageFiles.js'
+import { writePasteDropFile, writePasteImageFile } from './pasteDropFiles.js'
vi.mock('./osClipboard.js', () => ({ writeImageToOsClipboard: vi.fn() }))
-vi.mock('./pasteImageFiles.js', () => ({ writePasteImageFile: vi.fn() }))
+vi.mock('./pasteDropFiles.js', () => ({ writePasteImageFile: vi.fn(), writePasteDropFile: vi.fn() }))
class FakeStream implements TerminalStreamHandle {
readonly runtime = { backend: 'tmux' as const, paneId: '%1' }
@@ -84,6 +84,7 @@ describe('TerminalStreamManager', () => {
now: () => Date.now(),
})
vi.mocked(writePasteImageFile).mockReset().mockResolvedValue('/fake/paste-images/fake.png')
+ vi.mocked(writePasteDropFile).mockReset().mockImplementation(async (filename: string) => `/fake/paste-drops/id-${filename}`)
vi.mocked(writeImageToOsClipboard).mockReset().mockResolvedValue({ state: 'written' })
})
@@ -308,6 +309,82 @@ describe('TerminalStreamManager', () => {
})
})
+ describe('file paste (dropped non-image file)', () => {
+ const fileContent = Uint8Array.of(0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34)
+ const pasteFile = (streamId: string, filename = 'report.pdf'): TerminalBinaryClear => ({
+ kind: TerminalBinaryKind.pasteFile, streamId, seq: 0, compressed: false,
+ bytes: encodePasteFilePayload(filename, fileContent)!,
+ })
+
+ it('advertises pasteFile in terminal_capabilities', async () => {
+ await manager.handleFrame('web-1', 'terminal_capabilities', { requestId: 'r1' })
+ expect((sent.at(-1)?.payload.features as Record<string, unknown>).pasteFile).toBe(true)
+ })
+
+ it('rejects a legacy JSON terminal_paste_file the same way as terminal_paste/terminal_paste_image', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-file', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+ await manager.handleFrame('web-1', 'terminal_paste_file', { streamId })
+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_BINARY_REQUIRED')
+ })
+
+ it('writes the file under its original name and pastes the resulting path as text — never the clipboard', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-file', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+
+ await manager.handleBinary('web-1', pasteFile(streamId))
+
+ expect(vi.mocked(writePasteDropFile)).toHaveBeenCalledWith('report.pdf', fileContent)
+ expect(vi.mocked(writeImageToOsClipboard)).not.toHaveBeenCalled() // no clipboard attempt at all
+ expect(stream.writes).toHaveLength(0) // no Ctrl+V replay either
+ expect(stream.pastes).toEqual(['/fake/paste-drops/id-report.pdf'])
+ const result = sent.at(-1)!
+ expect(result.type).toBe('terminal_paste_file_result')
+ expect(result.payload).toMatchObject({ streamId, path: '/fake/paste-drops/id-report.pdf' })
+ })
+
+ it('rejects a malformed payload (bad filename-length header) without touching disk', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-file2', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+
+ await manager.handleBinary('web-1', {
+ kind: TerminalBinaryKind.pasteFile, streamId, seq: 0, compressed: false,
+ bytes: Uint8Array.of(0xff, 0xff, 1, 2), // claims a 65535-byte filename, supplies 2 bytes
+ })
+
+ expect(vi.mocked(writePasteDropFile)).not.toHaveBeenCalled()
+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_PASTE_FILE_INVALID')
+ })
+
+ it('reports a genuine write failure as an error', async () => {
+ vi.mocked(writePasteDropFile).mockRejectedValue(new Error('disk full'))
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-file3', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+
+ await manager.handleBinary('web-1', pasteFile(streamId))
+
+ expect(stream.pastes).toHaveLength(0)
+ expect(sent.at(-1)?.payload).toMatchObject({ code: 'TERMINAL_PASTE_FILE_FAILED', streamId, message: 'disk full' })
+ })
+
+ it('ignores an empty file paste', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-file4', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,
+ })
+ const streamId = sent[0].payload.streamId as string
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.pasteFile, streamId, seq: 0, compressed: false, bytes: new Uint8Array() })
+ expect(vi.mocked(writePasteDropFile)).not.toHaveBeenCalled()
+ })
+ })
+
it('does not replay pre-snapshot repaint bytes after the authoritative keyframe', async () => {
outputBeforeOpen = Buffer.from('\u001b[2Jstale repaint')
stream.snapshotBytes = Buffer.from('\u001bcnew prompt text')
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index bf4990439..cacb26d6a 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -4,11 +4,11 @@ import { deflateSync } from 'node:zlib'
import { ENGINES } from '../engines/types.js'
import type { RegisteredSession } from './registry.js'
import { writeImageToOsClipboard } from './osClipboard.js'
-import { writePasteImageFile } from './pasteImageFiles.js'
+import { writePasteDropFile, writePasteImageFile } from './pasteDropFiles.js'
import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'
import { terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type { TerminalStreamHandle, TerminalStreamSize } from './terminalTypes.js'
-import { TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'
+import { decodePasteFilePayload, TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'
/** Ctrl+V as a literal byte (ASCII SUB, 0x16) — the same nudge a real Ctrl+V keystroke sends down
* the ordinary keystroke pipe. Written after the OS clipboard write below succeeds, so the engine
@@ -160,9 +160,11 @@ export class TerminalStreamManager {
return true
case 'terminal_paste':
case 'terminal_paste_image':
+ case 'terminal_paste_file':
// Same reason as terminal_input: a paste is a binary frame (TerminalBinaryKind.paste /
- // .imagePaste) so it rides the same AEAD channel every other terminal byte does, which is
- // what makes it safe to deliver over a relayed (E2EE) connection. Nothing sends this as JSON.
+ // .imagePaste / .pasteFile) so it rides the same AEAD channel every other terminal byte
+ // does, which is what makes it safe to deliver over a relayed (E2EE) connection. Nothing
+ // sends this as JSON.
this.sendError(connId, 'TERMINAL_BINARY_REQUIRED', { streamId: typeof payload.streamId === 'string' ? payload.streamId : undefined })
return true
case 'terminal_scroll':
@@ -181,13 +183,17 @@ export class TerminalStreamManager {
async handleBinary(connId: string, frame: TerminalBinaryClear): Promise<void> {
if (frame.kind !== TerminalBinaryKind.input && frame.kind !== TerminalBinaryKind.paste
- && frame.kind !== TerminalBinaryKind.imagePaste) return
+ && frame.kind !== TerminalBinaryKind.imagePaste && frame.kind !== TerminalBinaryKind.pasteFile) return
const state = this.streams.get(frame.streamId)
if (!state || state.connId !== connId || state.closing) return
if (frame.kind === TerminalBinaryKind.imagePaste) {
await this.pasteImage(state, frame.bytes)
return
}
+ if (frame.kind === TerminalBinaryKind.pasteFile) {
+ await this.pasteFile(state, frame.bytes)
+ return
+ }
if (frame.kind === TerminalBinaryKind.paste) {
await this.paste(state, frame.bytes)
return
@@ -216,6 +222,10 @@ export class TerminalStreamManager {
// Ctrl+V and hoping the engine's own clipboard read finds something local — see
// `pasteImage()` for the frame this unlocks.
imagePaste: true,
+ // A client old enough to predate `TerminalBinaryKind.pasteFile` has no way to hand a
+ // dropped non-image file to a REMOTE pane at all (a local pane needs no capability — it
+ // pastes the file's own path directly, never touching the wire) — see `pasteFile()`.
+ pasteFile: true,
},
engines: terminalEngineCapabilities(this.deps.streamingAvailable),
})
@@ -531,6 +541,41 @@ export class TerminalStreamManager {
})
}
+ /**
+ * A dropped (non-image) FILE — writes it to disk on THIS machine (under its original name, see
+ * `writePasteDropFile`) and pastes that path as plain text, the same `pasteRaw` call `paste()`
+ * uses. Unlike `pasteImage()`, there is no OS-clipboard attempt and no Ctrl+V replay: the goal
+ * here is only "the pane gets a valid path", not "the engine auto-attaches this" — a client only
+ * sends this at all for a genuinely REMOTE pane (a local one pastes its own already-valid path
+ * without ever reaching the wire), so there is no local/remote branch to make here either.
+ */
+ private async pasteFile(state: ActiveStream, payload: Uint8Array): Promise<void> {
+ if (payload.length === 0) return
+ const decoded = decodePasteFilePayload(payload)
+ if (!decoded) {
+ this.sendError(state.connId, 'TERMINAL_PASTE_FILE_INVALID', { streamId: state.streamId, message: 'malformed file paste payload' })
+ return
+ }
+ state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
+ let path: string
+ try {
+ path = await writePasteDropFile(decoded.filename, decoded.content)
+ } catch (error) {
+ this.sendError(state.connId, 'TERMINAL_PASTE_FILE_FAILED', {
+ streamId: state.streamId,
+ message: error instanceof Error ? error.message : 'could not save the dropped file',
+ })
+ return
+ }
+ const result = await state.handle.pasteRaw(path)
+ if (result.state !== 'succeeded') {
+ this.sendError(state.connId, 'TERMINAL_PASTE_FILE_FAILED', { streamId: state.streamId, message: result.reason })
+ if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state)
+ return
+ }
+ this.deps.sendTarget(state.connId, 'terminal_paste_file_result', { streamId: state.streamId, path })
+ }
+
/** Scroll gestures arrive stream-scoped, same as resize — no ordering/seq guard needed since,
* unlike input, an out-of-order or dropped scroll frame just means one gesture scrolled a little
* more or less than intended, never a corrupted stream. The pane's live output stream (already