Skip to content

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

TypeScript

test(mcp-host): test the XLSX cell and format readers, native charts, chart cards and DOCX images directly

marcotebcff57b7345c4
diff --git a/mcp-host/src/workflow/__tests__/dashboardParts.test.ts b/mcp-host/src/workflow/__tests__/dashboardParts.test.ts
new file mode 100644
index 000000000..bd725859b
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/dashboardParts.test.ts
@@ -0,0 +1,59 @@
+/**
+ * The dashboard's parts tested apart from the tool: chart cards, and the
+ * helpers that put model text into HTML and into the page script.
+ */
+import { describe, expect, it } from 'vitest'
+import { DashboardCharts } from '../dashboardCharts'
+import { escapeHtml, escapeHtmlAttr, oneOf, safeJsonForScript } from '../dashboardHtml'
+
+const notes = () => ({ warnings: [] as string[], failures: [] as string[] })
+const bar = { type: 'bar', labels: ['a', 'b'], datasets: [{ label: 's', data: [1, '1,200'] }] }
+
+describe('DashboardCharts', () => {
+ it('keeps the spec of a chart the page draws, and a canvas for it', () => {
+ const charts = new DashboardCharts(true, notes())
+ const html = charts.card(bar, 'data.charts[0]', { title: 'Sales' })
+ expect(html).toContain('<h3 class="chart-card__title">Sales</h3>')
+ expect(html).toContain('<canvas id="chart-0"')
+ expect(charts.specs).toHaveLength(1)
+ expect(charts.drawn).toBe(1)
+ })
+
+ it('shows the values as a table when the page draws no charts', () => {
+ const charts = new DashboardCharts(false, notes())
+ const html = charts.card(bar, 'data.charts[0]')
+ expect(html).not.toContain('<canvas')
+ // The values as read: "1,200" sent as text is the number 1200.
+ expect(html).toContain('<td>b</td><td>1200</td>')
+ expect(charts.specs).toHaveLength(0)
+ expect(charts.drawn).toBe(1)
+ })
+
+ it('reports a chart it cannot draw in its place, escaped', () => {
+ const reported = notes()
+ const charts = new DashboardCharts(true, reported)
+ const html = charts.card({ type: '<b>pie3d</b>', labels: ['a'] }, 'data.charts[1]')
+ expect(html).toContain('This chart could not be drawn')
+ expect(html).not.toContain('<b>pie3d')
+ expect(reported.failures).toHaveLength(1)
+ expect(charts.drawn).toBe(0)
+ })
+})
+
+describe('dashboardHtml', () => {
+ it('escapes attributes as it escapes text', () => {
+ expect(escapeHtmlAttr(`'"<a>`)).toBe(escapeHtml(`'"<a>`))
+ })
+
+ it('takes only an allowed value, and only a string', () => {
+ expect(oneOf('dark', ['light', 'dark'] as const, 'light')).toBe('dark')
+ expect(oneOf('toString', ['light', 'dark'] as const, 'light')).toBe('light')
+ expect(oneOf(1, ['light', 'dark'] as const, 'light')).toBe('light')
+ })
+
+ it('writes JSON a script block cannot be closed or broken by', () => {
+ const text = safeJsonForScript({ a: '</script><script>alert(1)</script>', b: '\u2028&' })
+ expect(text).not.toMatch(/<|>|&|\u2028/)
+ expect(JSON.parse(text)).toEqual({ a: '</script><script>alert(1)</script>', b: '\u2028&' })
+ })
+})
diff --git a/mcp-host/src/workflow/__tests__/docxImages.test.ts b/mcp-host/src/workflow/__tests__/docxImages.test.ts
new file mode 100644
index 000000000..251397685
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/docxImages.test.ts
@@ -0,0 +1,64 @@
+/**
+ * One image paragraph of a DOCX: fitted to its box, with its drawing id, or
+ * left out with a warning that names the argument.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { createCanvas } from '@napi-rs/canvas'
+import { Document, Packer } from 'docx'
+import * as fs from 'fs'
+import JSZip from 'jszip'
+import * as os from 'os'
+import * as path from 'path'
+import { docxImageParagraph } from '../docxImages'
+
+let dir: string
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-docx-image-'))
+ fs.writeFileSync(path.join(dir, 'wide.png'), createCanvas(800, 200).toBuffer('image/png'))
+})
+afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+async function documentXml(paragraph: NonNullable<ReturnType<typeof docxImageParagraph>>) {
+ const buffer = await Packer.toBuffer(new Document({ sections: [{ children: [paragraph] }] }))
+ return (await JSZip.loadAsync(buffer)).file('word/document.xml')!.async('string')
+}
+
+describe('docxImageParagraph', () => {
+ it('fits the image to its box, keeping its proportions, under the id it is given', async () => {
+ const warnings: string[] = []
+ const box = { width: 400, height: 400 }
+ const paragraph = docxImageParagraph(
+ 'wide.png',
+ dir,
+ box,
+ { altText: 'Sales' },
+ warnings,
+ 'images[0]',
+ 7
+ )
+ expect(paragraph).toBeDefined()
+ const xml = await documentXml(paragraph!)
+ const extent = /<wp:extent cx="(\d+)" cy="(\d+)"/.exec(xml)!
+ // 400 x 100 pixels, in EMU.
+ expect([Number(extent[1]), Number(extent[2])]).toEqual([400 * 9525, 100 * 9525])
+ expect(xml).toMatch(/<wp:docPr id="7" name="wide.png" descr="Sales"/)
+ expect(warnings).toEqual([])
+ })
+
+ it('leaves out a missing image with a warning that names the argument', () => {
+ const warnings: string[] = []
+ const box = { width: 400, height: 400 }
+ expect(docxImageParagraph('nope.png', dir, box, {}, warnings, 'images[1]', 1)).toBeUndefined()
+ expect(warnings).toHaveLength(1)
+ expect(warnings[0]).toMatch(/^images\[1\]: /)
+ })
+
+ it('fails on a path out of the output folder, saying how to name the file', () => {
+ const box = { width: 400, height: 400 }
+ expect(() => docxImageParagraph('../x.png', dir, box, {}, [], 'images[2]', 1)).toThrow(
+ /images\[2\]: .*Pass the file name in the output folder/
+ )
+ })
+})
diff --git a/mcp-host/src/workflow/__tests__/pptxCharts.test.ts b/mcp-host/src/workflow/__tests__/pptxCharts.test.ts
new file mode 100644
index 000000000..e35e2d39e
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/pptxCharts.test.ts
@@ -0,0 +1,85 @@
+/**
+ * Native PowerPoint charts: how a chart spec is read, and the pptxgenjs
+ * arguments it becomes.
+ */
+import { describe, expect, it } from 'vitest'
+import { ChartSpecError, type NativeChart, nativeChartArgs, readNativeChart } from '../pptxCharts'
+
+const style = { colors: ['#111111', '#222222'], textColor: '#000000', mutedColor: '#666666' }
+const pptx = {
+ charts: { BAR: 'bar', LINE: 'line', PIE: 'pie', AREA: 'area', DOUGHNUT: 'doughnut' },
+}
+
+describe('readNativeChart', () => {
+ it('reads labels and datasets nested under data or at the top', () => {
+ const nested = readNativeChart(
+ { type: 'bar', data: { labels: ['a', 'b'], datasets: [{ label: 'x', data: [1, '1,200'] }] } },
+ 'slides[0].chart',
+ []
+ )
+ expect(nested).toEqual({
+ type: 'bar',
+ labels: ['a', 'b'],
+ series: [{ name: 'x', values: [1, 1200] }],
+ })
+ const top = readNativeChart(
+ { type: 'line', labels: ['a'], datasets: [{ label: 'x', data: [2] }] },
+ 'c',
+ []
+ )
+ expect(top?.series[0].values).toEqual([2])
+ })
+
+ it('draws a bar chart when no type is given, and says so', () => {
+ const warnings: string[] = []
+ const chart = readNativeChart({ labels: ['a'], datasets: [{ data: [1] }] }, 'c', warnings)
+ expect(chart?.type).toBe('bar')
+ expect(warnings[0]).toContain('c.type was missing')
+ })
+
+ it('has nothing to read without data', () => {
+ expect(readNativeChart({ type: 'bar' }, 'c', [])).toBeUndefined()
+ })
+
+ it('names the field of a type PowerPoint cannot draw, and the way out', () => {
+ expect(() =>
+ readNativeChart({ type: 'radar', labels: ['a'], datasets: [{ data: [1] }] }, 'c', [])
+ ).toThrow(ChartSpecError)
+ expect(() =>
+ readNativeChart({ type: 'radar', labels: ['a'], datasets: [{ data: [1] }] }, 'c', [])
+ ).toThrow(/c\.type "radar" has no native PowerPoint chart.*clerum__generate_chart/)
+ })
+})
+
+describe('nativeChartArgs', () => {
+ const chart = (over: Partial<NativeChart>): NativeChart => ({
+ type: 'bar',
+ labels: ['a', 'b'],
+ series: [{ name: 's', values: [1, 2] }],
+ ...over,
+ })
+
+ it('maps each type to the pptxgenjs chart and bar direction', () => {
+ expect(nativeChartArgs(chart({ type: 'horizontalBar' }), style, pptx).options.barDir).toBe(
+ 'bar'
+ )
+ expect(nativeChartArgs(chart({ type: 'stackedArea' }), style, pptx).type).toBe('area')
+ expect(nativeChartArgs(chart({ type: 'doughnut' }), style, pptx).type).toBe('doughnut')
+ })
+
+ it('gives a lone bar series one color, not one per bar', () => {
+ expect(nativeChartArgs(chart({}), style, pptx).options.chartColors).toEqual(['#111111'])
+ })
+
+ it('formats values with their decimals, grouped from a thousand', () => {
+ const small = nativeChartArgs(chart({ series: [{ name: 's', values: [1.5, 2] }] }), style, pptx)
+ expect(small.options.dataLabelFormatCode).toBe('[>=1000]#,##0;[<=-1000]-#,##0;General')
+ const large = nativeChartArgs(
+ chart({ series: [{ name: 's', values: [1200.25, 3] }] }),
+ style,
+ pptx
+ )
+ expect(large.options.dataLabelFormatCode).toBe('#,##0.00')
+ expect(large.options.valAxisLabelFormatCode).toBe('#,##0')
+ })
+})
diff --git a/mcp-host/src/workflow/__tests__/xlsxCells.test.ts b/mcp-host/src/workflow/__tests__/xlsxCells.test.ts
new file mode 100644
index 000000000..40b9d2d6b
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/xlsxCells.test.ts
@@ -0,0 +1,125 @@
+/**
+ * How one XLSX cell is read from what a model sends: which text becomes a
+ * number, a percent, an amount or a date, and which stays text because
+ * converting it would change it.
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ cellProblem,
+ codeDigits,
+ currencyPrefix,
+ currencySuffix,
+ isQuantityText,
+ looksLikeRefusedDate,
+ looksLikeUnreadNumber,
+ readCell,
+ ruleDate,
+ ruleNumber,
+ startsLikeFormula,
+ visualWidth,
+} from '../xlsxCells'
+
+describe('readCell', () => {
+ it('keeps values that are already typed', () => {
+ expect(readCell(null)).toEqual({ value: null, kind: 'empty', text: '' })
+ expect(readCell(true)).toMatchObject({ value: true, kind: 'boolean' })
+ expect(readCell(12.5)).toMatchObject({ value: 12.5, kind: 'number', written: 12.5 })
+ })
+
+ it('reads grouped numbers, percents and amounts', () => {
+ expect(readCell('1,200')).toMatchObject({ value: 1200, kind: 'number' })
+ expect(readCell('45%')).toMatchObject({ value: 0.45, kind: 'percent', written: 45 })
+ expect(readCell('$1,200.50')).toMatchObject({
+ value: 1200.5,
+ kind: 'currency',
+ currency: '$',
+ written: 1200.5,
+ })
+ expect(readCell('−5')).toMatchObject({ value: -5, kind: 'number' })
+ expect(readCell('(1,200)')).toMatchObject({ value: -1200, kind: 'number' })
+ })
+
+ it('keeps as text what a number would change', () => {
+ for (const text of ['00501', '4111111111111111', '(2024)', '1,5', '1.234,50', 'N/A']) {
+ expect(readCell(text), text).toMatchObject({ value: text, kind: 'text' })
+ }
+ })
+
+ it('keeps text as sent when the column is not converted', () => {
+ expect(readCell('1,200', false)).toEqual({ value: '1,200', kind: 'text', text: '1,200' })
+ })
+
+ it('reads ISO 8601 dates and times, and refuses one Excel would show wrong', () => {
+ const date = readCell('2026-09-22')
+ expect(date.kind).toBe('date')
+ expect((date.value as Date).toISOString()).toBe('2026-09-22T00:00:00.000Z')
+ expect(readCell('2026-09-22T10:30:00Z').kind).toBe('datetime')
+ expect(readCell('2026-02-30').kind).toBe('text')
+ expect(readCell('1900-02-28').kind).toBe('text')
+ })
+})
+
+describe('the text a reader leaves alone', () => {
+ it('names the refused dates and the numbers written for another locale', () => {
+ expect(looksLikeRefusedDate('2026-02-30')).toBe(true)
+ expect(looksLikeRefusedDate('2026-02-28')).toBe(false)
+ for (const text of ['1.234,50', '12,5%', '22/09/2026', '1e6', '€ 1.234,50']) {
+ expect(looksLikeUnreadNumber(text), text).toBe(true)
+ }
+ expect(looksLikeUnreadNumber('Revenue')).toBe(false)
+ })
+
+ it('tells codes from numbers', () => {
+ expect(codeDigits('00501')).toBe(true)
+ expect(codeDigits('1234567890123456')).toBe(true)
+ expect(codeDigits('12345')).toBe(false)
+ })
+
+ it('reads currency symbols and codes on either side', () => {
+ expect(currencyPrefix('$12')).toEqual(['$', 1])
+ expect(currencyPrefix('EUR 12')).toEqual(['€', 4])
+ expect(currencySuffix('12 €')).toEqual(['€', 1])
+ expect(currencyPrefix('ABC 12')).toBeUndefined()
+ expect(isQuantityText('-$5')).toBe(true)
+ expect(isQuantityText('5')).toBe(false)
+ })
+})
+
+describe('rule values', () => {
+ it('reads a rule threshold the way a cell is read', () => {
+ expect(ruleNumber('45%')).toBe(45)
+ expect(ruleNumber('$1,200')).toBe(1200)
+ expect(ruleNumber(Number.POSITIVE_INFINITY)).toBeUndefined()
+ expect(ruleNumber({})).toBeUndefined()
+ expect(ruleDate('2026-09-22')?.toISOString()).toBe('2026-09-22T00:00:00.000Z')
+ expect(ruleDate('next week')).toBeUndefined()
+ })
+})
+
+describe('cellProblem', () => {
+ it('accepts what a cell holds and names what it cannot', () => {
+ for (const ok of [null, undefined, 'a', 1, false]) expect(cellProblem(ok)).toBeUndefined()
+ expect(cellProblem(Number.NaN)).toBe('is not a finite number')
+ expect(cellProblem([1])).toBe('is an array; a cell holds a single value')
+ expect(cellProblem({ formula: 'NOW()' })).toContain('is an object (keys: formula)')
+ expect(cellProblem(new Date(0))).toContain('is a Date object')
+ })
+})
+
+describe('startsLikeFormula', () => {
+ it('flags every lead Excel reads as a formula', () => {
+ for (const lead of ['=1', '+1', '-1', '@x', '\tx', '\rx']) {
+ expect(startsLikeFormula(lead), JSON.stringify(lead)).toBe(true)
+ }
+ expect(startsLikeFormula('a=1')).toBe(false)
+ })
+})
+
+describe('visualWidth', () => {
+ it('counts CJK and emoji as two, marks as none, and takes the widest line', () => {
+ expect(visualWidth('abc')).toBe(3)
+ expect(visualWidth('売上')).toBe(4)
+ expect(visualWidth('é')).toBe(1)
+ expect(visualWidth('ab\nabcd')).toBe(4)
+ })
+})
diff --git a/mcp-host/src/workflow/__tests__/xlsxFormats.test.ts b/mcp-host/src/workflow/__tests__/xlsxFormats.test.ts
new file mode 100644
index 000000000..fd73bb1ec
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/xlsxFormats.test.ts
@@ -0,0 +1,103 @@
+/**
+ * The number format an XLSX column gets: the one a caller asks for by
+ * keyword or code, and the one its header and values suggest otherwise.
+ */
+import { describe, expect, it } from 'vitest'
+import {
+ NUMBER_FORMATS,
+ currencyFormat,
+ detectFormat,
+ displayedWidth,
+ formatSpec,
+ headerCurrency,
+ isIdentifierHeader,
+ percentFormat,
+} from '../xlsxFormats'
+
+describe('formatSpec', () => {
+ it('reads keywords in any case and spacing', () => {
+ expect(formatSpec('Currency USD')).toEqual({ type: 'currency', symbol: '$', decimals: 2 })
+ expect(formatSpec('percent-int')).toEqual({ type: 'percent', points: false, decimals: 0 })
+ expect(formatSpec('date')).toEqual({ type: 'date', numFmt: NUMBER_FORMATS.date })
+ })
+
+ it('reads a currency by its code, known or not', () => {
+ expect(formatSpec('EUR')).toEqual({ type: 'currency', symbol: '€' })
+ expect(formatSpec('currency:xyz')).toEqual({ type: 'currency', symbol: 'XYZ ' })
+ })
+
+ it('takes an Excel format code as it is, and nothing else', () => {
+ expect(formatSpec('#,##0.000')).toEqual({ type: 'custom', numFmt: '#,##0.000' })
+ expect(formatSpec('bold please')).toBeUndefined()
+ expect(formatSpec('toString')).toBeUndefined()
+ expect(formatSpec(42)).toBeUndefined()
+ })
+})
+
+describe('detectFormat', () => {
+ it('formats money, percents, dates and years from the header', () => {
+ expect(detectFormat('Revenue', [1200])).toEqual({ type: 'currency', symbol: '$' })
+ expect(detectFormat('Price (EUR)', [10])).toEqual({ type: 'currency', symbol: '€' })
+ expect(detectFormat('Monto', [1200])).toEqual({
+ type: 'number',
+ numFmt: NUMBER_FORMATS.integer,
+ })
+ expect(detectFormat('Churn rate', [0.05])).toEqual({ type: 'percent', points: false })
+ expect(detectFormat('Share', [45])).toEqual({ type: 'percent', points: true })
+ expect(detectFormat('Created at', [46000])).toEqual({
+ type: 'date',
+ numFmt: NUMBER_FORMATS.date,
+ })
+ expect(detectFormat('Year', [2026])).toEqual({ type: 'number', numFmt: NUMBER_FORMATS.plain })
+ })
+
+ it('keeps identifiers and exchange rates from being read as amounts or shares', () => {
+ expect(detectFormat('Invoice No.', [1001])).toEqual({
+ type: 'number',
+ numFmt: NUMBER_FORMATS.plain,
+ })
+ expect(detectFormat('Exchange rate', [17.2])).toEqual({
+ type: 'number',
+ numFmt: NUMBER_FORMATS.decimal,
+ })
+ })
+
+ it('shows as many decimals as a value needs', () => {
+ expect(detectFormat('p', [0.0012])).toEqual({ type: 'number', numFmt: '#,##0.0000' })
+ expect(detectFormat('x', [])).toBeUndefined()
+ })
+})
+
+describe('header words', () => {
+ it('names the currency of a header by code or symbol', () => {
+ expect(headerCurrency('Total (MXN)')).toBe('MX$')
+ expect(headerCurrency('Cost R$')).toBe('R$')
+ // "pen" is a word in lowercase, a currency only in capitals.
+ expect(headerCurrency('pen count')).toBeUndefined()
+ })
+
+ it('tells identifiers from counts and amounts', () => {
+ expect(isIdentifierHeader('Zip code')).toBe(true)
+ expect(isIdentifierHeader('Número de factura')).toBe(true)
+ expect(isIdentifierHeader('Number of employees')).toBe(false)
+ expect(isIdentifierHeader('Ticket price')).toBe(false)
+ })
+})
+
+describe('formats and widths', () => {
+ it('writes currency formats with the symbol quoted', () => {
+ expect(currencyFormat('€', 2)).toBe('"€"#,##0.00_);[Red]("€"#,##0.00)')
+ expect(currencyFormat('a"b', 0)).toBe('"ab"#,##0_);[Red]("ab"#,##0)')
+ })
+
+ it('shows whole percents without a decimal', () => {
+ expect(percentFormat(undefined, [0.25, 0.5])).toBe(NUMBER_FORMATS.percentInt)
+ expect(percentFormat(undefined, [0.255])).toBe(NUMBER_FORMATS.percent)
+ })
+
+ it('measures a value as its format shows it', () => {
+ expect(displayedWidth(1234567, NUMBER_FORMATS.integer)).toBe('1,234,567'.length)
+ expect(displayedWidth(new Date(0), NUMBER_FORMATS.date)).toBe(10)
+ expect(displayedWidth(new Date(0), NUMBER_FORMATS.datetime)).toBe(16)
+ })
+})