Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): return screenshots as image content blocks
elfcvaa08e53c4a2f
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.tsnew file mode 100644index 0000000000..f3be93ab7f--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserScreenshotResolver.test.ts@@ -0,0 +1,100 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import type { BrowserControlResult } from '@cindy/browser-control-runtime';+import { afterEach, describe, expect, it } from 'vitest';++import { resolveBrowserScreenshot } from '../browserScreenshotResolver.js';++const PNG_BYTES = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.from('test-png'),+]);++const tempRoots: string[] = [];++async function makeRuntimeDir(): Promise<string> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-screenshot-'));+ tempRoots.push(root);+ return root;+}++afterEach(async () => {+ await Promise.all(+ tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })),+ );+});++describe('resolveBrowserScreenshot', () => {+ it('strictly decodes an inline RSB screenshot and verifies its MIME', async () => {+ const result: BrowserControlResult = {+ ok: true,+ action: 'screenshot',+ data: {+ data: PNG_BYTES.toString('base64'),+ mimeType: 'image/png',+ bytes: PNG_BYTES.byteLength,+ tabId: 'tab-1',+ },+ };++ const resolved = await resolveBrowserScreenshot(result, { runtimeDir: undefined });++ expect(resolved).toEqual({ buffer: PNG_BYTES, mimeType: 'image/png' });+ });++ it('reads external screenshots only from the browser runtime media root', 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' },+ };++ const resolved = await resolveBrowserScreenshot(result, { runtimeDir });++ expect(resolved).toEqual({ buffer: PNG_BYTES, mimeType: 'image/png' });+ });++ it('rejects external paths outside the browser runtime media root', async () => {+ const runtimeDir = await makeRuntimeDir();+ const mediaRoot = path.join(runtimeDir, 'media', 'browser');+ const outsidePath = path.join(runtimeDir, 'outside.png');+ await fs.mkdir(mediaRoot, { recursive: true });+ await fs.writeFile(outsidePath, PNG_BYTES);+ const result: BrowserControlResult = {+ ok: true,+ action: 'screenshot',+ data: { path: outsidePath, targetId: 'tab-1' },+ };++ await expect(resolveBrowserScreenshot(result, { runtimeDir })).rejects.toThrow(+ 'Browser screenshot file is unavailable',+ );+ });++ it('rejects malformed Base64 and declared MIME mismatches', async () => {+ const malformed: BrowserControlResult = {+ ok: true,+ action: 'screenshot',+ data: { data: 'not-base64!', mimeType: 'image/png' },+ };+ await expect(resolveBrowserScreenshot(malformed, { runtimeDir: undefined })).rejects.toThrow(+ 'Browser screenshot payload is invalid',+ );++ const mismatched: BrowserControlResult = {+ ok: true,+ action: 'screenshot',+ data: { data: PNG_BYTES.toString('base64'), mimeType: 'image/jpeg' },+ };+ await expect(resolveBrowserScreenshot(mismatched, { runtimeDir: undefined })).rejects.toThrow(+ 'Browser screenshot MIME does not match its bytes',+ );+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.tsindex 0fcabf22b6..02f259edb2 100644--- a/apps/desktop/src/main/mcp-integrations/browser.ts+++ b/apps/desktop/src/main/mcp-integrations/browser.ts@@ -11,13 +11,13 @@ import nodePath from 'node:path';import { app, ipcMain } from 'electron';import {createBrowserControlRuntime,- type BrowserControlRuntime,} from '@cindy/browser-control-runtime';+import type { BrowserMcpDeps } from '@cindy/mcps';import { createLogger } from '../logger.js';import { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';-import { loadUserBrowserRecipes, type UserRecipesResult } from '../browser-recipes/loader.js';-import { writeUserRecipe, type WriteUserRecipeResult } from '../browser-recipes/writer.js';+import { loadUserBrowserRecipes } from '../browser-recipes/loader.js';+import { writeUserRecipe } from '../browser-recipes/writer.js';import { stopRuntimeForQuitIfUsed, trackBrowserRuntimeUsage } from './browser-dispose.js';import {BrowserBackendController,@@ -41,6 +41,8 @@ import { requireObject, optionalNullableString } from '../utils/ipcValidate.js';import { buildManagedConfig, MANAGED_PROFILE } from './browser-managed-config.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { createBrowserBackendIpcHandlers } from './browser-backend/settings-ipc.js';+import { resolveBrowserScreenshot } from './browserScreenshotResolver.js';+import { compressInlineImage } from './inlineImageCompressor.js';export { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';@@ -249,14 +251,7 @@ export async function setActiveBrowserBackendKind(kind: BackendKind): Promise<vo* BrowserControlRuntime contract so the desktop host does not depend on an* upstream product API or product-facing name.*/-export function getBrowserMcpDeps(): {- getRuntime(): BrowserControlRuntime;- supportsResourceDownloads(): boolean;- supportsSemanticQueries(): boolean;- logger: typeof logger;- getUserRecipes(): Promise<UserRecipesResult>;- saveUserRecipe(input: Parameters<typeof writeUserRecipe>[0]): Promise<WriteUserRecipeResult>;-} {+export function getBrowserMcpDeps(): BrowserMcpDeps {return {// L2 user-recipe layer (userData/browser-recipes); merged over the bundled// L1 catalog inside the MCP. Empty/missing dir → bundled-only (== before).@@ -267,6 +262,11 @@ export function getBrowserMcpDeps(): {// the backend split. Swapping the active backend (Phase 5) is invisible from// @cindy/mcps' perspective.getRuntime: () => backendController,+ resolveScreenshot: (result) =>+ resolveBrowserScreenshot(result, {+ runtimeDir: process.env.XDT_BROWSER_RUNTIME_DIR,+ }),+ compressInlineImage,supportsResourceDownloads: () => backendController.kind === 'rsb-webview',supportsSemanticQueries: () => backendController.kind === 'rsb-webview',logger,diff --git a/apps/desktop/src/main/mcp-integrations/browserScreenshotResolver.ts b/apps/desktop/src/main/mcp-integrations/browserScreenshotResolver.tsnew file mode 100644index 0000000000..7457eed5e8--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browserScreenshotResolver.ts@@ -0,0 +1,103 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';++import type { BrowserControlResult } from '@cindy/browser-control-runtime';+import type { ResolvedBrowserScreenshot } from '@cindy/mcps';++import { readBoundedFileNoFollow } from '../utils/readBoundedFile.js';++const MAX_BROWSER_SCREENSHOT_BYTES = 5 * 1024 * 1024;+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++export interface BrowserScreenshotResolverOptions {+ runtimeDir: string | undefined;+}++function sniffScreenshotMime(buffer: Buffer): ResolvedBrowserScreenshot['mimeType'] | null {+ if (buffer.subarray(0, PNG_SIGNATURE.byteLength).equals(PNG_SIGNATURE)) {+ return 'image/png';+ }+ if (buffer.byteLength >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {+ return 'image/jpeg';+ }+ return null;+}++function decodeStrictBase64(value: string): Buffer | null {+ if (+ value.length === 0 ||+ value.length % 4 !== 0 ||+ value.length > Math.ceil(MAX_BROWSER_SCREENSHOT_BYTES / 3) * 4 + 4 ||+ !/^[A-Za-z0-9+/]*={0,2}$/.test(value)+ ) {+ return null;+ }+ const buffer = Buffer.from(value, 'base64');+ if (buffer.byteLength === 0 || buffer.byteLength > MAX_BROWSER_SCREENSHOT_BYTES) return null;+ return buffer.toString('base64') === value ? buffer : null;+}++function isLexicallyWithinRoot(candidate: string, root: string): boolean {+ const relative = path.relative(root, candidate);+ return (+ relative !== '' &&+ !relative.startsWith(`..${path.sep}`) &&+ relative !== '..' &&+ !path.isAbsolute(relative)+ );+}++async function readExternalScreenshot(+ filePath: string,+ runtimeDir: string | undefined,+): Promise<Buffer> {+ if (!runtimeDir || !path.isAbsolute(filePath)) {+ throw new Error('Browser screenshot file is unavailable');+ }+ const mediaRoot = path.resolve(runtimeDir, 'media', 'browser');+ const candidate = path.resolve(filePath);+ if (!isLexicallyWithinRoot(candidate, mediaRoot)) {+ throw new Error('Browser screenshot file is unavailable');+ }+ try {+ const realRoot = await fs.realpath(mediaRoot);+ const buffer = await readBoundedFileNoFollow(candidate, MAX_BROWSER_SCREENSHOT_BYTES, {+ containWithin: realRoot,+ });+ if (!buffer || buffer.byteLength === 0) {+ throw new Error('Browser screenshot file is unavailable');+ }+ return buffer;+ } catch {+ throw new Error('Browser screenshot file is unavailable');+ }+}++/** Resolve both browser backends into verified bytes without exposing file reads to the MCP package. */+export async function resolveBrowserScreenshot(+ result: BrowserControlResult,+ options: BrowserScreenshotResolverOptions,+): Promise<ResolvedBrowserScreenshot> {+ const payload = result.data;+ if (!result.ok || result.action !== 'screenshot' || !payload || typeof payload !== 'object') {+ throw new Error('Browser screenshot payload is invalid');+ }+ const record = payload as Record<string, unknown>;+ let buffer: Buffer;+ if (typeof record.data === 'string') {+ const decoded = decodeStrictBase64(record.data);+ if (!decoded) throw new Error('Browser screenshot payload is invalid');+ buffer = decoded;+ } else if (typeof record.path === 'string') {+ buffer = await readExternalScreenshot(record.path, options.runtimeDir);+ } else {+ throw new Error('Browser screenshot payload is invalid');+ }++ const mimeType = sniffScreenshotMime(buffer);+ if (!mimeType) throw new Error('Browser screenshot payload is invalid');+ if (typeof record.mimeType === 'string' && record.mimeType !== mimeType) {+ throw new Error('Browser screenshot MIME does not match its bytes');+ }+ return { buffer, mimeType };+}diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.tsindex e3739a9b13..68f2d942a1 100644--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts@@ -4,7 +4,7 @@ import type { BrowserControlRuntime } from '@cindy/browser-control-runtime';import { describe, expect, it } from 'vitest';import { createBrowserMcpServer } from './server.js';-import type { BrowserMcpDeps } from '../types.js';+import { INLINE_IMAGE_TARGET_BYTES, type BrowserMcpDeps } from '../types.js';// `respond` lets a test script the result per call (e.g. a navigate that returns// a swapped targetId); default echoes the request back as data.@@ -687,6 +687,129 @@ describe('createBrowserMcpServer', () => {await h.cleanup();});+ it('returns oversized screenshots as bounded image blocks without leaking binary text', async () => {+ const original = Buffer.alloc(240_000, 0xab);+ const compressed = Buffer.from('compressed-webp');+ const h = await makeHarness(+ {+ resolveScreenshot: async () => ({ buffer: original, mimeType: 'image/png' }),+ compressInlineImage: async () => ({ buffer: compressed, mime: 'image/webp' }),+ },+ () => ({+ path: '/private/browser-runtime/media/browser/screenshot.png',+ targetId: 'tab-1',+ url: 'https://example.com/',+ }),+ );++ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: { name: 'browser', args: { action: 'screenshot', targetId: 'tab-1' } },+ });++ expect(result.isError).not.toBe(true);+ const content = result.content as Array<+ { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }+ >;+ expect(content).toHaveLength(2);+ const textBlock = content[0];+ expect(textBlock.type).toBe('text');+ const metadata = JSON.parse('text' in textBlock ? textBlock.text : '{}') as {+ data?: Record<string, unknown>;+ truncated?: boolean;+ };+ expect(metadata.truncated).not.toBe(true);+ expect(metadata.data).toMatchObject({+ targetId: 'tab-1',+ url: 'https://example.com/',+ mimeType: 'image/webp',+ bytes: compressed.byteLength,+ });+ expect(metadata.data).not.toHaveProperty('path');+ expect(metadata.data).not.toHaveProperty('data');+ expect('text' in textBlock ? textBlock.text : '').not.toContain(original.toString('base64'));+ expect(content[1]).toEqual({+ type: 'image',+ data: compressed.toString('base64'),+ mimeType: 'image/webp',+ });+ await h.cleanup();+ });++ it('fails closed when an oversized screenshot cannot be compressed for inline delivery', async () => {+ const original = Buffer.alloc(240_000, 0xab);+ const h = await makeHarness(+ {+ resolveScreenshot: async () => ({ buffer: original, mimeType: 'image/png' }),+ compressInlineImage: async () => null,+ },+ () => ({+ 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);+ const block = blocks[0];+ expect(block.type).toBe('text');+ expect(JSON.parse(block.text ?? '{}')).toMatchObject({+ ok: false,+ action: 'screenshot',+ errorCode: 'BROWSER_SCREENSHOT_TOO_LARGE',+ });+ expect(block.text).not.toContain(original.toString('base64'));+ 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';+ const h = await makeHarness(+ {+ resolveScreenshot: async () => ({ buffer: screenshot, mimeType: 'image/png' }),+ },+ () => ({+ path: '/private/browser-runtime/media/browser/screenshot.png',+ targetId: 'tab-1',+ url: 'https://example.com/',+ labels: true,+ labelsCount: 10_000,+ annotations: Array.from({ length: 10_000 }, () => ({ text: annotationMarker.repeat(20) })),+ }),+ );++ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: { name: 'browser', args: { action: 'screenshot', targetId: 'tab-1' } },+ });++ expect(result.isError).not.toBe(true);+ const serialized = JSON.stringify(result);+ expect(Buffer.byteLength(serialized, 'utf8')).toBeLessThan(256 * 1024);+ expect(serialized).not.toContain(annotationMarker);+ const text = (result.content as Array<{ type: string; text?: string }>)[0]?.text ?? '{}';+ expect(JSON.parse(text)).toMatchObject({+ ok: true,+ action: 'screenshot',+ data: {+ targetId: 'tab-1',+ labels: true,+ labelsCount: 10_000,+ annotationCount: 10_000,+ },+ });+ await h.cleanup();+ });+it('keeps the truncated payload within the cap even for quote-heavy content (no double-escape blowup)', async () => {// A quote/backslash-heavy blob: the preview gets re-escaped by the outer// JSON.stringify, so a naive slice-to-cap would emit ~2x the cap. The finaldiff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.tsindex 272fb4f838..9f4bc50410 100644--- a/packages/lizi-mcps/src/browser/tools.ts+++ b/packages/lizi-mcps/src/browser/tools.ts@@ -1,11 +1,15 @@import {isPublicHttpResourceUrl,type BrowserControlRequest,+ type BrowserControlResult,type BrowserControlRuntime,} from '@cindy/browser-control-runtime';import { z } from 'zod';-import type { BrowserMcpDeps } from '../types.js';+import {+ INLINE_IMAGE_TARGET_BYTES,+ type BrowserMcpDeps,+} from '../types.js';import type { BrowserToolRegistry } from './tool-registry.js';import {buildExtractFnSource,@@ -208,6 +212,127 @@ function errorResult(action: string, message: string): {};}+function browserScreenshotError(+ errorCode: 'BROWSER_SCREENSHOT_INVALID' | 'BROWSER_SCREENSHOT_TOO_LARGE',+ message: string,+): {+ content: Array<{ type: 'text'; text: string }>;+ isError: true;+} {+ return {+ content: [+ {+ type: 'text',+ text: resultText({ ok: false, action: 'screenshot', errorCode, message }),+ },+ ],+ isError: true,+ };+}++function screenshotMetadata(+ result: BrowserControlResult,+ mimeType: string,+ bytes: number,+ originalBytes: number,+): Record<string, unknown> {+ const rawData = result.data && typeof result.data === 'object' && !Array.isArray(result.data)+ ? result.data as Record<string, unknown>+ : {};+ const boundedString = (key: string, maxChars: number): string | undefined => {+ const value = rawData[key];+ return typeof value === 'string' ? value.slice(0, maxChars) : undefined;+ };+ const boundedCount = (key: string): number | undefined => {+ const value = rawData[key];+ return typeof value === 'number' && Number.isFinite(value) && value >= 0+ ? Math.floor(value)+ : undefined;+ };+ const annotationCount = Array.isArray(rawData.annotations)+ ? rawData.annotations.length+ : undefined;+ return {+ ok: true,+ action: 'screenshot',+ data: {+ ...(boundedString('targetId', 512) ? { targetId: boundedString('targetId', 512) } : {}),+ ...(boundedString('tabId', 512) ? { tabId: boundedString('tabId', 512) } : {}),+ ...(boundedString('url', 4_096) ? { url: boundedString('url', 4_096) } : {}),+ ...(typeof rawData.labels === 'boolean' ? { labels: rawData.labels } : {}),+ ...(boundedCount('labelsCount') !== undefined+ ? { labelsCount: boundedCount('labelsCount') }+ : {}),+ ...(boundedCount('labelsSkipped') !== undefined+ ? { labelsSkipped: boundedCount('labelsSkipped') }+ : {}),+ ...(annotationCount !== undefined ? { annotationCount } : {}),+ mimeType,+ bytes,+ ...(bytes !== originalBytes ? { originalBytes } : {}),+ },+ };+}++async function screenshotToolResult(+ result: BrowserControlResult,+ deps: BrowserMcpDeps,+) {+ if (!result.ok) {+ return {+ content: [{ type: 'text' as const, text: resultText(result) }],+ isError: true,+ };+ }+ if (!deps.resolveScreenshot) {+ return browserScreenshotError(+ 'BROWSER_SCREENSHOT_INVALID',+ '当前 host 无法把浏览器截图解析为模型图片输入。',+ );+ }++ const resolved = await deps.resolveScreenshot(result);+ 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) {+ return browserScreenshotError(+ 'BROWSER_SCREENSHOT_TOO_LARGE',+ '浏览器截图超过模型内联传输上限,且无法安全压缩。请缩小窗口后重试。',+ );+ }+ buffer = compressed.buffer;+ mimeType = compressed.mime;+ }++ if (!['image/png', 'image/jpeg', 'image/webp'].includes(mimeType) || buffer.byteLength === 0) {+ return browserScreenshotError(+ 'BROWSER_SCREENSHOT_INVALID',+ '浏览器截图没有返回受支持的有效图片。',+ );+ }++ return {+ content: [+ {+ type: 'text' as const,+ text: resultText(screenshotMetadata(result, mimeType, buffer.byteLength, originalBytes)),+ },+ {+ type: 'image' as const,+ data: buffer.toString('base64'),+ mimeType,+ },+ ],+ isError: false,+ };+}+// Forwards validated MCP args straight to the runtime. `extract` (MCP-only// sugar) is rewritten in the handler before this is reached, so every `action`// arriving here is a real BrowserControlAction.@@ -614,6 +739,9 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse} else {result = await runtime.call(toRuntimeRequest(args));}+ if (args.action === 'screenshot') {+ return await screenshotToolResult(result, deps);+ }// For extract, the runtime call may succeed (evaluate ran) while the// in-page extract reports ok:false (invalid selector); surface that as an// error so the agent sees + acts on the embedded hint.diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex 5e2066bac9..6be6cd4ed0 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -1,4 +1,7 @@-import type { BrowserControlRuntime } from '@cindy/browser-control-runtime';+import type {+ BrowserControlResult,+ BrowserControlRuntime,+} from '@cindy/browser-control-runtime';import type { AgentKind } from '@cindy/maker-core';import type { Recipe, SiteGuide } from './browser/recipe-loader.js';@@ -496,9 +499,24 @@ export type ControlResult<T extends object = object, E extends string = never> =*/export type ControlWorkerAgent = 'claude-code' | 'codex' | 'pi';+export interface ResolvedBrowserScreenshot {+ buffer: Buffer;+ mimeType: 'image/png' | 'image/jpeg';+}+/** Browser automation MCP host deps. Core browser execution is injected by host. */export interface BrowserMcpDeps {getRuntime(): BrowserControlRuntime;+ /**+ * Resolve a successful screenshot runtime result into verified image bytes.+ * The host owns file-system access so this package never receives a generic+ * arbitrary-path reader; inline-only hosts may validate and decode in memory.+ */+ resolveScreenshot?(+ result: BrowserControlResult,+ ): Promise<ResolvedBrowserScreenshot>;+ /** Shrink the LLM-facing copy to the shared stream-safe byte budget. */+ compressInlineImage?: CompressInlineImageFn;/** Whether the active backend accepts managed resource downloads. */supportsResourceDownloads?(): boolean;/** Whether the active backend accepts semantic element queries. */