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(desktop): queue canvas data requests over the concurrency cap (#103243)

posthog[bot]26dcf81efd1c
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index c26887a0fd63..7102ecdc19d6 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -37,7 +37,7 @@ const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// 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"}));})();`
+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 maxRetries=2,retryBaseDelay=1000;const call=(method,payload,attempt=0)=>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=arm(id,method,reject);const fail=(error,retryable)=>{if(!retryable||attempt>=maxRetries){reject(error);return}setTimeout(()=>call(method,payload,attempt+1).then(resolve,reject),retryBaseDelay*Math.pow(2,attempt)*(0.5+Math.random()))};pending.set(id,{method,resolve,reject:fail,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"),event.data.retryable===true);};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/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.md
index 3b7338926247..2272157ece76 100644
--- a/products/canvas/skills/querying-canvas-data/SKILL.md
+++ b/products/canvas/skills/querying-canvas-data/SKILL.md
@@ -104,10 +104,11 @@ PostHog queries can take several seconds each, and a board usually runs several.
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.
+ `await`s. The host runs 8 data requests at a time and makes the rest wait in a 32-deep queue,
+ so a board with more sections than slots still loads, section by section. A board wide enough to
+ outlast the queue gets its extra requests refused, with the reason in the error message, and the
+ runtime sends each one again after a backoff before it gives up; a board that wide consolidates
+ its queries (one query returning every row, sliced client-side), still 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 —
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index c6ebb596d18c..09d9417b8f29 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -283,6 +283,9 @@ export const hostToCanvasMessageSchema = z.discriminatedUnion("type", [
ok: z.boolean(),
result: z.unknown().optional(),
error: z.string().optional(),
+ // The failure clears on its own, so the canvas runtime may send the same
+ // request again after a backoff.
+ retryable: z.boolean().optional(),
}),
]);
export type HostToCanvasMessage = z.infer<typeof hostToCanvasMessageSchema>;
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 1852b7881d25..edb724ffc514 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1366,6 +1366,22 @@ export interface CanvasRuntimeErrorProperties {
csp_directive?: string;
}
+export interface CanvasDataRequestRejectedProperties {
+ /** Which host bridge refused it: the authoring sandbox or a published build. */
+ surface: "freeform" | "built";
+ /**
+ * Why the host refused it. The request method only — never the payload, which
+ * is agent-authored and can carry query results.
+ */
+ reason:
+ | "payload-too-large"
+ | "data-queue-full"
+ | "connector-queue-full"
+ | "needs-user-action"
+ | "agent-needs-user-action";
+ method: string;
+}
+
export type ContextActionType =
| "save_version"
| "generate_started"
@@ -1832,6 +1848,7 @@ export const ANALYTICS_EVENTS = {
CANVAS_VIEWED: "Canvas viewed",
CANVAS_RENDERED: "Canvas rendered",
CANVAS_RUNTIME_ERROR: "Canvas runtime error",
+ CANVAS_DATA_REQUEST_REJECTED: "Canvas data request rejected",
CONTEXT_ACTION: "Context action",
PROJECT_MENU_ACTION: "Project menu action",
@@ -2055,6 +2072,7 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.CANVAS_VIEWED]: CanvasViewedProperties;
[ANALYTICS_EVENTS.CANVAS_RENDERED]: CanvasRenderedProperties;
[ANALYTICS_EVENTS.CANVAS_RUNTIME_ERROR]: CanvasRuntimeErrorProperties;
+ [ANALYTICS_EVENTS.CANVAS_DATA_REQUEST_REJECTED]: CanvasDataRequestRejectedProperties;
[ANALYTICS_EVENTS.CONTEXT_ACTION]: ContextActionProperties;
[ANALYTICS_EVENTS.PROJECT_MENU_ACTION]: ProjectMenuActionProperties;
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
index 083872804089..080038d5f609 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
@@ -7,6 +7,8 @@ import {
} from "@posthog/core/canvas/freeformSchemas";
import type { CanvasCapabilities } from "@posthog/shared";
import { isSafeGitHubPullRequestUrl } from "@posthog/shared";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { track } from "@posthog/ui/shell/analytics";
import { logger } from "@posthog/ui/shell/logger";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
@@ -208,6 +210,13 @@ export function BuiltCanvas({
onCommentActivate: (id) => latest.current.onCommentActivate?.(id),
}),
hasUserActivation: () => navigator.userActivation?.isActive === true,
+ onDataRequestRejected: (reason, method) => {
+ track(ANALYTICS_EVENTS.CANVAS_DATA_REQUEST_REJECTED, {
+ surface: "built",
+ reason,
+ method,
+ });
+ },
// Only validated GitHub PR links skip confirmation after the gesture gate.
openExternal: (url) => {
if (
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
index 3e421945ce77..9ad51293239c 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
@@ -4,6 +4,8 @@ import {
type CanvasNavIntent,
canvasToHostMessageSchema,
} from "@posthog/core/canvas/freeformSchemas";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { track } from "@posthog/ui/shell/analytics";
import { logger } from "@posthog/ui/shell/logger";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
@@ -174,6 +176,13 @@ export function FreeformCanvas({
onCommentActivate: (id) => latest.current.onCommentActivate?.(id),
}),
hasUserActivation: () => navigator.userActivation?.isActive === true,
+ onDataRequestRejected: (reason, method) => {
+ track(ANALYTICS_EVENTS.CANVAS_DATA_REQUEST_REJECTED, {
+ surface: "freeform",
+ reason,
+ method,
+ });
+ },
openExternal: openExternalUrl,
// This host's policy is to log dropped opens rather than drop silently.
onExternalOpenBlocked: (url, reason) => {
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 1cfde382872e..39f27db9e496 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
@@ -1,6 +1,23 @@
import { describe, expect, it, vi } from "vitest";
import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
+// Lets the router hand a freed slot to the next queued request before the
+// test asserts on it.
+function flushTimers(): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+// Settles every in-flight request, then the ones each freed slot starts.
+async function drain(
+ completions: Array<(value: unknown) => void>,
+): Promise<void> {
+ await flushTimers();
+ while (completions.length > 0) {
+ for (const resolve of completions.splice(0)) resolve(null);
+ await flushTimers();
+ }
+}
+
describe("createCanvasHostMessageRouter", () => {
it.each([false, true])(
"requires activation for task composition (%s)",
@@ -270,7 +287,7 @@ describe("createCanvasHostMessageRouter", () => {
}
});
- it("bounds pending connectors separately from ordinary requests", async () => {
+ it("queues pending connectors separately from ordinary requests", async () => {
const post = vi.fn();
const completions: Array<(value: unknown) => void> = [];
const route = createCanvasHostMessageRouter({
@@ -293,20 +310,13 @@ describe("createCanvasHostMessageRouter", () => {
payload: { provider: "github", tool: "list_pull_requests" },
}),
);
- await route({
+ const overflow = route({
channel: "posthog-canvas",
type: "data-request",
id: "overflow",
method: "connectorCall",
payload: { provider: "github", tool: "list_pull_requests" },
});
- expect(post).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "overflow",
- ok: false,
- error: "Canvas data request exceeds runtime limits",
- }),
- );
await route({
channel: "posthog-canvas",
type: "data-request",
@@ -317,10 +327,263 @@ describe("createCanvasHostMessageRouter", () => {
expect(post).toHaveBeenCalledWith(
expect.objectContaining({ id: "ordinary", ok: true }),
);
- completions.forEach((resolve) => {
- resolve(null);
+ // The 9th connector holds its turn instead of failing.
+ expect(post).not.toHaveBeenCalledWith(
+ expect.objectContaining({ id: "overflow" }),
+ );
+
+ for (const resolve of completions.splice(0)) resolve(null);
+ await Promise.all(requests);
+ await flushTimers();
+ for (const resolve of completions.splice(0)) resolve(null);
+ await overflow;
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "overflow", ok: true }),
+ );
+ });
+
+ it("runs a queued request as soon as a slot frees", async () => {
+ const post = vi.fn();
+ const completions: Array<(value: unknown) => void> = [];
+ let concurrent = 0;
+ let peakConcurrent = 0;
+ let canvas = "first";
+ const owners: string[] = [];
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => {
+ const owner = canvas;
+ return {
+ onDataRequest: () => {
+ owners.push(owner);
+ concurrent += 1;
+ peakConcurrent = Math.max(peakConcurrent, concurrent);
+ return new Promise((resolve) => {
+ completions.push((value) => {
+ concurrent -= 1;
+ resolve(value);
+ });
+ });
+ },
+ };
+ },
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
});
+
+ // A canvas whose cards fan out past the concurrency cap: every request
+ // must still be answered, none dropped. The warm-frame pool can swap the
+ // frame to another canvas while requests wait, and a waiting request must
+ // still run as the canvas that sent it.
+ const requests = Array.from({ length: 20 }, (_, index) =>
+ route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: `query-${index}`,
+ method: "stateGet",
+ payload: { scope: "user", key: `k${index}` },
+ }),
+ );
+ canvas = "second";
+ await drain(completions);
await Promise.all(requests);
+
+ expect(owners).toEqual(Array(20).fill("first"));
+ expect(peakConcurrent).toBe(8);
+ expect(post).toHaveBeenCalledTimes(20);
+ expect(post.mock.calls.every(([message]) => message.ok === true)).toBe(
+ true,
+ );
+ });
+
+ it("names the cause when the queue is full, and marks it retryable", async () => {
+ const post = vi.fn();
+ const onDataRequestRejected = vi.fn();
+ const completions: Array<(value: unknown) => void> = [];
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({
+ onDataRequest: () =>
+ new Promise((resolve) => {
+ completions.push(resolve);
+ }),
+ }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ onDataRequestRejected,
+ });
+
+ // 8 in flight plus a full 32-deep queue; the next one has nowhere to wait.
+ const requests = Array.from({ length: 40 }, (_, index) =>
+ route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: `query-${index}`,
+ method: "stateGet",
+ payload: { scope: "user", key: `k${index}` },
+ }),
+ );
+ await route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "overflow",
+ method: "stateGet",
+ payload: { scope: "user", key: "overflow" },
+ });
+
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "overflow",
+ ok: false,
+ error: "Too many canvas data requests are already waiting",
+ retryable: true,
+ }),
+ );
+ expect(onDataRequestRejected).toHaveBeenCalledWith(
+ "data-queue-full",
+ "stateGet",
+ );
+
+ await drain(completions);
+ await Promise.all(requests);
+ });
+
+ it("keeps a timed-out request's slot until its call settles", async () => {
+ vi.useFakeTimers();
+ try {
+ const post = vi.fn();
+ const completions: Array<(value: unknown) => void> = [];
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({
+ onDataRequest: () =>
+ new Promise((resolve) => {
+ completions.push(resolve);
+ }),
+ }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ });
+ for (let index = 0; index < 8; index += 1) {
+ void route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: `query-${index}`,
+ method: "stateGet",
+ payload: { scope: "user", key: `k${index}` },
+ });
+ }
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "query-0",
+ ok: false,
+ error: "Canvas data request timed out",
+ }),
+ );
+
+ // No host passes an abort signal, so a reported timeout leaves the query
+ // running. Starting the next request on its slot would put 9 in flight.
+ void route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "after-timeout",
+ method: "stateGet",
+ payload: { scope: "user", key: "after" },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(completions).toHaveLength(8);
+
+ // The slot is free once the call itself settles.
+ for (const resolve of completions.splice(0)) resolve(null);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(completions).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops waiting for a slot before the canvas runtime gives up", async () => {
+ vi.useFakeTimers();
+ try {
+ const post = vi.fn();
+ const onDataRequest = vi.fn(() => new Promise<unknown>(() => {}));
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({ onDataRequest }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ });
+ for (let index = 0; index < 8; index += 1) {
+ void route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: `query-${index}`,
+ method: "stateGet",
+ payload: { scope: "user", key: `k${index}` },
+ });
+ }
+ const queued = route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "queued",
+ method: "stateGet",
+ payload: { scope: "user", key: "queued" },
+ });
+
+ // The canvas runtime abandons a request 120s after it sends it. A wait
+ // that outlives the queue limit must come back as the real cause, not
+ // as a query the host starts once nobody is listening.
+ await vi.advanceTimersByTimeAsync(10_000);
+ await queued;
+
+ expect(onDataRequest).toHaveBeenCalledTimes(8);
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "queued",
+ ok: false,
+ error: "Too many canvas data requests are already waiting",
+ retryable: true,
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("separates an oversized payload from a full queue, and never retries it", async () => {
+ const post = vi.fn();
+ const onDataRequest = vi.fn();
+ const onDataRequestRejected = vi.fn();
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({ onDataRequest }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ onDataRequestRejected,
+ });
+
+ await route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "oversized",
+ method: "stateSet",
+ payload: { scope: "user", key: "k", value: "x".repeat(64 * 1024 + 1) },
+ });
+
+ expect(onDataRequest).not.toHaveBeenCalled();
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "oversized",
+ ok: false,
+ error: "Canvas data request is over the 64KB payload limit",
+ retryable: false,
+ }),
+ );
+ expect(onDataRequestRejected).toHaveBeenCalledWith(
+ "payload-too-large",
+ "stateSet",
+ );
});
it.each(["agentRequest", "connectorCall"] as const)(
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 aa7ec0475220..af26f3f2009e 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -13,12 +13,21 @@ const EXTERNAL_OPEN_MIN_INTERVAL_MS = 1_000;
// ship oversized payloads, or hold a request slot forever.
const MAX_CONCURRENT_DATA_REQUESTS = 8;
const MAX_CONCURRENT_CONNECTOR_REQUESTS = 8;
+// A canvas that fans out more cards than there are slots is normal, so requests
+// over the cap wait for a free slot instead of failing. The wait list is bounded
+// too: a runaway loop must still hit a wall rather than grow without end.
+const MAX_QUEUED_DATA_REQUESTS = 32;
+const MAX_QUEUED_CONNECTOR_REQUESTS = 32;
const MAX_DATA_REQUEST_BYTES = 64 * 1024;
// 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;
+// A request waits here before its DATA_REQUEST_TIMEOUT_MS starts, so the wait
+// plus that timeout must stay inside the artifact runtime's 120s backstop.
+// Refuse early, so a retry can still finish before the runtime gives up.
+const MAX_QUEUE_WAIT_MS = 10_000;
const REPLAYABLE_SHORTCUT_KEYS = new Set([
",",
"/",
@@ -56,6 +65,62 @@ function isBoundedPayload(payload: unknown): boolean {
}
}
+// Concurrency slots with a bounded FIFO wait list. A released slot passes
+// straight to the next waiter rather than going back to the pool, so a request
+// that arrives while waiters are queued cannot jump ahead of them.
+interface RequestSlots {
+ active: number;
+ readonly limit: number;
+ readonly queueLimit: number;
+ readonly waiting: Array<() => void>;
+}
+
+function createRequestSlots(limit: number, queueLimit: number): RequestSlots {
+ return { active: 0, limit, queueLimit, waiting: [] };
+}
+
+function acquireSlot(slots: RequestSlots): Promise<boolean> {
+ if (slots.active < slots.limit) {
+ slots.active += 1;
+ return Promise.resolve(true);
+ }
+ if (slots.waiting.length >= slots.queueLimit) return Promise.resolve(false);
+ return new Promise<boolean>((resolve) => {
+ const take = (): void => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ const timer = setTimeout(() => {
+ const index = slots.waiting.indexOf(take);
+ if (index > -1) slots.waiting.splice(index, 1);
+ resolve(false);
+ }, MAX_QUEUE_WAIT_MS);
+ slots.waiting.push(take);
+ });
+}
+
+function withRequestTimeout<T>(call: Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return Promise.race([
+ call,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error("Canvas data request timed out")),
+ DATA_REQUEST_TIMEOUT_MS,
+ );
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+function releaseSlot(slots: RequestSlots): void {
+ const next = slots.waiting.shift();
+ if (next) {
+ next();
+ return;
+ }
+ slots.active -= 1;
+}
+
interface CanvasHostCallbacks {
onDataRequest: (method: string, payload: unknown) => Promise<unknown>;
onError?: (message: string, stack?: string) => void;
@@ -68,6 +133,23 @@ interface CanvasHostCallbacks {
type ExternalOpenBlockReason = "unsafe-url" | "no-interaction" | "throttled";
+/** Why a data request was refused before it reached the host callback. */
+export type CanvasDataRequestRejectReason =
+ | "payload-too-large"
+ | "data-queue-full"
+ | "connector-queue-full"
+ | "needs-user-action"
+ | "agent-needs-user-action";
+
+const REJECT_MESSAGES: Record<CanvasDataRequestRejectReason, string> = {
+ "payload-too-large": "Canvas data request is over the 64KB payload limit",
+ "data-queue-full": "Too many canvas data requests are already waiting",
+ "connector-queue-full":
+ "Too many canvas connector requests are already waiting",
+ "needs-user-action": "Canvas actions require a user action",
+ "agent-needs-user-action": "Agent requests require a user action",
+};
+
export interface CanvasHostMessageRouterOptions {
/** Transport back into the canvas (window.postMessage or a MessagePort). */
post: (message: HostToCanvasMessage) => void;
@@ -84,6 +166,11 @@ export interface CanvasHostMessageRouterOptions {
url: string,
reason: ExternalOpenBlockReason,
) => void;
+ /** A refused data request, with why. Hosts use this to measure the limits. */
+ onDataRequestRejected?: (
+ reason: CanvasDataRequestRejectReason,
+ method: string,
+ ) => void;
}
// The host side of the canvas postMessage protocol, shared by the built-
@@ -94,8 +181,38 @@ export function createCanvasHostMessageRouter(
options: CanvasHostMessageRouterOptions,
): (message: CanvasToHostMessage) => Promise<void> {
let lastExternalOpen = 0;
- let activeDataRequests = 0;
- let activeConnectorRequests = 0;
+ const dataSlots = createRequestSlots(
+ MAX_CONCURRENT_DATA_REQUESTS,
+ MAX_QUEUED_DATA_REQUESTS,
+ );
+ const connectorSlots = createRequestSlots(
+ MAX_CONCURRENT_CONNECTOR_REQUESTS,
+ MAX_QUEUED_CONNECTOR_REQUESTS,
+ );
+
+ const refuse = (
+ id: string,
+ method: string,
+ reason: CanvasDataRequestRejectReason,
+ ): void => {
+ options.onDataRequestRejected?.(reason, method);
+ options.post({
+ channel: "posthog-canvas",
+ type: "data-response",
+ id,
+ ok: false,
+ error: REJECT_MESSAGES[reason],
+ retryable:
+ reason === "data-queue-full" || reason === "connector-queue-full",
+ });
+ };
+
+ const slotsFor = (method: string): RequestSlots | null => {
+ // Approval waits must not consume ordinary read/write slots.
+ // Connector calls have their own limit; agent requests are single-flight.
+ if (method === "agentRequest") return null;
+ return method === "connectorCall" ? connectorSlots : dataSlots;
+ };
return async (message) => {
switch (message.type) {
@@ -107,44 +224,49 @@ export function createCanvasHostMessageRouter(
message.method === "agentRequest") &&
!options.hasUserActivation()
) {
- options.post({
- channel: "posthog-canvas",
- type: "data-response",
- id: message.id,
- ok: false,
- error:
- message.method === "agentRequest"
- ? "Agent requests require a user action"
- : "Canvas actions require a user action",
- });
+ refuse(
+ message.id,
+ message.method,
+ message.method === "agentRequest"
+ ? "agent-needs-user-action"
+ : "needs-user-action",
+ );
break;
}
- // Approval waits must not consume ordinary read/write slots.
- // Connector calls have their own limit; agent requests are single-flight.
- const isConnectorRequest = message.method === "connectorCall";
- const holdsSlot =
- message.method !== "agentRequest" && !isConnectorRequest;
- if (
- (holdsSlot && activeDataRequests >= MAX_CONCURRENT_DATA_REQUESTS) ||
- (isConnectorRequest &&
- activeConnectorRequests >= MAX_CONCURRENT_CONNECTOR_REQUESTS) ||
- !isBoundedPayload(message.payload)
- ) {
- options.post({
- channel: "posthog-canvas",
- type: "data-response",
- id: message.id,
- ok: false,
- error: "Canvas data request exceeds runtime limits",
- });
+ if (!isBoundedPayload(message.payload)) {
+ refuse(message.id, message.method, "payload-too-large");
break;
}
- if (holdsSlot) activeDataRequests += 1;
- if (isConnectorRequest) activeConnectorRequests += 1;
+ // Read the callbacks before any wait. The warm-frame pool can move this
+ // frame to another canvas meanwhile, and the request must not run with
+ // that canvas's identity or connector consent.
+ const { onDataRequest } = options.callbacks();
+ const slots = slotsFor(message.method);
+ // A refusal here means the canvas stayed saturated for the whole wait,
+ // so the request never ran and the canvas may send it again.
+ if (slots && !(await acquireSlot(slots))) {
+ refuse(
+ message.id,
+ message.method,
+ message.method === "connectorCall"
+ ? "connector-queue-full"
+ : "data-queue-full",
+ );
+ break;
+ }
+ // The async wrapper turns a callback that throws on the spot, such as a
+ // capability check, into a rejection the slot release can follow.
+ const call = (async () =>
+ onDataRequest(message.method, message.payload))();
+ // A timed-out request is reported to the canvas, but the call behind it
+ // keeps running: no host passes an abort signal down to the query. The
+ // slot therefore follows the call, not the report, so the cap counts
+ // the work that is really in flight.
+ if (slots) {
+ const release = (): void => releaseSlot(slots);
+ call.then(release, release);
+ }
try {
- const call = options
- .callbacks()
- .onDataRequest(message.method, message.payload);
// Approval dialogs can stay open longer than the I/O timeout.
// Do not report a failure while a later approval can still run the call.
const result =
@@ -152,15 +274,7 @@ export function createCanvasHostMessageRouter(
message.method === "actionInvoke" ||
message.method === "connectorCall"
? await call
- : await Promise.race([
- call,
- new Promise<never>((_, reject) =>
- setTimeout(
- () => reject(new Error("Canvas data request timed out")),
- DATA_REQUEST_TIMEOUT_MS,
- ),
- ),
- ]);
+ : await withRequestTimeout(call);
options.post({
channel: "posthog-canvas",
type: "data-response",
@@ -176,9 +290,6 @@ export function createCanvasHostMessageRouter(
ok: false,
error: error instanceof Error ? error.message : String(error),
});
- } finally {
- if (holdsSlot) activeDataRequests -= 1;
- if (isConnectorRequest) activeConnectorRequests -= 1;
}
break;
}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts
index 32f889b3cd0b..1033ec437a49 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts
@@ -103,49 +103,88 @@ describe("decodeJsxUnicodeEscapes", () => {
});
});
+interface PostedMessage {
+ type: string;
+ id: string;
+ method?: string;
+ [key: string]: unknown;
+}
+
+interface PublishedRuntimeApi {
+ navigate: {
+ toNewTask: (options: { prompt: string; repository: string }) => void;
+ };
+ openExternal: (url: string) => void;
+ state: { get: (key: string) => Promise<unknown> };
+}
+
+// Boots the published runtime (a string bundle) against stub globals and
+// connects a fake host port, so a test can drive `ph.*` and answer the
+// protocol messages it posts.
+function bootPublishedRuntime(): {
+ ph: PublishedRuntimeApi;
+ userActivation: { isActive: boolean };
+ posted: PostedMessage[];
+ requests: () => PostedMessage[];
+ respond: (id: string, body: Record<string, unknown>) => void;
+} {
+ const source = builderSource.match(/const runtime = `([^`]*)`/)?.[1];
+ if (!source) throw new Error("Published runtime not found");
+ const listeners = new Map<string, (event: unknown) => void>();
+ const portListeners = new Map<string, (event: unknown) => void>();
+ const posted: PostedMessage[] = [];
+ const port = {
+ postMessage: (message: PostedMessage) => posted.push(message),
+ addEventListener: (name: string, listener: (event: unknown) => void) =>
+ portListeners.set(name, listener),
+ start: vi.fn(),
+ };
+ const frame = { ph: undefined as unknown as PublishedRuntimeApi };
+ const userActivation = { isActive: true };
+ const parent = {};
+ new Function(
+ "window",
+ "document",
+ "location",
+ "parent",
+ "navigator",
+ "addEventListener",
+ source,
+ )(
+ frame,
+ document,
+ { hash: "" },
+ parent,
+ { userActivation },
+ (name: string, listener: (event: unknown) => void) =>
+ listeners.set(name, listener),
+ );
+ listeners.get("message")?.({
+ source: parent,
+ data: { channel: "posthog-canvas", type: "connect" },
+ ports: [port],
+ });
+ return {
+ ph: frame.ph,
+ userActivation,
+ posted,
+ requests: () => posted.filter((message) => message.type === "data-request"),
+ respond: (id, body) =>
+ portListeners.get("message")?.({
+ data: { channel: "posthog-canvas", type: "data-response", id, ...body },
+ }),
+ };
+}
+
describe("buildSandboxDocument", () => {
it("publishes navigation and the same GitHub URL restriction as the host", () => {
- const source = builderSource.match(/const runtime = `([^`]*)`/)?.[1];
- if (!source) throw new Error("Published runtime not found");
- const listeners = new Map<string, (event: unknown) => void>();
- const postMessage = vi.fn();
- const frame = {
- ph: undefined as unknown as {
- navigate: {
- toNewTask: (options: { prompt: string; repository: string }) => void;
- };
- openExternal: (url: string) => void;
- },
- };
- const userActivation = { isActive: true };
- const parent = {};
- new Function(
- "window",
- "document",
- "location",
- "parent",
- "navigator",
- "addEventListener",
- source,
- )(
- frame,
- document,
- { hash: "" },
- parent,
- { userActivation },
- (name: string, listener: (event: unknown) => void) =>
- listeners.set(name, listener),
- );
- listeners.get("message")?.({
- source: parent,
- data: { channel: "posthog-canvas", type: "connect" },
- ports: [{ postMessage, addEventListener: vi.fn(), start: vi.fn() }],
- });
- frame.ph.navigate.toNewTask({
+ const { ph, userActivation, posted } = bootPublishedRuntime();
+
+ ph.navigate.toNewTask({
prompt: "Inspect this PR",
repository: "example/app",
});
- expect(postMessage).toHaveBeenCalledWith({
+ expect(posted.at(-1)).toEqual({
channel: "posthog-canvas",
type: "navigate",
nav: {
@@ -154,26 +193,69 @@ describe("buildSandboxDocument", () => {
repository: "example/app",
},
});
- frame.ph.openExternal("https://github.com/example/app/pull/42");
- expect(postMessage).toHaveBeenLastCalledWith({
+ ph.openExternal("https://github.com/example/app/pull/42");
+ expect(posted.at(-1)).toEqual({
channel: "posthog-canvas",
type: "open-external",
url: "https://github.com/example/app/pull/42",
});
- expect(() => frame.ph.openExternal("https://github.com/login")).toThrow(
+ expect(() => ph.openExternal("https://github.com/login")).toThrow(
"not allowed",
);
expect(() =>
- frame.ph.openExternal("https://github.com.evil.com/example/app/pull/42"),
+ ph.openExternal("https://github.com.evil.com/example/app/pull/42"),
).toThrow("not allowed");
userActivation.isActive = false;
expect(() =>
- frame.ph.navigate.toNewTask({
- prompt: "Inspect",
- repository: "example/app",
- }),
+ ph.navigate.toNewTask({ prompt: "Inspect", repository: "example/app" }),
).toThrow("user action");
});
+
+ // A canvas that fans out more requests than the host runs at once gets its
+ // extras refused once the host queue is full. Before the retry the cards
+ // stayed broken until someone refreshed the whole canvas.
+ it("sends a refused request again when the host marks it retryable", async () => {
+ vi.useFakeTimers();
+ try {
+ const { ph, requests, respond } = bootPublishedRuntime();
+ const read = ph.state.get("board");
+
+ respond(requests()[0].id, {
+ ok: false,
+ error: "Too many canvas data requests are already waiting",
+ retryable: true,
+ });
+ await vi.advanceTimersByTimeAsync(2_000);
+
+ expect(requests()).toHaveLength(2);
+ const retry = requests()[1];
+ expect(retry.method).toBe("stateGet");
+ respond(retry.id, { ok: true, result: { columns: 3 } });
+ await expect(read).resolves.toEqual({ columns: 3 });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("gives up on a refusal the host does not mark retryable", async () => {
+ const { ph, requests, respond } = bootPublishedRuntime();
+ const read = ph.state.get("board");
+
+ respond(requests()[0].id, {
+ ok: false,
+ error: "Canvas data request is over the 64KB payload limit",
+ });
+
+ await expect(read).rejects.toThrow("64KB payload limit");
+ expect(requests()).toHaveLength(1);
+ });
+
+ it("sends a refused request again in the authoring sandbox too", () => {
+ const html = buildSandboxDocument();
+ expect(html).toContain("d.retryable === true");
+ expect(html).toContain("call(method, payload, attempt + 1)");
+ });
+
it("inlines the unicode-escape decoder into the bootstrap", () => {
const html = buildSandboxDocument();
expect(html).toContain(
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
index b00ecad4a839..e22bcb588034 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -46,6 +46,12 @@ import {
// CDN path as a one-line fallback while v4 is validated against real canvases.
const TAILWIND_ENGINE: "v3" | "v4" = "v4";
+// Retry tuning for the in-iframe data shim below. The host refuses only after
+// its queue has stayed full for seconds, so the first retry waits about a
+// second, jittered to keep a refused batch from coming back in one burst.
+const MAX_CALL_RETRIES = 2;
+const RETRY_BASE_DELAY_MS = 1_000;
+
// Tailwind v4 browser JIT. `@import "tailwindcss"` brings in v4's layered theme/
// base(preflight)/components/utilities — so preflight sits in `@layer base`,
// BELOW Quill's `@layer components` (primitives.css), and can't clobber Quill
@@ -224,10 +230,28 @@ export function buildSandboxDocument(
// --- data shim: the ONLY way canvas code reaches PostHog. No token here. ---
const pending = new Map();
let reqSeq = 0;
- const call = (method, payload) =>
+ // The host caps how many requests run at once and queues the rest. Past
+ // that queue it refuses the request and marks it retryable.
+ const MAX_CALL_RETRIES = ${MAX_CALL_RETRIES};
+ const RETRY_BASE_DELAY_MS = ${RETRY_BASE_DELAY_MS};
+ const call = (method, payload, attempt = 0) =>
new Promise((resolve, reject) => {
const id = String(++reqSeq);
- pending.set(id, { resolve, reject });
+ pending.set(id, {
+ resolve,
+ reject: (error, retryable) => {
+ if (!retryable || attempt >= MAX_CALL_RETRIES) {
+ reject(error);
+ return;
+ }
+ const delay =
+ RETRY_BASE_DELAY_MS * Math.pow(2, attempt) * (0.5 + Math.random());
+ setTimeout(
+ () => call(method, payload, attempt + 1).then(resolve, reject),
+ delay,
+ );
+ },
+ });
post({ type: "data-request", id, method, payload });
});
// posthog-js runs IN here (the only way replay records the app's DOM). It is
@@ -705,7 +729,9 @@ export function buildSandboxDocument(
const p = pending.get(d.id);
if (!p) return;
pending.delete(d.id);
- d.ok ? p.resolve(d.result) : p.reject(new Error(d.error || "data error"));
+ d.ok
+ ? p.resolve(d.result)
+ : p.reject(new Error(d.error || "data error"), d.retryable === true);
}
});