:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(canvas): instruct agents to build progressively rendering canvases (#87173)
Peter Kirkham75eef61fe58d
diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 62e0d2388709..ea0027429e6e 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -55,8 +55,9 @@ implementation contracts. Load every companion that applies before writing sourc`<canvas>`, or WebGL work where application components add no useful structure. It owns semanticmarkup, direct browser APIs, animation cleanup, and non-Quill theming.- **`querying-canvas-data`** whenever the canvas reads PostHog data, captures events, or navigates.- It owns the `ph` SDK, saved-insight preference, result shapes, variables, date ranges, and declared- data capabilities. Load it alongside either implementation skill when data is involved.+ It owns the `ph` SDK, saved-insight preference, result shapes, variables, date ranges, progressive+ per-query loading, and declared data capabilities. Load it alongside either implementation skill+ when data is involved.- **`validating-and-publishing-canvases`** for every canvas. It owns project shape, capabilitydeclarations, validation diagnostics, guarded publishes, drafts, builds, and conflict recovery.diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.mdindex 3fa78a84b5d6..aab812441002 100644--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md@@ -15,8 +15,9 @@ The whole application is one React/TSX file (`src/canvas.tsx` in the source projreact-dom or call createRoot.Start from the working scaffold in [references/starter-scaffold.md](references/starter-scaffold.md)-on a first build: it already wires the date picker, theme tokens, per-card skeletons, and correct-typed-node result reading. Keep that wiring; replace the sample metric and layout.+on a first build: it already wires the date picker, theme tokens, per-query loading state (every+card fills in independently as its own data lands), and correct typed-node result reading. Keep+that wiring; replace the sample metrics and layout.## Imports@@ -74,8 +75,15 @@ text-card-foreground`; borders `border-border`. Never a hardcoded hex or light-oEvery data point renders a skeleton in its own `Card` while loading or refreshing: `SkeletonText`(matching `lines` and text-size `className`) for text/number values, `Skeleton` for blocks/charts.-Drive `isLoading` off the data calls and set it true again on refresh; never show a blank or a-jumping layout.++Render progressively — each query owns its loading state. The chrome (heading, date picker,+card frames with skeletons inside) renders immediately, every independent query fires+concurrently on mount, and each card swaps its skeleton for data the moment its own query+resolves, so a slow query only holds back its own card. Never drive the whole canvas off one+shared `loading` flag or a `Promise.all` across independent queries — that makes the fastest+metric wait for the slowest. Set each section's loading state true again on refresh; never show+a blank or a jumping layout. Content the first paint doesn't show (an inactive tab, a collapsed+section, a drill-down) defers its query until the user reveals it.A failed query and an empty result are different states — never let one render as the other.`.catch` on every `ph.query`/`ph.loadInsight` must set an error state that renders visibly (thediff --git a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.mdindex 6f4785d2b2e3..3716dd60a79a 100644--- a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md+++ b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md@@ -1,16 +1,21 @@# Canvas starter scaffoldA known-good baseline for a React + Quill data canvas. It already wires the pieces that are easy-to get wrong — the date picker (self-sizing, no `compact`), theme-aware tokens, per-card loading-skeletons, reading a typed-node result correctly, and the "View query" verification dialog every-ad-hoc data card must carry. Start from it on a first build: keep the wiring, replace the sample-"total events" metric and the layout with what the user asked for.-Ideally swap the inline `ph.query` typed node for a saved insight loaded with+to get wrong — the date picker (self-sizing, no `compact`), theme-aware tokens, per-query loading+state so every card fills in the moment its own data lands, reading a typed-node result correctly,+and the "View query" verification dialog every ad-hoc data card must carry. Start from it on a+first build: keep the wiring, replace the sample metrics and the layout with what the user asked+for. Ideally swap the inline `ph.query` typed nodes for saved insights loaded with`ph.loadInsight(shortId, { dateRange })` (see the `querying-canvas-data` skill) — then replace the"View query" dialog with a "View in PostHog" button calling `ph.openExternal(insightUrl)`, the URLminted at authoring time by the `generate-app-url` MCP tool (`/insights/{id}`), so viewers verifythe numbers on the real insight with their own permissions applied.+The load-bearing pattern is `useCanvasQuery`: one instance per query, each owning its+`{ loading, error, data }`. All queries start concurrently on mount and each card renders as soon+as its own result arrives — a slow query only holds back its own card. Keep that shape as you add+metrics; never collapse the queries behind one shared `loading` flag or a `Promise.all`.+```tsximport React, { useEffect, useState } from 'react'import {@@ -35,63 +40,134 @@ import {import { RefreshCw } from 'lucide-react'import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'-// One builder feeds both the ph.query call and the "View query" dialog, so the-// query a viewer inspects is exactly the one that ran. `event: null` = all-// events (works on any project).-const totalEventsQuery = (win) => ({+// One builder per query feeds both the ph.query call and its "View query"+// dialog, so the query a viewer inspects is exactly the one that ran. Typed+// query nodes are computed by PostHog's own runner so the numbers match the+// UI exactly. `event: null` = all events (works on any project).+const totalEventsQuery = (dateRange) => ({kind: 'TrendsQuery',series: [{ kind: 'EventsNode', event: null, name: 'All events', math: 'total' }],- dateRange: {- date_from: win.start.toISOString(),- date_to: win.end.toISOString(),- },+ dateRange,})-export default function Canvas() {- const def = quickRanges.find((r) => r.name === 'Last 30 days') ?? quickRanges[0]- const [win, setWin] = useState({- start: def.rangeSetter(new Date()),- end: new Date(),- range: def,- })- const [open, setOpen] = useState(false)-- const [loading, setLoading] = useState(true)- const [error, setError] = useState(null)- const [total, setTotal] = useState(0)- const [series, setSeries] = useState([])- // Refresh plumbing: bump this nonce to re-run the data effect on demand.- const [nonce, setNonce] = useState(0)+// BoldNumber makes the runner compute uniques across the whole period;+// summing the per-day values (`count`) would recount anyone active on+// several days.+const uniqueUsersQuery = (dateRange) => ({+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', event: null, name: 'Unique users', math: 'dau' }],+ trendsFilter: { display: 'BoldNumber' },+ dateRange,+})+// One instance per query. Each section owns its own { loading, error, data }+// and renders the moment ITS result lands — never share one loading flag+// across queries or gate the canvas on Promise.all: that makes the fastest+// card wait for the slowest query.+function useCanvasQuery(runQuery, deps) {+ const [state, setState] = useState({ loading: true, error: null, data: null })useEffect(() => {let cancelled = false- setLoading(true)- setError(null)- // Typed query node, computed by PostHog's own runner so the numbers match- // the UI exactly.- ph.query(totalEventsQuery(win))- .then((res) => {+ setState({ loading: true, error: null, data: null })+ runQuery()+ .then((data) => {if (cancelled) return- // Typed-node result: `results` is an array of SERIES OBJECTS, not rows.- const s = res.results[0] ?? {}- setTotal(s.count ?? 0)- setSeries((s.days ?? []).map((day, i) => ({ day, value: s.data?.[i] ?? 0 })))- setLoading(false)+ setState({ loading: false, error: null, data })}).catch((err) => {if (cancelled) return- setLoading(false)// A failed query must LOOK failed — falling through to zeros or an// empty chart reads as "no data" and hides real breakage.- setError(String(err?.message ?? err))+ setState({ loading: false, error: String(err?.message ?? err), data: null })})return () => {cancelled = true}- }, [win, nonce])+ }, deps)+ return state+}++function CardError({ message, onRetry }) {+ return (+ <div className="flex items-center justify-between gap-2">+ <p className="text-sm text-destructive">Couldn't load: {message}</p>+ <Button variant="outline" size="sm" onClick={onRetry}>+ Retry+ </Button>+ </div>+ )+}++// Every ad-hoc ph.query card carries a verification affordance showing the+// exact query that ran. A card backed by a saved insight instead renders a+// "View in PostHog" Button calling ph.openExternal(insightUrl) — the URL+// minted by the generate-app-url MCP tool, never hand-built.+function ViewQueryDialog({ query }) {+ return (+ <Dialog>+ <DialogTrigger+ render={+ <Button variant="outline" size="sm">+ View query+ </Button>+ }+ />+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Query behind this figure</DialogTitle>+ </DialogHeader>+ <div className="max-h-80 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 font-mono text-xs">+ {JSON.stringify(query, null, 2)}+ </div>+ </DialogContent>+ </Dialog>+ )+}++export default function Canvas() {+ const def = quickRanges.find((r) => r.name === 'Last 30 days') ?? quickRanges[0]+ const [win, setWin] = useState({+ start: def.rangeSetter(new Date()),+ end: new Date(),+ range: def,+ })+ const [open, setOpen] = useState(false)+ // Refresh plumbing: bump this nonce to re-run every data effect on demand.+ const [nonce, setNonce] = useState(0)+ const retry = () => setNonce((n) => n + 1)++ const dateRange = {+ date_from: win.start.toISOString(),+ date_to: win.end.toISOString(),+ }++ // Both queries fire concurrently on mount; the cards below fill in+ // independently as each result arrives.+ const events = useCanvasQuery(+ () =>+ ph.query(totalEventsQuery(dateRange)).then((res) => {+ // Typed-node result: `results` is an array of SERIES OBJECTS, not rows.+ const firstSeries = res.results[0] ?? {}+ return {+ total: firstSeries.count ?? 0,+ series: (firstSeries.days ?? []).map((day, index) => ({+ day,+ value: firstSeries.data?.[index] ?? 0,+ })),+ }+ }),+ [win, nonce]+ )+ const visitors = useCanvasQuery(+ () => ph.query(uniqueUsersQuery(dateRange)).then((res) => res.results[0]?.aggregated_value ?? 0),+ [win, nonce]+ )+ const anyLoading = events.loading || visitors.loadingreturn (- // The canvas root must resolve height against the iframe viewport.+ // The canvas root must resolve height against the iframe viewport. The+ // chrome (heading, date picker, card frames) renders immediately — only+ // the value inside each card waits, each for its own query.<div className="flex h-screen flex-col gap-4 overflow-y-auto p-6"><div className="flex items-center justify-between"><Heading size="xl" className="mb-4">@@ -114,36 +190,42 @@ export default function Canvas() {/></PopoverContent></Popover>- <Button variant="outline" disabled={loading} onClick={() => setNonce((n) => n + 1)}>- <RefreshCw size={14} className={loading ? 'animate-spin' : undefined} />+ <Button variant="outline" disabled={anyLoading} onClick={retry}>+ <RefreshCw size={14} className={anyLoading ? 'animate-spin' : undefined} />Refresh</Button></div></div>- {error && (+ <div className="grid gap-4 md:grid-cols-3"><Card size="sm">- <CardContent className="flex items-center justify-between gap-4">- <p className="text-sm text-destructive">Couldn't load data: {error}</p>- <Button variant="outline" size="sm" onClick={() => setNonce((n) => n + 1)}>- Retry- </Button>+ <CardHeader>+ <CardTitle>Total events</CardTitle>+ </CardHeader>+ <CardContent>+ {events.loading ? (+ <SkeletonText lines={1} className="text-3xl" />+ ) : events.error ? (+ <CardError message={events.error} onRetry={retry} />+ ) : (+ <Heading size="2xl">{events.data.total.toLocaleString()}</Heading>+ )}</CardContent></Card>- )}-- <div className="grid gap-4 md:grid-cols-3"><Card size="sm"><CardHeader>- <CardTitle>Total events</CardTitle>+ <div className="flex items-center justify-between gap-2">+ <CardTitle>Unique users</CardTitle>+ <ViewQueryDialog query={uniqueUsersQuery(dateRange)} />+ </div></CardHeader><CardContent>- {loading ? (+ {visitors.loading ? (<SkeletonText lines={1} className="text-3xl" />- ) : error ? (- <p className="text-sm text-muted-foreground">—</p>+ ) : visitors.error ? (+ <CardError message={visitors.error} onRetry={retry} />) : (- <Heading size="2xl">{total.toLocaleString()}</Heading>+ <Heading size="2xl">{visitors.data.toLocaleString()}</Heading>)}</CardContent></Card>@@ -153,39 +235,18 @@ export default function Canvas() {<CardHeader><div className="flex items-center justify-between gap-2"><CardTitle>Events over time</CardTitle>- {/* Every data card carries a verification affordance. An ad-hoc- ph.query card shows the query it ran; a card backed by a saved- insight instead renders a "View in PostHog" Button calling- ph.openExternal(insightUrl) — the URL minted by the- generate-app-url MCP tool, never hand-built. */}- <Dialog>- <DialogTrigger- render={- <Button variant="outline" size="sm">- View query- </Button>- }- />- <DialogContent>- <DialogHeader>- <DialogTitle>Query behind this chart</DialogTitle>- </DialogHeader>- <div className="max-h-80 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 font-mono text-xs">- {JSON.stringify(totalEventsQuery(win), null, 2)}- </div>- </DialogContent>- </Dialog>+ <ViewQueryDialog query={totalEventsQuery(dateRange)} /></div></CardHeader><CardContent>- {loading ? (+ {events.loading ? (<SkeletonText lines={6} />- ) : error ? (- <p className="text-sm text-muted-foreground">—</p>+ ) : events.error ? (+ <CardError message={events.error} onRetry={retry} />) : (<div className="h-[280px] w-full"><ResponsiveContainer>- <LineChart data={series}>+ <LineChart data={events.data.series}><CartesianGrid stroke="var(--border)" strokeDasharray="3 3" /><XAxis dataKey="day" stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} /><YAxis stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} />diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.mdindex e5206820f6c5..f2edcc1406e9 100644--- a/products/canvas/skills/querying-canvas-data/SKILL.md+++ b/products/canvas/skills/querying-canvas-data/SKILL.md@@ -4,9 +4,9 @@ description: >Get PostHog data into a canvas correctly: the host-injected `ph` SDK (loadInsight, query,capture, state, openExternal, navigate), the data hierarchy (saved insights first, typed query nodessecond, inline HogQL last), verifiability (insight-backed metrics link their saved insight in- PostHog; ad-hoc queries expose the exact query that ran), per-insight-type result shapes, date-range wiring, and event- capture from a canvas. Use whenever a canvas shows metrics, charts, tables, or any PostHog data, or- needs to send analytics events.+ PostHog; ad-hoc queries expose the exact query that ran), per-insight-type result shapes,+ progressive per-query loading, date-range wiring, and event capture from a canvas. Use whenever a+ canvas shows metrics, charts, tables, or any PostHog data, or needs to send analytics events.---# Querying canvas data@@ -83,12 +83,34 @@ await ph.query(queryNode, {}, { refresh: 30 })`days: string[]` (ISO), `labels: string[]`, `count` (sum), `aggregated_value` (single-valuetotal), `label`, and optional `compare_label: "current" | "previous"`. A KPI total is`results[0].count` (or `.aggregated_value`); a line chart plots `results[0].data` over- `results[0].days`. With a compare period, find the prior series by `compare_label === "previous"`+ `results[0].days`. `count` sums the per-interval values, which double-counts a unique-users+ series (`math: "dau"`) for anyone active on several days — for a period-unique KPI, set+ `trendsFilter: { display: "BoldNumber" }` on the query and read `aggregated_value` instead.+ With a compare period, find the prior series by `compare_label === "previous"`— never by index. `columns` is empty here.- **SQL results**: `{ columns: string[], results: rows[][] }` — each row an array of cell values in`columns` order.-Load data in `useEffect` with `useState`, show a loading state, and aggregate in the query; never+## Load progressively — render each section when its own data lands++PostHog queries can take several seconds each, and a board usually runs several. Never gate+rendering on all of them:++- Fire independent queries concurrently on mount; never chain unrelated queries with sequential+ `await`s. The host caps a canvas at 8 in-flight data requests and rejects the ninth ("Canvas+ data request exceeds runtime limits") rather than queuing it — a board that needs more than 8+ consolidates them (one query returning every row, sliced client-side) or throttles the overflow+ behind a small concurrency limiter, still with one state per section.+- Give every query its own `{ loading, error, data }` state and let each card, chart, or table+ swap its skeleton for data the moment its own result arrives. One shared `loading` flag or a+ single `Promise.all` across independent queries makes the fastest metric wait for the slowest —+ the canvas must fill in progressively, not appear all at once.+- Render the static chrome (heading, date picker, card frames with skeletons inside) immediately;+ only the value inside each section waits for its query.+- Defer queries the first paint doesn't need: content behind a tab, a collapsed section, or a+ drill-down runs its query when the user reveals it, not on mount.++Load data in `useEffect` with `useState`, and aggregate in the query; neverfetch raw event dumps. Treat a rejected query and an empty result as different states: `.catch`must set an error state that renders visibly (message + retry), never fall through to zeros, anempty chart, or a "no data" message — a swallowed error makes real breakage (a missing table, an