Skip to content

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

TypeScript

fix(mcp-host): keep bubbles solid and show a caller's per-value and bar colors

marcotebc1154c090344
diff --git a/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts b/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts
index 9c7cf24e2..748ebbe58 100644
--- a/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts
+++ b/mcp-host/src/workflow/__tests__/seriesPaint.parity.test.ts
@@ -25,8 +25,10 @@ const KINDS = [
const XY = new Set(['scatter', 'bubble'])
+type Own = Record<string, string | string[]>
+
/** Two series; the caller's colors, if any, on the first. */
-function chartData(kind: string, own: Record<string, string>) {
+function chartData(kind: string, own: Own) {
const values = XY.has(kind)
? (k: number) => [
{ x: 1, y: 2 * k, ...(kind === 'bubble' ? { r: 4 } : {}) },
@@ -45,14 +47,18 @@ function chartData(kind: string, own: Record<string, string>) {
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>) {
+function roles(ds: Record<string, unknown>, palette: Palette, own: Own) {
const name = (value: unknown): string => {
if (value === undefined) return 'none'
+ if (Array.isArray(value)) return `[${value.map(name).join(', ')}]`
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`
+ for (const [key, colors] of Object.entries(own)) {
+ for (const [i, color] of (Array.isArray(colors) ? colors : [colors]).entries()) {
+ const which = Array.isArray(colors) ? `own ${key}[${i}]` : `own ${key}`
+ if (value === color) return which
+ if (value === tintOf(color)) return `${which} tint`
+ }
}
return `other ${JSON.stringify(value)}`
}
@@ -63,7 +69,7 @@ function roles(ds: Record<string, unknown>, palette: Palette, own: Record<string
}
}
-function pngRoles(kind: string, own: Record<string, string>) {
+function pngRoles(kind: string, own: Own) {
const normalized = normalizeChartData(chartData(kind, own), { chartType: kind })
const { datasets } = paintedDatasets(
kind,
@@ -79,7 +85,7 @@ function pngRoles(kind: string, own: Record<string, string>) {
})
}
-function dashboardRoles(kind: string, own: Record<string, string>) {
+function dashboardRoles(kind: string, own: Own) {
const prepared = prepareDashboardChart({ type: kind, ...chartData(kind, own) }, 'charts[0]')
expect(prepared.error).toBeUndefined()
return prepared.chart!.datasets.map((ds, i) =>
@@ -87,8 +93,9 @@ function dashboardRoles(kind: string, own: Record<string, string>) {
)
}
-const OWN_COLORS: Array<Record<string, string>> = [
+const OWN_COLORS: Own[] = [
{},
+ { borderColor: ['#ff0000', '#00ff00', '#0000ff'] },
{ borderColor: '#ff0000' },
{ borderColor: '#f00' },
{ borderColor: 'red' },
@@ -136,6 +143,57 @@ describe('how a series is painted', () => {
}
})
+ it('fills a bubble in its solid color, as both outputs did before', () => {
+ for (const each of [pngRoles('bubble', {}), dashboardRoles('bubble', {})]) {
+ expect(each[0]).toEqual({ border: 'palette', fill: 'palette', points: 'none' })
+ }
+ })
+
+ it("fills a bar with the caller's color, which an outline would not show", () => {
+ const own = { borderColor: '#f00' }
+ for (const each of [pngRoles('bar', own), dashboardRoles('bar', own)]) {
+ expect(each[0]).toEqual({
+ border: 'own borderColor',
+ fill: 'own borderColor',
+ points: 'none',
+ })
+ }
+ })
+
+ it("colors each scatter point and line point with the caller's color for it", () => {
+ const own = { borderColor: ['#ff0000', '#00ff00'] }
+ for (const each of [pngRoles('scatter', own), dashboardRoles('scatter', own)]) {
+ expect(each[0].fill).toBe('[own borderColor[0], own borderColor[1]]')
+ }
+ // A short list wraps over the values, as Chart.js wraps it.
+ for (const each of [pngRoles('line', own), dashboardRoles('line', own)]) {
+ expect(each[0].points).toBe('[own borderColor[0], own borderColor[1]]')
+ }
+ })
+
+ it('leaves out a color that is not a CSS color, in both outputs, with a warning', () => {
+ const own = { borderColor: 'brand-blue' }
+ expect(pngRoles('stackedArea', own)).toEqual(dashboardRoles('stackedArea', own))
+ expect(pngRoles('stackedArea', own)[0]).toEqual({
+ border: 'palette',
+ fill: 'palette',
+ points: 'palette',
+ })
+ const warnings: string[] = []
+ const normalized = normalizeChartData(chartData('stackedArea', own), {
+ chartType: 'stackedArea',
+ })
+ paintedDatasets(
+ 'stackedArea',
+ normalized.datasets as never,
+ normalized.labels,
+ theme,
+ {},
+ warnings
+ )
+ expect(warnings.join(' ')).toContain('"brand-blue" is not a CSS color')
+ })
+
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)]) {
diff --git a/mcp-host/src/workflow/chartColors.ts b/mcp-host/src/workflow/chartColors.ts
new file mode 100644
index 000000000..7a91bb6b6
--- /dev/null
+++ b/mcp-host/src/workflow/chartColors.ts
@@ -0,0 +1,93 @@
+/**
+ * Colors a caller sends with a chart, read the same by the PNG renderer and
+ * the dashboard: one that is not a CSS color is left out for the palette's,
+ * with a warning, rather than drawn black.
+ */
+
+/** CSS color keywords, which canvas and Chart.js both read. */
+const NAMED_COLORS = new Set(
+ (
+ 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue ' +
+ 'blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk ' +
+ 'crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki ' +
+ 'darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen ' +
+ 'darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue ' +
+ 'dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite ' +
+ 'gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki ' +
+ 'lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan ' +
+ 'lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen ' +
+ 'lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen ' +
+ 'magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen ' +
+ 'mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream ' +
+ 'mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid ' +
+ 'palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +
+ 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown ' +
+ 'seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen ' +
+ 'steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow ' +
+ 'yellowgreen transparent'
+ ).split(' ')
+)
+
+/** Longer than any CSS color a chart needs, e.g. "hsl(210deg 50% 40% / 0.8)". */
+const MAX_COLOR_LENGTH = 64
+
+export function isCssColor(value: unknown): boolean {
+ if (typeof value !== 'string' || value.length > MAX_COLOR_LENGTH) return false
+ const v = value.trim().toLowerCase()
+ return (
+ /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(v) ||
+ /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\((?:[\d\s.,%/+-]|deg|g?rad|turn|none)*\)$/.test(v) ||
+ NAMED_COLORS.has(v)
+ )
+}
+
+/** Color warnings written out per chart; the rest are counted in one line. */
+const COLOR_WARNINGS_SHOWN = 3
+
+type ColorList = Array<string | undefined>
+
+/**
+ * `ds` without the colors that are not CSS colors: a single one is dropped,
+ * and an entry of a per-value list is left empty, for the palette to fill.
+ * Each rejected value's path and text go to `bad`.
+ */
+export function withoutInvalidColors<
+ T extends { backgroundColor?: string | ColorList; borderColor?: string | ColorList },
+>(ds: T, index: number, where: string, bad: Array<{ at: string; value: unknown }>): T {
+ const out = { ...ds }
+ for (const key of ['backgroundColor', 'borderColor'] as const) {
+ const value = ds[key]
+ if (value === undefined) continue
+ const at = `${where}.datasets[${index}].${key}`
+ if (!Array.isArray(value)) {
+ if (!isCssColor(value)) {
+ bad.push({ at, value })
+ delete out[key]
+ }
+ continue
+ }
+ out[key] = value.map((v, j) => {
+ if (isCssColor(v)) return v
+ if (v !== undefined) bad.push({ at: `${at}[${j}]`, value: v })
+ return undefined
+ }) as T[typeof key]
+ }
+ return out
+}
+
+export function colorWarnings(bad: Array<{ at: string; value: unknown }>, where: string): string[] {
+ const shown = bad.slice(0, COLOR_WARNINGS_SHOWN).map(({ at, value }) => {
+ const text = JSON.stringify(
+ typeof value === 'string' && value.length > 40 ? `${value.slice(0, 40)}…` : value
+ )
+ return (
+ `${at} ${text} is not a CSS color, so the palette color was used. ` +
+ 'Pass hex such as "#2563eb", rgb(), hsl() or a color name.'
+ )
+ })
+ const more = bad.length - shown.length
+ if (more > 0) {
+ shown.push(`${where}: ${more} more colors are not CSS colors and were replaced the same way.`)
+ }
+ return shown
+}
diff --git a/mcp-host/src/workflow/chartDatasets.ts b/mcp-host/src/workflow/chartDatasets.ts
index de781231f..9d8a1ee53 100644
--- a/mcp-host/src/workflow/chartDatasets.ts
+++ b/mcp-host/src/workflow/chartDatasets.ts
@@ -4,10 +4,11 @@
* Chart.js draws.
*/
import type { ChartType } from 'chart.js'
+import { colorWarnings, withoutInvalidColors } from './chartColors'
import type { NormalizedPoint } from './chartData'
import { sliceColors } from './chartPlugins'
import type { ChartTheme } from './chartThemes'
-import { datasetKind, seriesDefaults } from './seriesPaint'
+import { datasetKind, filled, seriesDefaults } from './seriesPaint'
export interface ChartDataset {
label?: string
@@ -107,15 +108,9 @@ function applyThemePalette(
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 ?? paint.backgroundColor)
- }
+ out.borderColor = filled(out.borderColor, paint.borderColor, color)
+ out.backgroundColor = filled(out.backgroundColor, paint.backgroundColor, color)
if (chartType === 'area' && out.fill === undefined) {
out.fill = true
}
@@ -345,6 +340,11 @@ export function paintedDatasets(
args: Record<string, unknown>,
warnings: string[]
): { datasets: ChartDataset[]; resolved: ResolvedChartType } {
- const themed = applyThemePalette(datasets, theme, chartTypeRaw, warnings)
+ // A color that is not a CSS color is left out for the palette's, as the
+ // dashboard leaves it, instead of drawn black.
+ const bad: Array<{ at: string; value: unknown }> = []
+ const checked = datasets.map((ds, i) => withoutInvalidColors(ds, i, 'data', bad))
+ warnings.push(...colorWarnings(bad, 'data'))
+ const themed = applyThemePalette(checked, theme, chartTypeRaw, warnings)
return { datasets: themed, resolved: resolveChartType(chartTypeRaw, themed, labels, theme, args) }
}
diff --git a/mcp-host/src/workflow/dashboardCharts.ts b/mcp-host/src/workflow/dashboardCharts.ts
index ef77cd5df..792f16fd7 100644
--- a/mcp-host/src/workflow/dashboardCharts.ts
+++ b/mcp-host/src/workflow/dashboardCharts.ts
@@ -4,11 +4,12 @@
* written, so an unusable chart becomes a note in its own card and a warning
* for the agent instead of an error that stops the page script.
*/
+import { colorWarnings, withoutInvalidColors } from './chartColors'
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'
+import { TINT_ALPHA, filled, seriesDefaults } from './seriesPaint'
export { DASHBOARD_CHART_TYPES } from './dashboardVocabulary'
@@ -96,62 +97,17 @@ function seriesColors(ds: NormalizedDataset, index: number, type: string): Recor
// 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 } : {}
- // 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: filled(ds.borderColor, paint.borderColor),
- backgroundColor: filled(ds.backgroundColor, paint.backgroundColor),
+ borderColor: filled(ds.borderColor, paint.borderColor, color),
+ backgroundColor: filled(ds.backgroundColor, paint.backgroundColor, color),
...(paint.pointBackgroundColor ? { pointBackgroundColor: paint.pointBackgroundColor } : {}),
...dashed,
}
}
-/** CSS color keywords, which canvas and Chart.js both read. */
-const NAMED_COLORS = new Set(
- (
- 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue ' +
- 'blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk ' +
- 'crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki ' +
- 'darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen ' +
- 'darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue ' +
- 'dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite ' +
- 'gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki ' +
- 'lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan ' +
- 'lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen ' +
- 'lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen ' +
- 'magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen ' +
- 'mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream ' +
- 'mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid ' +
- 'palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +
- 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown ' +
- 'seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen ' +
- 'steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow ' +
- 'yellowgreen transparent'
- ).split(' ')
-)
-
-/** Longer than any CSS color a chart needs, e.g. "hsl(210deg 50% 40% / 0.8)". */
-const MAX_COLOR_LENGTH = 64
-
-function isCssColor(value: unknown): boolean {
- if (typeof value !== 'string' || value.length > MAX_COLOR_LENGTH) return false
- const v = value.trim().toLowerCase()
- return (
- /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(v) ||
- /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\((?:[\d\s.,%/+-]|deg|g?rad|turn|none)*\)$/.test(v) ||
- NAMED_COLORS.has(v)
- )
-}
-
-/** Color warnings written out per chart; the rest are counted in one line. */
-const COLOR_WARNINGS_SHOWN = 3
-
/**
- * `ds` without the colors that are not CSS colors, which canvas would paint
- * black: a single color is dropped for the palette's, a per-point one gets the
- * palette color of its point (slices) or of its series. Each rejected value's
- * path and text go to `bad`.
+ * `ds` without the colors that are not CSS colors (chartColors.ts); a slice
+ * with no usable color, or none of its own, takes its palette color.
*/
function checkColors(
ds: NormalizedDataset,
@@ -160,46 +116,15 @@ function checkColors(
where: string,
bad: Array<{ at: string; value: unknown }>
): NormalizedDataset {
- const out = { ...ds }
+ const out = withoutInvalidColors(ds, index, where, bad)
+ if (!SLICE_TYPES.has(type)) return out
for (const key of ['backgroundColor', 'borderColor'] as const) {
- const value = ds[key]
- if (value === undefined) continue
- const at = `${where}.datasets[${index}].${key}`
- if (!Array.isArray(value)) {
- if (!isCssColor(value)) {
- bad.push({ at, value })
- delete out[key]
- }
- continue
- }
- out[key] = value.map((v, j) => {
- if (isCssColor(v)) return v
- if (v !== undefined) bad.push({ at: `${at}[${j}]`, value: v })
- // 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
- })
+ const value = out[key]
+ if (Array.isArray(value)) out[key] = value.map((v, j) => v ?? paletteColor(j).color)
}
return out
}
-function colorWarnings(bad: Array<{ at: string; value: unknown }>, where: string): string[] {
- const shown = bad.slice(0, COLOR_WARNINGS_SHOWN).map(({ at, value }) => {
- const text = JSON.stringify(
- typeof value === 'string' && value.length > 40 ? `${value.slice(0, 40)}…` : value
- )
- return (
- `${at} ${text} is not a CSS color, so the palette color was used. ` +
- 'Pass hex such as "#2563eb", rgb(), hsl() or a color name.'
- )
- })
- const more = bad.length - shown.length
- if (more > 0) {
- shown.push(`${where}: ${more} more colors are not CSS colors and were replaced the same way.`)
- }
- return shown
-}
-
function readout(n: number): string {
return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)))
}
diff --git a/mcp-host/src/workflow/seriesPaint.ts b/mcp-host/src/workflow/seriesPaint.ts
index 76c6c7249..271d04bca 100644
--- a/mcp-host/src/workflow/seriesPaint.ts
+++ b/mcp-host/src/workflow/seriesPaint.ts
@@ -5,12 +5,10 @@
* palette its own way: hex colors in the PNG, theme tokens in the dashboard.
*/
import { color } from 'chart.js/helpers'
+import { isCssColor } from './chartColors'
/** 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'])
+const TINTED_FILL = new Set(['line', 'area', 'radar'])
/** Lines and webs whose values are point marks in the series color, not the tint. */
const POINT_MARKS = new Set(['line', 'area', 'stackedArea', 'radar'])
@@ -24,11 +22,14 @@ export interface PaletteColors {
tint: string
}
+/** One color for a whole series, or one per value. */
+export type SeriesColors = string | string[]
+
export interface SeriesDefaults {
borderColor: string
- backgroundColor: string
+ backgroundColor: SeriesColors
/** Set only for kinds that draw point marks. */
- pointBackgroundColor?: string
+ pointBackgroundColor?: SeriesColors
}
/** A caller's color at TINT_ALPHA, or undefined when chart.js cannot read it. */
@@ -40,25 +41,28 @@ export function tintOf(css: string): string | 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.
+ * caller's borderColor, one color or one per value, else the palette's; a
+ * value with no usable color of its own takes the palette's. Fills that lie
+ * over one another (line, area, radar) are the tint of a single series color,
+ * the palette's tint otherwise or when chart.js cannot read the color; every
+ * other mark, a bar, a bubble, a scatter point or a stacked area, is filled in
+ * the series color, so a caller's color shows (a bar's outline is not drawn).
+ * 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 own = ds.borderColor
+ const single = typeof own === 'string' && isCssColor(own) ? own : undefined
+ const perValue = Array.isArray(own)
+ ? own.map(c => (typeof c === 'string' && isCssColor(c) ? c : palette.color))
+ : undefined
+ const seriesColor: SeriesColors = single ?? perValue ?? palette.color
const backgroundColor = TINTED_FILL.has(kind)
- ? ((own !== undefined ? tintOf(own) : undefined) ?? palette.tint)
- : SERIES_FILL.has(kind)
- ? seriesColor
- : palette.color
+ ? ((single !== undefined ? tintOf(single) : undefined) ?? palette.tint)
+ : seriesColor
return {
borderColor: palette.color,
backgroundColor,
@@ -66,6 +70,21 @@ export function seriesDefaults(
}
}
+/**
+ * `value`, with `fallback` where it sets no color: for the whole series when
+ * it is unset, and for each empty entry of a per-value list, which takes the
+ * fallback's color for that value, else `last`.
+ */
+export function filled(
+ value: string | Array<string | undefined> | undefined,
+ fallback: SeriesColors,
+ last: string
+): SeriesColors {
+ if (value === undefined || value === '') return fallback
+ if (!Array.isArray(value)) return value
+ return value.map((c, i) => c ?? (Array.isArray(fallback) ? (fallback[i] ?? last) : fallback))
+}
+
/** 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'