Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(browser): 收敛截图错误分类并区分压缩降级

cnxpfcv-oss06dc7b7e7212
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts
index f3be93ab7f..6b7dc94c8c 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts
@@ -78,6 +78,92 @@ describe('resolveBrowserScreenshot', () => {
);
});
+ it('rejects a symlink inside the media root that points outside it', async () => {
+ const runtimeDir = await makeRuntimeDir();
+ const mediaRoot = path.join(runtimeDir, 'media', 'browser');
+ const outsideTarget = path.join(runtimeDir, 'outside-target.png');
+ const symlinkPath = path.join(mediaRoot, 'escape.png');
+ await fs.mkdir(mediaRoot, { recursive: true });
+ await fs.writeFile(outsideTarget, PNG_BYTES);
+ await fs.symlink(outsideTarget, symlinkPath);
+ const result: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: { path: symlinkPath, targetId: 'tab-1' },
+ };
+
+ await expect(resolveBrowserScreenshot(result, { runtimeDir })).rejects.toThrow(
+ 'Browser screenshot file is unavailable',
+ );
+ });
+
+ it('rejects external screenshot files above the 5 MiB read cap', async () => {
+ const runtimeDir = await makeRuntimeDir();
+ const mediaRoot = path.join(runtimeDir, 'media', 'browser');
+ const oversizedPath = path.join(mediaRoot, 'oversized.png');
+ await fs.mkdir(mediaRoot, { recursive: true });
+ await fs.writeFile(
+ oversizedPath,
+ Buffer.concat([PNG_BYTES, Buffer.alloc(5 * 1024 * 1024, 0x00)]),
+ );
+ const result: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: { path: oversizedPath, targetId: 'tab-1' },
+ };
+
+ await expect(resolveBrowserScreenshot(result, { runtimeDir })).rejects.toThrow(
+ 'Browser screenshot file is unavailable',
+ );
+ });
+
+ it('rejects path-based screenshots when no runtimeDir is configured', async () => {
+ const runtimeDir = await makeRuntimeDir();
+ const mediaRoot = path.join(runtimeDir, 'media', 'browser');
+ const screenshotPath = path.join(mediaRoot, 'screen.png');
+ await fs.mkdir(mediaRoot, { recursive: true });
+ await fs.writeFile(screenshotPath, PNG_BYTES);
+ const result: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: { path: screenshotPath, targetId: 'tab-1' },
+ };
+
+ await expect(
+ resolveBrowserScreenshot(result, { runtimeDir: undefined }),
+ ).rejects.toThrow('Browser screenshot file is unavailable');
+ });
+
+ it('rejects non-object payloads, payloads without data/path, and unknown magic bytes', async () => {
+ const nonObject: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: undefined,
+ };
+ await expect(resolveBrowserScreenshot(nonObject, { runtimeDir: undefined })).rejects.toThrow(
+ 'Browser screenshot payload is invalid',
+ );
+
+ const missingBoth: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: { targetId: 'tab-1' },
+ };
+ await expect(resolveBrowserScreenshot(missingBoth, { runtimeDir: undefined })).rejects.toThrow(
+ 'Browser screenshot payload is invalid',
+ );
+
+ // 合法 Base64,但内容既不是 PNG 也不是 JPEG 签名。
+ const unknownMagic: BrowserControlResult = {
+ ok: true,
+ action: 'screenshot',
+ data: { data: Buffer.alloc(64, 0x00).toString('base64'), targetId: 'tab-1' },
+ };
+ await expect(resolveBrowserScreenshot(unknownMagic, { runtimeDir: undefined })).rejects.toThrow(
+ 'Browser screenshot payload is invalid',
+ );
+ });
+
it('rejects malformed Base64 and declared MIME mismatches', async () => {
const malformed: BrowserControlResult = {
ok: true,
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index 68f2d942a1..a75168209f 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -736,7 +736,9 @@ describe('createBrowserMcpServer', () => {
await h.cleanup();
});
- it('fails closed when an oversized screenshot cannot be compressed for inline delivery', async () => {
+ it('reports compressor degradation (null) as COMPRESSION_UNAVAILABLE, not TOO_LARGE', async () => {
+ // CompressInlineImageFn 契约:null = 压缩器不可用/解码失败/超时的预期降级,
+ // 不代表图片本身无法缩小 — 错误码必须与"压缩后仍超标"区分开。
const original = Buffer.alloc(240_000, 0xab);
const h = await makeHarness(
{
@@ -764,12 +766,82 @@ describe('createBrowserMcpServer', () => {
expect(JSON.parse(block.text ?? '{}')).toMatchObject({
ok: false,
action: 'screenshot',
- errorCode: 'BROWSER_SCREENSHOT_TOO_LARGE',
+ errorCode: 'BROWSER_SCREENSHOT_COMPRESSION_UNAVAILABLE',
});
expect(block.text).not.toContain(original.toString('base64'));
await h.cleanup();
});
+ it('fails closed with TOO_LARGE only when the compressed copy still exceeds the inline budget', async () => {
+ const original = Buffer.alloc(400_000, 0xab);
+ const stillOversized = Buffer.alloc(INLINE_IMAGE_TARGET_BYTES + 1, 0xcd);
+ const h = await makeHarness(
+ {
+ resolveScreenshot: async () => ({ buffer: original, mimeType: 'image/png' }),
+ compressInlineImage: async () => ({ buffer: stillOversized, mime: 'image/webp' }),
+ },
+ () => ({
+ data: original.toString('base64'),
+ mimeType: 'image/png',
+ bytes: original.byteLength,
+ tabId: 'tab-1',
+ }),
+ );
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: { name: 'browser', args: { action: 'screenshot', targetId: 'tab-1' } },
+ });
+
+ expect(result.isError).toBe(true);
+ const blocks = result.content as Array<{ type: string; text?: string }>;
+ expect(blocks).toHaveLength(1);
+ expect(JSON.parse(blocks[0].text ?? '{}')).toMatchObject({
+ ok: false,
+ action: 'screenshot',
+ errorCode: 'BROWSER_SCREENSHOT_TOO_LARGE',
+ });
+ expect(blocks[0].text).not.toContain(original.toString('base64'));
+ expect(blocks[0].text).not.toContain(stillOversized.toString('base64'));
+ await h.cleanup();
+ });
+
+ it('maps resolveScreenshot rejections to BROWSER_SCREENSHOT_INVALID without leaking details', async () => {
+ // resolver 的 8 类校验 throw(路径越界 / Base64 损坏 / MIME 不匹配等)必须
+ // 收敛为稳定的 BROWSER_SCREENSHOT_INVALID,而不是穿透外层 catch 被泛化成
+ // BROWSER_RUNTIME_ACTION_FAILED;error 里的路径不得进入模型可见结果。
+ const secretPath = '/private/browser-runtime/media/browser/secret-screenshot.png';
+ const h = await makeHarness(
+ {
+ resolveScreenshot: async () => {
+ throw new Error(`Browser screenshot file is unavailable: ${secretPath}`);
+ },
+ },
+ () => ({
+ path: secretPath,
+ targetId: 'tab-1',
+ }),
+ );
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: { name: 'browser', args: { action: 'screenshot', targetId: 'tab-1' } },
+ });
+
+ expect(result.isError).toBe(true);
+ const blocks = result.content as Array<{ type: string; text?: string }>;
+ expect(blocks).toHaveLength(1);
+ expect(blocks[0].type).toBe('text');
+ expect(JSON.parse(blocks[0].text ?? '{}')).toMatchObject({
+ ok: false,
+ action: 'screenshot',
+ errorCode: 'BROWSER_SCREENSHOT_INVALID',
+ });
+ expect(blocks[0].text).not.toContain(secretPath);
+ expect(blocks[0].text).not.toContain('BROWSER_RUNTIME_ACTION_FAILED');
+ await h.cleanup();
+ });
+
it('keeps the complete screenshot tool result below the stream-json atomic-write budget', async () => {
const screenshot = Buffer.alloc(INLINE_IMAGE_TARGET_BYTES, 0xab);
const annotationMarker = 'must-not-enter-result';
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 9f4bc50410..74ee1d974d 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -9,6 +9,7 @@ import { z } from 'zod';
import {
INLINE_IMAGE_TARGET_BYTES,
type BrowserMcpDeps,
+ type ResolvedBrowserScreenshot,
} from '../types.js';
import type { BrowserToolRegistry } from './tool-registry.js';
import {
@@ -213,7 +214,10 @@ function errorResult(action: string, message: string): {
}
function browserScreenshotError(
- errorCode: 'BROWSER_SCREENSHOT_INVALID' | 'BROWSER_SCREENSHOT_TOO_LARGE',
+ errorCode:
+ | 'BROWSER_SCREENSHOT_INVALID'
+ | 'BROWSER_SCREENSHOT_TOO_LARGE'
+ | 'BROWSER_SCREENSHOT_COMPRESSION_UNAVAILABLE',
message: string,
): {
content: Array<{ type: 'text'; text: string }>;
@@ -291,19 +295,53 @@ async function screenshotToolResult(
);
}
- const resolved = await deps.resolveScreenshot(result);
+ let resolved: ResolvedBrowserScreenshot;
+ try {
+ resolved = await deps.resolveScreenshot(result);
+ } catch (err) {
+ // resolver 抛错(路径越界 / Base64 损坏 / MIME 不匹配等)是截图内容校验
+ // 失败,不是 runtime 动作失败:映射到稳定的 BROWSER_SCREENSHOT_INVALID,
+ // 不能穿透到外层被泛化成 BROWSER_RUNTIME_ACTION_FAILED。原始 error 可能
+ // 含文件路径,只进 host 日志,不进模型可见的错误信封。
+ deps.logger?.warn('browser screenshot resolve failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return browserScreenshotError(
+ 'BROWSER_SCREENSHOT_INVALID',
+ '浏览器截图内容校验失败,无法作为模型图片输入。',
+ );
+ }
const originalBytes = resolved.buffer.byteLength;
let buffer = resolved.buffer;
let mimeType: string = resolved.mimeType;
if (buffer.byteLength > INLINE_IMAGE_TARGET_BYTES) {
- const compressed = await deps.compressInlineImage?.(buffer, mimeType, {
- targetBytes: INLINE_IMAGE_TARGET_BYTES,
- });
- if (!compressed || compressed.buffer.byteLength > INLINE_IMAGE_TARGET_BYTES) {
+ let compressed: Awaited<ReturnType<NonNullable<BrowserMcpDeps['compressInlineImage']>>> = null;
+ try {
+ compressed = (await deps.compressInlineImage?.(buffer, mimeType, {
+ targetBytes: INLINE_IMAGE_TARGET_BYTES,
+ })) ?? null;
+ } catch (err) {
+ // CompressInlineImageFn 契约是永不 throw;真 throw 了按"压缩器不可用"
+ // 降级处理,不让异常穿透成 BROWSER_RUNTIME_ACTION_FAILED。
+ deps.logger?.warn('browser screenshot compression threw, treating as unavailable', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ compressed = null;
+ }
+ // null 是压缩器的契约降级值(sharp 缺失 / 解码失败 / 超时,见
+ // CompressInlineImageFn):不是图片本身超标,不能报 TOO_LARGE。截图仍
+ // 超过内联预算所以必须 fail-closed,但错误码和文案要说真话。
+ if (!compressed) {
+ return browserScreenshotError(
+ 'BROWSER_SCREENSHOT_COMPRESSION_UNAVAILABLE',
+ '浏览器截图超过模型内联传输上限,且当前主机图片压缩不可用(压缩器缺失、无法解码或超时),无法安全内联。',
+ );
+ }
+ if (compressed.buffer.byteLength > INLINE_IMAGE_TARGET_BYTES) {
return browserScreenshotError(
'BROWSER_SCREENSHOT_TOO_LARGE',
- '浏览器截图超过模型内联传输上限,且无法安全压缩。请缩小窗口后重试。',
+ '浏览器截图压缩后仍超过模型内联传输上限。请缩小窗口后重试。',
);
}
buffer = compressed.buffer;