diff --git a/CHANGELOG.md b/CHANGELOG.md index fd3cdf9..8541081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,17 @@ Harness spec 3.7.0: one display in every client. give the text in full. `paste: full` in the config (or `/settings`) shows pastes whole, as before. +- **Images from the clipboard on macOS and Windows, and JPEG, WebP and GIF** besides PNG: ctrl+v + reads the clipboard through OpenTUI's host clipboard, with `wl-paste` / `xclip` behind it. It + no longer holds the screen while a clipboard answers, and says so when there is no image. + Pasted images are kept under the state directory and removed after a week. +- **Images over SSH.** A terminal cannot hand over the clipboard image of the machine you sit at, + so: an image pasted as text — a `data:image/png;base64,…` URL, or the base64 itself — is + recognised, saved and shown as `[Image N]`; with `ssh -X` the forwarded X clipboard is read; in + kitty the terminal itself is asked for its clipboard (its clipboard protocol, OSC 5522 — it asks + you once); and when nothing came through, one line names what works: the data URL, `@path` after + copying the file over, or attaching it to the same chat in the web, Desktop or Android app. + ### Changed - **The terminal opened from the web UI or Desktop picks a shell that exists.** `$SHELL` when diff --git a/src/project/image.ts b/src/project/image.ts index d5e87b2..d3e28bd 100644 --- a/src/project/image.ts +++ b/src/project/image.ts @@ -1,6 +1,6 @@ // Images for vision models: read, size-checked, downscaled when ImageMagick is there. -import { readFileSync, statSync } from "node:fs" -import { extname } from "node:path" +import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { extname, join } from "node:path" import { imageSize } from "../provider/tokens.ts" import type { ImagePart } from "../provider/types.ts" @@ -43,19 +43,147 @@ export function loadImage(path: string): ImagePart | string { return { type: "image", mime: "image/jpeg", data: Buffer.from(r.stdout).toString("base64") } } -/** An image on the clipboard (Wayland or X11), saved to `dest`; undefined when there is none. */ -export function clipboardImage(dest: string): string | undefined { - const tries: string[][] = [] - if (Bun.which("wl-paste")) tries.push(["wl-paste", "--no-newline", "--type", "image/png"]) - if (Bun.which("xclip")) tries.push(["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]) - for (const cmd of tries) { - const r = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "ignore" }) - const out = r.stdout - // A PNG starts with \x89PNG; anything else is text or nothing. - if (r.exitCode === 0 && out.length > 8 && out[0] === 0x89 && out[1] === 0x50) { - Bun.write(dest, out) - return dest - } - } +/** What a pasted or clipboard image may be, in the order asked for. */ +export const CLIPBOARD_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const +const EXT_OF: Record = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif" } +/** The most a pasted image may be before it is saved (loadImage shrinks, or refuses, when it is sent). */ +export const MAX_PASTE_BYTES = 20_000_000 + +/** What kind of image these bytes are, by their signature — never by what they were called. */ +export function sniffImage(b: Uint8Array): (typeof CLIPBOARD_TYPES)[number] | undefined { + if (b.length < 12) return undefined + if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return "image/png" + if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg" + if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38) return "image/gif" + if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) return "image/webp" return undefined } + +let saved = 0 +/** Save pasted image bytes under `dir` (made if missing), named by time and kind. */ +export function savePastedImage(dir: string, bytes: Uint8Array, mime: string): string { + mkdirSync(dir, { recursive: true, mode: 0o700 }) + const path = join(dir, `paste-${Date.now()}-${++saved}${EXT_OF[mime] ?? ".png"}`) + writeFileSync(path, bytes, { mode: 0o600 }) + return path +} + +/** Pasted text that is an image: a `data:image/(png|jpeg|webp|gif);base64,…` URL, or bare base64 + * that decodes to an image's signature — the way an image gets through a terminal that cannot + * hand over a clipboard image (over SSH). The bytes, a reason it is refused, or undefined when + * the text is not an image at all. */ +export function imageFromText(text: string): { mime: string; bytes: Uint8Array } | { error: string } | undefined { + let t = text.trim() + if (t.length < 24) return undefined + const url = /^data:image\/(?:png|jpeg|webp|gif);base64,/i.exec(t.slice(0, 40)) + if (url) t = t.slice(url[0].length) + // Bare base64 is looked at only when it starts as an image would: PNG, JPEG, GIF, WebP. + else if (!/^(?:iVBORw0KGgo|\/9j\/|R0lGOD|UklGR)/.test(t)) return undefined + // Line breaks are a terminal's or a mail program's; anything else is not base64. + if (/[^A-Za-z0-9+/=\s]/.test(t)) return undefined + t = t.replace(/\s+/g, "") + if (Math.floor((t.length * 3) / 4) > MAX_PASTE_BYTES) return { error: `the pasted image is over ${MAX_PASTE_BYTES / 1e6} MB — copy the file over and use @path` } + const bytes = new Uint8Array(Buffer.from(t, "base64")) + const mime = sniffImage(bytes) + if (!mime) return url ? { error: "the pasted data URL is not a PNG, JPEG, WebP or GIF image" } : undefined + return { mime, bytes } +} + +export type ClipboardImage = { status: "read"; mime: string; bytes: Uint8Array } | { status: "empty" | "unsupported" | "too-large" } + +type Env = Record + +/** The clipboard programs that can hand over an image here, in order: Wayland's, then X11's (the + * local display, or the one `ssh -X` forwards). */ +export function clipboardCommands(env: Env = process.env, which: (cmd: string) => string | null = Bun.which): ((type: string) => string[])[] { + const out: ((type: string) => string[])[] = [] + if (env.WAYLAND_DISPLAY && which("wl-paste")) out.push((type) => ["wl-paste", "--no-newline", "--type", type]) + if (env.DISPLAY && which("xclip")) out.push((type) => ["xclip", "-selection", "clipboard", "-t", type, "-o"]) + return out +} + +async function runFor(cmd: string[], timeoutMs: number): Promise { + try { + const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "ignore", env: process.env }) + const timer = setTimeout(() => p.kill(), timeoutMs) + try { + const out = new Uint8Array(await new Response(p.stdout).arrayBuffer()) + return (await p.exited) === 0 ? out : undefined + } finally { + clearTimeout(timer) + } + } catch { + return undefined + } +} + +/** The fallback: ask wl-paste or xclip for each kind of image in turn. */ +async function clipboardImageByProgram(o: { env?: Env; which?: (cmd: string) => string | null; timeoutMs: number }): Promise { + const commands = clipboardCommands(o.env, o.which) + if (!commands.length) return { status: "unsupported" } + for (const command of commands) { + for (const type of CLIPBOARD_TYPES) { + const out = await runFor(command(type), o.timeoutMs) + if (!out || !sniffImage(out)) continue + if (out.length > MAX_PASTE_BYTES) return { status: "too-large" } + return { status: "read", mime: sniffImage(out)!, bytes: out } + } + } + return { status: "empty" } +} + +export interface HostClipboardLike { + read(o: { preferredTypes: readonly [string, ...string[]] }): Promise<{ status: string; representation?: { mimeType: string; bytes: Uint8Array } }> + dispose(): Promise +} + +/** An image on this machine's clipboard — PNG, JPEG, WebP or GIF; Linux (Wayland, X11), macOS and + * Windows through OpenTUI's host clipboard, with wl-paste / xclip where that is not available. + * Never blocks: everything is awaited. `host`: the clipboard to ask (tests); by default OpenTUI's. */ +export async function clipboardImage(o: { env?: Env; which?: (cmd: string) => string | null; timeoutMs?: number; host?: () => HostClipboardLike | Promise } = {}): Promise { + const timeoutMs = o.timeoutMs ?? 3000 + let host: HostClipboardLike | undefined + let hostEmpty = false + try { + host = await (o.host ?? (async () => (await import("@opentui/core")).createHostClipboard({ timeoutMs, maxReadBytes: MAX_PASTE_BYTES }) as unknown as HostClipboardLike))() + const r = await host.read({ preferredTypes: CLIPBOARD_TYPES }) + if (r.status === "read" && r.representation) { + // Believed by its bytes: a clipboard may call anything image/png. + const mime = sniffImage(r.representation.bytes) + if (mime) return { status: "read", mime, bytes: r.representation.bytes } + } + if (r.status === "limit-exceeded") return { status: "too-large" } + // Something that is not an image (text called image/png) is no image on the clipboard. + hostEmpty = r.status === "empty" || r.status === "read" + } catch { + // No host clipboard in this build or on this machine: the programs below. + } finally { + void host?.dispose().catch(() => {}) + } + // The programs are asked as well when the host clipboard found nothing: over `ssh -X` the + // clipboard that matters is the forwarded X display's. + const byProgram = await clipboardImageByProgram({ env: o.env, which: o.which, timeoutMs }) + return byProgram.status === "unsupported" && hostEmpty ? { status: "empty" } : byProgram +} + +/** Pasted images are copies: those older than `days` go when the TUI starts. */ +export function cleanPastedImages(dir: string, days = 7, now = Date.now()): number { + let gone = 0 + let names: string[] + try { + names = readdirSync(dir) + } catch { + return 0 + } + for (const name of names) { + if (!/^paste-[\w-]+\.(png|jpe?g|webp|gif)$/.test(name)) continue + const path = join(dir, name) + try { + if (now - statSync(path).mtimeMs > days * 86_400_000) { + rmSync(path) + gone++ + } + } catch {} + } + return gone +} diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 041af38..ad22d7b 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -10,7 +10,7 @@ import { COMMANDS, findCommand, type CommandCtx } from "./commands.ts" import { Dialog, type DialogSpec } from "./components/dialog.tsx" import { Messages } from "./components/messages.tsx" import { PermissionPrompt } from "./components/permission.tsx" -import { copiedMessage, copyText } from "./clipboard.ts" +import { copiedMessage, copyText, isRemote } from "./clipboard.ts" import { QuestionCard } from "./components/question.tsx" import { PlanCard } from "./components/plancard.tsx" import { PlanPanel } from "./components/plan.tsx" @@ -83,15 +83,20 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => // The finished-reply notice (notify.ts): a reply that ends, or an answer the agent waits for, // while the terminal is not focused — the bell and a desktop notification naming the session. const focus = new FocusWatch((ev, fn) => renderer.on(ev, fn)) + /** Raw sequences to the terminal, and the OSC replies it sends back. */ + const writeRaw = (seq: string) => { + const r = renderer as unknown as { writeOut?: (s: string) => void } + if (r.writeOut) r.writeOut(seq) + else process.stdout.write(seq) + } + const terminal = { write: writeRaw, subscribeOsc: (h: (sequence: string) => void) => renderer.subscribeOsc(h) } const notice = (what: "finished" | "waiting" | "failed") => { if (focus.focused || app.loaded.config.notify === false) return const id = app.engine.sessionId const title = id ? app.store?.session(id)?.title : undefined const seq = noticeSequence(noticeText(title, what)) - const r = renderer as unknown as { writeOut?: (s: string) => void } try { - if (r.writeOut) r.writeOut(seq) - else process.stdout.write(seq) + writeRaw(seq) } catch {} } app.bus.on((e) => e.type === "done" && e.reason !== "cancelled" && notice(e.reason === "error" ? "failed" : "finished")) @@ -668,7 +673,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => - !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> + !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} remote={() => isRemote(renderer as never)} terminal={terminal} note={(text, warn) => (warn ? view.info(text, "warn") : text.length > 60 ? view.info(text) : flash(text))} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> (rev(), share.label())} spend={spend} team={teamWord} /> diff --git a/src/tui/components/prompt.tsx b/src/tui/components/prompt.tsx index d90399d..7fd0462 100644 --- a/src/tui/components/prompt.tsx +++ b/src/tui/components/prompt.tsx @@ -1,8 +1,9 @@ import { RGBA, SyntaxStyle, type PasteEvent, type TextareaRenderable } from "@opentui/core" -import { existsSync, mkdirSync } from "node:fs" +import { existsSync } from "node:fs" import { join } from "node:path" import { paths } from "../../config/paths.ts" -import { clipboardImage, isImage } from "../../project/image.ts" +import { cleanPastedImages, clipboardImage, CLIPBOARD_TYPES, imageFromText, isImage, savePastedImage, type ClipboardImage } from "../../project/image.ts" +import { kittyClipboardLikely, kittyReadImage, type KittyRead, type OscTerminal } from "../kitty-clipboard.ts" import { escapeMention } from "../../project/attach.ts" import fuzzysort from "fuzzysort" import { createMemo, createSignal, For, onCleanup, Show } from "solid-js" @@ -26,6 +27,14 @@ interface Popup { token: number } +/** Where pasted images are kept until they are old (cleanPastedImages). */ +const CLIP_DIR = join(paths.state, "clipboard") +/** Sent with a clipboard read so a terminal that asks the person can remember the answer for + * this run of the program. */ +const CLIPBOARD_PASSWORD = crypto.randomUUID() +/** Said when an image paste over SSH found nothing: the ways that do work. */ +export const REMOTE_IMAGE_HINT = "no image reached this terminal over SSH — paste it as a data URL (data:image/png;base64,…), copy the file here and use @path, or attach it to this chat in the web, Desktop or Android app" + /** What the app may ask of the box beyond its text. */ export interface PromptHandle { /** The box's text with every paste placeholder replaced by what it stands for. */ @@ -59,6 +68,12 @@ export function Prompt(p: { onSubmit: (text: string, shown?: string) => boolean | void ref?: (r: TextareaRenderable) => void handle?: (h: PromptHandle) => void + /** Whether the terminal is on another machine (SSH): its clipboard is not this machine's. */ + remote?: () => boolean + /** The terminal, for asking it for its clipboard (kitty's protocol). */ + terminal?: OscTerminal + /** A short line for the person (nothing on the clipboard, why an image was not taken). */ + note?: (text: string, warn?: boolean) => void /** The messages waiting to go in: how many, take one out, put it back. */ queue?: { count(): number; take(index: number): string | undefined; putBack(index: number, text: string): void } /** A burst of ↑/↓ that was a mouse wheel: scroll the transcript `lines` up (-1) or down (1). */ @@ -77,6 +92,8 @@ export function Prompt(p: { }) onCleanup(() => style().destroy()) let marks: Placeholders | undefined + // Pasted images are copies; old ones go when the box is made. + cleanPastedImages(CLIP_DIR) /** The box's text as it is sent: placeholders replaced by what they stand for. */ const full = () => marks?.expanded() ?? area?.plainText ?? "" const pasteWhole = () => app.loaded.config.paste === "full" @@ -176,14 +193,35 @@ export function Prompt(p: { marks.insert({ kind: "image", label: imageLabel(marks.nextImage()), content: ref }) } - /** An image on the clipboard becomes a saved copy and a placeholder for it. */ - const pasteClipboardImage = (): boolean => { - const dir = join(paths.state, "clipboard") - mkdirSync(dir, { recursive: true }) - const saved = clipboardImage(join(dir, `paste-${Date.now()}.png`)) - if (!saved || !area) return false - insertImage(saved) - return true + /** An image on the clipboard becomes a saved copy and a placeholder for it. Awaited, never + * blocking: the box stays usable while a clipboard (or the person, asked by their terminal) + * takes its time, and the placeholder goes in where the cursor is when the image arrives. + * + * Over SSH this machine's clipboard is not the person's. What can still work: the X display + * `ssh -X` forwards, and a terminal that hands its clipboard over itself (kitty). When neither + * does, one line says what does. */ + let reading = false + const pasteClipboardImage = async () => { + if (reading || !area) return + reading = true + try { + const remote = p.remote?.() ?? false + let r: ClipboardImage | KittyRead = { status: "unsupported" } + if (!remote) r = await clipboardImage() + else if (process.env.DISPLAY) r = await clipboardImage({ env: { DISPLAY: process.env.DISPLAY } }) + if (r.status !== "read" && remote && p.terminal && kittyClipboardLikely()) { + p.note?.("asking the terminal for the image on its clipboard…") + r = await kittyReadImage(p.terminal, { types: CLIPBOARD_TYPES, password: CLIPBOARD_PASSWORD, name: "LLeMbas CLI" }) + } + if (r.status === "read") return insertImage(savePastedImage(CLIP_DIR, r.bytes, r.mime)) + if (r.status === "too-large") return p.note?.("the image on the clipboard is too large to paste — save it and use @path", true) + if (r.status === "denied") return p.note?.("the terminal did not allow reading its clipboard", true) + p.note?.(remote ? REMOTE_IMAGE_HINT : r.status === "unsupported" ? "no clipboard to read an image from here (install wl-clipboard or xclip), or use @path" : "no image on the clipboard") + } catch (e) { + p.note?.(`the clipboard could not be read: ${(e as Error).message.split("\n")[0]}`, true) + } finally { + reading = false + } } /** A pasted path to an image (dragged from a file manager: quoted, escaped or file://) → @path. */ @@ -203,9 +241,17 @@ export function Prompt(p: { // Some terminals hand over an image-only clipboard as an empty bracketed paste. if (!text.trim()) { e.preventDefault() - pasteClipboardImage() + void pasteClipboardImage() return } + // An image pasted as text — a data URL, or base64 of one: the way through a terminal that + // cannot hand over a clipboard image (over SSH). + const data = imageFromText(text) + if (data) { + e.preventDefault() + if ("error" in data) return p.note?.(data.error, true) + return insertImage(savePastedImage(CLIP_DIR, data.bytes, data.mime)) + } const img = imagePath(text) e.preventDefault() if (img) return insertImage(img) @@ -294,7 +340,10 @@ export function Prompt(p: { onPaste={onPaste} onKeyDown={(e) => { if (!area) return - if (e.ctrl && e.name === "v" && pasteClipboardImage()) return e.preventDefault() + if (e.ctrl && e.name === "v" && !e.shift && !e.meta) { + void pasteClipboardImage() + return e.preventDefault() + } if (e.ctrl && e.name === "b" && p.onBackground) { p.onBackground() return e.preventDefault() diff --git a/src/tui/kitty-clipboard.ts b/src/tui/kitty-clipboard.ts new file mode 100644 index 0000000..99c4fc0 --- /dev/null +++ b/src/tui/kitty-clipboard.ts @@ -0,0 +1,142 @@ +// Reading an image from the clipboard through the terminal itself: kitty's clipboard protocol +// (OSC 5522). It is the one way a clipboard image crosses an SSH connection — the terminal on the +// person's own machine reads its clipboard and sends the bytes down the same connection the +// keystrokes use. OSC 52 carries text only. +// +// → ESC ] 5522 ; type=read[:id=…:pw=…:name=…] ; base64("image/png image/jpeg") ST +// ← ESC ] 5522 ; type=read:status=OK ST +// ← ESC ] 5522 ; type=read:status=DATA:mime=base64(mime) ; base64(chunk) ST (chunks ≤ 4096 bytes) +// ← ESC ] 5522 ; type=read:status=DONE ST +// ← ESC ] 5522 ; type=read:status=EPERM | ENOSYS | EBUSY ST (instead of OK) +// +// The request "." lists the kinds on the clipboard and needs no permission; the read itself the +// terminal asks the person about (once, when it remembers the password sent with it). +const OSC = "\x1b]5522;" +const ST = "\x1b\\" + +export interface OscTerminal { + /** Write to the terminal. */ + write(data: string): void + /** Every OSC sequence the terminal sends, whole. Returns what unsubscribes. */ + subscribeOsc(handler: (sequence: string) => void): () => void +} + +const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64") + +/** One OSC 5522 sequence as its metadata and payload; undefined for any other sequence. */ +export function parse5522(sequence: string): { meta: Record; payload: string } | undefined { + if (!sequence.startsWith(OSC)) return undefined + const body = sequence.slice(OSC.length).replace(/(?:\x1b\\|\x07)$/, "") + const cut = body.indexOf(";") + const head = cut === -1 ? body : body.slice(0, cut) + const meta: Record = {} + for (const pair of head.split(":")) { + const eq = pair.indexOf("=") + if (eq > 0) meta[pair.slice(0, eq)] = pair.slice(eq + 1) + } + return { meta, payload: cut === -1 ? "" : body.slice(cut + 1) } +} + +/** Whether the terminal is one that speaks the protocol: kitty (also through `ssh`, which carries + * TERM), and not inside a multiplexer that would swallow the replies. */ +export function kittyClipboardLikely(env: Record = process.env): boolean { + if (env.TMUX || env.STY || env.ZELLIJ) return false + return !!env.KITTY_WINDOW_ID || /kitty/i.test(env.TERM ?? "") +} + +export type KittyRead = { status: "read"; mime: string; bytes: Uint8Array } | { status: "unsupported" | "empty" | "denied" | "busy" | "too-large" | "timed-out" } + +interface ReadOptions { + types: readonly string[] + /** How long the terminal has to answer the listing: one that does not know the protocol says nothing. */ + listTimeoutMs?: number + /** How long the read may take — the person may be looking at the terminal's permission question. */ + readTimeoutMs?: number + maxBytes?: number + /** Sent with the read so the terminal can remember the person's answer for this program. */ + password?: string + name?: string +} + +/** One request and its replies: resolves with the data packets by kind, or how it failed. */ +function request(term: OscTerminal, meta: string, payload: string, id: string, timeoutMs: number, maxBytes: number): Promise<{ status: "done"; data: Map } | { status: Exclude }> { + return new Promise((resolve) => { + const data = new Map() + let total = 0 + const finish = (r: Parameters[0]) => { + clearTimeout(timer) + off() + resolve(r) + } + const timer = setTimeout(() => finish({ status: "timed-out" }), timeoutMs) + const off = term.subscribeOsc((sequence) => { + const p = parse5522(sequence) + // Another request's reply (a different id) is not ours; a terminal that sends no id back is believed. + if (!p || p.meta.type !== "read" || (p.meta.id !== undefined && p.meta.id !== id)) return + switch (p.meta.status) { + case "OK": + return + case "DATA": { + const mime = Buffer.from(p.meta.mime ?? "", "base64").toString("utf8") + const chunk = new Uint8Array(Buffer.from(p.payload, "base64")) + total += chunk.length + if (total > maxBytes) return finish({ status: "too-large" }) + const list = data.get(mime) ?? [] + list.push(chunk) + data.set(mime, list) + return + } + case "DONE": + return finish({ status: "done", data }) + case "EPERM": + return finish({ status: "denied" }) + case "EBUSY": + return finish({ status: "busy" }) + default: + return finish({ status: "unsupported" }) + } + }) + try { + term.write(`${OSC}type=read:id=${id}${meta};${b64(payload)}${ST}`) + } catch { + finish({ status: "unsupported" }) + } + }) +} + +const join = (chunks: Uint8Array[]) => { + const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)) + let at = 0 + for (const c of chunks) { + out.set(c, at) + at += c.length + } + return out +} + +let serial = 0 + +/** An image from the clipboard of the terminal's own machine: the kinds are listed first (no + * permission needed, and a terminal that does not answer does not speak the protocol), then the + * first of `types` that is there is read. */ +export async function kittyReadImage(term: OscTerminal, o: ReadOptions): Promise { + const maxBytes = o.maxBytes ?? 20_000_000 + const id = `lembas${process.pid}.${++serial}` + const listed = await request(term, "", ".", id, o.listTimeoutMs ?? 1500, 65_536) + // Silence within the listing's time is a terminal that does not know OSC 5522. + if (listed.status === "timed-out") return { status: "unsupported" } + if (listed.status !== "done") return { status: listed.status } + const kinds = new Set( + [...listed.data.values()] + .flatMap((chunks) => Buffer.from(join(chunks)).toString("utf8").split(/\s+/)) + .filter(Boolean), + ) + const type = o.types.find((t) => kinds.has(t)) + if (!type) return { status: "empty" } + const auth = o.password && o.name ? `:pw=${b64(o.password)}:name=${b64(o.name)}` : "" + const read = await request(term, auth, type, `${id}r`, o.readTimeoutMs ?? 60_000, maxBytes) + if (read.status !== "done") return { status: read.status } + const chunks = read.data.get(type) ?? [...read.data.values()][0] + if (!chunks?.length) return { status: "empty" } + return { status: "read", mime: type, bytes: join(chunks) } +} diff --git a/tests/clipboard-image.test.ts b/tests/clipboard-image.test.ts new file mode 100644 index 0000000..247a5c0 --- /dev/null +++ b/tests/clipboard-image.test.ts @@ -0,0 +1,207 @@ +// Images that reach the prompt box other than as a file: the clipboard (OpenTUI's host clipboard, +// wl-paste / xclip behind it), text that is an image (a data URL, base64), and the terminal's own +// clipboard through kitty's OSC 5522. +import { expect, test } from "bun:test" +import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { cleanPastedImages, clipboardCommands, clipboardImage, imageFromText, MAX_PASTE_BYTES, savePastedImage, sniffImage } from "../src/project/image.ts" +import { kittyClipboardLikely, kittyReadImage, parse5522, type OscTerminal } from "../src/tui/kitty-clipboard.ts" + +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64") +const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10]), Buffer.from("JFIF\0"), Buffer.alloc(16)]) +const GIF = Buffer.concat([Buffer.from("GIF89a"), Buffer.alloc(16)]) +const WEBP = Buffer.concat([Buffer.from("RIFF"), Buffer.from([4, 0, 0, 0]), Buffer.from("WEBPVP8 "), Buffer.alloc(8)]) + +test("an image is known by its bytes", () => { + expect(sniffImage(PNG)).toBe("image/png") + expect(sniffImage(JPEG)).toBe("image/jpeg") + expect(sniffImage(GIF)).toBe("image/gif") + expect(sniffImage(WEBP)).toBe("image/webp") + expect(sniffImage(Buffer.from(""))).toBeUndefined() + expect(sniffImage(Buffer.from("RIFF....WAVEfmt "))).toBeUndefined() + expect(sniffImage(new Uint8Array(3))).toBeUndefined() +}) + +test("pasted text that is an image: a data URL, base64 with line breaks, bare base64", () => { + const b64 = PNG.toString("base64") + expect(imageFromText(`data:image/png;base64,${b64}`)).toEqual({ mime: "image/png", bytes: new Uint8Array(PNG) }) + // What it is called does not decide what it is. + expect(imageFromText(` data:image/jpeg;base64,${b64}\n`)).toMatchObject({ mime: "image/png" }) + expect(imageFromText(`data:image/jpeg;base64,${JPEG.toString("base64")}`)).toMatchObject({ mime: "image/jpeg" }) + // Wrapped at 76 columns, as base64(1) and mail programs write it. + const wrapped = b64.replace(/(.{20})/g, "$1\n") + expect(imageFromText(wrapped)).toMatchObject({ mime: "image/png" }) + expect(imageFromText(`data:image/gif;base64,${GIF.toString("base64")}`)).toMatchObject({ mime: "image/gif" }) + expect(imageFromText(WEBP.toString("base64"))).toMatchObject({ mime: "image/webp" }) +}) + +test("pasted text that is not an image stays text; a data URL that is not one is refused in words", () => { + expect(imageFromText("hello there, this is a perfectly ordinary sentence")).toBeUndefined() + // Starts as a PNG would, but is prose. + expect(imageFromText("iVBORw0KGgo is how a PNG starts in base64, did you know?")).toBeUndefined() + // Base64 of something else. + expect(imageFromText(Buffer.from("just some bytes, nothing more than that").toString("base64"))).toBeUndefined() + expect(imageFromText("data:text/plain;base64,aGVsbG8gd29ybGQsIGhlbGxvIHdvcmxk")).toBeUndefined() + expect(imageFromText(`data:image/svg+xml;base64,${Buffer.from("".repeat(8)).toString("base64")}`)).toBeUndefined() + expect(imageFromText(`data:image/png;base64,${Buffer.from("not an image at all, only text").toString("base64")}`)).toEqual({ error: "the pasted data URL is not a PNG, JPEG, WebP or GIF image" }) + const huge = `data:image/png;base64,${"A".repeat(Math.ceil((MAX_PASTE_BYTES * 4) / 3) + 8)}` + expect(imageFromText(huge)).toMatchObject({ error: expect.stringContaining("over 20 MB") }) +}) + +test("the clipboard: the host clipboard's image, believed by its bytes — JPEG too", async () => { + let disposed = 0 + const host = (status: string, bytes?: Uint8Array, mimeType = "image/png") => () => ({ + read: async (o: { preferredTypes: readonly string[] }) => { + expect(o.preferredTypes).toEqual(["image/png", "image/jpeg", "image/webp", "image/gif"]) + return { status, ...(bytes ? { representation: { mimeType, bytes } } : {}) } + }, + dispose: async () => void disposed++, + }) + const none = { env: {}, which: () => null } + expect(await clipboardImage({ ...none, host: host("read", JPEG, "image/png") })).toEqual({ status: "read", mime: "image/jpeg", bytes: JPEG }) + expect(await clipboardImage({ ...none, host: host("empty") })).toEqual({ status: "empty" }) + expect(await clipboardImage({ ...none, host: host("unsupported") })).toEqual({ status: "unsupported" }) + expect(await clipboardImage({ ...none, host: host("limit-exceeded") })).toEqual({ status: "too-large" }) + // Text on the clipboard handed over as an "image" is not one. + expect(await clipboardImage({ ...none, host: host("read", Buffer.from("plain text, not a picture")) })).toEqual({ status: "empty" }) + // A host clipboard that cannot even be made (no native library): the programs, here none. + expect( + await clipboardImage({ + ...none, + host: () => { + throw new Error("no native clipboard") + }, + }), + ).toEqual({ status: "unsupported" }) + expect(disposed).toBe(5) +}) + +test("the clipboard: where the host clipboard has nothing, xclip on the display there is (ssh -X)", async () => { + expect(clipboardCommands({}, () => "/usr/bin/x").length).toBe(0) + expect(clipboardCommands({ DISPLAY: "localhost:10.0" }, () => "/usr/bin/x").map((c) => c("image/png")[0])).toEqual(["xclip"]) + expect(clipboardCommands({ WAYLAND_DISPLAY: "wayland-0", DISPLAY: ":0" }, () => "/usr/bin/x").map((c) => c("image/png")[0])).toEqual(["wl-paste", "xclip"]) + expect(clipboardCommands({ DISPLAY: ":0" }, () => null)).toEqual([]) + // A stand-in xclip that has a JPEG and no PNG. + const bin = mkdtempSync(join(tmpdir(), "lembas-clip-")) + writeFileSync(join(bin, "pic.jpg"), JPEG) + writeFileSync(join(bin, "xclip"), `#!/bin/sh\ncase "$*" in *image/jpeg*) cat "${bin}/pic.jpg";; *) exit 1;; esac\n`) + chmodSync(join(bin, "xclip"), 0o755) + const path = process.env.PATH + process.env.PATH = `${bin}:${path}` + try { + const empty = () => ({ read: async () => ({ status: "empty" }), dispose: async () => {} }) + const r = await clipboardImage({ env: { DISPLAY: "localhost:10.0" }, which: (c) => (c === "xclip" ? join(bin, "xclip") : null), host: empty }) + expect(r).toEqual({ status: "read", mime: "image/jpeg", bytes: new Uint8Array(JPEG) }) + } finally { + process.env.PATH = path + } +}) + +test("pasted images are saved by kind, and old ones are cleaned up — nothing else in the folder", () => { + const dir = join(mkdtempSync(join(tmpdir(), "lembas-clip-")), "clipboard") + const a = savePastedImage(dir, PNG, "image/png") + const b = savePastedImage(dir, JPEG, "image/jpeg") + expect(a).toMatch(/paste-\d+-\d+\.png$/) + expect(b).toMatch(/paste-\d+-\d+\.jpg$/) + expect(a).not.toBe(b) + expect(readFileSync(b).equals(JPEG)).toBe(true) + writeFileSync(join(dir, "notes.txt"), "mine") + const old = new Date(Date.now() - 9 * 86_400_000) + utimesSync(a, old, old) + utimesSync(join(dir, "notes.txt"), old, old) + expect(cleanPastedImages(dir)).toBe(1) + expect(readdirSync(dir).sort()).toEqual([b.split("/").pop()!, "notes.txt"].sort()) + expect(existsSync(a)).toBe(false) + expect(cleanPastedImages(join(dir, "missing"))).toBe(0) +}) + +// A terminal that speaks kitty's clipboard protocol, as its specification describes it. +function kitty(clipboard: Record, o: { deny?: boolean; silent?: boolean; echoId?: boolean; bel?: boolean; busy?: boolean } = {}) { + const handlers = new Set<(s: string) => void>() + const wrote: string[] = [] + const end = o.bel ? "\x07" : "\x1b\\" + const send = (meta: string, payload = "") => queueMicrotask(() => handlers.forEach((h) => h(`\x1b]5522;${meta}${payload ? `;${payload}` : ""}${end}`))) + const b64 = (s: string | Uint8Array) => Buffer.from(s as never).toString("base64") + const term: OscTerminal = { + subscribeOsc: (h) => (handlers.add(h), () => void handlers.delete(h)), + write(data) { + wrote.push(data) + if (o.silent) return + const p = parse5522(data)! + const id = o.echoId === false ? "" : `:id=${p.meta.id}` + const want = Buffer.from(p.payload, "base64").toString("utf8") + if (o.busy) return send(`type=read:status=EBUSY${id}`) + if (want === ".") { + send(`type=read:status=OK${id}`) + send(`type=read:status=DATA:mime=${b64(".")}${id}`, b64(Object.keys(clipboard).join(" "))) + return send(`type=read:status=DONE${id}`) + } + if (o.deny) return send(`type=read:status=EPERM${id}`) + send(`type=read:status=OK${id}`) + for (const mime of want.split(" ")) { + const bytes = clipboard[mime] + if (!bytes) continue + // Chunks of at most 4096 bytes, each padded on its own. + for (let at = 0; at < bytes.length; at += 4096) send(`type=read:status=DATA:mime=${b64(mime)}${id}`, b64(bytes.subarray(at, at + 4096))) + } + send(`type=read:status=DONE${id}`) + }, + } + return { term, wrote, listeners: () => handlers.size } +} + +const TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"] + +test("kitty's clipboard protocol: the kinds are listed, the first image kind is read in chunks and put together", async () => { + // Larger than two chunks, and not a multiple of three: every chunk's padding matters. + const big = Buffer.concat([JPEG, Buffer.from(Array.from({ length: 10_001 }, (_, i) => i % 251))]) + const k = kitty({ "text/plain": Buffer.from("words"), "image/jpeg": big }) + const r = await kittyReadImage(k.term, { types: TYPES, password: "secret", name: "LLeMbas CLI" }) + expect(r.status).toBe("read") + expect(r).toMatchObject({ mime: "image/jpeg" }) + expect(Buffer.from((r as { bytes: Uint8Array }).bytes).equals(big)).toBe(true) + // The listing asks for "." and carries no password; the read names the kind and who asks. + expect(parse5522(k.wrote[0]!)).toMatchObject({ meta: { type: "read" }, payload: Buffer.from(".").toString("base64") }) + expect(k.wrote[0]).not.toContain("pw=") + const read = parse5522(k.wrote[1]!)! + expect(Buffer.from(read.payload, "base64").toString()).toBe("image/jpeg") + expect(Buffer.from(read.meta.pw!, "base64").toString()).toBe("secret") + expect(Buffer.from(read.meta.name!, "base64").toString()).toBe("LLeMbas CLI") + expect(read.meta.id).toMatch(/^[a-zA-Z0-9\-_+.]+$/) + expect(k.wrote.every((w) => w.startsWith("\x1b]5522;") && w.endsWith("\x1b\\"))).toBe(true) + expect(k.listeners()).toBe(0) // nothing left listening +}) + +test("kitty's clipboard protocol: no image, a refusal, a busy multiplexer, BEL terminators, no id echoed", async () => { + expect(await kittyReadImage(kitty({ "text/plain": Buffer.from("words") }).term, { types: TYPES })).toEqual({ status: "empty" }) + expect(await kittyReadImage(kitty({ "image/png": PNG }, { deny: true }).term, { types: TYPES })).toEqual({ status: "denied" }) + expect(await kittyReadImage(kitty({ "image/png": PNG }, { busy: true }).term, { types: TYPES })).toEqual({ status: "busy" }) + const r = await kittyReadImage(kitty({ "image/png": PNG }, { bel: true, echoId: false }).term, { types: TYPES }) + expect(r).toMatchObject({ status: "read", mime: "image/png" }) + expect(Buffer.from((r as { bytes: Uint8Array }).bytes).equals(PNG)).toBe(true) + expect(await kittyReadImage(kitty({ "image/png": Buffer.alloc(9000) }).term, { types: TYPES, maxBytes: 8000 })).toEqual({ status: "too-large" }) +}) + +test("kitty's clipboard protocol: a terminal that says nothing does not speak it, and nobody waits long", async () => { + const k = kitty({}, { silent: true }) + const t0 = performance.now() + expect(await kittyReadImage(k.term, { types: TYPES, listTimeoutMs: 80 })).toEqual({ status: "unsupported" }) + expect(performance.now() - t0).toBeLessThan(1000) + expect(k.wrote.length).toBe(1) // the read was never asked + expect(k.listeners()).toBe(0) + // Another program's reply (a different id) is not taken for ours. + const handlers = new Set<(s: string) => void>() + const other: OscTerminal = { subscribeOsc: (h) => (handlers.add(h), () => void handlers.delete(h)), write: () => queueMicrotask(() => handlers.forEach((h) => h("\x1b]5522;type=read:status=DONE:id=someone-else\x1b\\"))) } + expect(await kittyReadImage(other, { types: TYPES, listTimeoutMs: 80 })).toEqual({ status: "unsupported" }) +}) + +test("which terminals are asked: kitty, also through ssh; never inside a multiplexer", () => { + expect(kittyClipboardLikely({ TERM: "xterm-kitty" })).toBe(true) + expect(kittyClipboardLikely({ TERM: "xterm-256color", KITTY_WINDOW_ID: "3" })).toBe(true) + expect(kittyClipboardLikely({ TERM: "xterm-256color" })).toBe(false) + expect(kittyClipboardLikely({ TERM: "xterm-kitty", TMUX: "/tmp/tmux-1000/default,1,0" })).toBe(false) + expect(kittyClipboardLikely({})).toBe(false) + expect(parse5522("\x1b]52;c;aGk=\x07")).toBeUndefined() + expect(parse5522("\x1b]5522;type=read:status=DATA:mime=aW1hZ2UvcG5n;QUJD\x07")).toEqual({ meta: { type: "read", status: "DATA", mime: "aW1hZ2UvcG5n" }, payload: "QUJD" }) +}) diff --git a/tests/tui/paste.test.tsx b/tests/tui/paste.test.tsx index c32679c..32dbab7 100644 --- a/tests/tui/paste.test.tsx +++ b/tests/tui/paste.test.tsx @@ -224,3 +224,88 @@ test("an @file completed after wide characters replaces its own token, nothing e await t.settle() expect(a.plainText).toBe("日本語の説明 @hello.txt ") }) + +const PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" +/** Run with these environment variables set, then put back. */ +async function withEnv(vars: Record, fn: () => Promise) { + const before = Object.fromEntries(Object.keys(vars).map((k) => [k, process.env[k]])) + for (const [k, v] of Object.entries(vars)) v === undefined ? delete process.env[k] : (process.env[k] = v) + try { + await fn() + } finally { + for (const [k, v] of Object.entries(before)) v === undefined ? delete process.env[k] : (process.env[k] = v) + } +} +const NOT_REMOTE = { SSH_CONNECTION: undefined, SSH_TTY: undefined, SSH_CLIENT: undefined } + +test("an image pasted as a data URL is saved and shown as [Image 1]; a broken one is said, not pasted", async () => { + t = await tui([{ chunks: [delta({ content: "Seen." }), usage(100, 5)] }]) + const a = box(t.setup.renderer.root) + await t.input.typeText("what is this ") + await t.input.pasteBracketedText(`data:image/png;base64,${PNG_B64}`) + await t.settle() + expect(a.plainText).toBe("what is this [Image 1] ") + await t.input.pasteBracketedText(`data:image/png;base64,${Buffer.from("this is certainly not a picture").toString("base64")}`) + await t.settle() + expect(a.plainText).toBe("what is this [Image 1] ") + expect(t.frame()).toContain("not a PNG, JPEG, WebP or GIF image") + t.input.pressEnter() + expect(await t.until("Seen.")).toBe(true) + // Sent as the @path of the copy kept under the state directory. + const m = /@(\S+clipboard\/paste-[\w-]+\.png)/.exec(JSON.parse(sent()) as string) + expect(m).not.toBeNull() + expect(readFileSync(m![1]!).toString("base64")).toBe(PNG_B64) + expect(m![1]!.startsWith(join(paths.state, "clipboard"))).toBe(true) +}) + +test("ctrl+v with no image: said in a word, the box stays usable; over SSH one line names what works", async () => { + await withEnv({ ...NOT_REMOTE, DISPLAY: undefined, WAYLAND_DISPLAY: undefined }, async () => { + t = await tui([]) + const a = box(t.setup.renderer.root) + t.input.pressKey("v", { ctrl: true }) + // Not waited for: typing goes on at once. + await t.input.typeText("still typing") + expect(a.plainText).toBe("still typing") + expect(await t.until("or use @path")).toBe(true) + t.stop() + }) + await withEnv({ SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-256color", KITTY_WINDOW_ID: undefined, TMUX: undefined }, async () => { + t = await tui([], { width: 220, height: 30 }) + t.input.pressKey("v", { ctrl: true }) + expect(await t.until("no image reached this terminal over SSH")).toBe(true) + const f = t.frame() + expect(f).toContain("data:image/png;base64") + expect(f).toContain("@path") + expect(f).toContain("web, Desktop or Android app") + }) +}) + +test("over SSH in kitty: ctrl+v asks the terminal for its clipboard, and the image arrives as [Image 1]", async () => { + await withEnv({ SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-kitty", TMUX: undefined, STY: undefined, ZELLIJ: undefined }, async () => { + t = await tui([]) + const a = box(t.setup.renderer.root) + const r = t.setup.renderer as any + const b64 = (s: string) => Buffer.from(s).toString("base64") + const asked: string[] = [] + // The terminal's half, answered through the renderer's own input: what kitty would send back. + r.writeOut = (seq: string) => { + if (!seq.startsWith("\x1b]5522;")) return + asked.push(seq) + const id = /id=([^:;]+)/.exec(seq)![1] + const want = Buffer.from(seq.slice(seq.lastIndexOf(";") + 1).replace("\x1b\\", ""), "base64").toString() + const reply = (meta: string, payload = "") => r.stdin.emit("data", Buffer.from(`\x1b]5522;type=read:status=${meta}:id=${id}${payload ? `;${payload}` : ""}\x1b\\`)) + setTimeout(() => { + reply("OK") + if (want === ".") reply(`DATA:mime=${b64(".")}`, b64("text/plain image/png")) + else reply(`DATA:mime=${b64("image/png")}`, PNG_B64) + reply("DONE") + }, 5) + } + await t.input.typeText("see ") + t.input.pressKey("v", { ctrl: true }) + const end = Date.now() + 4000 + while (Date.now() < end && !a.plainText.includes("[Image 1]")) await t.settle(40) + expect(a.plainText).toBe("see [Image 1] ") + expect(asked.length).toBe(2) + }) +})