terminal-image.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import { execSync } from "node:child_process";
  2. export type ImageProtocol = "kitty" | "iterm2" | null;
  3. export interface TerminalCapabilities {
  4. images: ImageProtocol;
  5. trueColor: boolean;
  6. hyperlinks: boolean;
  7. }
  8. export interface CellDimensions {
  9. widthPx: number;
  10. heightPx: number;
  11. }
  12. export interface ImageDimensions {
  13. widthPx: number;
  14. heightPx: number;
  15. }
  16. export interface ImageRenderOptions {
  17. maxWidthCells?: number;
  18. maxHeightCells?: number;
  19. preserveAspectRatio?: boolean;
  20. /** Kitty image ID. If provided, reuses/replaces existing image with this ID. */
  21. imageId?: number;
  22. /** Whether Kitty should apply its default cursor movement after placement. */
  23. moveCursor?: boolean;
  24. }
  25. let cachedCapabilities: TerminalCapabilities | null = null;
  26. // Default cell dimensions - updated by TUI when terminal responds to query
  27. let cellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 };
  28. export function getCellDimensions(): CellDimensions {
  29. return cellDimensions;
  30. }
  31. export function setCellDimensions(dims: CellDimensions): void {
  32. cellDimensions = dims;
  33. }
  34. /**
  35. * Checks whether the attached tmux client forwards OSC 8 hyperlinks to the
  36. * outer terminal. tmux only re-emits them when its `client_termfeatures` lists
  37. * `hyperlinks`, and strips them otherwise. On any error fallbacks `false`.
  38. */
  39. function probeTmuxHyperlinks(): boolean {
  40. try {
  41. const termfeatures = execSync("tmux display-message -p '#{client_termfeatures}'", {
  42. encoding: "utf8",
  43. timeout: 250,
  44. stdio: ["ignore", "pipe", "ignore"],
  45. });
  46. return termfeatures
  47. .split(",")
  48. .map((feature) => feature.trim())
  49. .includes("hyperlinks");
  50. } catch {
  51. return false;
  52. }
  53. }
  54. export function detectCapabilities(tmuxForwardsHyperlink: () => boolean = probeTmuxHyperlinks): TerminalCapabilities {
  55. const termProgram = process.env.TERM_PROGRAM?.toLowerCase() || "";
  56. const terminalEmulator = process.env.TERMINAL_EMULATOR?.toLowerCase() || "";
  57. const term = process.env.TERM?.toLowerCase() || "";
  58. const colorTerm = process.env.COLORTERM?.toLowerCase() || "";
  59. const hasTrueColorHint = colorTerm === "truecolor" || colorTerm === "24bit";
  60. // Emit OSC 8 hyperlinks only when tmux confirms it forwards.
  61. // Image protocols are unreliable under tmux, so leave `images: null`.
  62. if (process.env.TMUX || term.startsWith("tmux")) {
  63. return { images: null, trueColor: hasTrueColorHint, hyperlinks: tmuxForwardsHyperlink() };
  64. }
  65. // screen does not forward OSC 8 hyperlinks, so keep them off there.
  66. if (term.startsWith("screen")) {
  67. return { images: null, trueColor: hasTrueColorHint, hyperlinks: false };
  68. }
  69. if (process.env.KITTY_WINDOW_ID || termProgram === "kitty") {
  70. return { images: "kitty", trueColor: true, hyperlinks: true };
  71. }
  72. if (termProgram === "ghostty" || term.includes("ghostty") || process.env.GHOSTTY_RESOURCES_DIR) {
  73. return { images: "kitty", trueColor: true, hyperlinks: true };
  74. }
  75. if (process.env.WEZTERM_PANE || termProgram === "wezterm") {
  76. return { images: "kitty", trueColor: true, hyperlinks: true };
  77. }
  78. if (process.env.ITERM_SESSION_ID || termProgram === "iterm.app") {
  79. return { images: "iterm2", trueColor: true, hyperlinks: true };
  80. }
  81. if (process.env.WT_SESSION) {
  82. return { images: null, trueColor: true, hyperlinks: true };
  83. }
  84. if (termProgram === "vscode") {
  85. return { images: null, trueColor: true, hyperlinks: true };
  86. }
  87. if (termProgram === "alacritty") {
  88. return { images: null, trueColor: true, hyperlinks: true };
  89. }
  90. if (terminalEmulator === "jetbrains-jediterm") {
  91. return { images: null, trueColor: true, hyperlinks: false };
  92. }
  93. // Unknown terminal: be conservative. OSC 8 is rendered invisibly as "just
  94. // text" on terminals that swallow it, which means the URL disappears from
  95. // the rendered output. Default to the legacy `text (url)` behavior unless we
  96. // have positively identified a hyperlink-capable terminal above.
  97. return { images: null, trueColor: hasTrueColorHint, hyperlinks: false };
  98. }
  99. export function getCapabilities(): TerminalCapabilities {
  100. if (!cachedCapabilities) {
  101. cachedCapabilities = detectCapabilities();
  102. }
  103. return cachedCapabilities;
  104. }
  105. export function resetCapabilitiesCache(): void {
  106. cachedCapabilities = null;
  107. }
  108. /** Override the cached capabilities. Useful in tests to exercise both code paths. */
  109. export function setCapabilities(caps: TerminalCapabilities): void {
  110. cachedCapabilities = caps;
  111. }
  112. const KITTY_PREFIX = "\x1b_G";
  113. const ITERM2_PREFIX = "\x1b]1337;File=";
  114. export function isImageLine(line: string): boolean {
  115. // Fast path: sequence at line start (single-row images)
  116. if (line.startsWith(KITTY_PREFIX) || line.startsWith(ITERM2_PREFIX)) {
  117. return true;
  118. }
  119. // Slow path: sequence elsewhere (multi-row images have cursor-up prefix)
  120. return line.includes(KITTY_PREFIX) || line.includes(ITERM2_PREFIX);
  121. }
  122. /**
  123. * Generate a random image ID for Kitty graphics protocol.
  124. * Uses random IDs to avoid collisions between different module instances
  125. * (e.g., main app vs extensions).
  126. */
  127. export function allocateImageId(): number {
  128. // Use random ID in range [1, 0xffffffff] to avoid collisions
  129. return Math.floor(Math.random() * 0xfffffffe) + 1;
  130. }
  131. export function encodeKitty(
  132. base64Data: string,
  133. options: {
  134. columns?: number;
  135. rows?: number;
  136. imageId?: number;
  137. /** Whether Kitty should apply its default cursor movement after placement. Default: true. */
  138. moveCursor?: boolean;
  139. } = {},
  140. ): string {
  141. const CHUNK_SIZE = 4096;
  142. const params: string[] = ["a=T", "f=100", "q=2"];
  143. if (options.moveCursor === false) params.push("C=1");
  144. if (options.columns) params.push(`c=${options.columns}`);
  145. if (options.rows) params.push(`r=${options.rows}`);
  146. if (options.imageId) params.push(`i=${options.imageId}`);
  147. if (base64Data.length <= CHUNK_SIZE) {
  148. return `\x1b_G${params.join(",")};${base64Data}\x1b\\`;
  149. }
  150. const chunks: string[] = [];
  151. let offset = 0;
  152. let isFirst = true;
  153. while (offset < base64Data.length) {
  154. const chunk = base64Data.slice(offset, offset + CHUNK_SIZE);
  155. const isLast = offset + CHUNK_SIZE >= base64Data.length;
  156. if (isFirst) {
  157. chunks.push(`\x1b_G${params.join(",")},m=1;${chunk}\x1b\\`);
  158. isFirst = false;
  159. } else if (isLast) {
  160. chunks.push(`\x1b_Gm=0;${chunk}\x1b\\`);
  161. } else {
  162. chunks.push(`\x1b_Gm=1;${chunk}\x1b\\`);
  163. }
  164. offset += CHUNK_SIZE;
  165. }
  166. return chunks.join("");
  167. }
  168. /**
  169. * Delete a Kitty graphics image by ID.
  170. * Uses uppercase 'I' to also free the image data.
  171. */
  172. export function deleteKittyImage(imageId: number): string {
  173. return `\x1b_Ga=d,d=I,i=${imageId},q=2\x1b\\`;
  174. }
  175. /**
  176. * Delete all visible Kitty graphics images.
  177. * Uses uppercase 'A' to also free the image data.
  178. */
  179. export function deleteAllKittyImages(): string {
  180. return "\x1b_Ga=d,d=A,q=2\x1b\\";
  181. }
  182. export function encodeITerm2(
  183. base64Data: string,
  184. options: {
  185. width?: number | string;
  186. height?: number | string;
  187. name?: string;
  188. preserveAspectRatio?: boolean;
  189. inline?: boolean;
  190. } = {},
  191. ): string {
  192. const params: string[] = [`inline=${options.inline !== false ? 1 : 0}`];
  193. if (options.width !== undefined) params.push(`width=${options.width}`);
  194. if (options.height !== undefined) params.push(`height=${options.height}`);
  195. if (options.name) {
  196. const nameBase64 = Buffer.from(options.name).toString("base64");
  197. params.push(`name=${nameBase64}`);
  198. }
  199. if (options.preserveAspectRatio === false) {
  200. params.push("preserveAspectRatio=0");
  201. }
  202. return `\x1b]1337;File=${params.join(";")}:${base64Data}\x07`;
  203. }
  204. export interface ImageCellSize {
  205. columns: number;
  206. rows: number;
  207. }
  208. export function calculateImageCellSize(
  209. imageDimensions: ImageDimensions,
  210. maxWidthCells: number,
  211. maxHeightCells?: number,
  212. cellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },
  213. ): ImageCellSize {
  214. const maxWidth = Math.max(1, Math.floor(maxWidthCells));
  215. const maxHeight = maxHeightCells === undefined ? undefined : Math.max(1, Math.floor(maxHeightCells));
  216. const imageWidth = Math.max(1, imageDimensions.widthPx);
  217. const imageHeight = Math.max(1, imageDimensions.heightPx);
  218. const widthScale = (maxWidth * cellDimensions.widthPx) / imageWidth;
  219. const heightScale = maxHeight === undefined ? widthScale : (maxHeight * cellDimensions.heightPx) / imageHeight;
  220. const scale = Math.min(widthScale, heightScale);
  221. const scaledWidthPx = imageWidth * scale;
  222. const scaledHeightPx = imageHeight * scale;
  223. const columns = Math.ceil(scaledWidthPx / cellDimensions.widthPx);
  224. const rows = Math.ceil(scaledHeightPx / cellDimensions.heightPx);
  225. return {
  226. columns: Math.max(1, Math.min(maxWidth, columns)),
  227. rows: Math.max(1, maxHeight === undefined ? rows : Math.min(maxHeight, rows)),
  228. };
  229. }
  230. export function calculateImageRows(
  231. imageDimensions: ImageDimensions,
  232. targetWidthCells: number,
  233. cellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },
  234. ): number {
  235. return calculateImageCellSize(imageDimensions, targetWidthCells, undefined, cellDimensions).rows;
  236. }
  237. export function getPngDimensions(base64Data: string): ImageDimensions | null {
  238. try {
  239. const buffer = Buffer.from(base64Data, "base64");
  240. if (buffer.length < 24) {
  241. return null;
  242. }
  243. if (buffer[0] !== 0x89 || buffer[1] !== 0x50 || buffer[2] !== 0x4e || buffer[3] !== 0x47) {
  244. return null;
  245. }
  246. const width = buffer.readUInt32BE(16);
  247. const height = buffer.readUInt32BE(20);
  248. return { widthPx: width, heightPx: height };
  249. } catch {
  250. return null;
  251. }
  252. }
  253. export function getJpegDimensions(base64Data: string): ImageDimensions | null {
  254. try {
  255. const buffer = Buffer.from(base64Data, "base64");
  256. if (buffer.length < 2) {
  257. return null;
  258. }
  259. if (buffer[0] !== 0xff || buffer[1] !== 0xd8) {
  260. return null;
  261. }
  262. let offset = 2;
  263. while (offset < buffer.length - 9) {
  264. if (buffer[offset] !== 0xff) {
  265. offset++;
  266. continue;
  267. }
  268. const marker = buffer[offset + 1];
  269. if (marker >= 0xc0 && marker <= 0xc2) {
  270. const height = buffer.readUInt16BE(offset + 5);
  271. const width = buffer.readUInt16BE(offset + 7);
  272. return { widthPx: width, heightPx: height };
  273. }
  274. if (offset + 3 >= buffer.length) {
  275. return null;
  276. }
  277. const length = buffer.readUInt16BE(offset + 2);
  278. if (length < 2) {
  279. return null;
  280. }
  281. offset += 2 + length;
  282. }
  283. return null;
  284. } catch {
  285. return null;
  286. }
  287. }
  288. export function getGifDimensions(base64Data: string): ImageDimensions | null {
  289. try {
  290. const buffer = Buffer.from(base64Data, "base64");
  291. if (buffer.length < 10) {
  292. return null;
  293. }
  294. const sig = buffer.slice(0, 6).toString("ascii");
  295. if (sig !== "GIF87a" && sig !== "GIF89a") {
  296. return null;
  297. }
  298. const width = buffer.readUInt16LE(6);
  299. const height = buffer.readUInt16LE(8);
  300. return { widthPx: width, heightPx: height };
  301. } catch {
  302. return null;
  303. }
  304. }
  305. export function getWebpDimensions(base64Data: string): ImageDimensions | null {
  306. try {
  307. const buffer = Buffer.from(base64Data, "base64");
  308. if (buffer.length < 30) {
  309. return null;
  310. }
  311. const riff = buffer.slice(0, 4).toString("ascii");
  312. const webp = buffer.slice(8, 12).toString("ascii");
  313. if (riff !== "RIFF" || webp !== "WEBP") {
  314. return null;
  315. }
  316. const chunk = buffer.slice(12, 16).toString("ascii");
  317. if (chunk === "VP8 ") {
  318. if (buffer.length < 30) return null;
  319. const width = buffer.readUInt16LE(26) & 0x3fff;
  320. const height = buffer.readUInt16LE(28) & 0x3fff;
  321. return { widthPx: width, heightPx: height };
  322. } else if (chunk === "VP8L") {
  323. if (buffer.length < 25) return null;
  324. const bits = buffer.readUInt32LE(21);
  325. const width = (bits & 0x3fff) + 1;
  326. const height = ((bits >> 14) & 0x3fff) + 1;
  327. return { widthPx: width, heightPx: height };
  328. } else if (chunk === "VP8X") {
  329. if (buffer.length < 30) return null;
  330. const width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;
  331. const height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;
  332. return { widthPx: width, heightPx: height };
  333. }
  334. return null;
  335. } catch {
  336. return null;
  337. }
  338. }
  339. export function getImageDimensions(base64Data: string, mimeType: string): ImageDimensions | null {
  340. if (mimeType === "image/png") {
  341. return getPngDimensions(base64Data);
  342. }
  343. if (mimeType === "image/jpeg") {
  344. return getJpegDimensions(base64Data);
  345. }
  346. if (mimeType === "image/gif") {
  347. return getGifDimensions(base64Data);
  348. }
  349. if (mimeType === "image/webp") {
  350. return getWebpDimensions(base64Data);
  351. }
  352. return null;
  353. }
  354. export function renderImage(
  355. base64Data: string,
  356. imageDimensions: ImageDimensions,
  357. options: ImageRenderOptions = {},
  358. ): { sequence: string; rows: number; imageId?: number } | null {
  359. const caps = getCapabilities();
  360. if (!caps.images) {
  361. return null;
  362. }
  363. const maxWidth = options.maxWidthCells ?? 80;
  364. const size = calculateImageCellSize(imageDimensions, maxWidth, options.maxHeightCells, getCellDimensions());
  365. if (caps.images === "kitty") {
  366. const sequence = encodeKitty(base64Data, {
  367. columns: size.columns,
  368. rows: size.rows,
  369. imageId: options.imageId,
  370. moveCursor: options.moveCursor,
  371. });
  372. return { sequence, rows: size.rows, imageId: options.imageId };
  373. }
  374. if (caps.images === "iterm2") {
  375. const sequence = encodeITerm2(base64Data, {
  376. width: size.columns,
  377. height: "auto",
  378. preserveAspectRatio: options.preserveAspectRatio ?? true,
  379. });
  380. return { sequence, rows: size.rows };
  381. }
  382. return null;
  383. }
  384. /**
  385. * Wrap text in an OSC 8 hyperlink sequence.
  386. * The text is rendered as a clickable hyperlink in terminals that support OSC 8
  387. * (Ghostty, Kitty, WezTerm, iTerm2, VSCode, and others).
  388. * In terminals that do not support OSC 8, the escape sequences are ignored
  389. * and only the plain text is displayed.
  390. *
  391. * @param text - The visible text to display
  392. * @param url - The URL to link to
  393. */
  394. export function hyperlink(text: string, url: string): string {
  395. // BEL termination is recognized more consistently by macOS terminals for
  396. // Command-click hit testing, especially when the link is wrapped across
  397. // multiple physical lines.
  398. return `\x1b]8;;${url}\x07${text}\x1b]8;;\x07`;
  399. }
  400. export function imageFallback(mimeType: string, dimensions?: ImageDimensions, filename?: string): string {
  401. const parts: string[] = [];
  402. if (filename) parts.push(filename);
  403. parts.push(`[${mimeType}]`);
  404. if (dimensions) parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`);
  405. return `[Image: ${parts.join(" ")}]`;
  406. }