Skip to content

: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.

fix(canvas): give cold canvas queries time to finish on load (#107743)

Peter Kirkham6aac9d525c81
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.py
index 871ed5a6e6f8..919509cd56c7 100644
--- a/products/canvas/backend/tests/test_cloud_builder.py
+++ b/products/canvas/backend/tests/test_cloud_builder.py
@@ -300,10 +300,14 @@ class TestCanvasCloudBuilder(SimpleTestCase):
def test_runtime_flushes_data_requests_queued_before_the_port_connects(self) -> None:
# The host delivers the MessagePort only after the artifact iframe's
# load event, so a ph.query issued while the app mounts runs before the
- # port exists. Dropping it leaves the request to die on its 30s timeout.
+ # port exists. Dropping it leaves the request to die on its timeout.
# A request whose timeout already rejected must not be delivered on
# connect — the caller has given up, so executing it anyway would fire
- # late host side effects.
+ # late host side effects. The runtime timer is only a backstop: it must
+ # outlast the host's 90s guard, which gives a cold query time to compute,
+ # and must not run while the host waits on a viewer's connector consent.
+ # Before connect every call has a timer, and connect restarts it, so a
+ # slow iframe load cannot use up a request's budget.
result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))
runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")
@@ -311,6 +315,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):
[
"const listeners = {};",
"const timers = new Map();",
+ "const delays = new Map();",
"let timerId = 0;",
"globalThis.window = globalThis;",
"globalThis.parent = {};",
@@ -318,7 +323,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):
'globalThis.location = { hash: "" };',
"globalThis.MutationObserver = class { observe() {} };",
"globalThis.addEventListener = (type, fn) => { (listeners[type] ||= []).push(fn); };",
- "globalThis.setTimeout = (fn) => { timers.set(++timerId, fn); return timerId; };",
+ "globalThis.setTimeout = (fn, ms) => { timers.set(++timerId, fn); delays.set(timerId, ms); return timerId; };",
"globalThis.clearTimeout = (id) => { timers.delete(id); };",
runtime,
"const received = [];",
@@ -326,11 +331,22 @@ class TestCanvasCloudBuilder(SimpleTestCase):
'window.ph.query("SELECT expired").catch(() => {});',
"timers.get(timerId)();",
'window.ph.query("SELECT 1");',
+ "const queuedQueryTimer = timerId;",
+ 'window.ph.connectors.call("github", "list_issues").catch(() => {});',
+ "const queuedConnectorTimer = timerId;",
+ 'if (queuedConnectorTimer === queuedQueryTimer) { console.error("pre-connect connector call has no backstop"); process.exit(1); }',
'for (const fn of listeners.message) fn({ source: parent, data: { channel: "posthog-canvas", type: "connect" }, ports: [port] });',
+ 'if (timers.has(queuedQueryTimer) || timers.has(queuedConnectorTimer)) { console.error("connect kept the pre-connect timers"); process.exit(1); }',
+ 'if (timerId !== queuedConnectorTimer + 1 || !(delays.get(timerId) > 90000)) { console.error("connect did not re-arm the queued query"); process.exit(1); }',
'const requests = received.filter((m) => m.type === "data-request" && m.method === "query");',
'if (!requests.some((m) => m.payload.hogql === "SELECT 1")) { console.error("pre-connect request was dropped"); process.exit(1); }',
'if (requests.some((m) => m.payload.hogql === "SELECT expired")) { console.error("expired request was still delivered"); process.exit(1); }',
'if (!received.some((m) => m.type === "ready")) { console.error("ready was not posted"); process.exit(1); }',
+ 'window.ph.query("SELECT cold");',
+ 'if (!(delays.get(timerId) > 90000)) { console.error("query times out before the host guard: " + delays.get(timerId)); process.exit(1); }',
+ "const timersBeforeConnector = timerId;",
+ 'window.ph.connectors.call("github", "list_pull_requests");',
+ 'if (timerId !== timersBeforeConnector) { console.error("connector call can time out while consent is pending"); process.exit(1); }',
'Object.defineProperty(globalThis, "navigator", { value: { userActivation: { isActive: false } }, configurable: true });',
'try { window.ph.connectors.connect("github"); throw new Error("connector navigation did not require activation"); } catch (error) { if (!error.message.includes("user action")) throw error; }',
'if (received.some((message) => message.type === "navigate")) throw new Error("connector navigation escaped without activation");',
@@ -350,7 +366,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):
# connects, so each violation shares the 256-slot pre-connect queue with
# data requests. A canvas that misses one origin can render many blocked
# resources; without a bound the burst fills the queue and a later
- # ph.query is dropped and dies on its 30s timeout. Reporting each
+ # ph.query is dropped and dies on its timeout. Reporting each
# directive once keeps the queue open for the request.
result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 347cd1a6d150..c26887a0fd63 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -32,7 +32,12 @@ const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);const github=url.hostname==="github.com"&&!url.username&&!url.password&&!url.port&&!url.search&&new RegExp("^/[a-z0-9-]+/[a-z0-9_.-]+/pull/[1-9][0-9]*(/(files|commits|checks))?/?$","i").test(url.pathname);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")||github))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,navigate:{toTask:(taskId)=>post({type:"navigate",nav:{target:"task",taskId}}),toNewTask:(options)=>{if(!navigator.userActivation?.isActive)throw new Error("Opening a task requires a user action");post({type:"navigate",nav:{target:options?"compose-task":"new-task",prompt:options?.prompt,repository:options?.repository}})},toCanvas:(dashboardId)=>post({type:"navigate",nav:{target:"canvas",dashboardId}}),toNewCanvas:()=>post({type:"navigate",nav:{target:"new-canvas"}})},agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+// The request timer is only a backstop for a host that never answers, so it
+// must outlast the desktop's DATA_REQUEST_TIMEOUT_MS (canvasHostMessageRouter.ts).
+// The timer restarts when the port connects, so a slow iframe load does not
+// use up a request's budget. From then on, calls that wait on the viewer's
+// approval get no timer, as on the host.
+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const waitsOnViewer=(method)=>method==="connectorCall"||method==="actionInvoke"||method==="agentRequest";const arm=(id,method,reject)=>port&&waitsOnViewer(method)?undefined:setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},120000);const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);pending.set(id,{method,resolve,reject,timer:arm(id,method,reject)});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);const github=url.hostname==="github.com"&&!url.username&&!url.password&&!url.port&&!url.search&&new RegExp("^/[a-z0-9-]+/[a-z0-9_.-]+/pull/[1-9][0-9]*(/(files|commits|checks))?/?$","i").test(url.pathname);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")||github))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,navigate:{toTask:(taskId)=>post({type:"navigate",nav:{target:"task",taskId}}),toNewTask:(options)=>{if(!navigator.userActivation?.isActive)throw new Error("Opening a task requires a user action");post({type:"navigate",nav:{target:options?"compose-task":"new-task",prompt:options?.prompt,repository:options?.repository}})},toCanvas:(dashboardId)=>post({type:"navigate",nav:{target:"canvas",dashboardId}}),toNewCanvas:()=>post({type:"navigate",nav:{target:"new-canvas"}})},agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length){const message=queued.shift();const request=message.type==="data-request"&&pending.get(message.id);if(request){clearTimeout(request.timer);request.timer=arm(message.id,request.method,request.reject)}port.postMessage(message)}if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
// Notebook source remains arbitrary JavaScript, and its separate AI review is advisory.
// The cross-origin sandbox, CSP, host authorization, and frame allow-list are
// load-bearing controls. Navigation interception is defense in depth: the Navigation
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
index 6569b55397b2..1cfde382872e 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
@@ -199,10 +199,10 @@ describe("createCanvasHostMessageRouter", () => {
: { provider: "mcp:calendar.example.com", tool: "list_events" },
});
- // Elapse well past the 30s generic data-request timeout: an approval
+ // Elapse well past the 90s generic data-request timeout: an approval
// dialog can sit open this long, and the canvas must not be told it
// failed while a later approval could still start the run.
- await vi.advanceTimersByTimeAsync(60_000);
+ await vi.advanceTimersByTimeAsync(180_000);
expect(post).not.toHaveBeenCalled();
// The viewer's approval is the only response the canvas receives.
@@ -222,6 +222,54 @@ describe("createCanvasHostMessageRouter", () => {
},
);
+ it("gives a cold query time to compute before it times out", async () => {
+ vi.useFakeTimers();
+ try {
+ const post = vi.fn();
+ const finishes: Array<(value: unknown) => void> = [];
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({
+ onDataRequest: () =>
+ new Promise<unknown>((resolve) => {
+ finishes.push(resolve);
+ }),
+ }),
+ hasUserActivation: () => false,
+ openExternal: vi.fn(),
+ });
+ const request = (id: string) =>
+ route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id,
+ method: "query",
+ payload: { hogql: "SELECT 1" },
+ });
+
+ const cold = request("cold");
+ const stuck = request("stuck");
+ await vi.advanceTimersByTimeAsync(45_000);
+ finishes[0]({ columns: [], results: [] });
+ await cold;
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "cold", ok: true }),
+ );
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ await stuck;
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "stuck",
+ ok: false,
+ error: "Canvas data request timed out",
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("bounds pending connectors separately from ordinary requests", async () => {
const post = vi.fn();
const completions: Array<(value: unknown) => void> = [];
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
index 89c92da5283b..aa7ec0475220 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -14,7 +14,11 @@ const EXTERNAL_OPEN_MIN_INTERVAL_MS = 1_000;
const MAX_CONCURRENT_DATA_REQUESTS = 8;
const MAX_CONCURRENT_CONNECTOR_REQUESTS = 8;
const MAX_DATA_REQUEST_BYTES = 64 * 1024;
-const DATA_REQUEST_TIMEOUT_MS = 30_000;
+// ClickHouse stops a query at 60s. A cold-cache read needs that time plus the
+// API queue and the round trip, or it fails here and then loads from cache on
+// the next open. The artifact runtime's own timer in canvas_builder/build.mjs
+// must stay longer than this.
+const DATA_REQUEST_TIMEOUT_MS = 90_000;
const REPLAYABLE_SHORTCUT_KEYS = new Set([
",",
"/",