refactor: move ink-picture rendering from call() to UI React tree
Browse files- Remove direct stdout ANSI rendering from ImageShowTool.call() (protocol
detection, renderImage, etc.)
- Simplify call() to only load image and return dimensions
- Add ImageDisplay component in UI.tsx using InkPictureProvider + Image
from ink-picture, mounted in Codev's React tree
- Image component reserves a TUI placeholder and renders the actual
image directly to the terminal framebuffer via Kitty/Sixel protocol
(bypassing Ink render cycle)
- Merge standalone.tsx to use ImageDisplay from UI.tsx
Co-Authored-By: Claude Big Pickle <noreply@anthropic.com>
Files changed (3)
9 unmodified lines10111213141516171819202122231325141516171819202122231 unmodified line252627282930313233343536373839404130 unmodified lines7273747374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741757576775 unmodified lines83848518718886878889909192939473 unmodified lines1681691702682692701711721731741752751761771781791801811821832821841851861872861881891901917 unmodified lines1992002013002029 unmodified lines renderToolResultMessage, renderToolUseMessage,} from './UI.js'import type { PixelData, PngData } from "../../ink-picture/renderers/types.js";import { makeKittyTransmitChunks, makeKittyPlacement,} from "../../ink-picture/renderers/kitty.js";import { renderSixel } from "../../ink-picture/renderers/sixel.js";import { renderITerm2 } from "../../ink-picture/renderers/iterm2.js";import { renderHalfBlock } from "../../ink-picture/renderers/halfBlock.js";import { renderBraille } from "../../ink-picture/renderers/braille.js";import { renderAscii } from "../../ink-picture/renderers/ascii.js";import generateKittyId from "../../ink-picture/utils/generateKittyId.js";
// ── Utility functions (kept for standalone UI and external use) ──// ── Constants ──
export const CELL_WIDTH = 8;export const CELL_HEIGHT = 16;
// ── Types ──
export interface ImageDimensions { width: number; // 字符宽度 height: number; // 字符高度1 unmodified line pixelHeight: number; // 像素高度}
export interface ImageShowOutput { src: string success: boolean width?: number height?: number pixelWidth?: number pixelHeight?: number}
// ── Utilities ──
export function getImagePath(args: string[]): string { return args[0] || "/home/yuki/Pictures/Wallpapers/3god.jpg";}30 unmodified lines };}
// ── Protocol detection ──
type Protocol = 'kitty' | 'sixel' | 'iterm2' | 'halfBlock' | 'braille' | 'ascii'
function detectProtocol(): Protocol { const termProgram = process.env.TERM_PROGRAM const term = process.env.TERM
// Kitty protocol — stores image in terminal GPU memory, survives screen clears if (termProgram === 'ghostty' || termProgram === 'kitty' || term?.includes('kitty')) { return 'kitty' }
// Sixel if (term?.includes('sixel') || termProgram === 'ghostty' || termProgram === 'vscode') { return 'sixel' }
// iTerm2 inline images if (termProgram === 'iTerm.app' || termProgram === 'WezTerm' || termProgram === 'WarpTerminal') { return 'iterm2' }
// Text-based fallback const colorterm = process.env.COLORTERM const supportsColor = colorterm === 'truecolor' || !!colorterm || term?.includes('truecolor') || term?.includes('256color') const supportsUnicode = true // all modern terminals
if (supportsUnicode && supportsColor) return 'halfBlock' if (supportsUnicode) return 'braille' return 'ascii'}
type JimpInstance = Awaited<ReturnType<typeof Jimp.read>>
async function renderImage(image: JimpInstance, dims: ImageDimensions): Promise<void> { const protocol = detectProtocol()
image.cover({ w: dims.pixelWidth, h: dims.pixelHeight })
const pixels: PixelData = { data: image.bitmap.data, info: { width: image.bitmap.width, height: image.bitmap.height, channels: 4 }, }
switch (protocol) { case 'kitty': { const pngBuf = await image.getBuffer("image/png") const b64 = pngBuf.toString('base64') const imgId = generateKittyId() const chunks = makeKittyTransmitChunks(imgId, b64) for (const chunk of chunks) { process.stdout.write(chunk) } process.stdout.write('\n') process.stdout.write(makeKittyPlacement(imgId, 1, dims.width, dims.height)) process.stdout.write('\n') break } case 'sixel': { const output = renderSixel(pixels) process.stdout.write(output) process.stdout.write('\n') break } case 'iterm2': { const pngBuf = await image.getBuffer("image/png") const pngData: PngData = { data: pngBuf, info: { width: image.bitmap.width, height: image.bitmap.height }, } const output = renderITerm2(pngData, { width: dims.pixelWidth, height: dims.pixelHeight }) process.stdout.write(output) process.stdout.write('\n') break } case 'halfBlock': { const output = renderHalfBlock(pixels) process.stdout.write('\n') process.stdout.write(output) process.stdout.write('\n') break } case 'braille': { const output = renderBraille(pixels) process.stdout.write('\n') process.stdout.write(output) process.stdout.write('\n') break } case 'ascii': { const output = renderAscii(pixels, { colored: !!(process.env.COLORTERM || process.env.TERM?.includes('truecolor')), }) process.stdout.write('\n') process.stdout.write(output) process.stdout.write('\n') break } }}
// ── Tool definition ──
const inputSchema = lazySchema(() =>5 unmodified lines
const outputSchema = lazySchema(() => z.object({ src: z.string().describe('The image source that was displayed'), success: z.boolean().describe('Whether the image was displayed successfully'), src: z.string(), success: z.boolean(), width: z.number().optional(), height: z.number().optional(), pixelWidth: z.number().optional(), pixelHeight: z.number().optional(), }),)type OutputSchema = ReturnType<typeof outputSchema>73 unmodified lines cols, )
// Render the image directly to terminal using ink-picture await renderImage(image, dims)
return { data: { src, success: true, ...dims, } satisfies Output, } satisfies ImageShowOutput, } } catch (error) { console.error(`[ImageShowTool] Failed to display ${src}:`, error) return { data: { src, success: false, } satisfies Output, } satisfies ImageShowOutput, } } }, mapToolResultToToolResultBlockParam(output, toolUseID) { mapToolResultToToolResultBlockParam(output: ImageShowOutput, toolUseID: string) { return { tool_use_id: toolUseID, type: 'tool_result',7 unmodified lines ], } },} satisfies ToolDef<InputSchema, Output>)} satisfies ToolDef<InputSchema, ImageShowOutput>)12234567891011121314151617181920212223242526272829303132333435363738394013 unmodified lines545556235758596061626364651 unmodified line67686934707172733637383940414274757677787980818283848586876 unmodified lines9495965797import React from 'react'import { MessageResponse } from '../../components/MessageResponse.js'import Image, { InkPictureProvider } from '../../ink-picture/index.js'import { Box, Text } from '../../ink.js'import { MessageResponse } from '../../components/MessageResponse.js'import type { ImageShowOutput } from './ImageShowTool.js'
// ── Image display component ──// Renders a placeholder in Ink's TUI and uses Kitty/Sixel protocol to draw// the full-resolution image directly on the terminal framebuffer (bypassing// the Ink render cycle). The placeholder reserves character cells so the TUI// layout isn't broken; ink-picture's useDirectRenderer repositions the image// after each Ink screen refresh.
export function ImageDisplay({ src, width, height, pixelWidth, pixelHeight }: { src: string width: number height: number pixelWidth: number pixelHeight: number}) { return ( <Box flexDirection="column"> <InkPictureProvider> <Image src={src} width={width} height={height} pixelWidth={pixelWidth} pixelHeight={pixelHeight} alt={typeof src === 'string' ? src : 'image'} /> </InkPictureProvider> </Box> )}
// ── Tool rendering functions ──
export function renderToolUseMessage( { src }: { src?: string },13 unmodified lines}
export function renderToolResultMessage( { src, success }: { src: string; success: boolean }, output: ImageShowOutput, _progressMessages: unknown[], { verbose }: { verbose: boolean },): React.ReactNode { const { src, success, width, height, pixelWidth, pixelHeight } = output
if (!success) { return ( <MessageResponse height={1}>1 unmodified line </MessageResponse> ) } if (verbose) {
// Render the image via ink-picture when we have dimension data if (width && height && pixelWidth && pixelHeight) { return ( <Box flexDirection="column"> <MessageResponse height={1}> <Text> Image displayed: <Text bold>{src}</Text> </Text> </MessageResponse> </Box> <ImageDisplay src={src} width={width} height={height} pixelWidth={pixelWidth} pixelHeight={pixelHeight} /> ) }
// Fallback: text-only summary return ( <MessageResponse height={1}> <Text>6 unmodified linesexport function getToolUseSummary(input: { src?: string } | undefined): string | null { if (!input?.src) return null return input.src.length > 80 ? input.src.slice(0, 77) + '...' : input.src}}11 unmodified lines121314151516171 unmodified line1920212223242510 unmodified lines363738393940414222 unmodified lines65666768697071727374756869707172737476777576777879838011 unmodified lines
import { useEffect, useState } from "react";import { render, Box, Text, useApp } from "ink";import Image, { InkPictureProvider } from "../../ink-picture/index.ts";import { getImagePath, isUrl,1 unmodified line calculateDimensions, type ImageDimensions,} from "./ImageShowTool.ts";import { ImageDisplay } from "./UI.js";
const args = process.argv.slice(2);const IMAGE_PATH = getImagePath(args);10 unmodified lines const dims = calculateDimensions( image.bitmap.width, image.bitmap.height, process.stdout.columns ?? 80 process.stdout.columns ?? 80, ); setDimensions(dims); } catch (e) {22 unmodified lines
return ( <Box flexDirection="column"> <InkPictureProvider> <Image src={IMAGE_PATH} width={dimensions.width} height={dimensions.height} pixelWidth={dimensions.pixelWidth} pixelHeight={dimensions.pixelHeight} alt={isUrl(IMAGE_PATH) ? "url-image" : "local-image"} <ImageDisplay src={IMAGE_PATH} width={dimensions.width} height={dimensions.height} pixelWidth={dimensions.pixelWidth} pixelHeight={dimensions.pixelHeight} /> /> </InkPictureProvider> </Box> );}
const { waitUntilExit } = render(<App />);await waitUntilExit();await waitUntilExit();src/tools/ImageShowTool/ImageShowTool.ts+26-124
src/tools/ImageShowTool/UI.tsx+51-11
src/tools/ImageShowTool/standalone.tsx+10-13