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): harden viewer-approved canvas agent requests (#83541)

Peter Kirkham5fb40e6228aa
diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
index 5638b67a7bdd..d01385c7d962 100644
--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
@@ -3,6 +3,7 @@ import {
canvasBuildStatusSchema,
} from "@posthog/shared";
import { z } from "zod";
+import { canvasAgentRequestInputSchema } from "./freeformSchemas";
// A canvas record from the PostHog canvases API, normalized to camelCase and
// epoch-ms timestamps. Source code and version history are NOT part of the
@@ -214,7 +215,6 @@ export const canvasActionResultSchema = z.object({
});
export type CanvasActionResult = z.infer<typeof canvasActionResultSchema>;
-export const requestCanvasAgentInput = z.object({
+export const requestCanvasAgentInput = canvasAgentRequestInputSchema.extend({
id: z.string().min(1),
- prompt: z.string().min(1).max(10_000),
});
diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.ts
index dc75a88c15e6..59a41c5cac0a 100644
--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts
@@ -494,18 +494,28 @@ export class DashboardsService {
id: string;
prompt: string;
}): Promise<CanvasAgentRequestResult> {
- const body = await this.api.json<{
- request_outcome: string;
- task_id: string;
- }>(
+ const res = await this.api.fetch(
`canvases/${encodeURIComponent(input.id)}/request_agent/`,
- "request canvas agent",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: input.prompt }),
},
);
+ const body = (await res.json().catch(() => ({}))) as {
+ detail?: string;
+ request_outcome?: string;
+ task_id?: string;
+ };
+ // The backend answers quota, capability, and missing-task refusals with a
+ // structured `detail`; surface it so the viewer sees the reason, not a bare
+ // status code.
+ if (!res.ok) {
+ throw new ProjectApiError(
+ body.detail ?? `Failed to request canvas agent (${res.status})`,
+ res.status,
+ );
+ }
return canvasAgentRequestResultSchema.parse({
requestOutcome: body.request_outcome,
taskId: body.task_id,
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx
index 3962fdaf5b48..c49d1d045ae5 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx
@@ -49,7 +49,6 @@ export function CanvasAgentRequestDialog({
<Button
variant="primary"
loading={loading}
- disabled={loading}
data-attr="canvas-agent-request-confirm"
onClick={onConfirm}
>
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
index f054080804a4..199c9c0166a5 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -18,6 +18,7 @@ import {
} from "@posthog/core/canvas/canvasBuildSchemas";
import type { CanvasDraft } from "@posthog/core/canvas/dashboardSchemas";
import {
+ type CanvasAgentRequestResult,
type CanvasAnalyticsConfig,
type CanvasCommentHighlight,
type CanvasTextSelection,
@@ -126,6 +127,19 @@ function canvasErrorType(message: string): string {
);
}
+// One toast per outcome: only new_run actually starts a run — signaled hands
+// the prompt to a run already in progress, and already_queued means an
+// identical request beat this one, so "Agent run started" would misreport both.
+const AGENT_REQUEST_OUTCOME_TOASTS: Record<
+ CanvasAgentRequestResult["requestOutcome"],
+ string
+> = {
+ new_run: "Agent run started",
+ signaled: "Request sent to the running agent",
+ already_queued: "An identical request is already in progress",
+ reported: "Request sent to the canvas creator",
+};
+
// Badge tone for a draft's latest build status: ready is good, failed is bad,
// in-flight is cautionary, and no build yet is neutral.
function draftBadgeVariant(
@@ -552,9 +566,13 @@ export function FreeformCanvasView({
// The prompt is bound to the canvas that issued it: FreeformCanvasView is
// reused across navigation, so a dialog approved after switching canvases
// must not submit the old prompt against the newly selected canvas.
+ // `submitting` lives here rather than reading the mutation's isPending: the
+ // mutation is shared across requests, so a still-in-flight submission from a
+ // previous canvas would render a brand-new dialog pre-locked.
const [agentRequest, setAgentRequest] = useState<{
prompt: string;
dashboardId: string;
+ submitting: boolean;
} | null>(null);
const agentRequestPromiseRef = useRef<{
resolve: (value: unknown) => void;
@@ -585,6 +603,7 @@ export function FreeformCanvasView({
setAgentRequest({
prompt: input.prompt,
dashboardId: dashboardIdRef.current,
+ submitting: false,
});
return new Promise<unknown>((resolve, reject) => {
agentRequestPromiseRef.current = { resolve, reject };
@@ -608,7 +627,8 @@ export function FreeformCanvasView({
);
const confirmAgentRequest = useCallback(async () => {
const pending = agentRequestPromiseRef.current;
- if (!pending || agentRequest === null) return;
+ if (!pending || agentRequest === null || agentRequest.submitting) return;
+ setAgentRequest({ ...agentRequest, submitting: true });
try {
const result = await requestAgent.mutateAsync({
id: agentRequest.dashboardId,
@@ -617,26 +637,24 @@ export function FreeformCanvasView({
pending.resolve(result);
// Navigation or unmount during the request may have rejected `pending`
// and stored a newer request in the ref. Only clear the shared dialog
- // state when it still belongs to this request, so a stale continuation
- // can't close a newer canvas's dialog and orphan its pending promise.
+ // state and toast when it still belongs to this request, so a stale
+ // continuation can't close a newer canvas's dialog, orphan its pending
+ // promise, or report an outcome the viewer would read as the current
+ // canvas's.
if (agentRequestPromiseRef.current === pending) {
setAgentRequest(null);
agentRequestPromiseRef.current = null;
+ toast.success(AGENT_REQUEST_OUTCOME_TOASTS[result.requestOutcome]);
}
- toast.success(
- result.requestOutcome === "reported"
- ? "Request sent to the canvas creator"
- : "Agent run started",
- );
} catch (error) {
pending.reject(error instanceof Error ? error : new Error(String(error)));
if (agentRequestPromiseRef.current === pending) {
setAgentRequest(null);
agentRequestPromiseRef.current = null;
+ toast.error("Couldn't start the agent run", {
+ description: error instanceof Error ? error.message : String(error),
+ });
}
- toast.error("Couldn't start the agent run", {
- description: error instanceof Error ? error.message : String(error),
- });
}
}, [agentRequest, requestAgent]);
@@ -789,7 +807,7 @@ export function FreeformCanvasView({
<Flex height="100%" overflow="hidden" position="relative">
<CanvasAgentRequestDialog
prompt={agentRequest?.prompt ?? null}
- loading={requestAgent.isPending}
+ loading={agentRequest?.submitting ?? false}
onCancel={cancelAgentRequest}
onConfirm={() => void confirmAgentRequest()}
/>
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 42b8ba9354a3..4efff015ea8b 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
@@ -129,18 +129,60 @@ describe("createCanvasHostMessageRouter", () => {
expect(post).not.toHaveBeenCalled();
// The viewer's approval is the only response the canvas receives.
- approve({ requestOutcome: "started" });
+ approve({ requestOutcome: "new_run" });
await routed;
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith(
expect.objectContaining({
id: "request-1",
ok: true,
- result: { requestOutcome: "started" },
+ result: { requestOutcome: "new_run" },
}),
);
} finally {
vi.useRealTimers();
}
});
+
+ it("does not count a pending agent request against the concurrency limit", async () => {
+ const post = vi.fn();
+ const onDataRequest = vi.fn((method: string) =>
+ method === "agentRequest"
+ ? new Promise<unknown>(() => {}) // dialog open, never settles
+ : Promise.resolve(null),
+ );
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({ onDataRequest }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ });
+
+ void route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "agent-1",
+ method: "agentRequest",
+ payload: { prompt: "Change it" },
+ });
+
+ // With the dialog sitting unanswered, the canvas's ordinary reads must
+ // still get all 8 slots: none may be rejected for runtime limits.
+ await Promise.all(
+ Array.from({ length: 8 }, (_, i) =>
+ route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: `query-${i}`,
+ method: "stateGet",
+ payload: { scope: "user", key: `k${i}` },
+ }),
+ ),
+ );
+
+ expect(post).toHaveBeenCalledTimes(8);
+ expect(post.mock.calls.every(([message]) => message.ok === true)).toBe(
+ true,
+ );
+ });
});
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 f45b6fa0155a..9efa820a5831 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -68,7 +68,7 @@ export function createCanvasHostMessageRouter(
return async (message) => {
switch (message.type) {
- case "data-request":
+ case "data-request": {
// Canvas code is untrusted, so the host is what stops a canvas from
// firing writes just by being loaded or rendered.
if (
@@ -88,8 +88,13 @@ export function createCanvasHostMessageRouter(
});
break;
}
+ // agentRequest settles on a viewer's decision, not on I/O, so it stays
+ // out of the shared slot pool: an approval dialog left open must not
+ // starve the canvas's ordinary reads/writes. Its own bound is the
+ // host's single-flight guard (one request awaiting approval at a time).
+ const holdsSlot = message.method !== "agentRequest";
if (
- activeDataRequests >= MAX_CONCURRENT_DATA_REQUESTS ||
+ (holdsSlot && activeDataRequests >= MAX_CONCURRENT_DATA_REQUESTS) ||
!isBoundedPayload(message.payload)
) {
options.post({
@@ -101,7 +106,7 @@ export function createCanvasHostMessageRouter(
});
break;
}
- activeDataRequests += 1;
+ if (holdsSlot) activeDataRequests += 1;
try {
const call = options
.callbacks()
@@ -139,9 +144,10 @@ export function createCanvasHostMessageRouter(
error: error instanceof Error ? error.message : String(error),
});
} finally {
- activeDataRequests -= 1;
+ if (holdsSlot) activeDataRequests -= 1;
}
break;
+ }
case "error":
options.callbacks().onError?.(message.message, message.stack);
break;