: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
fix(canvas): buffer runtime messages posted before the port connects (#78243)
jake sciotto93368ad4c8f0
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.pyindex 2f8d7bf2f2fc..306d4089e47f 100644--- a/products/canvas/backend/tests/test_cloud_builder.py+++ b/products/canvas/backend/tests/test_cloud_builder.py@@ -95,6 +95,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")self.assertIn('event.data?.type!=="connect"', runtime)self.assertIn("event.ports[0]", runtime)+ self.assertIn("port.postMessage", runtime)self.assertIn("port?.postMessage", runtime)self.assertIn('event.data?.type==="set-comment-highlights"', runtime)self.assertIn('CSS.highlights.set("posthog-canvas-comment"', runtime)@@ -108,6 +109,48 @@ class TestCanvasCloudBuilder(SimpleTestCase):self.assertIn("if(selection&&!selection.isCollapsed)return", runtime)self.assertNotIn("parent.postMessage({channel,...message}", runtime)+ 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.+ # 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.+ 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")+ harness = "\n".join(+ [+ "const listeners = {};",+ "const timers = new Map();",+ "let timerId = 0;",+ "globalThis.window = globalThis;",+ "globalThis.parent = {};",+ 'globalThis.document = { readyState: "complete", body: {}, head: { appendChild: () => {} }, addEventListener: () => {}, createElement: () => ({}) };',+ '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.clearTimeout = (id) => { timers.delete(id); };",+ runtime,+ "const received = [];",+ "const port = { postMessage: (m) => received.push(m), addEventListener: () => {}, start: () => {} };",+ 'window.ph.query("SELECT expired").catch(() => {});',+ "timers.get(timerId)();",+ 'window.ph.query("SELECT 1");',+ 'for (const fn of listeners.message) fn({ source: parent, data: { channel: "posthog-canvas", type: "connect" }, ports: [port] });',+ '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); }',+ "process.exit(0);",+ ]+ )++ process = subprocess.run([node_executable()], input=harness, capture_output=True, text=True, timeout=60)++ self.assertEqual(process.returncode, 0, process.stderr or process.stdout)+def test_runtime_bounds_host_side_effects(self) -> None: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.mjsindex dcc44d3c381f..ea122a25c23d 100644--- a/products/canvas/packages/canvas_builder/build.mjs+++ b/products/canvas/packages/canvas_builder/build.mjs@@ -23,7 +23,11 @@ const htmlAttribute = /([a-zA-Z][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gconst forbiddenHtml = /(?:src|href)\s*=\s*["']\s*(javascript|data:text\/html|vbscript)/iconst extensions = ['', '.ts', '.tsx', '.js', '.jsx', '.css', '.json', '.svg', '.txt']const runtimePath = 'assets/canvas-runtime.js'-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map;let sequence=0,port;const post=(message)=>port?.postMessage({channel,...message});const call=(method,payload)=>new Promise((resolve,reject)=>{const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);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";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));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);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal};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();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}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`+// The host only delivers the MessagePort after the artifact iframe's load+// 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)=>{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";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));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);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal};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}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`// A published canvas runs the runtime baked into its artifact by this builder,// while an unpublished one runs the desktop's sandbox document — two copies of// the same selection behavior. The pair below is ported from the desktop's