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.

feat(desktop): add viewer-approved canvas agent requests (#83020)

Peter Kirkhamd61c8107604e
diff --git a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts b/products/desktop/packages/core/src/canvas/canvasCapabilities.ts
index 293912580ebd..fe2532fb855a 100644
--- a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts
+++ b/products/desktop/packages/core/src/canvas/canvasCapabilities.ts
@@ -58,6 +58,11 @@ export function assertCanvasCapability(
}
return;
}
+ case "agentRequest":
+ if (!capabilities.posthog.agentRequests) {
+ throw new Error("Agent requests are not allowed by this canvas");
+ }
+ return;
default:
throw new Error(`Method "${method}" is not allowed by this canvas`);
}
diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
index afb03e9081d1..5638b67a7bdd 100644
--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
@@ -213,3 +213,8 @@ export const canvasActionResultSchema = z.object({
result: z.record(z.string(), z.unknown()),
});
export type CanvasActionResult = z.infer<typeof canvasActionResultSchema>;
+
+export const requestCanvasAgentInput = z.object({
+ 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 f25d539353d0..dc75a88c15e6 100644
--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts
@@ -16,7 +16,11 @@ import type {
CanvasVersion,
DashboardRecord,
} from "./dashboardSchemas";
-import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";
+import {
+ type CanvasAgentRequestResult,
+ canvasAgentRequestResultSchema,
+ FREEFORM_TEMPLATE_ID,
+} from "./freeformSchemas";
import {
PROJECT_API_CLIENT,
type ProjectApiClient,
@@ -485,4 +489,26 @@ export class DashboardsService {
throw new Error(`Failed to delete canvas (${res.status})`);
}
}
+
+ async requestAgent(input: {
+ id: string;
+ prompt: string;
+ }): Promise<CanvasAgentRequestResult> {
+ const body = await this.api.json<{
+ request_outcome: string;
+ task_id: string;
+ }>(
+ `canvases/${encodeURIComponent(input.id)}/request_agent/`,
+ "request canvas agent",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ prompt: input.prompt }),
+ },
+ );
+ return canvasAgentRequestResultSchema.parse({
+ requestOutcome: body.request_outcome,
+ taskId: body.task_id,
+ });
+ }
}
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index a04c89c3c370..f95998524663 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -94,6 +94,21 @@ export type CanvasCaptureInput = z.infer<typeof canvasCaptureInput>;
export const canvasCaptureResultSchema = z.object({ ok: z.boolean() });
export type CanvasCaptureResult = z.infer<typeof canvasCaptureResultSchema>;
+export const canvasAgentRequestInputSchema = z.object({
+ prompt: z.string().min(1).max(10_000),
+});
+export type CanvasAgentRequestInput = z.infer<
+ typeof canvasAgentRequestInputSchema
+>;
+
+export const canvasAgentRequestResultSchema = z.object({
+ requestOutcome: z.enum(["signaled", "new_run", "already_queued", "reported"]),
+ taskId: z.string().min(1),
+});
+export type CanvasAgentRequestResult = z.infer<
+ typeof canvasAgentRequestResultSchema
+>;
+
// What the host hands the UI to bootstrap in-iframe analytics/replay. The
// public capture key + the signed-in user's distinct_id; the private token is
// never included. The UI forwards this into the iframe `init` frame.
@@ -274,6 +289,7 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [
"stateSet",
"stateList",
"actionInvoke",
+ "agentRequest",
]),
payload: z.unknown(),
}),
diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.ts
index 1ec4d98cb31b..50bad68cf19c 100644
--- a/products/desktop/packages/core/src/canvas/services.ts
+++ b/products/desktop/packages/core/src/canvas/services.ts
@@ -15,6 +15,7 @@ import type {
DashboardRecord,
} from "./dashboardSchemas";
import type {
+ CanvasAgentRequestResult,
CanvasCaptureConfig,
CanvasCaptureInput,
CanvasCaptureResult,
@@ -98,6 +99,10 @@ export interface IDashboardsService {
actOnBuild(input: CanvasBuildActionInput): Promise<CanvasBuildRecord>;
rename(input: { id: string; name: string }): Promise<DashboardRecord>;
delete(id: string): Promise<void>;
+ requestAgent(input: {
+ id: string;
+ prompt: string;
+ }): Promise<CanvasAgentRequestResult>;
}
export interface ICanvasDataService {
diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
index a77894b1463d..fe6e0b09def6 100644
--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts
+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
@@ -22,6 +22,7 @@ import {
promoteCanvasInput,
renameDashboardInput,
reportCanvasErrorInput,
+ requestCanvasAgentInput,
revertCanvasInput,
saveContextInput,
setGenerationTaskInput,
@@ -179,4 +180,11 @@ export const dashboardsRouter = router({
.get<IDashboardsService>(DASHBOARDS_SERVICE)
.delete(input.id),
),
+ requestAgent: publicProcedure
+ .input(requestCanvasAgentInput)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<IDashboardsService>(DASHBOARDS_SERVICE)
+ .requestAgent(input),
+ ),
});
diff --git a/products/desktop/packages/shared/src/canvas-contracts.ts b/products/desktop/packages/shared/src/canvas-contracts.ts
index 18c20fd05bf3..2c6789e065fa 100644
--- a/products/desktop/packages/shared/src/canvas-contracts.ts
+++ b/products/desktop/packages/shared/src/canvas-contracts.ts
@@ -24,6 +24,7 @@ export const canvasCapabilitiesSchema = z.object({
.max(2)
.default([]),
actions: z.array(z.string().min(1).max(64)).max(32).default([]),
+ agentRequests: z.boolean().default(false),
}),
network: z.object({
origins: z.array(z.string().url().max(2_048)).max(20),
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
index e6019e3afec5..a7fe6acd080d 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
@@ -17,6 +17,7 @@ describe("BuiltCanvas", () => {
captureEvents: [],
state: [],
actions: [],
+ agentRequests: false,
},
network: { origins: [] },
};
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.stories.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.stories.tsx
new file mode 100644
index 000000000000..0c7dbe5e10b3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.stories.tsx
@@ -0,0 +1,23 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { fn } from "storybook/test";
+import { CanvasAgentRequestDialog } from "./CanvasAgentRequestDialog";
+
+const meta = {
+ title: "Canvas/CanvasAgentRequestDialog",
+ component: CanvasAgentRequestDialog,
+ args: {
+ prompt: "Summarize the retro board and add the themes below the cards.",
+ loading: false,
+ onCancel: fn(),
+ onConfirm: fn(),
+ },
+} satisfies Meta<typeof CanvasAgentRequestDialog>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Default: Story = {};
+
+export const StartingRun: Story = {
+ args: { loading: true },
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx
new file mode 100644
index 000000000000..3962fdaf5b48
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasAgentRequestDialog.tsx
@@ -0,0 +1,62 @@
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@posthog/quill";
+
+interface CanvasAgentRequestDialogProps {
+ prompt: string | null;
+ loading: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}
+
+export function CanvasAgentRequestDialog({
+ prompt,
+ loading,
+ onCancel,
+ onConfirm,
+}: CanvasAgentRequestDialogProps) {
+ return (
+ <Dialog
+ open={prompt !== null}
+ onOpenChange={(open) => {
+ if (!open && !loading) onCancel();
+ }}
+ >
+ <DialogContent className="max-w-lg" showCloseButton={false}>
+ <DialogHeader>
+ <DialogTitle>Ask the canvas agent to make this change?</DialogTitle>
+ <DialogDescription>
+ Review the exact request. Accepting starts an agent run that uses
+ compute. The result arrives as a draft for review.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded border bg-surface-primary p-3 text-sm">
+ {prompt}
+ </pre>
+ </DialogBody>
+ <DialogFooter>
+ <Button variant="outline" disabled={loading} onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ loading={loading}
+ disabled={loading}
+ data-attr="canvas-agent-request-confirm"
+ onClick={onConfirm}
+ >
+ Accept and run
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
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 1ba8d8401144..f054080804a4 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -21,6 +21,7 @@ import {
type CanvasAnalyticsConfig,
type CanvasCommentHighlight,
type CanvasTextSelection,
+ canvasAgentRequestInputSchema,
limitCanvasCommentHighlights,
} from "@posthog/core/canvas/freeformSchemas";
import { textToContent } from "@posthog/core/message-editor/content";
@@ -90,6 +91,7 @@ import { Link } from "@tanstack/react-router";
import { AnimatePresence, motion } from "framer-motion";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { BuiltCanvas } from "./BuiltCanvas";
+import { CanvasAgentRequestDialog } from "./CanvasAgentRequestDialog";
import { CanvasBuildStatus } from "./CanvasBuildStatus";
import { CanvasFramePlaceholder } from "./CanvasFramePlaceholder";
import { CanvasGenerateHero } from "./CanvasGenerateHero";
@@ -544,11 +546,99 @@ export function FreeformCanvasView({
// fresh signed artifactUrl — every 2s refetch) would churn the warm-frame
// pool, which assumes stable callbacks. View-mode capability gating happens
// in BuiltCanvas via the `capabilities` prop below.
+ const requestAgent = useMutation(
+ trpc.dashboards.requestAgent.mutationOptions(),
+ );
+ // 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.
+ const [agentRequest, setAgentRequest] = useState<{
+ prompt: string;
+ dashboardId: string;
+ } | null>(null);
+ const agentRequestPromiseRef = useRef<{
+ resolve: (value: unknown) => void;
+ reject: (reason: Error) => void;
+ } | null>(null);
+ const dashboardIdRef = useRef(dashboardId);
+ useEffect(() => {
+ dashboardIdRef.current = dashboardId;
+ if (agentRequestPromiseRef.current) {
+ agentRequestPromiseRef.current.reject(
+ new Error("Agent request canceled: the canvas changed"),
+ );
+ agentRequestPromiseRef.current = null;
+ setAgentRequest(null);
+ }
+ }, [dashboardId]);
const onDataRequest = useCallback(
- (method: string, payload: unknown) =>
- handleFreeformDataRequest(method, payload, queryClient, { dashboardId }),
+ (method: string, payload: unknown) => {
+ if (method !== "agentRequest") {
+ return handleFreeformDataRequest(method, payload, queryClient, {
+ dashboardId,
+ });
+ }
+ const input = canvasAgentRequestInputSchema.parse(payload);
+ if (agentRequestPromiseRef.current) {
+ throw new Error("Another agent request is awaiting approval");
+ }
+ setAgentRequest({
+ prompt: input.prompt,
+ dashboardId: dashboardIdRef.current,
+ });
+ return new Promise<unknown>((resolve, reject) => {
+ agentRequestPromiseRef.current = { resolve, reject };
+ });
+ },
[queryClient, dashboardId],
);
+ const cancelAgentRequest = useCallback(() => {
+ agentRequestPromiseRef.current?.reject(new Error("Agent request canceled"));
+ agentRequestPromiseRef.current = null;
+ setAgentRequest(null);
+ }, []);
+ useEffect(
+ () => () => {
+ agentRequestPromiseRef.current?.reject(
+ new Error("Canvas closed before the agent request was approved"),
+ );
+ agentRequestPromiseRef.current = null;
+ },
+ [],
+ );
+ const confirmAgentRequest = useCallback(async () => {
+ const pending = agentRequestPromiseRef.current;
+ if (!pending || agentRequest === null) return;
+ try {
+ const result = await requestAgent.mutateAsync({
+ id: agentRequest.dashboardId,
+ prompt: agentRequest.prompt,
+ });
+ 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.
+ if (agentRequestPromiseRef.current === pending) {
+ setAgentRequest(null);
+ agentRequestPromiseRef.current = null;
+ }
+ 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),
+ });
+ }
+ }, [agentRequest, requestAgent]);
// Dedupes the runtime-error capture without a store dependency: reading
// runtimeError in the callbacks would change their identity on every
@@ -697,6 +787,12 @@ export function FreeformCanvasView({
return (
<Flex height="100%" overflow="hidden" position="relative">
+ <CanvasAgentRequestDialog
+ prompt={agentRequest?.prompt ?? null}
+ loading={requestAgent.isPending}
+ onCancel={cancelAgentRequest}
+ onConfirm={() => void confirmAgentRequest()}
+ />
{/* When the embedded chat isn't visible — panel minimized, or still shut
mid-slide-in (waitingForHeroExit) — a paused tool-permission request
would have nowhere to go, so surface it as a modal. When the panel is
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 b971b1ac98e2..42b8ba9354a3 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
@@ -67,4 +67,80 @@ describe("createCanvasHostMessageRouter", () => {
value: 1,
});
});
+
+ it("rejects agent requests that are not triggered by a user action", async () => {
+ const post = vi.fn();
+ const onDataRequest = vi.fn();
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({ onDataRequest }),
+ hasUserActivation: () => false,
+ openExternal: vi.fn(),
+ });
+
+ await route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "request-1",
+ method: "agentRequest",
+ payload: { prompt: "Change it" },
+ });
+
+ expect(onDataRequest).not.toHaveBeenCalled();
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "request-1",
+ ok: false,
+ error: "Agent requests require a user action",
+ }),
+ );
+ });
+
+ it("does not apply the data-request timeout to approved agent requests", async () => {
+ vi.useFakeTimers();
+ try {
+ const post = vi.fn();
+ let approve: (value: unknown) => void = () => {};
+ const onDataRequest = vi.fn(
+ () =>
+ new Promise<unknown>((resolve) => {
+ approve = resolve;
+ }),
+ );
+ const route = createCanvasHostMessageRouter({
+ post,
+ callbacks: () => ({ onDataRequest }),
+ hasUserActivation: () => true,
+ openExternal: vi.fn(),
+ });
+
+ const routed = route({
+ channel: "posthog-canvas",
+ type: "data-request",
+ id: "request-1",
+ method: "agentRequest",
+ payload: { prompt: "Change it" },
+ });
+
+ // Elapse well past the 30s 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);
+ expect(post).not.toHaveBeenCalled();
+
+ // The viewer's approval is the only response the canvas receives.
+ approve({ requestOutcome: "started" });
+ await routed;
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "request-1",
+ ok: true,
+ result: { requestOutcome: "started" },
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
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 3686d402a92a..f45b6fa0155a 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -71,13 +71,20 @@ export function createCanvasHostMessageRouter(
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 (message.method === "actionInvoke" && !options.hasUserActivation()) {
+ if (
+ (message.method === "actionInvoke" ||
+ message.method === "agentRequest") &&
+ !options.hasUserActivation()
+ ) {
options.post({
channel: "posthog-canvas",
type: "data-response",
id: message.id,
ok: false,
- error: "Canvas actions require a user action",
+ error:
+ message.method === "agentRequest"
+ ? "Agent requests require a user action"
+ : "Canvas actions require a user action",
});
break;
}
@@ -96,22 +103,32 @@ export function createCanvasHostMessageRouter(
}
activeDataRequests += 1;
try {
+ const call = options
+ .callbacks()
+ .onDataRequest(message.method, message.payload);
+ // agentRequest settles only when a viewer approves or cancels the
+ // request in a dialog, which can take arbitrarily long. Racing it
+ // against the generic timeout would tell the canvas the request
+ // failed while the dialog is still open and a later approval could
+ // still start the run, so it opts out of the timeout.
+ const result =
+ message.method === "agentRequest"
+ ? await call
+ : await Promise.race([
+ call,
+ new Promise<never>((_, reject) =>
+ setTimeout(
+ () => reject(new Error("Canvas data request timed out")),
+ DATA_REQUEST_TIMEOUT_MS,
+ ),
+ ),
+ ]);
options.post({
channel: "posthog-canvas",
type: "data-response",
id: message.id,
ok: true,
- result: await Promise.race([
- options
- .callbacks()
- .onDataRequest(message.method, message.payload),
- new Promise<never>((_, reject) =>
- setTimeout(
- () => reject(new Error("Canvas data request timed out")),
- DATA_REQUEST_TIMEOUT_MS,
- ),
- ),
- ]),
+ result,
});
} catch (error) {
options.post({
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.ts
index bdf9e59ad429..739dc24c9f6a 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
@@ -23,6 +23,7 @@ const capabilities: CanvasCapabilities = {
posthog: {
insights: ["allowed-insight"],
inlineQueries: false,
+ agentRequests: false,
captureEvents: ["allowed-event"],
state: ["user"],
actions: ["tasks.create"],
@@ -37,6 +38,7 @@ describe("assertCanvasCapability", () => {
["capture", { event: "other-event" }],
["stateSet", { scope: "shared", key: "k", value: 1 }],
["actionInvoke", { verb: "annotations.create", payload: {} }],
+ ["agentRequest", { prompt: "Change it" }],
])("rejects undeclared %s access", (method, payload) => {
expect(() => assertCanvasCapability(capabilities, method, payload)).toThrow(
"not allowed",
@@ -54,6 +56,19 @@ describe("assertCanvasCapability", () => {
).not.toThrow();
});
+ it("allows agent requests only when the manifest declares them", () => {
+ expect(() =>
+ assertCanvasCapability(
+ {
+ ...capabilities,
+ posthog: { ...capabilities.posthog, agentRequests: true },
+ },
+ "agentRequest",
+ { prompt: "Change it" },
+ ),
+ ).not.toThrow();
+ });
+
it("rejects requests when the published manifest is missing", () => {
expect(() =>
assertCanvasCapability(undefined, "query", { hogql: "select 1" }),
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 d033573dbb01..76c104596ee4 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -282,6 +282,12 @@ export function buildSandboxDocument(
actions: {
invoke: (verb, payload) => call("actionInvoke", { verb, payload: payload ?? {} }),
},
+ // Ask the authoring agent for a change; the host shows the exact prompt
+ // and asks the viewer to approve before anything is dispatched:
+ // \`ph.agent.request("Make the square blue")\`.
+ agent: {
+ request: (prompt) => call("agentRequest", { prompt }),
+ },
// Brokered by the host: PostHog-only https URLs, rate-limited, and
// ignored while the canvas is unfocused (no auto-opens on load).
openExternal: (url) => post({ type: "open-external", url }),