Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): paint a chart's series the same in the PNG and the dashboard
marcotebfb5aaf24356e
diff --git a/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts b/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.tsnew file mode 100644index 000000000..615c65e81--- /dev/null+++ b/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts@@ -0,0 +1,149 @@+// The PNG chart and the dashboard paint the same chart alike: each color of+// each series plays the same role (palette color, its tint, the caller's color+// or its tint) in both outputs, although one writes hex and the other tokens.+import { describe, expect, it } from 'vitest'+import { normalizeChartData } from '../chartData'+import { paintedDatasets } from '../chartGenerator'+import { CHART_THEMES } from '../chartThemes'+import { prepareDashboardChart } from '../dashboardCharts'+import { tintOf } from '../seriesPaint'++const theme = CHART_THEMES.light++const KINDS = [+ 'bar',+ 'horizontalBar',+ 'stackedBar',+ 'line',+ 'area',+ 'stackedArea',+ 'radar',+ 'scatter',+ 'bubble',+ 'mixedBarLine',+] as const++const XY = new Set(['scatter', 'bubble'])++/** Two series; the caller's colors, if any, on the first. */+function chartData(kind: string, own: Record<string, string>) {+ const values = XY.has(kind)+ ? (k: number) => [+ { x: 1, y: 2 * k, ...(kind === 'bubble' ? { r: 4 } : {}) },+ { x: 2, y: 3 * k, ...(kind === 'bubble' ? { r: 6 } : {}) },+ ]+ : (k: number) => [1 * k, 2 * k, 3 * k]+ return {+ ...(XY.has(kind) ? {} : { labels: ['a', 'b', 'c'] }),+ datasets: [+ { label: 'One', data: values(1), ...own },+ { label: 'Two', data: values(2) },+ ],+ }+}++type Palette = { color: string; tint: string }++/** What each color of a series is, independent of how the output writes it. */+function roles(ds: Record<string, unknown>, palette: Palette, own: Record<string, string>) {+ const name = (value: unknown): string => {+ if (value === undefined) return 'none'+ if (value === palette.color) return 'palette'+ if (value === palette.tint) return 'palette tint'+ for (const [key, color] of Object.entries(own)) {+ if (value === color) return `own ${key}`+ if (value === tintOf(color)) return `own ${key} tint`+ }+ return `other ${JSON.stringify(value)}`+ }+ return {+ border: name(ds.borderColor),+ fill: name(ds.backgroundColor),+ points: name(ds.pointBackgroundColor),+ }+}++function pngRoles(kind: string, own: Record<string, string>) {+ const normalized = normalizeChartData(chartData(kind, own), { chartType: kind })+ const { datasets } = paintedDatasets(+ kind,+ normalized.datasets as never,+ normalized.labels,+ theme,+ {},+ []+ )+ return datasets.map((ds, i) => {+ const color = theme.palette[i % theme.palette.length]+ return roles(ds as unknown as Record<string, unknown>, { color, tint: `${color}33` }, own)+ })+}++function dashboardRoles(kind: string, own: Record<string, string>) {+ const prepared = prepareDashboardChart({ type: kind, ...chartData(kind, own) }, 'charts[0]')+ expect(prepared.error).toBeUndefined()+ return prepared.chart!.datasets.map((ds, i) =>+ roles(ds, { color: `$chart-${i}`, tint: `$chart-${i}@0.2` }, own)+ )+}++const OWN_COLORS: Array<Record<string, string>> = [+ {},+ { borderColor: '#ff0000' },+ { borderColor: '#f00' },+ { borderColor: 'red' },+ { borderColor: 'rgb(255, 0, 0)' },+ { backgroundColor: '#22c55e' },+ { borderColor: 'red', backgroundColor: '#22c55e' },+]++describe('the PNG chart and the dashboard paint a series alike', () => {+ for (const kind of KINDS) {+ it.each(OWN_COLORS)(`${kind} with %j`, own => {+ expect(pngRoles(kind, own)).toEqual(dashboardRoles(kind, own))+ })+ }+})++describe('how a series is painted', () => {+ it('fills a stacked area in its solid color: the areas do not overlap', () => {+ for (const each of [pngRoles('stackedArea', {}), dashboardRoles('stackedArea', {})]) {+ expect(each[0]).toEqual({ border: 'palette', fill: 'palette', points: 'palette' })+ }+ })++ it('draws the points of a radar in the series color, over its tinted web', () => {+ for (const each of [pngRoles('radar', {}), dashboardRoles('radar', {})]) {+ expect(each[0]).toEqual({ border: 'palette', fill: 'palette tint', points: 'palette' })+ }+ })++ it("tints a line's fill and colors its points from the caller's line color", () => {+ const own = { borderColor: '#f00' }+ for (const each of [pngRoles('area', own), dashboardRoles('area', own)]) {+ expect(each[0]).toEqual({+ border: 'own borderColor',+ fill: 'own borderColor tint',+ points: 'own borderColor',+ })+ }+ })++ it("keeps a caller's fill on scatter marks", () => {+ const own = { backgroundColor: '#22c55e' }+ for (const each of [pngRoles('scatter', own), dashboardRoles('scatter', own)]) {+ expect(each[0]).toEqual({ border: 'palette', fill: 'own backgroundColor', points: 'none' })+ }+ })++ it('falls back to the palette tint for a color chart.js cannot read', () => {+ const own = { borderColor: 'oklch(0.6 0.2 30)' }+ for (const each of [pngRoles('line', own), dashboardRoles('line', own)]) {+ expect(each[0]).toEqual({+ border: 'own borderColor',+ fill: 'palette tint',+ points: 'own borderColor',+ })+ }+ })+})diff --git a/mcp-host/src/workflow/chartGenerator.ts b/mcp-host/src/workflow/chartGenerator.tsindex bb502acc3..e7bd5ef50 100644--- a/mcp-host/src/workflow/chartGenerator.ts+++ b/mcp-host/src/workflow/chartGenerator.ts@@ -40,6 +40,7 @@ import { drawnTexts, recordDrawnText } from './drawnText'import { PNG_BASE_PPM } from './embeddedImages'import { CHART_FONT_STACK, ensureFontsReady, sanitizeForFont } from './fonts'import { choose } from './ownEntry'+import { datasetKind, seriesDefaults } from './seriesPaint'import type { InternalToolResult } from './types'// Register Chart.js controllers/scales/elements/plugins once. Chart.js v4 ships@@ -58,9 +59,6 @@ function prepareChartFonts(): void {Chart.defaults.color = '#0f172a'}-/** Types whose series overlap, so their fill has to let the one below show. */-const TRANSLUCENT_FILL_TYPES = new Set(['line', 'area', 'radar'])-/** Widest a single bar may be drawn, in nominal pixels. */const MAX_BAR_THICKNESS = 120@@ -255,20 +253,28 @@ function applyThemePalette(}} else {const color = theme.palette[idx % theme.palette.length]- // Translucent wherever series are drawn over one another — a solid- // radar fill hides every series behind the first.- const fill = TRANSLUCENT_FILL_TYPES.has(chartType) ? `${color}33` : color- if (!out.borderColor) out.borderColor = color- if (!out.backgroundColor) out.backgroundColor = fill- // A value with no color of its own in a list takes the series color.- if (Array.isArray(out.borderColor)) out.borderColor = out.borderColor.map(c => c ?? color)+ // Shared with the dashboard (seriesPaint.ts); `${color}33` is the+ // palette color at TINT_ALPHA.+ const paint = seriesDefaults(datasetKind(chartType, idx), ds, {+ color,+ tint: `${color}33`,+ })+ if (!out.borderColor) out.borderColor = paint.borderColor+ if (!out.backgroundColor) out.backgroundColor = paint.backgroundColor+ // A value with no color of its own in a list takes the series default.+ if (Array.isArray(out.borderColor)) {+ out.borderColor = out.borderColor.map(c => c ?? paint.borderColor)+ }if (Array.isArray(out.backgroundColor)) {- out.backgroundColor = out.backgroundColor.map(c => c ?? fill)+ out.backgroundColor = out.backgroundColor.map(c => c ?? paint.backgroundColor)}if (chartType === 'area' && out.fill === undefined) {out.fill = true}const point = out as unknown as Record<string, unknown>+ if (paint.pointBackgroundColor && point.pointBackgroundColor === undefined) {+ point.pointBackgroundColor = paint.pointBackgroundColor+ }const points = Array.isArray(ds.data) ? ds.data.length : 0if (chartType === 'scatter') {if (point.pointRadius === undefined) point.pointRadius = pointRadius(6, 100, points)@@ -276,7 +282,6 @@ function applyThemePalette(// A value with a gap on both sides gets no segment, so its point is// its only mark.if (point.pointRadius === undefined) point.pointRadius = pointRadius(4, 60, points)- if (point.pointBackgroundColor === undefined) point.pointBackgroundColor = color}}return out@@ -646,6 +651,23 @@ function crc32(buf: Buffer): number {return (crc ^ 0xffffffff) >>> 0}+/**+ * The datasets as Chart.js draws them: the theme's colors applied, then the+ * composed types lowered. Also read by the check that the PNG and the+ * dashboard paint a chart alike.+ */+export function paintedDatasets(+ chartTypeRaw: string,+ datasets: ChartDataset[],+ labels: string[] | undefined,+ theme: ChartTheme,+ args: Record<string, unknown>,+ warnings: string[]+): { datasets: ChartDataset[]; resolved: ResolvedChartType } {+ const themed = applyThemePalette(datasets, theme, chartTypeRaw, warnings)+ return { datasets: themed, resolved: resolveChartType(chartTypeRaw, themed, labels, theme, args) }+}+export async function runGenerateChart(args: Record<string, unknown>,outputDir: string@@ -696,8 +718,14 @@ export async function runGenerateChart(...(ds.label ? { label: sanitizeForFont(ds.label) } : {}),})) as ChartDataset[]- const themedDatasets = applyThemePalette(datasets, theme, chartTypeRaw, warnings)- const resolved = resolveChartType(chartTypeRaw, themedDatasets, labels, theme, args)+ const { datasets: themedDatasets, resolved } = paintedDatasets(+ chartTypeRaw,+ datasets,+ labels,+ theme,+ args,+ warnings+ )const chartType = resolved.chartTypeif (resolved.labels !== undefined) labels = resolved.labelswarnings.push(...resolved.notes)diff --git a/mcp-host/src/workflow/dashboardCharts.ts b/mcp-host/src/workflow/dashboardCharts.tsindex c1b543c63..09b2ad1d6 100644--- a/mcp-host/src/workflow/dashboardCharts.ts+++ b/mcp-host/src/workflow/dashboardCharts.ts@@ -8,13 +8,13 @@ import { ChartDataError, coerceNumber, normalizeChartData } from './chartData'import type { NormalizedDataset, NormalizedPoint } from './chartData'import { escapeHtml } from './dashboardHtml'import { DASHBOARD_CHART_TYPES } from './dashboardVocabulary'+import { TINT_ALPHA, seriesDefaults } from './seriesPaint'export { DASHBOARD_CHART_TYPES } from './dashboardVocabulary'const KNOWN_TYPES = new Set<string>(DASHBOARD_CHART_TYPES)const SLICE_TYPES = new Set(['pie', 'doughnut', 'polarArea'])const XY_TYPES = new Set(['scatter', 'bubble'])-const TRANSLUCENT_TYPES = new Set(['line', 'area', 'stackedArea', 'radar', 'scatter', 'bubble'])/*** What the page script needs to draw one chart. Colors are left as tokens@@ -91,16 +91,16 @@ function seriesColors(ds: NormalizedDataset, index: number, type: string): Recor}}const { color, dash } = paletteColor(index)- const border = ds.borderColor ?? color+ // Shared with the PNG renderer (seriesPaint.ts).+ const paint = seriesDefaults(type, ds, { color, tint: paletteColor(index, TINT_ALPHA).color })const dashed = dash && ds.borderColor === undefined ? { borderDash: dash } : {}- if (!TRANSLUCENT_TYPES.has(type)) {- return { borderColor: border, backgroundColor: ds.backgroundColor ?? color, ...dashed }- }- // Points take the fill color by default, which here is the faint area tint.+ // A value with no color of its own in a list takes the series default.+ const filled = (value: NormalizedDataset['borderColor'], fallback: string) =>+ Array.isArray(value) ? value.map(c => c ?? fallback) : (value ?? fallback)return {- borderColor: border,- backgroundColor: ds.backgroundColor ?? paletteColor(index, 0.2).color,- pointBackgroundColor: border,+ borderColor: filled(ds.borderColor, paint.borderColor),+ backgroundColor: filled(ds.backgroundColor, paint.backgroundColor),+ ...(paint.pointBackgroundColor ? { pointBackgroundColor: paint.pointBackgroundColor } : {}),...dashed,}}@@ -172,9 +172,10 @@ function checkColors(}out[key] = value.map((v, j) => {if (isCssColor(v)) return v- // A value placed by its label with no color of its own takes the palette's.if (v !== undefined) bad.push({ at: `${at}[${j}]`, value: v })- return paletteColor(SLICE_TYPES.has(type) ? j : index).color+ // A slice with no usable color takes its palette color; a value of a+ // series takes the series default (seriesColors).+ return SLICE_TYPES.has(type) ? paletteColor(j).color : undefined})}return out@@ -408,7 +409,7 @@ export interface PreparedChart {}/** Validate one chart spec found at `where` in the arguments. */-function prepareDashboardChart(raw: unknown, where: string): PreparedChart {+export function prepareDashboardChart(raw: unknown, where: string): PreparedChart {if (!isRecord(raw)) {return {warnings: [],diff --git a/mcp-host/src/workflow/seriesPaint.ts b/mcp-host/src/workflow/seriesPaint.tsnew file mode 100644index 000000000..76c6c7249--- /dev/null+++ b/mcp-host/src/workflow/seriesPaint.ts@@ -0,0 +1,73 @@+/**+ * How a chart series is painted, the same in the PNG renderer (chartGenerator)+ * and the dashboard (dashboardCharts): which kinds tint their fill, which draw+ * point marks, and what a caller's own colors change. Each output resolves the+ * palette its own way: hex colors in the PNG, theme tokens in the dashboard.+ */+import { color } from 'chart.js/helpers'++/** Fills that lie over one another, drawn as a tint of the series color. */+const TINTED_FILL = new Set(['line', 'area', 'radar', 'bubble'])++/** Fills in the series color: stacked areas do not overlap, scatter marks are its points. */+const SERIES_FILL = new Set(['stackedArea', 'scatter'])++/** Lines and webs whose values are point marks in the series color, not the tint. */+const POINT_MARKS = new Set(['line', 'area', 'stackedArea', 'radar'])++/** The opacity of a tinted fill. */+export const TINT_ALPHA = 0.2++/** A series' palette color and its tint, as an output writes them. */+export interface PaletteColors {+ color: string+ tint: string+}++export interface SeriesDefaults {+ borderColor: string+ backgroundColor: string+ /** Set only for kinds that draw point marks. */+ pointBackgroundColor?: string+}++/** A caller's color at TINT_ALPHA, or undefined when chart.js cannot read it. */+export function tintOf(css: string): string | undefined {+ const parsed = color(css)+ return parsed.valid ? parsed.alpha(TINT_ALPHA).rgbString() : undefined+}++/**+ * The colors one series of `kind` takes where the caller set none (`kind` per+ * dataset: the lines of a mixedBarLine are 'line'). The series color is the+ * caller's single borderColor, else the palette's. Fills that lie over one+ * another are its tint, the palette's tint when chart.js cannot read the+ * caller's color; stacked areas and scatter marks are the color itself; bars+ * keep the palette's fill under a caller's outline. Points on lines and webs+ * take the series color.+ */+export function seriesDefaults(+ kind: string,+ ds: { borderColor?: unknown },+ palette: PaletteColors+): SeriesDefaults {+ const own =+ typeof ds.borderColor === 'string' && ds.borderColor !== '' ? ds.borderColor : undefined+ const seriesColor = own ?? palette.color+ const backgroundColor = TINTED_FILL.has(kind)+ ? ((own !== undefined ? tintOf(own) : undefined) ?? palette.tint)+ : SERIES_FILL.has(kind)+ ? seriesColor+ : palette.color+ return {+ borderColor: palette.color,+ backgroundColor,+ ...(POINT_MARKS.has(kind) ? { pointBackgroundColor: seriesColor } : {}),+ }+}++/** The kind each dataset of a `chartType` chart is painted as. */+export function datasetKind(chartType: string, index: number): string {+ if (chartType === 'mixedBarLine') return index === 0 ? 'bar' : 'line'+ return chartType+}