⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: let agents draw charts in the chat (#187)
Croffa9df467c6d0f
diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 021cc91e..648158a2 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -105,6 +105,7 @@ export const app = new Elysia()name: 'Analytics',description: 'Project metrics: stats, pulse, throughput, breakdowns, activity',},+ { name: 'Charts', description: 'Chart specs an agent builds to show in a chat' },{name: 'Webhook test',description: 'Test receiver for inspecting webhook deliveries (dev aid)',diff --git a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.tsindex 0118a482..5474df3a 100644--- a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts+++ b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts@@ -210,10 +210,17 @@ export const AGENT_ACTIONS: ToolMeta[] = [},];-// Read-only actions, always granted to an internal agent so it can see its project-// regardless of which actions it is allowed to take. Listed for the UI only; these-// keys are never stored on the agent (see normalizeToolKeys).+// Actions that change nothing, always granted to an internal agent so it can read its+// project and show what it found, regardless of which actions it is allowed to take.+// Listed for the UI only; these keys are never stored on the agent (see normalizeToolKeys).export const ALWAYS_ON_ACTIONS: ToolMeta[] = [+ {+ key: 'create_chart',+ group: 'project',+ label: 'Draw charts',+ description: 'Build a chart to show in the chat instead of writing the numbers out.',+ always: true,+ },{key: 'get_current_date',group: 'project',diff --git a/apps/api/src/modules/charts/__tests__/integration/charts.test.ts b/apps/api/src/modules/charts/__tests__/integration/charts.test.tsnew file mode 100644index 00000000..a4eda878--- /dev/null+++ b/apps/api/src/modules/charts/__tests__/integration/charts.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';++const spec = {+ type: 'bar' as const,+ title: 'Issues per week',+ x: 'week',+ series: [{ key: 'created', label: 'Created' }],+ data: [+ { week: 'W10', created: 8 },+ { week: 'W11', created: 12 },+ ],+};++async function setupOwnerProject() {+ const owner = await signUpTestUser();+ const asOwner = authedApi(owner.cookie);+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });+ return asOwner;+}++describe('charts', () => {+ beforeEach(async () => {+ await resetDb();+ });++ it('answers with the spec it was given', async () => {+ const asOwner = await setupOwnerProject();++ const res = await asOwner.projects({ projectKey: 'MKT' }).charts.post(spec);+ expect(res.status).toBe(200);+ expect(res.data).toEqual(spec);+ });++ it('accepts every chart type, several series, and stacking', async () => {+ const asOwner = await setupOwnerProject();++ const types = [+ 'bar',+ 'line',+ 'area',+ 'pie',+ 'radar',+ 'radial',+ 'scatter',+ 'funnel',+ 'treemap',+ ] as const;++ for (const type of types) {+ const res = await asOwner.projects({ projectKey: 'MKT' }).charts.post({+ ...spec,+ type,+ stacked: true,+ series: [{ key: 'created' }, { key: 'closed', color: '#22c55e' }],+ data: [{ week: 'W10', created: 8, closed: 5 }],+ });+ expect(res.status).toBe(200);+ }+ });++ it('accepts how a chart is drawn: percent stacking, sides, curve, values, and a mixed series', async () => {+ const asOwner = await setupOwnerProject();++ const res = await asOwner.projects({ projectKey: 'MKT' }).charts.post({+ ...spec,+ stacked: 'percent',+ horizontal: true,+ curve: 'step',+ showValues: true,+ series: [{ key: 'created' }, { key: 'average', type: 'line' }],+ data: [{ week: 'W10', created: 8, average: 4 }],+ });+ expect(res.status).toBe(200);+ });++ it('rejects a spec the renderer could not draw', async () => {+ const asOwner = await setupOwnerProject();+ const charts = asOwner.projects({ projectKey: 'MKT' }).charts;++ // @ts-expect-error the type has to be one the renderer draws+ expect((await charts.post({ ...spec, type: 'sankey' })).status).toBe(400);+ // @ts-expect-error stacking is on, off, or by percent+ expect((await charts.post({ ...spec, stacked: 'always' })).status).toBe(400);+ // @ts-expect-error a series is drawn as a bar, a line, or an area+ expect((await charts.post({ ...spec, series: [{ key: 'created', type: 'pie' }] })).status).toBe(+ 400,+ );+ expect((await charts.post({ ...spec, x: '' })).status).toBe(400);+ expect((await charts.post({ ...spec, series: [] })).status).toBe(400);+ expect((await charts.post({ ...spec, series: [{ key: '' }] })).status).toBe(400);+ expect((await charts.post({ ...spec, data: [] })).status).toBe(400);+ // @ts-expect-error a data cell holds a string, a number, or null+ expect((await charts.post({ ...spec, data: [{ week: { nested: 1 } }] })).status).toBe(400);+ });++ it('denies a non-member and answers 404 for an unknown project', async () => {+ await setupOwnerProject();+ const outsider = authedApi((await signUpTestUser()).cookie);++ const denied = await outsider.projects({ projectKey: 'MKT' }).charts.post(spec);+ expect(denied.status).toBe(403);++ const missing = await outsider.projects({ projectKey: 'NOPE' }).charts.post(spec);+ expect(missing.status).toBe(404);+ });+});diff --git a/apps/api/src/modules/charts/index.ts b/apps/api/src/modules/charts/index.tsnew file mode 100644index 00000000..ddc7cbe4--- /dev/null+++ b/apps/api/src/modules/charts/index.ts@@ -0,0 +1,47 @@+import { Elysia } from 'elysia';+import { guards } from '#shared/guards';+import { authContext } from '#shared/auth-context';+import { mcpTool } from '#mcp/generate';+import { commonErrors } from '#shared/responses';+import { chartSpec } from './model';++// Building a chart is one endpoint and nothing else: it checks a spec and answers+// with it. Nothing is stored — the chart lives in the answer the agent writes, in a+// ```chart fence holding the spec, which is what the chat draws in place (see the web+// app's markdownSegments). A tool call is shown as its own block, so a chart placed+// that way could not sit between two sentences; the fence can.+//+// The round trip is what makes the format one thing rather than three: this schema is+// the create_chart tool's arguments for an internal agent and an MCP client alike (see+// mcp/generate.ts), and a spec the model got wrong comes back as a 400 it can correct+// instead of a chart nobody can draw.+export const chartRoutes = new Elysia({ name: 'charts', detail: { tags: ['Charts'] } })+ .use(authContext)+ .use(guards)+ .post('/projects/:projectKey/charts', ({ body }) => body, {+ body: chartSpec,+ projectMember: true,+ response: { 200: chartSpec, ...commonErrors },+ detail: {+ summary: 'Build a chart',+ description:+ 'Checks a chart spec and returns it. Put the returned spec in your answer ' ++ 'inside a fenced block tagged `chart`, where the chart belongs in the text, ' ++ 'and the app draws it there:\n\n' ++ '```chart\n{"type":"bar","x":"week","series":[{"key":"created"}],' ++ '"data":[{"week":"W10","created":8}]}\n```\n\n' ++ 'Use it instead of writing a table of numbers out, and do not repeat the ' ++ 'numbers next to it. Nothing is stored.\n\n' ++ 'Pick the type by the question the chart answers:\n' ++ '- bar — one number per category; `horizontal` for long names or a ranking\n' ++ '- line, area — a number over time; `stacked` on an area for what it is made of\n' ++ '- bar or area with `stacked: "percent"` — how a composition shifts over time\n' ++ '- pie, radial — the parts of one total, up to about six of them\n' ++ '- treemap — the same parts when there are more than that\n' ++ '- funnel — how many are left at each stage, given rows that only fall\n' ++ '- radar — several categories scored on the same scale\n' ++ '- scatter — whether two numbers move together\n' ++ '- a `type` on a single series — a count as bars with an average as a line',+ ...mcpTool('create_chart', { readOnlyHint: true, idempotentHint: true }),+ },+ });diff --git a/apps/api/src/modules/charts/model.ts b/apps/api/src/modules/charts/model.tsnew file mode 100644index 00000000..b85b6a0e--- /dev/null+++ b/apps/api/src/modules/charts/model.ts@@ -0,0 +1,96 @@+import { t } from 'elysia';++// The chart spec: the one shape a chart is described in. An agent fills it, the+// endpoint checks it, and the chat draws it from the ```chart fence the agent writes+// into its answer — so this schema is what the model reads as the create_chart+// arguments and every field carries its description.+export const chartSpec = t.Object({+ type: t.Union(+ [+ t.Literal('bar'),+ t.Literal('line'),+ t.Literal('area'),+ t.Literal('pie'),+ t.Literal('radar'),+ t.Literal('radial'),+ t.Literal('scatter'),+ t.Literal('funnel'),+ t.Literal('treemap'),+ ],+ {+ description:+ 'How to draw it. `bar` compares categories, `line` and `area` follow a value ' ++ 'over time, `pie` and `radial` show parts of a whole, `treemap` shows the same ' ++ 'parts when there are too many for a pie, `funnel` shows what is left at each ' ++ 'stage, `radar` compares several measures over the same categories, `scatter` ' ++ 'puts one number against another. Pie, radial, funnel, and treemap show the ' ++ 'first series only.',+ },+ ),+ title: t.Optional(t.String({ maxLength: 200, description: 'Heading shown above the chart.' })),+ x: t.String({+ minLength: 1,+ maxLength: 100,+ description:+ 'The key holding the category of each row: the x axis for bar, line, area, and ' ++ 'scatter, the slice name for pie, radial, funnel, and treemap, the corner name ' ++ 'for radar. On a scatter chart it holds a number, everywhere else a name.',+ }),+ series: t.Array(+ t.Object({+ key: t.String({+ minLength: 1,+ maxLength: 100,+ description: 'The key holding this series’ number in every data row.',+ }),+ label: t.Optional(t.String({ maxLength: 200, description: 'Name shown for the series.' })),+ color: t.Optional(+ t.String({+ maxLength: 30,+ description: 'Hex color such as #6366f1. Left out, the chart palette is used.',+ }),+ ),+ type: t.Optional(+ t.Union([t.Literal('bar'), t.Literal('line'), t.Literal('area')], {+ description:+ 'Draws this series as a bar, a line, or an area instead of what `type` says, ' ++ 'so one chart can show a count as bars and an average as a line. Read on ' ++ 'bar, line, and area charts.',+ }),+ ),+ }),+ { minItems: 1, maxItems: 12, description: 'One entry per measure drawn.' },+ ),+ data: t.Array(t.Record(t.String(), t.Union([t.String(), t.Number(), t.Null()])), {+ minItems: 1,+ maxItems: 500,+ description:+ 'The rows, each holding the `x` key and every series key, e.g. { "week": "W12", "created": 8 }.',+ }),+ stacked: t.Optional(+ t.Union([t.Boolean(), t.Literal('percent')], {+ description:+ 'Stack the series instead of drawing them side by side. "percent" stacks them ' ++ 'as shares of 100%, which shows how a composition shifts rather than how it grew.',+ }),+ ),+ horizontal: t.Optional(+ t.Boolean({+ description:+ 'Turn a bar chart on its side, so the categories run down the left. Use it for ' ++ 'long category names or a ranking of more than about eight of them.',+ }),+ ),+ curve: t.Optional(+ t.Union([t.Literal('monotone'), t.Literal('linear'), t.Literal('step')], {+ description:+ 'The shape a line or an area takes between two points: smoothed, straight, or ' ++ 'held until the next value. Default monotone.',+ }),+ ),+ showValues: t.Optional(+ t.Boolean({+ description: 'Print each number on the chart. Leave it off past about a dozen rows.',+ }),+ ),+});diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.tsindex ef8cd792..834eda22 100644--- a/apps/api/src/planner.ts+++ b/apps/api/src/planner.ts@@ -26,6 +26,7 @@ import { githubSettingsRoutes } from './modules/github';import { dashboardRoutes } from './modules/dashboards';import { noteBoardRoutes } from './modules/note-boards';import { analyticsRoutes } from './modules/analytics';+import { chartRoutes } from './modules/charts';import { settingsRoutes } from './settings/routes';import { godRoutes } from './god/routes';import { agentScheduleRoutes } from './modules/agents/schedules';@@ -103,6 +104,7 @@ export const planner = new Elysia({ name: 'planner' }).use(dashboardRoutes).use(noteBoardRoutes).use(analyticsRoutes)+ .use(chartRoutes).use(notificationRoutes).use(notificationSettingsRoutes).use(notificationPreferenceRoutes)diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.jsonindex 326f94ea..846f8e81 100644--- a/apps/web/messages/ar/common.json+++ b/apps/web/messages/ar/common.json@@ -143,5 +143,9 @@"tableAddColumn": "إضافة عمود","tableDeleteColumn": "حذف عمود","tableDelete": "حذف الجدول"+ },+ "chart": {+ "download": "احفظ الرسم البياني",+ "downloadFailed": "مقدرناش نحفظ الرسم البياني"}}diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.jsonindex 7474e336..a837a71f 100644--- a/apps/web/messages/en/common.json+++ b/apps/web/messages/en/common.json@@ -143,5 +143,9 @@"tableAddColumn": "Add column","tableDeleteColumn": "Delete column","tableDelete": "Delete table"+ },+ "chart": {+ "download": "Save chart",+ "downloadFailed": "The chart could not be saved"}}diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.jsonindex c37ffb7a..ed22aa00 100644--- a/apps/web/messages/ru/common.json+++ b/apps/web/messages/ru/common.json@@ -143,5 +143,9 @@"tableAddColumn": "Добавить столбец","tableDeleteColumn": "Удалить столбец","tableDelete": "Удалить таблицу"+ },+ "chart": {+ "download": "Сохранить график",+ "downloadFailed": "Не удалось сохранить график"}}diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.jsonindex cff597ac..49c93d2c 100644--- a/apps/web/messages/uk/common.json+++ b/apps/web/messages/uk/common.json@@ -143,5 +143,9 @@"tableAddColumn": "Додати стовпець","tableDeleteColumn": "Видалити стовпець","tableDelete": "Видалити таблицю"+ },+ "chart": {+ "download": "Зберегти графік",+ "downloadFailed": "Не вдалося зберегти графік"}}diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.jsonindex 040df089..abcf4a9f 100644--- a/apps/web/messages/zh-CN/common.json+++ b/apps/web/messages/zh-CN/common.json@@ -143,5 +143,9 @@"tableAddColumn": "添加列","tableDeleteColumn": "删除列","tableDelete": "删除表格"+ },+ "chart": {+ "download": "保存图表",+ "downloadFailed": "图表保存失败"}}diff --git a/apps/web/src/components/common/Markdown.tsx b/apps/web/src/components/common/Markdown.tsxindex 918e9a20..1770d12e 100644--- a/apps/web/src/components/common/Markdown.tsx+++ b/apps/web/src/components/common/Markdown.tsx@@ -1,13 +1,42 @@+'use client';+import { useMemo } from 'react';-import { renderMarkdown } from '@/lib/markdown';+import dynamic from 'next/dynamic';+import { markdownSegments } from '@/lib/markdown';+import { Skeleton } from '@/components/ui/skeleton';++// recharts is loaded only by the answers that actually carry a chart, so the views+// that just show markdown do not pull it in.+const ChartBlock = dynamic(() => import('./chart/ChartBlock'));// Renders markdown text as formatted HTML with the shared `.md-content` styles// (headings, lists, code, blockquote, links), without the virtualized-table image// sizing the markdown table cell adds. Links open in a new tab so following one-// does not replace the view the reader was on.+// does not replace the view the reader was on. A ```chart fence is drawn as a chart+// where it sits in the text (see markdownSegments).export default function Markdown({ children }: { children: string }) {- const html = useMemo(() => renderMarkdown(children, { newTabLinks: true }), [children]);+ const segments = useMemo(() => markdownSegments(children, { newTabLinks: true }), [children]);// `dir="auto"` reads the direction from the text itself, so an Arabic comment in// an English interface — and the reverse — is laid out the way it was written.- return <div dir="auto" className="md-content" dangerouslySetInnerHTML={{ __html: html }} />;+ return (+ <div dir="auto">+ {segments.map((segment, index) => {+ if (segment.kind === 'chart') {+ return <ChartBlock key={index} spec={segment.spec} source={segment.source} />;+ }+ // The fence is still streaming in: hold its place rather than showing the+ // half-written JSON that would turn into the chart a moment later.+ if (segment.kind === 'pending') {+ return <Skeleton key={index} className="my-3 h-[220px] w-full" />;+ }+ return (+ <div+ key={index}+ className="md-content"+ dangerouslySetInnerHTML={{ __html: segment.html }}+ />+ );+ })}+ </div>+ );}diff --git a/apps/web/src/components/common/chart/ChartBlock.tsx b/apps/web/src/components/common/chart/ChartBlock.tsxnew file mode 100644index 00000000..09803221--- /dev/null+++ b/apps/web/src/components/common/chart/ChartBlock.tsx@@ -0,0 +1,303 @@+'use client';++import { memo, useRef } from 'react';+import {+ Area,+ Bar,+ CartesianGrid,+ Cell,+ ComposedChart,+ Funnel,+ FunnelChart,+ LabelList,+ Line,+ Pie,+ PieChart,+ PolarAngleAxis,+ PolarGrid,+ Radar,+ RadarChart,+ RadialBar,+ RadialBarChart,+ Scatter,+ Treemap,+ XAxis,+ YAxis,+} from 'recharts';+import {+ chartHasLegend,+ chartLegend,+ seriesColor,+ type ChartLegendEntry,+ type ChartSeries,+ type ChartSpec,+} from '@/utils/chartSpec';+import {+ ChartContainer,+ ChartLegend,+ ChartLegendContent,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from '@/components/ui/chart';+import ChartDownload from './ChartDownload';++// Draws a chart spec — what an agent gets back from the create_chart tool, drawn where+// the ```chart fence carrying it sits in the answer.+//+// Colors are passed to each mark directly rather than through the chart config,+// because a series key is written by a model and would otherwise end up in a+// `--color-<key>` CSS variable name. What the config holds is the labels: the shadcn+// tooltip and legend print the entry they find in it and nothing when they find none,+// so it is keyed the way they look an entry up — by category for a pie and a radial,+// by series for the rest (see chartLegend).+function ChartBlock({ spec }: { spec: ChartSpec; source: string }) {+ const chartRef = useRef<HTMLDivElement>(null);+ const legend = chartLegend(spec);+ const config: ChartConfig = Object.fromEntries(+ legend.map((entry) => [entry.key, { label: entry.label }]),+ );++ return (+ // `min-w-64` gives the figure an intrinsic width: the chart container is sized in+ // percentages, so it contributes nothing to the fit-content width of the chat+ // bubble around it and a chart-only answer would collapse to the header row.+ <figure className="my-3 w-full min-w-64">+ <div className="mb-2 flex items-center gap-2">+ {spec.title && (+ <figcaption className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {spec.title}+ </figcaption>+ )}+ <ChartDownload chartRef={chartRef} spec={spec} />+ </div>+ {/* Recharts draws to absolute SVG coordinates and does not read the document+ direction, so a mirrored chart would put its axes and series out of step+ with each other. The labels and the tooltip still follow the text. */}+ {/* The treemap draws its own labels over the filled rectangles, and recharts+ leaves them the default black; the rule reaches those nodes only. */}+ <ChartContainer+ ref={chartRef}+ dir="ltr"+ config={config}+ className="h-[220px] w-full [&_[class*='recharts-treemap-depth']_text]:fill-white"+ >+ {chart(spec, legend)}+ </ChartContainer>+ </figure>+ );+}++// The answer is re-split into segments on every streamed token, so the spec is a new+// object each time it is read out of the fence. Comparing the fence text it came from+// is what stops a finished chart from redrawing for the rest of the message.+export default memo(ChartBlock, (previous, next) => previous.source === next.source);++function chart(spec: ChartSpec, legend: ChartLegendEntry[]) {+ switch (spec.type) {+ case 'pie':+ return pie(spec, legend);+ case 'radial':+ return radial(spec, legend);+ case 'radar':+ return radar(spec);+ case 'funnel':+ return funnel(spec, legend);+ case 'treemap':+ return treemap(spec, legend);+ default:+ return cartesian(spec);+ }+}++function legendOf(spec: ChartSpec, nameKey?: string) {+ if (!chartHasLegend(spec)) return null;+ return <ChartLegend content={<ChartLegendContent nameKey={nameKey} />} />;+}++function valueLabels(spec: ChartSpec, position: 'top' | 'right' | 'insideStart') {+ if (!spec.showValues) return null;+ return <LabelList position={position} offset={6} fontSize={11} className="fill-current" />;+}++// One measure per pie, so it draws the first series and colors by slice.+function pie(spec: ChartSpec, legend: ChartLegendEntry[]) {+ return (+ <PieChart>+ <ChartTooltip content={<ChartTooltipContent nameKey={spec.x} />} />+ <Pie+ data={spec.data}+ dataKey={spec.series[0].key}+ nameKey={spec.x}+ innerRadius={45}+ strokeWidth={2}+ label={spec.showValues}+ >+ {legend.map((entry, index) => (+ <Cell key={index} fill={entry.color} />+ ))}+ </Pie>+ {legendOf(spec, spec.x)}+ </PieChart>+ );+}++// The same one measure as a pie, drawn as a ring per row. A radial bar takes its color+// from the row it draws rather than from a child element, so the rows are handed to it+// with the slice color written in.+function radial(spec: ChartSpec, legend: ChartLegendEntry[]) {+ const data = spec.data.map((row, index) => ({ ...row, fill: legend[index].color }));+ return (+ <RadialBarChart data={data} innerRadius="25%" outerRadius="100%">+ <ChartTooltip content={<ChartTooltipContent nameKey={spec.x} />} />+ <RadialBar dataKey={spec.series[0].key} background cornerRadius={4}>+ {valueLabels(spec, 'insideStart')}+ </RadialBar>+ {legendOf(spec, spec.x)}+ </RadialBarChart>+ );+}++// Every series over the same categories, drawn as a shape with one corner per+// category — what compares several measures that share a scale.+function radar(spec: ChartSpec) {+ return (+ <RadarChart data={spec.data}>+ <ChartTooltip content={<ChartTooltipContent />} />+ <PolarGrid />+ <PolarAngleAxis dataKey={spec.x} fontSize={11} />+ {spec.series.map((series, index) => (+ <Radar+ key={series.key}+ dataKey={series.key}+ stroke={seriesColor(series, index)}+ fill={seriesColor(series, index)}+ fillOpacity={0.25}+ >+ {valueLabels(spec, 'top')}+ </Radar>+ ))}+ {legendOf(spec)}+ </RadarChart>+ );+}++// The stages of a funnel, widest first. Recharts draws no legend for it, so the name+// of every stage is written into the trapezoid it belongs to — white, because it sits+// on the slice color in either theme.+function funnel(spec: ChartSpec, legend: ChartLegendEntry[]) {+ return (+ <FunnelChart>+ <ChartTooltip content={<ChartTooltipContent nameKey={spec.x} />} />+ <Funnel dataKey={spec.series[0].key} nameKey={spec.x} data={spec.data}>+ {legend.map((entry, index) => (+ <Cell key={index} fill={entry.color} />+ ))}+ <LabelList dataKey={spec.x} position="center" fontSize={11} fill="#ffffff" stroke="none" />+ {spec.showValues && (+ <LabelList+ dataKey={spec.series[0].key}+ position="right"+ fontSize={11}+ className="fill-current"+ />+ )}+ </Funnel>+ </FunnelChart>+ );+}++// One rectangle per row, its area the row's number — what a pie cannot do past a+// handful of categories. The name is drawn in the rectangle where it fits, so this+// chart carries no legend either; the colors are handed over as the panel recharts+// picks from by position.+function treemap(spec: ChartSpec, legend: ChartLegendEntry[]) {+ return (+ <Treemap+ data={spec.data}+ dataKey={spec.series[0].key}+ nameKey={spec.x}+ colorPanel={legend.map((entry) => entry.color)}+ aspectRatio={4 / 3}+ isAnimationActive={false}+ >+ <ChartTooltip content={<ChartTooltipContent nameKey={spec.x} />} />+ </Treemap>+ );+}++const percentTick = (value: number) => `${Math.round(value * 100)}%`;++// Bars, lines, areas, and points share every axis, so they are drawn by one composed+// chart that differs only in the mark each series gets — which is also what lets a+// series carry a mark of its own and one chart mix them.+function cartesian(spec: ChartSpec) {+ const percent = spec.stacked === 'percent';+ // A scatter chart puts a number on both axes; a horizontal one swaps which axis+ // carries the categories.+ const category = {+ dataKey: spec.x,+ type: spec.type === 'scatter' ? ('number' as const) : ('category' as const),+ tickMargin: 8,+ };+ const value = { type: 'number' as const, tickFormatter: percent ? percentTick : undefined };+ const axis = { tickLine: false, axisLine: false, fontSize: 11 };++ return (+ <ComposedChart+ data={spec.data}+ layout={spec.horizontal ? 'vertical' : 'horizontal'}+ stackOffset={percent ? 'expand' : undefined}+ >+ <CartesianGrid+ horizontal={!spec.horizontal}+ vertical={Boolean(spec.horizontal) || spec.type === 'scatter'}+ />+ <XAxis {...axis} {...(spec.horizontal ? value : category)} />+ <YAxis+ {...axis}+ {...(spec.horizontal ? category : value)}+ width={spec.horizontal ? 90 : 40}+ />+ <ChartTooltip content={<ChartTooltipContent />} />+ {spec.series.map((series, index) => mark(spec, series, seriesColor(series, index)))}+ {legendOf(spec)}+ </ComposedChart>+ );+}++function mark(spec: ChartSpec, series: ChartSeries, color: string) {+ const key = series.key;+ const stackId = spec.stacked ? 'a' : undefined;+ const curve = spec.curve ?? 'monotone';+ switch (series.type ?? spec.type) {+ case 'line':+ return (+ <Line key={key} dataKey={key} type={curve} stroke={color} strokeWidth={2} dot={false}>+ {valueLabels(spec, 'top')}+ </Line>+ );+ case 'area':+ return (+ <Area+ key={key}+ dataKey={key}+ type={curve}+ stackId={stackId}+ stroke={color}+ fill={color}+ fillOpacity={0.25}+ >+ {valueLabels(spec, 'top')}+ </Area>+ );+ case 'scatter':+ return <Scatter key={key} dataKey={key} fill={color} />;+ default:+ return (+ <Bar key={key} dataKey={key} stackId={stackId} fill={color} radius={3}>+ {valueLabels(spec, spec.horizontal ? 'right' : 'top')}+ </Bar>+ );+ }+}diff --git a/apps/web/src/components/common/chart/ChartDownload.tsx b/apps/web/src/components/common/chart/ChartDownload.tsxnew file mode 100644index 00000000..43e6f24b--- /dev/null+++ b/apps/web/src/components/common/chart/ChartDownload.tsx@@ -0,0 +1,66 @@+'use client';++import { useState, type RefObject } from 'react';+import { Download } from 'lucide-react';+import { toast } from 'sonner';+import { useTranslations } from 'next-intl';+import type { ChartSpec } from '@/utils/chartSpec';+import { chartFileName, chartSvgMarkup, downloadBlob, svgToPng } from '@/utils/chartExport';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';++// Saves the chart drawn next to it as a file. The picture is built from the SVG in+// the page (see chartExport), so the button reads the rendered chart out of its+// container rather than drawing a second one.+export default function ChartDownload({+ chartRef,+ spec,+}: {+ chartRef: RefObject<HTMLDivElement | null>;+ spec: ChartSpec;+}) {+ const t = useTranslations('common.chart');+ const [saving, setSaving] = useState(false);++ async function save(format: 'svg' | 'png') {+ const chart = chartRef.current?.querySelector('svg');+ if (!chart) return;+ setSaving(true);+ try {+ const markup = chartSvgMarkup(chart, spec);+ const blob =+ format === 'svg'+ ? new Blob([markup], { type: 'image/svg+xml;charset=utf-8' })+ : await svgToPng(markup);+ downloadBlob(blob, chartFileName(spec, format));+ } catch {+ toast.error(t('downloadFailed'));+ } finally {+ setSaving(false);+ }+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ disabled={saving}+ title={t('download')}+ aria-label={t('download')}+ className="ms-auto shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground disabled:opacity-50"+ >+ <Download className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => save('png')}>PNG</DropdownMenuItem>+ <DropdownMenuItem onClick={() => save('svg')}>SVG</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/apps/web/src/features/dashboards/components/widgets/BreakdownWidget.tsx b/apps/web/src/features/dashboards/components/widgets/BreakdownWidget.tsxindex 747567a1..ecba0f0c 100644--- a/apps/web/src/features/dashboards/components/widgets/BreakdownWidget.tsx+++ b/apps/web/src/features/dashboards/components/widgets/BreakdownWidget.tsx@@ -1,6 +1,7 @@import { Cell, Pie, PieChart } from 'recharts';import { useTranslations } from 'next-intl';import type { BreakdownBy, WidgetConfig } from '@/utils/dashboardWidgets';+import { CHART_PALETTE } from '@/utils/chartSpec';import { Skeleton } from '@/components/ui/skeleton';import { ChartContainer, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart';import { useBreakdownQuery } from '../../services/analytics.service';@@ -9,19 +10,6 @@ import { useBreakdownQuery } from '../../services/analytics.service';// messages under `dashboards.breakdown.by`.export const BY_OPTIONS: BreakdownBy[] = ['status', 'priority', 'type', 'assignee', 'delegate'];-// Fallback slice colors for categories without their own color (priority,-// assignee). Status and type carry their entity color and use it directly.-const PALETTE = [- '#6366f1',- '#22c55e',- '#eab308',- '#ec4899',- '#06b6d4',- '#f97316',- '#8b5cf6',- '#64748b',-];-// Issue counts grouped by a chosen dimension, drawn as a donut. The dimension is a// per-widget config choice, edited from the header settings popover (see// BreakdownWidgetSettings) and persisted on save.@@ -41,7 +29,9 @@ export default function BreakdownWidget({const chartData = items.map((i, idx) => ({name: i.label,value: i.count,- fill: i.color ?? PALETTE[idx % PALETTE.length],+ // Status and type carry their entity color; the other dimensions fall back to+ // the shared chart palette.+ fill: i.color ?? CHART_PALETTE[idx % CHART_PALETTE.length],}));function chart() {diff --git a/apps/web/src/lib/markdown.test.ts b/apps/web/src/lib/markdown.test.tsnew file mode 100644index 00000000..3bfbeba5--- /dev/null+++ b/apps/web/src/lib/markdown.test.ts@@ -0,0 +1,39 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { markdownSegments } from './markdown';++const spec =+ '{"type":"bar","x":"week","series":[{"key":"created"}],"data":[{"week":"W1","created":3}]}';++const kinds = (value: string) => markdownSegments(value).map((s) => s.kind);++describe('markdownSegments', () => {+ it('keeps plain markdown as one segment', () => {+ assert.deepEqual(kinds('# Title\n\ntext'), ['markdown']);+ });++ it('splits a chart fence out of the text around it', () => {+ const segments = markdownSegments(`before\n\n\`\`\`chart\n${spec}\n\`\`\`\n\nafter`);+ assert.deepEqual(+ segments.map((s) => s.kind),+ ['markdown', 'chart', 'markdown'],+ );+ assert.equal(segments[1].kind === 'chart' && segments[1].spec.type, 'bar');+ });++ it('reports an unclosed fence as pending, so a streaming spec is not shown raw', () => {+ assert.deepEqual(kinds('text\n\n```chart\n{"type":"bar"'), ['markdown', 'pending']);+ });++ it('leaves a fence whose body is not a spec as markdown', () => {+ assert.deepEqual(kinds('```chart\n{ broken\n```'), ['markdown']);+ });++ it('reads several fences in one answer', () => {+ assert.deepEqual(kinds(`\`\`\`chart\n${spec}\n\`\`\`\ngap\n\`\`\`chart\n${spec}\n\`\`\``), [+ 'chart',+ 'markdown',+ 'chart',+ ]);+ });+});diff --git a/apps/web/src/lib/markdown.ts b/apps/web/src/lib/markdown.tsindex f3af70c5..84831fc8 100644--- a/apps/web/src/lib/markdown.ts+++ b/apps/web/src/lib/markdown.ts@@ -1,5 +1,6 @@import { marked } from 'marked';import DOMPurify from 'isomorphic-dompurify';+import { parseChartSpec, type ChartSpec } from '@/utils/chartSpec';// Content whose links lead away from the current view (release notes, agent chat)// asks for newTabLinks, so following one does not replace what the reader was on.@@ -36,3 +37,63 @@ export function renderMarkdown(value: string, options?: HtmlOptions): string {const html = marked.parse(value, { async: false, breaks: true }) as string;return sanitizeHtml(html, options);}++// A chart an agent embedded in its answer, as one fenced block:+//+// ```chart+// { "type": "bar", "x": "week", "series": [...], "data": [...] }+// ```+//+// The spec is what the create_chart tool hands back; the fence is how the agent+// places it in the text. Splitting the fences out is what draws them as charts+// instead of the JSON code block `marked` would produce.+export type MarkdownSegment =+ | { kind: 'markdown'; html: string }+ // The fence is still open: the answer is streaming in and the spec is incomplete.+ | { kind: 'pending' }+ // `source` is the fence body the spec was parsed from: the answer is re-split on+ // every streamed token, so it is what tells an unchanged chart from a new one.+ | { kind: 'chart'; spec: ChartSpec; source: string };++const OPEN_FENCE = '```chart';+const CLOSE_FENCE = '```';++// The markdown between the chart fences, and the specs of the fences themselves. A+// fence whose body is not a valid spec is left in the markdown, so a model that wrote+// malformed JSON shows it as the code block it is instead of vanishing.+export function markdownSegments(value: string, options?: HtmlOptions): MarkdownSegment[] {+ const lines = value.split('\n');+ const segments: MarkdownSegment[] = [];+ let buffer: string[] = [];++ function flush(): void {+ const text = buffer.join('\n');+ buffer = [];+ if (text.trim()) segments.push({ kind: 'markdown', html: renderMarkdown(text, options) });+ }++ for (let i = 0; i < lines.length; i++) {+ if (lines[i].trim() !== OPEN_FENCE) {+ buffer.push(lines[i]);+ continue;+ }+ let end = i + 1;+ while (end < lines.length && lines[end].trim() !== CLOSE_FENCE) end++;+ if (end === lines.length) {+ flush();+ segments.push({ kind: 'pending' });+ return segments;+ }+ const source = lines.slice(i + 1, end).join('\n');+ const spec = parseChartSpec(source);+ if (spec) {+ flush();+ segments.push({ kind: 'chart', spec, source });+ } else {+ buffer.push(...lines.slice(i, end + 1));+ }+ i = end;+ }+ flush();+ return segments;+}diff --git a/apps/web/src/utils/chartExport.test.ts b/apps/web/src/utils/chartExport.test.tsnew file mode 100644index 00000000..4015a9f0--- /dev/null+++ b/apps/web/src/utils/chartExport.test.ts@@ -0,0 +1,34 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { chartFileName } from './chartExport';+import type { ChartSpec } from './chartSpec';++const spec: ChartSpec = {+ type: 'bar',+ x: 'week',+ series: [{ key: 'created' }],+ data: [{ week: 'W1', created: 3 }],+};++describe('chartFileName', () => {+ it('names the file after the chart title', () => {+ assert.equal(+ chartFileName({ ...spec, title: 'Issues per week' }, 'png'),+ 'issues-per-week.png',+ );+ });++ it('falls back to a plain name for a chart with no title', () => {+ assert.equal(chartFileName(spec, 'svg'), 'chart.svg');+ });++ it('keeps letters of any script and drops the rest', () => {+ assert.equal(chartFileName({ ...spec, title: 'Задачи / неделя!' }, 'png'), 'задачи-неделя.png');+ assert.equal(chartFileName({ ...spec, title: '///' }, 'png'), 'chart.png');+ });++ it('cuts a very long title', () => {+ const name = chartFileName({ ...spec, title: 'a'.repeat(200) }, 'svg');+ assert.equal(name, `${'a'.repeat(60)}.svg`);+ });+});diff --git a/apps/web/src/utils/chartExport.ts b/apps/web/src/utils/chartExport.tsnew file mode 100644index 00000000..91a86084--- /dev/null+++ b/apps/web/src/utils/chartExport.ts@@ -0,0 +1,223 @@+// Saving a chart the app drew. recharts renders to SVG in the page, so the file is+// that SVG lifted out of the document — with everything it inherited from the page+// written onto it, since a standalone file has no stylesheet, no theme variables, and+// no Tailwind classes behind it.+//+// The legend and the title are HTML next to the chart, not part of its SVG, so both+// are drawn into the exported picture from the spec instead of copied from the DOM.+// The PNG is that same SVG rasterized, so the two formats show the same thing.++import {+ chartHasLegend,+ chartLegend,+ type ChartLegendEntry,+ type ChartSpec,+} from '@/utils/chartSpec';++// What an element takes from the page rather than from its own attributes: recharts+// sets geometry as attributes but leaves color, weight, and font to CSS.+const INHERITED = [+ 'fill',+ 'fill-opacity',+ 'stroke',+ 'stroke-width',+ 'stroke-dasharray',+ 'stroke-opacity',+ 'opacity',+ 'font-family',+ 'font-size',+ 'font-weight',+ 'text-anchor',+];++const TITLE_HEIGHT = 28;+const LEGEND_HEIGHT = 24;+const LEGEND_SWATCH = 10;+const LEGEND_SWATCH_GAP = 5;+const LEGEND_GAP = 16;+const PADDING = 12;+// Rasterized at twice the drawn size, so the PNG stays sharp on a high-density screen.+const PNG_SCALE = 2;+const SVG_NS = 'http://www.w3.org/2000/svg';++function inlineStyles(source: Element, clone: Element): void {+ const from = [source, ...source.querySelectorAll('*')];+ const to = [clone, ...clone.querySelectorAll('*')];+ from.forEach((element, index) => {+ const target = to[index];+ if (!(target instanceof SVGElement) || !(element instanceof SVGElement)) return;+ const computed = getComputedStyle(element);+ for (const property of INHERITED) {+ target.style.setProperty(property, computed.getPropertyValue(property));+ }+ });+}++function element(name: string, attributes: Record<string, string | number>): SVGElement {+ const node = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));+ return node;+}++function text(value: string, attributes: Record<string, string | number>): SVGElement {+ const node = element('text', attributes);+ node.textContent = value;+ return node;+}++// The page background, so a chart saved in the dark theme is not light text on+// nothing. A transparent body means the default white page underneath it.+function pageBackground(): string {+ const color = getComputedStyle(document.body).backgroundColor;+ return !color || color === 'transparent' || color === 'rgba(0, 0, 0, 0)' ? '#ffffff' : color;+}++// Rough advance per character: the exported file carries no layout engine to measure+// text with, and the legend only has to not overlap itself.+const CHAR_WIDTH = 7;++function entryWidth(entry: ChartLegendEntry): number {+ return LEGEND_SWATCH + LEGEND_SWATCH_GAP + entry.label.length * CHAR_WIDTH + LEGEND_GAP;+}++interface PlacedEntry extends ChartLegendEntry {+ x: number;+ row: number;+}++// Where every legend entry sits at the chart's width, and how many rows they wrap+// onto. The height the document reserves and the drawn entries both read this one+// layout, so they cannot disagree on where the legend ends.+function layoutLegend(+ entries: ChartLegendEntry[],+ width: number,+): { entries: PlacedEntry[]; rows: number } {+ const placed: PlacedEntry[] = [];+ let x = PADDING;+ let row = 0;+ for (const entry of entries) {+ if (x > PADDING && x + entryWidth(entry) > width - PADDING) {+ row++;+ x = PADDING;+ }+ placed.push({ ...entry, x, row });+ x += entryWidth(entry);+ }+ return { entries: placed, rows: placed.length ? row + 1 : 0 };+}++// The height recharts already left empty at the bottom of the chart's svg: it draws+// its own legend as HTML beside the svg but shrinks the plot inside it to make room.+function reservedLegendBand(chart: SVGSVGElement): number {+ const wrapper = chart.parentElement?.querySelector('.recharts-legend-wrapper');+ return wrapper?.getBoundingClientRect().height ?? 0;+}++function legend(entries: PlacedEntry[], top: number, foreground: string): SVGElement {+ const group = element('g', { 'font-size': 12, fill: foreground });+ for (const entry of entries) {+ const y = top + LEGEND_SWATCH + entry.row * LEGEND_HEIGHT;+ group.append(+ element('rect', {+ x: entry.x,+ y: y - LEGEND_SWATCH,+ width: LEGEND_SWATCH,+ height: LEGEND_SWATCH,+ rx: 2,+ fill: entry.color,+ }),+ text(entry.label, { x: entry.x + LEGEND_SWATCH + LEGEND_SWATCH_GAP, y }),+ );+ }+ return group;+}++// The chart as a standalone SVG document: the drawn chart with its inherited styles+// written in, under its title and over its legend.+export function chartSvgMarkup(chart: SVGSVGElement, spec: ChartSpec): string {+ const { width, height } = chart.getBoundingClientRect();+ const chartStyle = getComputedStyle(chart);+ const foreground = chartStyle.color || '#000000';+ const titleHeight = spec.title ? TITLE_HEIGHT : 0;+ const legendLayout = chartHasLegend(spec) ? layoutLegend(chartLegend(spec), width) : null;+ const legendHeight = (legendLayout?.rows ?? 0) * LEGEND_HEIGHT;+ // The drawn legend goes into the band the chart already reserved, so only the rows+ // that do not fit in it make the document taller.+ const reserved = legendLayout ? reservedLegendBand(chart) : 0;+ const total = titleHeight + height + Math.max(0, legendHeight - reserved) + PADDING * 2;++ const root = element('svg', {+ xmlns: SVG_NS,+ width,+ height: total,+ viewBox: `0 0 ${width} ${total}`,+ 'font-family': chartStyle.fontFamily || 'sans-serif',+ });+ root.append(element('rect', { width, height: total, fill: pageBackground() }));++ if (spec.title) {+ root.append(+ text(spec.title, {+ x: PADDING,+ y: PADDING + 16,+ 'font-size': 14,+ 'font-weight': 600,+ fill: foreground,+ }),+ );+ }++ const clone = chart.cloneNode(true) as SVGSVGElement;+ inlineStyles(chart, clone);+ clone.setAttribute('x', '0');+ clone.setAttribute('y', String(PADDING + titleHeight));+ clone.setAttribute('width', String(width));+ clone.setAttribute('height', String(height));+ root.append(clone);++ if (legendLayout) {+ root.append(+ legend(legendLayout.entries, PADDING + titleHeight + height - reserved, foreground),+ );+ }+ return new XMLSerializer().serializeToString(root);+}++export async function svgToPng(markup: string): Promise<Blob> {+ const image = new Image();+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;+ await image.decode();+ const canvas = document.createElement('canvas');+ canvas.width = image.width * PNG_SCALE;+ canvas.height = image.height * PNG_SCALE;+ const context = canvas.getContext('2d');+ if (!context) throw new Error('Canvas is unavailable');+ context.scale(PNG_SCALE, PNG_SCALE);+ context.drawImage(image, 0, 0);+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error('The chart could not be rasterized'))),+ 'image/png',+ );+ });+}++export function chartFileName(spec: ChartSpec, extension: 'svg' | 'png'): string {+ const slug = (spec.title ?? '')+ .toLowerCase()+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 60);+ return `${slug || 'chart'}.${extension}`;+}++export function downloadBlob(blob: Blob, fileName: string): void {+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = fileName;+ link.click();+ // Revoked on the next tick: Safari reads the URL after the click handler returns,+ // and a URL revoked in the same tick gives it nothing to save.+ setTimeout(() => URL.revokeObjectURL(url), 0);+}diff --git a/apps/web/src/utils/chartSpec.test.ts b/apps/web/src/utils/chartSpec.test.tsnew file mode 100644index 00000000..ce0fe27e--- /dev/null+++ b/apps/web/src/utils/chartSpec.test.ts@@ -0,0 +1,129 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import {+ CHART_PALETTE,+ chartHasLegend,+ chartLegend,+ isSliceChart,+ parseChartSpec,+ seriesColor,+} from './chartSpec';+import type { ChartSpec } from './chartSpec';++const spec = {+ type: 'bar',+ x: 'week',+ series: [{ key: 'created' }],+ data: [{ week: 'W1', created: 3 }],+};++function parse(patch: Record<string, unknown> = {}) {+ return parseChartSpec(JSON.stringify({ ...spec, ...patch }));+}++describe('parseChartSpec', () => {+ it('parses a complete spec', () => {+ assert.deepEqual(parse(), spec);+ });++ it('rejects anything that is not a spec object', () => {+ assert.equal(parseChartSpec('not json'), null);+ assert.equal(parseChartSpec('[]'), null);+ assert.equal(parseChartSpec('"text"'), null);+ });++ it('parses every type the renderer draws', () => {+ for (const type of [+ 'bar',+ 'line',+ 'area',+ 'pie',+ 'radar',+ 'radial',+ 'scatter',+ 'funnel',+ 'treemap',+ ]) {+ assert.equal(parse({ type })?.type, type);+ }+ });++ it('rejects a spec the renderer could not draw', () => {+ assert.equal(parse({ type: 'sankey' }), null);+ assert.equal(parse({ x: '' }), null);+ assert.equal(parse({ series: [] }), null);+ assert.equal(parse({ series: [{ label: 'no key' }] }), null);+ assert.equal(parse({ data: 'rows' }), null);+ assert.equal(parse({ data: [] }), null);+ });+});++describe('seriesColor', () => {+ it('prefers the color the spec names', () => {+ assert.equal(seriesColor({ key: 'a', color: '#123456' }, 0), '#123456');+ });++ it('falls back to the palette, wrapping past its end', () => {+ assert.equal(seriesColor({ key: 'a' }, 1), CHART_PALETTE[1]);+ assert.equal(seriesColor({ key: 'a' }, CHART_PALETTE.length), CHART_PALETTE[0]);+ });+});++describe('chartLegend', () => {+ it('lists the series of a bar, line, or area chart', () => {+ assert.deepEqual(+ chartLegend({+ ...(spec as ChartSpec),+ series: [{ key: 'created', label: 'Created' }, { key: 'closed' }],+ }),+ [+ { key: 'created', label: 'Created', color: CHART_PALETTE[0] },+ { key: 'closed', label: 'closed', color: CHART_PALETTE[1] },+ ],+ );+ });++ it('lists the categories of a pie and a radial, since they are coloured by slice', () => {+ for (const type of ['pie', 'radial'] as const) {+ assert.deepEqual(+ chartLegend({+ ...(spec as ChartSpec),+ type,+ data: [+ { week: 'Backlog', created: 2 },+ { week: 'Done', created: 12 },+ ],+ }),+ [+ { key: 'Backlog', label: 'Backlog', color: CHART_PALETTE[0] },+ { key: 'Done', label: 'Done', color: CHART_PALETTE[1] },+ ],+ );+ }+ });+});++describe('isSliceChart', () => {+ it('holds for the types drawn one shape per row', () => {+ assert.equal(isSliceChart({ ...(spec as ChartSpec), type: 'radial' }), true);+ assert.equal(isSliceChart({ ...(spec as ChartSpec), type: 'treemap' }), true);+ assert.equal(isSliceChart({ ...(spec as ChartSpec), type: 'radar' }), false);+ });+});++describe('chartHasLegend', () => {+ const rows = [+ { week: 'Backlog', created: 2 },+ { week: 'Done', created: 12 },+ ];++ it('holds once there is more than one entry to tell apart', () => {+ assert.equal(chartHasLegend(spec as ChartSpec), false);+ assert.equal(chartHasLegend({ ...(spec as ChartSpec), type: 'pie', data: rows }), true);+ });++ it('does not hold for a chart that names its shapes inside the drawing', () => {+ assert.equal(chartHasLegend({ ...(spec as ChartSpec), type: 'funnel', data: rows }), false);+ assert.equal(chartHasLegend({ ...(spec as ChartSpec), type: 'treemap', data: rows }), false);+ });+});diff --git a/apps/web/src/utils/chartSpec.ts b/apps/web/src/utils/chartSpec.tsnew file mode 100644index 00000000..09683504--- /dev/null+++ b/apps/web/src/utils/chartSpec.ts@@ -0,0 +1,136 @@+// The chart spec: one JSON shape that describes a chart. An agent sends it to the+// create_chart endpoint, which checks it and answers with it, and then writes it into+// a ```chart fence in its answer. The shared Markdown component draws that fence with+// ChartBlock, so the spec is the only thing the two ends have to agree on.+//+// The api validates the same shape in TypeBox (see+// apps/api/src/modules/charts/model.ts); this file is the browser's copy, next to the+// other types the web app keeps for what it reads over HTTP.++const CHART_TYPES = [+ 'bar',+ 'line',+ 'area',+ 'pie',+ 'radar',+ 'radial',+ 'scatter',+ 'funnel',+ 'treemap',+] as const;++export type ChartType = (typeof CHART_TYPES)[number];++// The types whose shapes are one per data row rather than one per series, so each of+// them is colored, labelled, and drawn from the first series alone.+const SLICE_TYPES: ChartType[] = ['pie', 'radial', 'funnel', 'treemap'];++// The types that write the name of every shape inside the drawing, so a legend under+// it would say the same thing twice.+const SELF_LABELLED_TYPES: ChartType[] = ['funnel', 'treemap'];++export interface ChartSeries {+ // The key of this series in every data row.+ key: string;+ label?: string;+ color?: string;+ // Draws this series as something other than what the chart's own type says, which+ // is what lets one chart carry bars and a line.+ type?: 'bar' | 'line' | 'area';+}++export interface ChartSpec {+ type: ChartType;+ // The key of the category (x axis for bar/line/area/scatter, slice name for+ // pie/radial, corner name for radar).+ x: string;+ title?: string;+ series: ChartSeries[];+ data: Record<string, string | number | null>[];+ stacked?: boolean | 'percent';+ horizontal?: boolean;+ curve?: 'monotone' | 'linear' | 'step';+ showValues?: boolean;+}++// Slice and series colors for a spec that names none, by position.+export const CHART_PALETTE = [+ '#6366f1',+ '#22c55e',+ '#eab308',+ '#ec4899',+ '#06b6d4',+ '#f97316',+ '#8b5cf6',+ '#64748b',+];++export function seriesColor(series: ChartSeries, index: number): string {+ return series.color ?? CHART_PALETTE[index % CHART_PALETTE.length];+}++export function isSliceChart(spec: ChartSpec): boolean {+ return SLICE_TYPES.includes(spec.type);+}++// Whether a legend is drawn under the chart at all. The drawn chart and the exported+// file both ask this, so a file cannot end up with a legend the chart never had.+export function chartHasLegend(spec: ChartSpec): boolean {+ return !SELF_LABELLED_TYPES.includes(spec.type) && chartLegend(spec).length > 1;+}++export interface ChartLegendEntry {+ key: string;+ label: string;+ color: string;+}++// What the legend of a chart lists, and in what color. A pie, a radial, a funnel, and+// a treemap are colored by shape, so their entries are the categories in the data;+// every other type draws one mark per series, so its entries are the series. Both the+// drawn chart and the exported file read the legend from here, which is what keeps+// their colors and labels in step.+export function chartLegend(spec: ChartSpec): ChartLegendEntry[] {+ if (isSliceChart(spec)) {+ // The palette is read by position rather than through seriesColor: a color set on+ // the single series would otherwise paint every slice the same.+ return spec.data.map((row, index) => {+ const name = String(row[spec.x] ?? '');+ return { key: name, label: name, color: CHART_PALETTE[index % CHART_PALETTE.length] };+ });+ }+ return spec.series.map((series, index) => ({+ key: series.key,+ label: series.label ?? series.key,+ color: seriesColor(series, index),+ }));+}++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isSeries(value: unknown): boolean {+ return isObject(value) && typeof value.key === 'string' && value.key !== '';+}++// A spec parsed out of an agent's JSON, or null when it is not one. The text is+// written by a model, so the fields recharts needs a value for — type, x, series, and+// data — are checked here: recharts throws on a missing dataKey rather than drawing an+// empty chart.+export function parseChartSpec(text: string): ChartSpec | null {+ let value: unknown;+ try {+ value = JSON.parse(text);+ } catch {+ return null;+ }+ if (!isObject(value)) return null;+ if (!CHART_TYPES.includes(value.type as ChartType)) return null;+ if (typeof value.x !== 'string' || !value.x) return null;+ if (!Array.isArray(value.series) || value.series.length === 0) return null;+ if (!value.series.every(isSeries)) return null;+ if (!Array.isArray(value.data) || value.data.length === 0) return null;+ if (!value.data.every(isObject)) return null;+ return value as unknown as ChartSpec;+}