clipboard-image.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import { execFile, spawnSync } from 'node:child_process';
  2. import { chmod, copyFile, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import { basename, extname, isAbsolute, join } from 'node:path';
  5. import { promisify } from 'node:util';
  6. import { fileURLToPath } from 'node:url';
  7. import type { TuiAttachment } from '../application/invocation.js';
  8. import { MINIMAX_CODE_MAX_TOTAL_ATTACHMENT_BYTES } from '../application/attachment-policy.js';
  9. import { inferTuiNativeVideoMimeType } from '../application/video-mime.js';
  10. export const MINIMAX_CODE_CLIPBOARD_IMAGE_MAX_BYTES = MINIMAX_CODE_MAX_TOTAL_ATTACHMENT_BYTES;
  11. const SUPPORTED_CLIPBOARD_IMAGE_MIME_TYPES = [
  12. 'image/png',
  13. 'image/jpeg',
  14. 'image/webp',
  15. 'image/gif',
  16. ] as const;
  17. const CLIPBOARD_COMMAND_LIST_TIMEOUT_MS = 1_000;
  18. const CLIPBOARD_COMMAND_READ_TIMEOUT_MS = 3_000;
  19. const CLIPBOARD_COMMAND_MAX_BUFFER_BYTES = 50 * 1024 * 1024;
  20. export type TuiClipboardImageErrorCode =
  21. | 'cancelled'
  22. | 'no-image'
  23. | 'permission-denied'
  24. | 'remote-terminal'
  25. | 'too-large'
  26. | 'unavailable'
  27. | 'unsupported-platform';
  28. export class TuiClipboardImageError extends Error {
  29. readonly code: TuiClipboardImageErrorCode;
  30. constructor(code: TuiClipboardImageErrorCode, message: string, options?: ErrorOptions) {
  31. super(message, options);
  32. this.name = 'TuiClipboardImageError';
  33. this.code = code;
  34. }
  35. }
  36. export interface TuiClipboardImageLease {
  37. attachment: TuiAttachment;
  38. dispose(): Promise<void>;
  39. }
  40. export async function copyTuiAttachmentToTemporaryLease(
  41. attachment: TuiAttachment,
  42. options: { readonly tempRoot?: string } = {},
  43. ): Promise<TuiClipboardImageLease> {
  44. const directory = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'minimax-code-clipboard-'));
  45. const suffix = extname(attachment.fileName).slice(0, 16);
  46. const filePath = join(directory, `recovered${suffix}`);
  47. let disposed = false;
  48. const dispose = async (): Promise<void> => {
  49. if (disposed) return;
  50. disposed = true;
  51. await rm(directory, { force: true, recursive: true });
  52. };
  53. try {
  54. await copyFile(attachment.filePath, filePath);
  55. await chmod(filePath, 0o600);
  56. } catch (error) {
  57. await dispose().catch(() => undefined);
  58. throw error;
  59. }
  60. return {
  61. attachment: { ...attachment, filePath },
  62. dispose,
  63. };
  64. }
  65. export interface TuiNativeClipboard {
  66. availableFormats?(): string[];
  67. getText?(): Promise<string>;
  68. hasImage(): boolean | Promise<boolean>;
  69. getImageBinary(): Promise<Array<number> | Uint8Array>;
  70. }
  71. export interface ReadTuiClipboardImageOptions {
  72. signal?: AbortSignal;
  73. platform?: NodeJS.Platform;
  74. environment?: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>>;
  75. tempRoot?: string;
  76. maxBytes?: number;
  77. now?: () => number;
  78. clipboard?: TuiNativeClipboard;
  79. loadClipboard?: () => Promise<TuiNativeClipboard>;
  80. readClipboardFilePaths?: () => Promise<readonly string[]>;
  81. retryClipboardDelay?: (delayMs: number) => Promise<void>;
  82. executeFile?: TuiClipboardExecuteFile;
  83. }
  84. interface TuiClipboardExecuteFileOptions {
  85. readonly encoding: 'utf8';
  86. readonly maxBuffer: number;
  87. readonly timeout: number;
  88. readonly signal?: AbortSignal;
  89. }
  90. type TuiClipboardExecuteFile = (
  91. file: string,
  92. args: readonly string[],
  93. options: TuiClipboardExecuteFileOptions,
  94. ) => Promise<{ readonly stdout: string }>;
  95. export async function readTuiClipboardImage(
  96. options: ReadTuiClipboardImageOptions = {},
  97. ): Promise<TuiClipboardImageLease> {
  98. const platform = options.platform ?? process.platform;
  99. const environment = options.environment ?? process.env;
  100. assertClipboardImageReadSupported(platform, environment);
  101. throwIfAborted(options.signal);
  102. const localWsl = isLocalWsl(platform, environment);
  103. let clipboard: TuiNativeClipboard | undefined;
  104. try {
  105. clipboard = options.clipboard ?? (await (options.loadClipboard ?? loadNativeClipboard)());
  106. } catch (error) {
  107. if (!localWsl) throw classifyClipboardImageError(error, 'unavailable');
  108. }
  109. const clipboardFilePaths = await (
  110. options.readClipboardFilePaths
  111. ? options.readClipboardFilePaths()
  112. : clipboard
  113. ? readClipboardFilePaths(platform, clipboard, options)
  114. : Promise.resolve([])
  115. ).catch(() => []);
  116. const clipboardFile = await resolveClipboardMediaFile(clipboardFilePaths);
  117. if (clipboardFile) {
  118. const maxBytes = normalizeMaximumBytes(options.maxBytes);
  119. if (clipboardFile.sizeBytes > maxBytes) {
  120. throw new TuiClipboardImageError(
  121. 'too-large',
  122. `The clipboard ${clipboardFile.mimeType.startsWith('video/') ? 'video' : 'image'} is ${formatBytes(clipboardFile.sizeBytes)}, above the ${formatBytes(maxBytes)} limit. Choose a smaller file and try again.`,
  123. );
  124. }
  125. throwIfAborted(options.signal);
  126. return copyTuiAttachmentToTemporaryLease(clipboardFile, {
  127. ...(options.tempRoot ? { tempRoot: options.tempRoot } : {}),
  128. });
  129. }
  130. if (platform === 'linux' && !options.clipboard && !options.executeFile) {
  131. const image = readLinuxClipboardImage(environment);
  132. if (image) return persistClipboardImageBytes(image.bytes, options, image.mimeType);
  133. }
  134. if (localWsl) {
  135. let bytes: Buffer | undefined;
  136. try {
  137. bytes = await readWslClipboardImageViaPowerShell(options);
  138. } catch (error) {
  139. throw classifyClipboardImageError(error, 'unavailable');
  140. }
  141. throwIfAborted(options.signal);
  142. if (!bytes?.length) {
  143. throw new TuiClipboardImageError(
  144. 'no-image',
  145. 'The Windows host clipboard does not contain an image that WSL can read.',
  146. );
  147. }
  148. return persistClipboardImageBytes(bytes, options, 'image/png');
  149. }
  150. if (!clipboard) {
  151. throw new TuiClipboardImageError(
  152. 'unavailable',
  153. 'The system clipboard image reader is unavailable. Save the image and reference it in the prompt with @.',
  154. );
  155. }
  156. let hasImage: boolean;
  157. try {
  158. hasImage = await retryWindowsClipboardRead(() => clipboard.hasImage(), platform, options);
  159. } catch (error) {
  160. throw classifyClipboardImageError(error, 'unavailable');
  161. }
  162. throwIfAborted(options.signal);
  163. if (!hasImage) {
  164. throw new TuiClipboardImageError(
  165. 'no-image',
  166. 'The system clipboard does not contain a supported image or copied video file.',
  167. );
  168. }
  169. let bytes: Buffer;
  170. try {
  171. bytes = Buffer.from(
  172. await retryWindowsClipboardRead(() => clipboard.getImageBinary(), platform, options),
  173. );
  174. } catch (error) {
  175. throw classifyClipboardImageError(error, 'unavailable');
  176. }
  177. throwIfAborted(options.signal);
  178. if (bytes.length === 0) {
  179. throw new TuiClipboardImageError(
  180. 'no-image',
  181. 'The system clipboard image is empty. Copy the image again and retry.',
  182. );
  183. }
  184. return persistClipboardImageBytes(bytes, options, 'image/png');
  185. }
  186. async function persistClipboardImageBytes(
  187. bytes: Buffer,
  188. options: ReadTuiClipboardImageOptions,
  189. mimeType: string,
  190. ): Promise<TuiClipboardImageLease> {
  191. throwIfAborted(options.signal);
  192. const maxBytes = normalizeMaximumBytes(options.maxBytes);
  193. if (bytes.length > maxBytes) {
  194. throw new TuiClipboardImageError(
  195. 'too-large',
  196. `The clipboard image is ${formatBytes(bytes.length)}, above the ${formatBytes(maxBytes)} limit. Save or resize it, then reference it in the prompt with @.`,
  197. );
  198. }
  199. const directory = await mkdtemp(
  200. join(options.tempRoot ?? tmpdir(), 'minimax-code-clipboard-'),
  201. ).catch((error: unknown) => {
  202. throw classifyClipboardImageError(error, 'unavailable');
  203. });
  204. const extension = extensionForClipboardImageMimeType(mimeType) ?? 'png';
  205. const fileName = `clipboard-${(options.now ?? Date.now)()}.${extension}`;
  206. const filePath = join(directory, fileName);
  207. let disposed = false;
  208. const dispose = async (): Promise<void> => {
  209. if (disposed) return;
  210. disposed = true;
  211. await rm(directory, { force: true, recursive: true });
  212. };
  213. try {
  214. await writeFile(filePath, bytes, { flag: 'wx', mode: 0o600 });
  215. throwIfAborted(options.signal);
  216. } catch (error) {
  217. await dispose().catch(() => undefined);
  218. if (error instanceof TuiClipboardImageError) throw error;
  219. throw classifyClipboardImageError(error, 'unavailable');
  220. }
  221. return {
  222. attachment: {
  223. type: 'image',
  224. filePath,
  225. fileName,
  226. mimeType,
  227. sizeBytes: bytes.length,
  228. },
  229. dispose,
  230. };
  231. }
  232. interface ClipboardImageBytes {
  233. readonly bytes: Buffer;
  234. readonly mimeType: string;
  235. }
  236. function readLinuxClipboardImage(
  237. environment: Readonly<Record<string, string | undefined>>,
  238. ): ClipboardImageBytes | undefined {
  239. if (environment.TERMUX_VERSION) return undefined;
  240. const wayland = Boolean(environment.WAYLAND_DISPLAY) || environment.XDG_SESSION_TYPE === 'wayland';
  241. const wsl = Boolean(environment.WSL_DISTRO_NAME || environment.WSLENV);
  242. if (wayland || wsl) {
  243. const waylandImage = readClipboardImageViaWlPaste(environment);
  244. if (waylandImage) return waylandImage;
  245. }
  246. return readClipboardImageViaXclip(environment);
  247. }
  248. function readClipboardImageViaWlPaste(
  249. environment: Readonly<Record<string, string | undefined>>,
  250. ): ClipboardImageBytes | undefined {
  251. const listed = runClipboardCommand('wl-paste', ['--list-types'], environment, true);
  252. if (!listed) return undefined;
  253. const mimeType = selectPreferredClipboardImageMimeType(
  254. listed.toString('utf8').split(/\r?\n/u),
  255. );
  256. if (!mimeType) return undefined;
  257. const bytes = runClipboardCommand(
  258. 'wl-paste',
  259. ['--type', mimeType, '--no-newline'],
  260. environment,
  261. false,
  262. );
  263. return bytes?.length ? { bytes, mimeType: baseMimeType(mimeType) } : undefined;
  264. }
  265. function readClipboardImageViaXclip(
  266. environment: Readonly<Record<string, string | undefined>>,
  267. ): ClipboardImageBytes | undefined {
  268. const targets = runClipboardCommand(
  269. 'xclip',
  270. ['-selection', 'clipboard', '-t', 'TARGETS', '-o'],
  271. environment,
  272. true,
  273. );
  274. const preferred = targets
  275. ? selectPreferredClipboardImageMimeType(targets.toString('utf8').split(/\r?\n/u))
  276. : undefined;
  277. const mimeTypes = preferred
  278. ? [preferred, ...SUPPORTED_CLIPBOARD_IMAGE_MIME_TYPES]
  279. : [...SUPPORTED_CLIPBOARD_IMAGE_MIME_TYPES];
  280. for (const mimeType of new Set(mimeTypes)) {
  281. const bytes = runClipboardCommand(
  282. 'xclip',
  283. ['-selection', 'clipboard', '-t', mimeType, '-o'],
  284. environment,
  285. false,
  286. );
  287. if (bytes?.length) return { bytes, mimeType: baseMimeType(mimeType) };
  288. }
  289. return undefined;
  290. }
  291. function runClipboardCommand(
  292. command: string,
  293. args: readonly string[],
  294. environment: Readonly<Record<string, string | undefined>>,
  295. listing: boolean,
  296. ): Buffer | undefined {
  297. const result = spawnSync(command, [...args], {
  298. timeout: listing ? CLIPBOARD_COMMAND_LIST_TIMEOUT_MS : CLIPBOARD_COMMAND_READ_TIMEOUT_MS,
  299. maxBuffer: CLIPBOARD_COMMAND_MAX_BUFFER_BYTES,
  300. env: environment as NodeJS.ProcessEnv,
  301. });
  302. if (result.error || result.status !== 0) return undefined;
  303. return Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout ?? '');
  304. }
  305. function selectPreferredClipboardImageMimeType(values: readonly string[]): string | undefined {
  306. const normalized = values
  307. .map((value) => value.trim())
  308. .filter(Boolean)
  309. .map((raw) => ({ raw, base: baseMimeType(raw) }));
  310. for (const preferred of SUPPORTED_CLIPBOARD_IMAGE_MIME_TYPES) {
  311. const match = normalized.find((candidate) => candidate.base === preferred);
  312. if (match) return match.raw;
  313. }
  314. return normalized.find((candidate) => candidate.base.startsWith('image/'))?.raw;
  315. }
  316. function baseMimeType(mimeType: string): string {
  317. return mimeType.split(';')[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();
  318. }
  319. export function extensionForClipboardImageMimeType(mimeType: string): string | undefined {
  320. switch (baseMimeType(mimeType)) {
  321. case 'image/png':
  322. return 'png';
  323. case 'image/jpeg':
  324. return 'jpg';
  325. case 'image/webp':
  326. return 'webp';
  327. case 'image/gif':
  328. return 'gif';
  329. default:
  330. return undefined;
  331. }
  332. }
  333. function isLocalWsl(
  334. platform: NodeJS.Platform,
  335. environment: Readonly<Record<string, string | undefined>>,
  336. ): boolean {
  337. return platform === 'linux' && Boolean(environment['WSL_DISTRO_NAME'] || environment['WSLENV']);
  338. }
  339. async function readWslClipboardImageViaPowerShell(
  340. options: ReadTuiClipboardImageOptions,
  341. ): Promise<Buffer | undefined> {
  342. const directory = await mkdtemp(
  343. join(options.tempRoot ?? tmpdir(), 'minimax-code-wsl-clipboard-'),
  344. );
  345. const filePath = join(directory, 'clipboard.png');
  346. const executeFile = options.executeFile ?? executeClipboardFile;
  347. const executionOptions = (
  348. timeout: number,
  349. maxBuffer: number,
  350. ): TuiClipboardExecuteFileOptions => ({
  351. encoding: 'utf8',
  352. maxBuffer,
  353. timeout,
  354. ...(options.signal ? { signal: options.signal } : {}),
  355. });
  356. try {
  357. const mappedPath = (
  358. await executeFile('wslpath', ['-w', filePath], executionOptions(1_000, 64 * 1024))
  359. ).stdout.trim();
  360. if (!mappedPath) throw new Error('wslpath returned an empty Windows path.');
  361. const quotedPath = mappedPath.replaceAll("'", "''");
  362. const script = [
  363. "$ErrorActionPreference = 'Stop'",
  364. 'Add-Type -AssemblyName System.Windows.Forms',
  365. 'Add-Type -AssemblyName System.Drawing',
  366. '$image = [System.Windows.Forms.Clipboard]::GetImage()',
  367. `if ($null -eq $image) { Write-Output 'empty' } else { try { $image.Save('${quotedPath}', [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } finally { $image.Dispose() } }`,
  368. ].join('; ');
  369. const output = (
  370. await executeFile(
  371. 'powershell.exe',
  372. ['-NoProfile', '-NonInteractive', '-Command', script],
  373. executionOptions(5_000, 64 * 1024),
  374. )
  375. ).stdout.trim();
  376. if (output === 'empty') return undefined;
  377. if (output !== 'ok')
  378. throw new Error(`PowerShell returned an unexpected clipboard result: ${output}`);
  379. return await readFile(filePath);
  380. } finally {
  381. await rm(directory, { force: true, recursive: true }).catch(() => undefined);
  382. }
  383. }
  384. function assertClipboardImageReadSupported(
  385. platform: NodeJS.Platform,
  386. environment: Readonly<Record<string, string | undefined>>,
  387. ): void {
  388. if (environment['SSH_CONNECTION'] || environment['SSH_CLIENT'] || environment['SSH_TTY']) {
  389. throw new TuiClipboardImageError(
  390. 'remote-terminal',
  391. 'Clipboard media paste is unavailable in a remote terminal. Save the media on the remote machine and reference it in the prompt with @.',
  392. );
  393. }
  394. if (platform !== 'darwin' && platform !== 'win32' && platform !== 'linux') {
  395. throw new TuiClipboardImageError(
  396. 'unsupported-platform',
  397. `Clipboard media paste is not supported on ${platform}. Save the media and reference it in the prompt with @.`,
  398. );
  399. }
  400. }
  401. async function loadNativeClipboard(): Promise<TuiNativeClipboard> {
  402. const loaded = (await import('@mariozechner/clipboard')) as unknown as {
  403. default?: TuiNativeClipboard;
  404. availableFormats?: TuiNativeClipboard['availableFormats'];
  405. getText?: TuiNativeClipboard['getText'];
  406. hasImage?: TuiNativeClipboard['hasImage'];
  407. getImageBinary?: TuiNativeClipboard['getImageBinary'];
  408. };
  409. const clipboard = loaded.default ?? loaded;
  410. const availableFormats = clipboard.availableFormats;
  411. const getText = clipboard.getText;
  412. const hasImage = clipboard.hasImage;
  413. const getImageBinary = clipboard.getImageBinary;
  414. if (typeof hasImage !== 'function' || typeof getImageBinary !== 'function') {
  415. throw new Error('The native clipboard image API is unavailable.');
  416. }
  417. return {
  418. ...(typeof availableFormats === 'function'
  419. ? { availableFormats: () => availableFormats.call(clipboard) }
  420. : {}),
  421. ...(typeof getText === 'function' ? { getText: () => getText.call(clipboard) } : {}),
  422. hasImage: () => hasImage.call(clipboard),
  423. getImageBinary: () => getImageBinary.call(clipboard),
  424. };
  425. }
  426. const execFileAsync = promisify(execFile);
  427. async function executeClipboardFile(
  428. file: string,
  429. args: readonly string[],
  430. options: TuiClipboardExecuteFileOptions,
  431. ): Promise<{ readonly stdout: string }> {
  432. const result = await execFileAsync(file, [...args], options);
  433. return { stdout: String(result.stdout) };
  434. }
  435. const MACOS_CLIPBOARD_FILE_PATHS_SCRIPT = String.raw`
  436. ObjC.import('AppKit');
  437. ObjC.import('Foundation');
  438. const pasteboard = $.NSPasteboard.generalPasteboard;
  439. const options = $.NSMutableDictionary.dictionary;
  440. options.setObjectForKey($.NSNumber.numberWithBool(true), $.NSPasteboardURLReadingFileURLsOnlyKey);
  441. const classes = $.NSArray.arrayWithObject($.NSURL);
  442. const urls = pasteboard.readObjectsForClassesOptions(classes, options);
  443. const paths = [];
  444. for (let index = 0; urls && index < urls.count; index += 1) {
  445. const value = urls.objectAtIndex(index).path;
  446. if (value) paths.push(ObjC.unwrap(value));
  447. }
  448. paths.join('\n');
  449. `.trim();
  450. async function readClipboardFilePaths(
  451. platform: NodeJS.Platform,
  452. clipboard: TuiNativeClipboard,
  453. options: ReadTuiClipboardImageOptions,
  454. ): Promise<readonly string[]> {
  455. if (options.readClipboardFilePaths) return options.readClipboardFilePaths();
  456. if (platform === 'darwin') {
  457. if (options.clipboard) return [];
  458. try {
  459. const result = await execFileAsync(
  460. 'osascript',
  461. ['-l', 'JavaScript', '-e', MACOS_CLIPBOARD_FILE_PATHS_SCRIPT],
  462. { encoding: 'utf8', maxBuffer: 1024 * 1024, timeout: 1_000 },
  463. );
  464. return parseClipboardFilePaths(result.stdout);
  465. } catch {
  466. return [];
  467. }
  468. }
  469. if (!clipboard.availableFormats || !clipboard.getText) return [];
  470. let formats: string[];
  471. try {
  472. formats = await retryWindowsClipboardRead(
  473. () => clipboard.availableFormats?.() ?? [],
  474. platform,
  475. options,
  476. );
  477. } catch {
  478. return [];
  479. }
  480. if (!formats.some(isClipboardFileFormat)) return [];
  481. try {
  482. return parseClipboardFilePaths(
  483. await retryWindowsClipboardRead(() => clipboard.getText?.() ?? '', platform, options),
  484. );
  485. } catch {
  486. return [];
  487. }
  488. }
  489. async function retryWindowsClipboardRead<T>(
  490. operation: () => T | Promise<T>,
  491. platform: NodeJS.Platform,
  492. options: Pick<ReadTuiClipboardImageOptions, 'signal' | 'retryClipboardDelay'>,
  493. ): Promise<T> {
  494. const retries = platform === 'win32' ? 2 : 0;
  495. const delay =
  496. options.retryClipboardDelay ??
  497. ((delayMs: number) => new Promise<void>((resolve) => setTimeout(resolve, delayMs)));
  498. for (let attempt = 0; ; attempt += 1) {
  499. throwIfAborted(options.signal);
  500. try {
  501. return await operation();
  502. } catch (error) {
  503. if (attempt >= retries || !isTransientWindowsClipboardError(error)) throw error;
  504. await delay(25 * (attempt + 1));
  505. }
  506. }
  507. }
  508. function isTransientWindowsClipboardError(error: unknown): boolean {
  509. const code =
  510. error && typeof error === 'object' && 'code' in error
  511. ? String((error as { code?: unknown }).code)
  512. : '';
  513. const message = error instanceof Error ? error.message : String(error);
  514. return (
  515. code === 'EAGAIN' ||
  516. code === 'EBUSY' ||
  517. /openclipboard|clipboard.*(?:busy|locked|temporarily unavailable)/iu.test(message)
  518. );
  519. }
  520. function isClipboardFileFormat(format: string): boolean {
  521. const normalized = format.trim().toLowerCase();
  522. return (
  523. normalized.includes('filedrop') ||
  524. normalized.includes('file-url') ||
  525. normalized.includes('file url') ||
  526. normalized.includes('filename') ||
  527. normalized.includes('nsfilenames') ||
  528. normalized.includes('com.apple.finder') ||
  529. normalized === 'text/uri-list' ||
  530. normalized === 'public.url'
  531. );
  532. }
  533. function parseClipboardFilePaths(value: string): string[] {
  534. return value
  535. .split(/[\r\n\0]+/u)
  536. .map((item) => item.trim())
  537. .filter((item) => item && !item.startsWith('#'))
  538. .map((item) => {
  539. if (!item.startsWith('file://')) return item;
  540. try {
  541. return fileURLToPath(item);
  542. } catch {
  543. return '';
  544. }
  545. })
  546. .filter((item) => item && isAbsolute(item));
  547. }
  548. async function resolveClipboardMediaFile(
  549. paths: readonly string[],
  550. ): Promise<TuiAttachment | undefined> {
  551. for (const filePath of paths) {
  552. const fileName = basename(filePath);
  553. const mimeType = inferClipboardMediaMimeType(fileName);
  554. if (!mimeType) continue;
  555. const info = await stat(filePath).catch(() => undefined);
  556. if (!info?.isFile()) continue;
  557. return {
  558. type: mimeType.startsWith('image/') ? 'image' : 'file',
  559. filePath,
  560. fileName,
  561. mimeType,
  562. sizeBytes: info.size,
  563. };
  564. }
  565. return undefined;
  566. }
  567. function inferClipboardMediaMimeType(fileName: string): string | undefined {
  568. const videoMimeType = inferTuiNativeVideoMimeType(fileName);
  569. if (videoMimeType) return videoMimeType;
  570. return CLIPBOARD_IMAGE_MIME_BY_EXTENSION[extname(fileName).toLowerCase()];
  571. }
  572. const CLIPBOARD_IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
  573. '.avif': 'image/avif',
  574. '.bmp': 'image/bmp',
  575. '.gif': 'image/gif',
  576. '.jpeg': 'image/jpeg',
  577. '.jpg': 'image/jpeg',
  578. '.png': 'image/png',
  579. '.webp': 'image/webp',
  580. };
  581. function classifyClipboardImageError(
  582. error: unknown,
  583. fallback: 'unavailable',
  584. ): TuiClipboardImageError {
  585. if (error instanceof TuiClipboardImageError) return error;
  586. const code =
  587. error && typeof error === 'object' && 'code' in error
  588. ? String((error as { code?: unknown }).code)
  589. : '';
  590. const message = error instanceof Error ? error.message : String(error);
  591. if (
  592. code === 'EACCES' ||
  593. code === 'EPERM' ||
  594. /access denied|not permitted|permission/iu.test(message)
  595. ) {
  596. return new TuiClipboardImageError(
  597. 'permission-denied',
  598. 'Minimax Code cannot read the system clipboard. Allow clipboard access, then try again.',
  599. { cause: error },
  600. );
  601. }
  602. return new TuiClipboardImageError(
  603. fallback,
  604. 'The system clipboard image reader is unavailable. Save the image and reference it in the prompt with @.',
  605. { cause: error },
  606. );
  607. }
  608. function throwIfAborted(signal: AbortSignal | undefined): void {
  609. if (!signal?.aborted) return;
  610. throw new TuiClipboardImageError(
  611. 'cancelled',
  612. 'Clipboard image paste was cancelled. The current draft was not changed.',
  613. );
  614. }
  615. function normalizeMaximumBytes(value: number | undefined): number {
  616. if (value === undefined || !Number.isFinite(value)) {
  617. return MINIMAX_CODE_CLIPBOARD_IMAGE_MAX_BYTES;
  618. }
  619. return Math.max(0, Math.floor(value));
  620. }
  621. function formatBytes(value: number): string {
  622. if (value < 1024) return `${value} B`;
  623. if (value < 1024 * 1024) return `${Math.ceil(value / 1024)} KB`;
  624. return `${Math.ceil(value / (1024 * 1024))} MB`;
  625. }