Skip to content

feat(agent): render_chart tool + inline Recharts visualizations - #138

Merged
gkhngyk merged 4 commits into
mainfrom
feat/agent-chart-rendering
Jun 1, 2026
Merged

gkhngyk merged 4 commits into
mainfrom
feat/agent-chart-rendering

Conversation

@gkhngyk

@gkhngyk gkhngyk commented May 31, 2026

Copy link
Copy Markdown
Contributor

Closes #126.

What

The agent could already quote numbers from the time-aware tools but had no way to draw them. Trends became row-by-row prose; cross-entity comparisons became tables. This PR adds a render_chart tool the model calls after it has the data, plus a UI dispatch that renders the resulting spec inline in the assistant bubble.

Pieces

  • web/src/lib/agent/tools.ts: new render_chart tool. Inert execute — the tool echoes its input back as output because the rendering is client-side. Zod schema:
    • type: line | bar | pie
    • data: array of Record<string, string | number>, max 200 rows
    • xKey + series (up to 5) for line / bar
    • valueKey + labelKey for pie
    • optional title
  • web/src/components/agent/agent-chart.tsx: Recharts wrapper that maps the spec to LineChart / BarChart / PieChart. Uses the existing --chart-1…--chart-5 oklch palette from globals.css so dark / light mode follows the dashboard. Mirrors the ResizeObserver replacement for ResponsiveContainer that the existing dashboard chart files use (React 19 compat).
  • Agent page: ToolCallDisclosure dispatch grows a tool-render_chart branch that renders AgentChart instead of the JSON disclosure. Other tools keep the existing chip + expandable JSON.
  • web/src/lib/agent/system-prompt.ts: new Visualization (render_chart) section pairing each chart type with the data tool it follows, plus hard rules:
    • Always call the data tool first, then render_chart
    • Pass values straight from the previous tool's response — never invent, reformat, or round
    • Write 1–2 sentences interpreting the chart after rendering

Persistence

Falls out for free — the chart spec is the tool part's output, already stored in agent_messages.tool_calls JSONB. Reloading a conversation re-renders the chart without re-running any tool calls.

Test plan

  1. Start a conversation, ask 'How has visibility changed over the last 30 days?'
  2. Expect get_visibility_trend to run, then render_chart with type=line, an inline line chart appears in the bubble, followed by a 1–2 sentence interpretation.
  3. Ask 'Compare share of voice across competitors'
  4. Expect get_competitor_comparison then render_chart with type=bar or pie.
  5. Reload the page — the chart should re-render from persisted state without re-running the tools.

Out of scope

  • Multi-axis / dual-scale charts. Single value axis only in v1.
  • Drilldown beyond Recharts' built-in tooltip.
  • A 'show as table' toggle.
  • Sankey, heatmap, geo, or any chart type not already used elsewhere in the dashboard.
  • Enforcing that the chart's data references a previous toolCallId — relying on the system-prompt rule for now; can tighten later if hallucinated charts show up in practice.

Closes #126.

The agent could already quote numbers from get_visibility_trend,
get_competitor_comparison, list_citations etc., but had no way to draw
them. Trends became row-by-row prose; cross-entity comparisons became
tables. This adds a render_chart tool that the model calls AFTER it has
the data, and a UI dispatch that renders the resulting spec inline in
the assistant bubble.

Pieces:

- web/src/lib/agent/tools.ts: new render_chart tool. Inert execute (the
  tool just echoes its input back as output) because the rendering is
  client-side. Zod schema accepts type=line|bar|pie, data (max 200 rows),
  xKey + series for line/bar, valueKey + labelKey for pie.
- web/src/components/agent/agent-chart.tsx: Recharts wrapper that maps
  the spec to LineChart / BarChart / PieChart. Uses the existing
  --chart-1..5 oklch palette from globals.css so dark/light mode follows
  the dashboard. Mirrors the ResizeObserver replacement for
  ResponsiveContainer that the insights _charts.tsx files already use
  (React 19 compat).
- agent page: ToolCallDisclosure dispatch grows a tool-render_chart
  branch that renders AgentChart instead of the JSON disclosure. Other
  tools keep the existing chip + expandable JSON. Persistence works for
  free — the spec is already in agent_messages.tool_calls JSONB, so
  reloading a conversation re-renders the chart without re-running any
  tool calls.
- system-prompt: a new 'Visualization (render_chart)' section pairing
  each chart type with the data tool it follows, plus hard rules: never
  call render_chart without real data in hand, pass values verbatim, and
  always interpret the chart in 1-2 sentences after rendering.
… key values

The render_chart tool's series array is whatever the model pasted in.
If two entries happen to share the same .key string (e.g. both labeled
'mentions' by mistake), React's duplicate-key warning fires when the
map renders inside Recharts' Fragment children. Prefix the React key
with the array index so duplicates are still unique in the tree even
though Recharts still uses dataKey={s.key} for its own bookkeeping.
…me-aware

The theme tokens in globals.css ship as full oklch(…) values, not
HSL components. I had wrapped them as hsl(var(--token)) which evaluates
to hsl(oklch(…)) — invalid CSS, so browsers fell back to default black.
In dark mode that meant black axis labels on a near-black background.

Switch every theme reference to var(--…) directly (no hsl() wrapper).
Recharts text color is controlled via the tick={{ fill }} prop, not
the axis stroke, so move the color there. Legend wrapperStyle gets a
matching color override so the series labels read against either
background.
…'s data isn't excluded

Reported via the in-product agent: asking 'how is the brand doing today'
on 31 May (with tracking already run at 09:00 UTC+3) came back with no
results and the agent quoted 30 May data instead.

Root cause: every Supabase query and RPC that takes a dateTo treats it
verbatim. A bare 'YYYY-MM-DD' parses as the *start* of that day in UTC,
so created_at <= '2026-05-31' is equivalent to <= 2026-05-31 00:00:00 UTC
— excluding everything that happened later on May 31.

Add a shared expandDateToEndOfDay helper in lib/dates.ts that detects
bare-date input and pins it to '23:59:59.999Z'. Full ISO timestamps are
passed through untouched, so callers that intentionally want a strict
mid-day upper bound still get it.

Apply it everywhere upstream code hands a user-supplied dateTo to either
a direct .lte('created_at', …) call or a p_date_to RPC param:

- web/src/lib/mcp/data.ts (agent + MCP REST surface)
- web/src/lib/actions/tracking.ts (insights / visibility / SoV / trend RPCs)
- web/src/lib/actions/citations.ts (citations page filters)

dateFrom is untouched — '2026-05-31' as start-of-day inclusive is the
intended semantic there and already correct.

This branch was successfully deployed

1 active deployment
Preview — 8dc59939 Deployed May 31, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(agent): inline chart rendering in the in-product agent (render_chart tool)

1 participant