Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): say and log why an SVG image was not drawn

marcoteb579762df50a2
diff --git a/mcp-host/src/workflow/__tests__/embeddedImages.svg.test.ts b/mcp-host/src/workflow/__tests__/embeddedImages.svg.test.ts
index 348357a3a..de9ed75ba 100644
--- a/mcp-host/src/workflow/__tests__/embeddedImages.svg.test.ts
+++ b/mcp-host/src/workflow/__tests__/embeddedImages.svg.test.ts
@@ -3,12 +3,20 @@
* follow their size, so costly features are refused up front and the rest is
* drawn in a child process the host can kill, never on its event loop.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import * as childProcess from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
+import { logger } from '../../logger'
import { INTERNAL_TOOLS } from '../internalTools'
+// The real spawn, watched, to read what the renderer process is given.
+vi.mock('child_process', async original => {
+ const actual = await original<typeof import('child_process')>()
+ return { ...actual, spawn: vi.fn(actual.spawn) }
+})
+
const pdf = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!
const markdown = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!
@@ -103,6 +111,31 @@ describe('SVG images', () => {
}, 30000)
})
+describe('an SVG the renderer cannot draw', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('says it could not be drawn and why, and logs the reason, instead of blaming the time', async () => {
+ const warn = vi.spyOn(logger, 'warn')
+ const result = await pdfWith('broken.svg', `<svg ${SVG} width="40" height="20"><rect width=`)
+ expect(result.success, result.error).toBe(true)
+ expect(result.content).toMatch(/broken\.svg' could not be drawn/)
+ expect(result.content).not.toMatch(/took longer/)
+ const logged = warn.mock.calls.find(([, message]) => String(message).includes('SVG'))
+ expect(logged?.[0]).toMatchObject({ component: 'EmbeddedImages', reason: 'exit', code: 1 })
+ })
+
+ it('gives the renderer no environment but a home directory', async () => {
+ const spawn = vi.mocked(childProcess.spawn)
+ spawn.mockClear()
+ await pdfWith('plain.svg', NORMAL)
+ const options = spawn.mock.calls.at(-1)?.[2] as { env?: Record<string, string> }
+ expect(Object.keys(options.env ?? {})).toEqual(['HOME'])
+ expect(options.env!.HOME).not.toBe('')
+ })
+})
+
describe('raster images a PDF would decode', () => {
it('leaves an image over the pixel limit out of a PDF, saying so, and still embeds it in a DOCX', async () => {
const { createCanvas } = await import('@napi-rs/canvas')
diff --git a/mcp-host/src/workflow/embeddedImages.ts b/mcp-host/src/workflow/embeddedImages.ts
index 143fffe19..7cff62d25 100644
--- a/mcp-host/src/workflow/embeddedImages.ts
+++ b/mcp-host/src/workflow/embeddedImages.ts
@@ -4,7 +4,9 @@
import { createCanvas, loadImage } from '@napi-rs/canvas'
import { spawn } from 'child_process'
import * as fs from 'fs'
+import * as os from 'os'
import * as path from 'path'
+import { logger } from '../logger'
import { isPartialArtifactName } from './artifactOutput'
import { imageTarget } from './inlineMarkup'
import { own } from './ownEntry'
@@ -447,11 +449,41 @@ process.stdin.on('end', async () => {
let svgQueue: Promise<unknown> = Promise.resolve()
-/** PNG bytes of `svg`, rendered in a child process, one at a time; undefined when it fails or runs too long. */
-function renderSvg(svg: Buffer): Promise<Buffer | undefined> {
+/** Bytes of the renderer's error output kept for the log. */
+const STDERR_KEPT = 512
+
+/** Why the renderer gave no image. */
+type SvgFailure = 'spawn' | 'exit' | 'too-large' | 'timeout' | 'output'
+
+type SvgRender = { png: Buffer } | { failure: SvgFailure }
+
+/** The note for an SVG the renderer gave no image for. */
+function svgFailureNote(failure: SvgFailure): string {
+ switch (failure) {
+ case 'timeout':
+ return `took longer than ${SVG_RENDER_MS / 1000} s to draw`
+ case 'too-large':
+ return 'draws more pixels than this tool converts'
+ default:
+ return 'could not be drawn'
+ }
+}
+
+/** PNG bytes of `svg`, rendered in a child process, one at a time, or why there are none. */
+function renderSvg(svg: Buffer): Promise<SvgRender> {
const run = svgQueue.then(
() =>
- new Promise<Buffer | undefined>(resolve => {
+ new Promise<SvgRender>(resolve => {
+ const failed = (
+ failure: SvgFailure,
+ detail: { code?: number | null; signal?: string | null; stderr?: string } = {}
+ ) => {
+ logger.warn(
+ { component: 'EmbeddedImages', reason: failure, ...detail },
+ 'An SVG image could not be drawn and was left out'
+ )
+ resolve({ failure })
+ }
let child: ReturnType<typeof spawn>
try {
child = spawn(
@@ -462,26 +494,49 @@ function renderSvg(svg: Buffer): Promise<Buffer | undefined> {
require.resolve('@napi-rs/canvas'),
String(MAX_DECODE_PIXELS),
],
- // No environment: the renderer needs none, and it holds no secret.
- { stdio: ['pipe', 'pipe', 'ignore'], env: {} }
+ // Only a home directory, which the renderer looks up when it loads
+ // the system fonts and which a user with no account entry lacks;
+ // it holds no secret.
+ {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { HOME: process.env.HOME || os.tmpdir() },
+ }
)
} catch {
- resolve(undefined)
+ failed('spawn')
return
}
const chunks: Buffer[] = []
let size = 0
- const timer = setTimeout(() => child.kill('SIGKILL'), SVG_RENDER_MS)
+ let stderr = ''
+ let ended: SvgFailure | undefined
+ const timer = setTimeout(() => {
+ ended = 'timeout'
+ child.kill('SIGKILL')
+ }, SVG_RENDER_MS)
child.stdout!.on('data', (chunk: Buffer) => {
size += chunk.length
- if (size > MAX_DECODE_PIXELS * 4) child.kill('SIGKILL')
- else chunks.push(chunk)
+ if (size > MAX_DECODE_PIXELS * 4) {
+ ended = 'too-large'
+ child.kill('SIGKILL')
+ } else chunks.push(chunk)
+ })
+ child.stderr!.on('data', (chunk: Buffer) => {
+ if (stderr.length < STDERR_KEPT) stderr += chunk.toString('utf8')
+ })
+ child.on('error', () => {
+ ended ??= 'spawn'
})
- child.on('error', () => undefined)
- child.on('close', code => {
+ child.on('close', (code, signal) => {
clearTimeout(timer)
const png = Buffer.concat(chunks)
- resolve(code === 0 && isPng(png) ? png : undefined)
+ if (!ended && code === 0 && isPng(png)) {
+ resolve({ png })
+ return
+ }
+ // Exit 2 is the renderer's own refusal of an image over the pixel limit.
+ const failure = ended ?? (code === 2 ? 'too-large' : code === 0 ? 'output' : 'exit')
+ failed(failure, { code, signal, stderr: stderr.slice(0, STDERR_KEPT) || undefined })
})
child.stdin!.on('error', () => undefined)
child.stdin!.end(svg)
@@ -613,12 +668,12 @@ export async function predecodeImages(args: unknown, outputDir: string): Promise
refuse(key, refusal)
continue
}
- const png = await renderSvg(input)
- if (png) {
+ const drawn = await renderSvg(input)
+ if ('png' in drawn) {
hold(key)
- keepDecoded(key, png)
+ keepDecoded(key, drawn.png)
} else {
- refuse(key, `took longer than ${SVG_RENDER_MS / 1000} s to draw, or could not be drawn`)
+ refuse(key, svgFailureNote(drawn.failure))
}
continue
}