Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ describe('<AssistantMessage />', () => {

expect(lastFrame()).toContain('MockTerminalImage:image/png:height=6');
});

it('gives image-only assistant messages the full image height budget', () => {
const { lastFrame } = render(
<AssistantMessage
text=""
images={[
{ data: 'Zmlyc3Q=', mimeType: 'image/png' },
{ data: 'c2Vjb25k', mimeType: 'image/png' },
]}
isPending={false}
availableTerminalHeight={20}
contentWidth={80}
/>,
);

expect(lastFrame()).toContain('MockTerminalImage:image/png:height=10');
});
});

describe('<AssistantMessageContent />', () => {
Expand Down
16 changes: 14 additions & 2 deletions packages/cli/src/ui/components/messages/ConversationMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,13 @@ const PrefixedMarkdownMessage: React.FC<PrefixedMarkdownMessageProps> = ({
const prefixWidth = getPrefixWidth(prefix);
const imageHeightBudget =
availableTerminalHeight !== undefined && images?.length
? Math.max(1, Math.floor(availableTerminalHeight / (images.length + 1)))
? Math.max(
1,
Math.floor(
availableTerminalHeight /
(images.length + (text.length > 0 ? 1 : 0)),
),
)
: availableTerminalHeight;

return (
Expand Down Expand Up @@ -226,7 +232,13 @@ const ContinuationMarkdownMessage: React.FC<
const prefixWidth = getPrefixWidth(basePrefix);
const imageHeightBudget =
availableTerminalHeight !== undefined && images?.length
? Math.max(1, Math.floor(availableTerminalHeight / (images.length + 1)))
? Math.max(
1,
Math.floor(
availableTerminalHeight /
(images.length + (text.length > 0 ? 1 : 0)),
),
)
: availableTerminalHeight;

return (
Expand Down
37 changes: 36 additions & 1 deletion packages/cli/src/ui/utils/terminal-image-renderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
containsCmdShellMetacharacters,
getTerminalImageRenderSupport,
INLINE_DECODE_NEGATIVE_CACHE_LIMIT,
MAX_INLINE_IMAGE_PIXELS,
markKittyImageWritten,
prepareInlineTerminalImage,
Expand Down Expand Up @@ -132,6 +133,40 @@ describe('terminalImageRenderer', () => {
}
});

it('caches repeated invalid inline payloads and evicts old entries', () => {
const invalidPayloads = Array.from(
{ length: INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 1 },
(_, index) => Buffer.from(`not a png ${index}`).toString('base64'),
);
const bufferFrom = vi.spyOn(Buffer, 'from');

try {
for (const data of invalidPayloads) {
prepareInlineTerminalImage({
data,
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
});
}

prepareInlineTerminalImage({
data: invalidPayloads[0],
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
});

expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 2,
);
} finally {
bufferFrom.mockRestore();
}
});

it('rejects inline payloads above the shared image limit before decoding', () => {
const oversizedBase64 = 'A'.repeat(MAX_INLINE_IMAGE_ENCODED_LENGTH + 1);

Expand Down
28 changes: 26 additions & 2 deletions packages/cli/src/ui/utils/terminal-image-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ const inlineDecodeCache = new Map<
string,
{ png: Buffer; size: { width: number; height: number } }
>();
export const INLINE_DECODE_NEGATIVE_CACHE_LIMIT = 64;
const invalidInlineImageCache = new Set<string>();

// A Kitty terminal keeps a transmitted image and redraws it from the placeholder
// cells alone. The live-row -> Static-row move and every resize remount
Expand Down Expand Up @@ -379,10 +381,23 @@ function getDecodedInlinePng(
return cached;
}

const negativeKey = crypto.createHash('sha256').update(data).digest('hex');
if (invalidInlineImageCache.has(negativeKey)) {
invalidInlineImageCache.delete(negativeKey);
invalidInlineImageCache.add(negativeKey);
return null;
}

const png = decodeInlineImage(data);
if (!png) return null;
if (!png) {
cacheInvalidInlineImage(negativeKey);
return null;
}
const size = readValidatedInlinePngSize(png);
if (!size) return null;
if (!size) {
cacheInvalidInlineImage(negativeKey);
return null;
}

const decoded = { png, size };
inlineDecodeCache.set(data, decoded);
Expand All @@ -394,6 +409,15 @@ function getDecodedInlinePng(
return decoded;
}

function cacheInvalidInlineImage(key: string): void {
invalidInlineImageCache.add(key);
while (invalidInlineImageCache.size > INLINE_DECODE_NEGATIVE_CACHE_LIMIT) {
const oldest = invalidInlineImageCache.values().next().value;
if (oldest === undefined) break;
invalidInlineImageCache.delete(oldest);
}
}

function readValidatedInlinePngSize(
png: Buffer,
): { width: number; height: number } | null {
Expand Down
11 changes: 11 additions & 0 deletions packages/cli/src/ui/utils/textUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ describe('textUtils', () => {
expect(escapeAnsiCtrlCodes('')).toBe('');
});

it('preserves inline image data while sanitizing surrounding text', () => {
const imageData = 'payload\u001bwith-control-code';
const sanitized = escapeAnsiCtrlCodes({
text: '\u001b[31mcaption\u001b[0m',
images: [{ data: imageData, mimeType: 'image/png' }],
});

expect(sanitized.text).toBe('\\u001b[31mcaption\\u001b[0m');
expect(sanitized.images[0].data).toBe(imageData);
});

describe('toolConfirmationDetails case study', () => {
it('should sanitize command and rootCommand for exec type', () => {
const details: ToolCallConfirmationDetails = {
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/ui/utils/textUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,16 @@ export function escapeAnsiCtrlCodes<T>(obj: T): T {
return obj;
}

const record = obj as Record<string, unknown>;
if (
!Array.isArray(obj) &&
typeof record['data'] === 'string' &&
typeof record['mimeType'] === 'string' &&
record['mimeType'].toLowerCase().startsWith('image/')
) {
return obj;
}
Comment on lines +379 to +386

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9cea67e0a7c0f5d9d13791289edf1f89d6b6619f.

The guard now reuses one Record<string, unknown> reference, so the existing typeof check narrows mimeType before toLowerCase() is called. I also removed the redundant toString() call. This is a type-safety-only change and preserves the existing runtime behavior; adjacent Suggestions were intentionally left out of this Critical-only round.

Verified with Node.js 22.23.1: CLI tsc --noEmit passed; the three focused test files passed 97/97 tests; repository build, bundle, and workspace typecheck passed; targeted Prettier, ESLint, and git diff --check passed. An independent verifier also returned VERIFIED_FIXED.

已在 9cea67e0a7c0f5d9d13791289edf1f89d6b6619f 修复。

现在复用同一个 Record<string, unknown> 引用,使现有的 typeof 检查能够在调用 toLowerCase() 前正确收窄 mimeType,同时删除多余的 toString()。这次只修类型安全问题,运行时行为不变;相邻的 Suggestion 刻意不纳入本轮 Critical 修复。

在 Node.js 22.23.1 下验证:CLI tsc --noEmit 通过;3 个聚焦测试文件共 97/97 通过;仓库 build、bundle、全 workspace typecheck 通过;目标文件 Prettier、ESLint 和 git diff --check 通过。独立验证结论也是 VERIFIED_FIXED。


if (Array.isArray(obj)) {
let newArr: unknown[] | null = null;

Expand Down
Loading