: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
feat(canvas): add refreshable reads to desktop runtime (#82938)
Peter Kirkham9c44ea65324b
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex f95998524663..40bce9e2c54a 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -31,6 +31,7 @@ export const canvasDataQueryInput = zhogql: z.string().min(1).max(20_000).optional(),// Reserved for bound parameters (Phase 3 named queries). Edit mode ignores it.params: z.record(z.string().max(128), z.unknown()).optional(),+ refresh: z.number().int().min(30).max(86_400).optional(),}).refine((v) => v.query != null || v.hogql != null, {message: "ph.query requires a query node or a HogQL string",@@ -77,6 +78,7 @@ export const canvasLoadInsightInput = z.object({// Keyed by the variable's `code_name`, not its uuid — the host resolves ids// server-side, so canvas code never carries a variable uuid.variables: z.record(z.string().min(1).max(128), z.unknown()).optional(),+ refresh: z.number().int().min(30).max(86_400).optional(),});export type CanvasLoadInsightInput = z.infer<typeof canvasLoadInsightInput>;diff --git a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts b/products/desktop/packages/core/src/canvas/freeformWhitelist.tsindex 47c94011395f..0a3d631db78c 100644--- a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts+++ b/products/desktop/packages/core/src/canvas/freeformWhitelist.ts@@ -59,6 +59,36 @@ export const FREEFORM_WHITELIST: WhitelistEntry[] = [},// One formatting/date util.{ name: "dayjs", version: "1.11.13", esm: `${ESM}/[email protected]` },+ { name: "d3", version: "7.9.0", esm: `${ESM}/[email protected]` },+ { name: "three", version: "0.179.1", esm: `${ESM}/[email protected]` },+ {+ name: "framer-motion",+ version: "12.23.12",+ esm: `${ESM}/[email protected]?external=react,react-dom`,+ },+ { name: "zod", version: "3.25.76", esm: `${ESM}/[email protected]` },+ {+ name: "@tanstack/react-table",+ version: "8.21.3",+ esm: `${ESM}/@tanstack/[email protected]?external=react,react-dom`,+ },+ {+ name: "@tanstack/react-virtual",+ version: "3.14.9",+ esm: `${ESM}/@tanstack/[email protected]?external=react,react-dom`,+ },+ {+ name: "react-hook-form",+ version: "7.85.0",+ esm: `${ESM}/[email protected]?external=react`,+ },+ { name: "lodash-es", version: "4.18.1", esm: `${ESM}/[email protected]` },+ {+ name: "react-markdown",+ version: "10.1.0",+ esm: `${ESM}/[email protected]?external=react`,+ },+ { name: "papaparse", version: "5.6.0", esm: `${ESM}/[email protected]` },];// The CDN host the edit-mode import map (and Babel) load from. The iframe CSPdiff --git a/products/desktop/packages/shared/src/canvas-platform.ts b/products/desktop/packages/shared/src/canvas-platform.tsindex 6b43f2dca4dc..314ee441dd16 100644--- a/products/desktop/packages/shared/src/canvas-platform.ts+++ b/products/desktop/packages/shared/src/canvas-platform.ts@@ -30,6 +30,37 @@ export const CANVAS_PLATFORM_MANIFEST = {version: "1.11.13",url: "https://esm.sh/[email protected]",},+ d3: { version: "7.9.0", url: "https://esm.sh/[email protected]" },+ three: { version: "0.179.1", url: "https://esm.sh/[email protected]" },+ "framer-motion": {+ version: "12.23.12",+ url: "https://esm.sh/[email protected]?external=react,react-dom",+ },+ zod: { version: "3.25.76", url: "https://esm.sh/[email protected]" },+ "@tanstack/react-table": {+ version: "8.21.3",+ url: "https://esm.sh/@tanstack/[email protected]?external=react,react-dom",+ },+ "@tanstack/react-virtual": {+ version: "3.14.9",+ url: "https://esm.sh/@tanstack/[email protected]?external=react,react-dom",+ },+ "react-hook-form": {+ version: "7.85.0",+ url: "https://esm.sh/[email protected]?external=react",+ },+ "lodash-es": {+ version: "4.18.1",+ url: "https://esm.sh/[email protected]",+ },+ "react-markdown": {+ version: "10.1.0",+ url: "https://esm.sh/[email protected]?external=react",+ },+ papaparse: {+ version: "5.6.0",+ url: "https://esm.sh/[email protected]",+ },},runtimeImports: {"react/jsx-runtime": "https://esm.sh/[email protected]/jsx-runtime",@@ -43,6 +74,16 @@ export const CANVAS_PLATFORM_MANIFEST = {"recharts","lucide-react","dayjs",+ "d3",+ "three",+ "framer-motion",+ "zod",+ "@tanstack/react-table",+ "@tanstack/react-virtual",+ "react-hook-form",+ "lodash-es",+ "react-markdown",+ "papaparse",],csp: "default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:",limits: {diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.tsindex 739dc24c9f6a..6362b22fa47e 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts@@ -144,4 +144,36 @@ describe("handleFreeformDataRequest", () => {expect(await read("surveys")).toEqual({ columns: ["mrr"], results: [[1]] });expect(loadInsight).toHaveBeenCalledTimes(2);});++ it("refreshes a cached read after its declared interval", async () => {+ vi.useFakeTimers();+ const queryClient = new QueryClient();+ loadInsight.mockReset();+ loadInsight+ .mockResolvedValueOnce({ columns: ["value"], results: [[1]] })+ .mockResolvedValueOnce({ columns: ["value"], results: [[2]] });++ const read = () =>+ handleFreeformDataRequest(+ "loadInsight",+ { shortId: "abc123", refresh: 30 },+ queryClient,+ );++ expect(await read()).toEqual({ columns: ["value"], results: [[1]] });+ await vi.advanceTimersByTimeAsync(30_001);+ expect(await read()).toEqual({ columns: ["value"], results: [[2]] });+ expect(loadInsight).toHaveBeenCalledTimes(2);+ vi.useRealTimers();+ });++ it("rejects refresh intervals below the platform floor", async () => {+ await expect(+ handleFreeformDataRequest(+ "loadInsight",+ { shortId: "abc123", refresh: 29 },+ new QueryClient(),+ ),+ ).rejects.toThrow("between 30 and 86400 seconds");+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.tsindex f1b51f6e5a19..d850629ddb5e 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts@@ -49,15 +49,30 @@ function cachedRead<T>(method: string,input: unknown,run: () => Promise<T>,+ refreshSeconds?: number,) {return queryClient.fetchQuery({queryKey: [CANVAS_QUERY_KEY, method, stableStringify(input)] as const,queryFn: run,- staleTime: 5 * 60_000,- gcTime: 10 * 60_000,+ staleTime: (refreshSeconds ?? 5 * 60) * 1_000,+ // At least the refresh interval, or GC would evict an inactive entry+ // before it goes stale and force an early backend re-read.+ gcTime: Math.max(refreshSeconds ?? 5 * 60, 10 * 60) * 1_000,});}+function refreshSeconds(value: unknown): number | undefined {+ if (value === undefined) return undefined;+ if (+ !Number.isInteger(value) ||+ (value as number) < 30 ||+ (value as number) > 86_400+ ) {+ throw new Error("refresh must be an integer between 30 and 86400 seconds");+ }+ return value as number;+}+// Resolves a `ph.*` data-request from a freeform canvas (edit mode). The host// injects the PostHog token; the iframe only ever sees the result. The QueryClient// is passed in by the calling component (via useQueryClient) rather than resolved@@ -94,8 +109,12 @@ export async function handleFreeformDataRequest(hogql: input.hogql,params: input.params,};- return cachedRead(queryClient, "query", args, () =>- hostClient().canvasData.query.mutate(args),+ return cachedRead(+ queryClient,+ "query",+ args,+ () => hostClient().canvasData.query.mutate(args),+ refreshSeconds(input.refresh),);}case "loadInsight": {@@ -111,8 +130,12 @@ export async function handleFreeformDataRequest(dateRange: input.dateRange,variables: input.variables,};- return cachedRead(queryClient, "loadInsight", args, () =>- hostClient().canvasData.loadInsight.mutate(args),+ return cachedRead(+ queryClient,+ "loadInsight",+ args,+ () => hostClient().canvasData.loadInsight.mutate(args),+ refreshSeconds(input.refresh),);}case "capture": {diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex 76c104596ee4..1d19a1268021 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -244,16 +244,17 @@ export function buildSandboxDocument(shortId,dateRange: opts && opts.dateRange,variables: opts && opts.variables,+ refresh: opts && opts.refresh,}),// Run a query. Pass a TYPED query node (\`{ kind: "TrendsQuery", … }\`) for// UI-matching numbers (preferred), or an inline HogQL string (escape hatch).// A built canvas needs \`capabilities.posthog.inlineQueries\` for this.- query: (queryOrHogql, params) =>+ query: (queryOrHogql, params, opts) =>call("query",typeof queryOrHogql === "string"- ? { hogql: queryOrHogql, params: params ?? {} }- : { query: queryOrHogql, params: params ?? {} },+ ? { hogql: queryOrHogql, params: params ?? {}, refresh: opts && opts.refresh }+ : { query: queryOrHogql, params: params ?? {}, refresh: opts && opts.refresh },),// Send an analytics event. Prefer in-iframe posthog-js (so it shares the// session/replay); otherwise host-mediated (no replay, still captured).