/** * ============================================================ * src/utils/clipboardImage.ts —— 三 OS 剪贴板取图(Ctrl+V / Alt+V 的后端) * ------------------------------------------------------------ * **为什么必须有这个模块**:终端不会把剪贴板里的图片字节送进 stdin——拖拽进来的是 * 「文件路径文本」(那条路已由 multimodal.ts 的行内路径识别覆盖),而 Ctrl+V 粘贴图片 * 在终端里根本不产生任何输入事件。想拿到图,只能**进程主动去问操作系统要**。 * * 返回的是「磁盘上的一个图片路径」而不是 base64:这样下游完全复用既有的 * `@"path"` → buildUserContent 通路,不新增任何数据形状、不改 loop / useChat。 * * **取图顺序:先要文件列表,再要位图字节**。资源管理器 / Finder 复制的是**文件**, * 截图工具 / 浏览器复制的是**位图数据**;先问文件列表就能直接拿到原文件——不落临时 * 文件、不重编码、保留原格式。 * * 三个平台各自的坑(都踩过实账,改之前先读): * - Windows 必须用 `powershell.exe`(5.1)而**不是** `pwsh`:PowerShell 7 删掉了 * `Get-Clipboard -Format`,且默认不带 System.Drawing。5.1 在每台 Win10/11 上都有。 * - PowerShell 输出必须显式 `[Console]::OutputEncoding = UTF8`,否则中文文件名回来是乱码 * (与 bash.ts 头注记的 GBK 事故同源)。 * - Windows 剪贴板位图原生是 BMP,而本项目 `isSupportedImageSource('.bmp') === false` * (OpenAI 兼容接口不吃 BMP)。让 PowerShell 直接 `.Save(..., ImageFormat::Png)`, * 就不必像 Claude Code 那样为了转码去拉 sharp。 * - Linux 的 wl-clipboard / xclip 是**可选外部依赖**,缺失时报错必须点名要装什么。 * * 依赖全部经参数注入(platform / env / run / tmpDir),命令拼装可纯函数断言, * 测试不用真读剪贴板、也不用 mock.module。 * ============================================================ */ import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { chmod, mkdir, readdir, stat, unlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { basename, dirname, extname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const TEMP_PREFIX = 'minimal-agent-clip-'; const TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000; const MAX_CLIPBOARD_IMAGE_BYTES = 10 * 1024 * 1024; const MAX_CLIPBOARD_TEXT_BYTES = 1024 * 1024; const COMMAND_TIMEOUT_MS = 8_000; /** 与 multimodal.ts 的 IMAGE_MIME_BY_EXT 支持集一致(.bmp 有意不在内)。 */ const SUPPORTED_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']); export interface ClipboardCommand { cmd: string; args: string[]; /** * true = 命令自己把图写到目标文件(Windows/macOS 用脚本落盘); * false = 图片字节从 stdout 出来,由本模块负责写盘(Linux)。 */ writesOutputFile: boolean; } export type ClipboardImageResult = | { ok: true; path: string; fromFile: boolean } | { ok: false; reason: string }; export type RunCommand = ( cmd: string, args: string[], options: { env?: NodeJS.ProcessEnv; input?: Buffer | string; maxBytes?: number; timeoutMs?: number; }, ) => Promise<{ stdout: Buffer }>; export interface ClipboardDeps { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; run?: RunCommand; tmpDir?: string; } export function isManagedClipboardTemp(path: string): boolean { return dirname(resolve(path)) === resolve(join(tmpdir(), 'minimal-agent-clipboard')) && basename(path).startsWith(TEMP_PREFIX); } export async function removeManagedClipboardTemp(path: string): Promise { if (isManagedClipboardTemp(path)) await unlink(path).catch(() => undefined); } /** * Spawn-based runner with an explicit byte cap. `execFile` buffers stdout with * a small default maxBuffer, which makes ordinary Linux screenshots fail. * * 两处刻意的选择(都踩过账): * - **stderr 用 `'ignore'` 而不是 `'pipe'`**:我们从不读它,而没人读的管道写满 * (约 64KB)会把子进程**堵死**,最后只能等超时——`xclip` 在没有 X 显示时正好会 * 往 stderr 狂写。丢弃它才是对的,报错信息由 exit code 表达。 * - 子进程退出不代表 stdout 已完整结束:继承管道的孙进程仍可能写数据。成功必须同时 * 等到 exit code 0 与 stdout end;若退出后管道迟迟不关,明确失败,绝不返回截断图片。 */ const EXIT_STDOUT_TIMEOUT_MS = 750; export const spawnClipboardCommand: RunCommand = (cmd, args, options) => new Promise((resolveRun, rejectRun) => { const child = spawn(cmd, args, { env: options.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true, }); const chunks: Buffer[] = []; let total = 0; let settled = false; let exited: number | null = null; let stdoutEnded = false; const maxBytes = options.maxBytes ?? MAX_CLIPBOARD_IMAGE_BYTES; const finish = (error?: Error) => { if (settled) return; settled = true; clearTimeout(timer); clearTimeout(drainTimer); if (error) rejectRun(error); else resolveRun({ stdout: Buffer.concat(chunks, total) }); }; let drainTimer: ReturnType | undefined; const timer = setTimeout(() => { child.kill(); finish(new Error('clipboard command timed out')); }, options.timeoutMs ?? COMMAND_TIMEOUT_MS); child.once('error', (error) => finish(error)); child.stdout.on('data', (chunk: Buffer) => { total += chunk.length; if (total > maxBytes) { child.kill(); finish(new Error(`clipboard payload exceeds ${maxBytes} bytes`)); return; } chunks.push(chunk); }); // stdout 自然结束时立即结算:正常情况下这比宽限窗口先到,不必白等 50ms。 child.stdout.once('error', (error) => finish(error)); child.stdout.once('end', () => { stdoutEnded = true; if (exited === 0) finish(); }); child.once('exit', (code) => { exited = code; if (code !== 0) { finish(Object.assign(new Error(`clipboard command exited with ${code}`), { code })); return; } if (stdoutEnded || child.stdout.readableEnded) finish(); else { drainTimer = setTimeout( () => finish(new Error('clipboard command stdout did not close after process exit')), EXIT_STDOUT_TIMEOUT_MS, ); } }); if (options.input !== undefined) child.stdin.end(options.input); else child.stdin.end(); }); /** PowerShell 单引号字符串转义(内部单引号翻倍)。 */ function psQuote(value: string): string { return `'${value.replace(/'/g, "''")}'`; } /** 所有 PowerShell 脚本的第一句:强制 UTF-8 输出,否则中文路径回来是乱码。 */ const PS_UTF8 = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8'; const PS_ARGS = ['-NoProfile', '-NonInteractive', '-Command']; /** * 「剪贴板里是不是复制了图片**文件**」——命中就能拿到原文件路径,最理想的情况。 * 导出供测试断言命令拼装。 */ export function clipboardFileListCommands( platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ): ClipboardCommand[] { if (platform === 'win32') { const script = [ PS_UTF8, '$files = Get-Clipboard -Format FileDropList', 'if (-not $files) { exit 1 }', '$files | ForEach-Object { $_.FullName }', ].join('; '); return [{ cmd: 'powershell.exe', args: [...PS_ARGS, script], writesOutputFile: false }]; } if (platform === 'darwin') { return [ { cmd: 'osascript', args: ['-e', 'get POSIX path of (the clipboard as «class furl»)'], writesOutputFile: false, }, ]; } return linuxOrder(env, [ { cmd: 'wl-paste', args: ['--type', 'text/uri-list'], writesOutputFile: false }, { cmd: 'xclip', args: ['-selection', 'clipboard', '-t', 'text/uri-list', '-o'], writesOutputFile: false }, ]); } /** * 「剪贴板里是不是位图数据」——截图工具 / 浏览器复制走这条。 * 导出供测试断言命令拼装。 */ export function clipboardImageCommands( platform: NodeJS.Platform, env: NodeJS.ProcessEnv, outPath: string, ): ClipboardCommand[] { if (platform === 'win32') { const script = [ PS_UTF8, 'Add-Type -AssemblyName System.Drawing', '$img = Get-Clipboard -Format Image', 'if (-not $img) { exit 1 }', // 存 PNG 而不是倒原始字节:剪贴板位图原生是 BMP,本项目不支持 BMP。 `$img.Save(${psQuote(outPath)}, [System.Drawing.Imaging.ImageFormat]::Png)`, ].join('; '); return [{ cmd: 'powershell.exe', args: [...PS_ARGS, script], writesOutputFile: true }]; } if (platform === 'darwin') { return [ { cmd: 'osascript', args: [ '-e', 'set png_data to (the clipboard as «class PNGf»)', '-e', `set fp to open for access POSIX file "${outPath}" with write permission`, '-e', 'write png_data to fp', '-e', 'close access fp', ], writesOutputFile: true, }, ]; } return linuxOrder(env, [ { cmd: 'wl-paste', args: ['--type', 'image/png'], writesOutputFile: false }, { cmd: 'xclip', args: ['-selection', 'clipboard', '-t', 'image/png', '-o'], writesOutputFile: false }, ]); } /** Wayland 会话优先试 wl-paste,否则 xclip 优先;两个都会试,缺哪个都只是 ENOENT。 */ function linuxOrder(env: NodeJS.ProcessEnv, [wayland, x11]: ClipboardCommand[]): ClipboardCommand[] { return env.WAYLAND_DISPLAY ? [wayland!, x11!] : [x11!, wayland!]; } type Attempt = | { status: 'ok'; stdout: Buffer } /** 可执行文件不存在(该后端没装) */ | { status: 'missing' } /** 跑起来了但没拿到东西(剪贴板里没这类内容) */ | { status: 'empty' }; async function attempt(command: ClipboardCommand, run: RunCommand, env: NodeJS.ProcessEnv): Promise { try { const { stdout } = await run(command.cmd, command.args, { env, maxBytes: MAX_CLIPBOARD_IMAGE_BYTES, timeoutMs: COMMAND_TIMEOUT_MS, }); return { status: 'ok', stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(String(stdout)) }; } catch (e) { const code = (e as NodeJS.ErrnoException).code; return code === 'ENOENT' ? { status: 'missing' } : { status: 'empty' }; } } /** 把剪贴板文件列表的一行(可能是 file:// URI)转成本地路径;不是受支持的图片则返回 null。 */ function toImagePath(line: string): string | null { const clean = line.trim().replace(/^"|"$/g, ''); if (!clean || clean.startsWith('#')) return null; let path = clean; if (clean.startsWith('file://')) { try { path = fileURLToPath(clean); } catch { return null; } } return SUPPORTED_EXT.has(extname(path).toLowerCase()) ? path : null; } /** 清掉 24h 前的同前缀临时图。不能即时删——文件要活到用户提交那一刻。 */ async function pruneOldTempImages(dir: string): Promise { try { const names = await readdir(dir); const deadline = Date.now() - TEMP_MAX_AGE_MS; await Promise.all( names .filter((name) => name.startsWith(TEMP_PREFIX)) .map(async (name) => { const full = join(dir, name); const info = await stat(full).catch(() => null); if (info && info.mtimeMs < deadline) await unlink(full).catch(() => undefined); }), ); } catch { // 清理是尽力而为,失败不影响取图。 } } export async function readClipboardImage(deps: ClipboardDeps = {}): Promise { const platform = deps.platform ?? process.platform; const env = deps.env ?? process.env; const run = deps.run ?? spawnClipboardCommand; const dir = deps.tmpDir ?? join(tmpdir(), 'minimal-agent-clipboard'); await mkdir(dir, { recursive: true, mode: 0o700 }); await chmod(dir, 0o700).catch(() => undefined); void pruneOldTempImages(dir); let anyBackendMissing = false; let anyBackendRan = false; // ① 先问文件列表:命中就直接用原文件,不落临时拷贝、不重编码。 for (const command of clipboardFileListCommands(platform, env)) { const result = await attempt(command, run, env); if (result.status === 'missing') { anyBackendMissing = true; continue; } anyBackendRan = true; if (result.status !== 'ok') continue; for (const line of result.stdout.toString('utf8').split(/\r?\n/)) { const path = toImagePath(line); // 剪贴板里可能是任意文件(.txt/.zip),只认得出图片才算命中。 if (path && (await stat(path).then((s) => s.isFile()).catch(() => false))) { return { ok: true, path, fromFile: true }; } } } // ② 再问位图字节:截图工具 / 浏览器复制走这条,落一个临时 PNG。 const outPath = join(dir, `${TEMP_PREFIX}${Date.now()}-${randomUUID()}.png`); for (const command of clipboardImageCommands(platform, env, outPath)) { const result = await attempt(command, run, env); if (result.status === 'missing') { anyBackendMissing = true; continue; } anyBackendRan = true; if (result.status !== 'ok') continue; if (command.writesOutputFile) { const size = await stat(outPath).then((s) => s.size).catch(() => 0); if (size > MAX_CLIPBOARD_IMAGE_BYTES) { await unlink(outPath).catch(() => undefined); return { ok: false, reason: '剪贴板图片超过 10MB 上限。' }; } if (size > 0) { await chmod(outPath, 0o600).catch(() => undefined); return { ok: true, path: outPath, fromFile: false }; } continue; } // stdout 就是图片字节(Linux)。空输出 = 剪贴板里没有这个类型。 if (result.stdout.length === 0) continue; if (result.stdout.length > MAX_CLIPBOARD_IMAGE_BYTES) { return { ok: false, reason: '剪贴板图片超过 10MB 上限。' }; } await writeFile(outPath, result.stdout, { mode: 0o600 }); return { ok: true, path: outPath, fromFile: false }; } if (anyBackendMissing && !anyBackendRan) { return { ok: false, reason: platform === 'linux' ? '读不到剪贴板:请先安装 wl-clipboard(Wayland)或 xclip(X11)。' : '读不到剪贴板:系统剪贴板工具不可用。', }; } return { ok: false, reason: '剪贴板里没有图片。' }; } /** Copy exact text without terminal decoration or ANSI escape sequences. */ export async function writeClipboardText( text: string, deps: Pick = {}, ): Promise { const bytes = Buffer.from(text, 'utf8'); if (bytes.length > MAX_CLIPBOARD_TEXT_BYTES) { throw new Error('要复制的内容超过 1MB 上限。'); } const platform = deps.platform ?? process.platform; const env = deps.env ?? process.env; const run = deps.run ?? spawnClipboardCommand; const commands = platform === 'darwin' ? [{ cmd: 'pbcopy', args: [] }] : platform === 'win32' ? [{ cmd: 'powershell.exe', args: [...PS_ARGS, `${PS_UTF8}; $input | Set-Clipboard`], }] : env.WAYLAND_DISPLAY ? [{ cmd: 'wl-copy', args: [] }, { cmd: 'xclip', args: ['-selection', 'clipboard'] }] : [{ cmd: 'xclip', args: ['-selection', 'clipboard'] }, { cmd: 'wl-copy', args: [] }]; let lastError: unknown; for (const command of commands) { try { await run(command.cmd, command.args, { env, input: bytes, maxBytes: 64 * 1024, timeoutMs: COMMAND_TIMEOUT_MS, }); return; } catch (error) { lastError = error; } } throw new Error( platform === 'linux' ? '写入剪贴板失败:请安装 wl-clipboard(Wayland)或 xclip(X11)。' : `写入剪贴板失败:${lastError instanceof Error ? lastError.message : String(lastError)}`, ); }