: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
feat(desktop): wire ph.state and ph.actions into the canvas bridge (#82951)
Peter Kirkhame2e57bfca6a3
diff --git a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts b/products/desktop/packages/core/src/canvas/canvasCapabilities.tsindex a342586352f1..293912580ebd 100644--- a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts+++ b/products/desktop/packages/core/src/canvas/canvasCapabilities.ts@@ -37,6 +37,27 @@ export function assertCanvasCapability(throw new Error("Event capture is not allowed by this canvas");}return;+ case "stateGet":+ case "stateSet":+ case "stateList": {+ const scope = (payload as { scope?: "user" | "shared" })?.scope;+ const declared = capabilities.posthog.state ?? [];+ // A scopeless list reads everything the canvas declared, so any+ // declaration admits it; a scoped call needs its scope declared.+ if (declared.length === 0 || (scope && !declared.includes(scope))) {+ throw new Error(+ `State scope "${scope ?? "any"}" is not allowed by this canvas`,+ );+ }+ return;+ }+ case "actionInvoke": {+ const verb = (payload as { verb?: string })?.verb;+ if (!verb || !(capabilities.posthog.actions ?? []).includes(verb)) {+ throw new Error(`Action "${verb ?? ""}" is 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.test.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.test.tsnew file mode 100644index 000000000000..c8c96c9cb939--- /dev/null+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { canvasStateSetInput } from "./dashboardSchemas";++describe("canvasStateSetInput", () => {+ const base = { id: "canvas-1", scope: "user" as const, key: "k" };++ // A non-finite number serializes to JSON null, which the backend reads as a+ // delete. Rejecting it here is what stops a silent destructive write.+ it.each([+ ["NaN", Number.NaN],+ ["Infinity", Number.POSITIVE_INFINITY],+ ["-Infinity", Number.NEGATIVE_INFINITY],+ ["nested NaN", { avg: Number.NaN }],+ ["NaN in array", [1, Number.NaN]],+ ])("rejects a %s value", (_label, value) => {+ expect(canvasStateSetInput.safeParse({ ...base, value }).success).toBe(+ false,+ );+ });++ it.each([+ ["null (the delete sentinel)", null],+ ["a finite number", 0],+ ["a string", "hello"],+ ["a boolean", true],+ ["a plain object", { columns: 3, title: "board" }],+ ["an array", [1, 2, 3]],+ ])("accepts a %s value", (_label, value) => {+ expect(canvasStateSetInput.safeParse({ ...base, value }).success).toBe(+ true,+ );+ });+});diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.tsindex 41e2b83d5b9f..afb03e9081d1 100644--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts@@ -146,3 +146,70 @@ export const reportCanvasErrorInput = z.object({buildId: z.string().min(1),errorType: z.string().min(1).max(64),});+export const canvasStateScopeSchema = z.enum(["user", "shared"]);+export type CanvasStateScope = z.infer<typeof canvasStateScopeSchema>;++// One key of a canvas's runtime key-value state (the ph.state store).+export const canvasStateEntrySchema = z.object({+ scope: canvasStateScopeSchema,+ key: z.string(),+ value: z.unknown(),+ updatedAt: z.string(),+});+export type CanvasStateEntry = z.infer<typeof canvasStateEntrySchema>;++export const canvasStateListInput = z.object({+ id: z.string().min(1),+ scope: canvasStateScopeSchema.optional(),+});++// State values cross to the backend as JSON, where a null value means "delete+// this key". JSON.stringify turns non-finite numbers (NaN, Infinity) into+// null, so without this guard a canvas storing one (e.g. total / count with a+// zero count) would silently delete the key and still get a success response.+// An explicit null stays the delete sentinel.+function isStorableStateValue(value: unknown): boolean {+ try {+ JSON.stringify(value, (_key, entry) => {+ if (typeof entry === "number" && !Number.isFinite(entry)) {+ throw new Error("non-finite number");+ }+ return entry;+ });+ return true;+ } catch {+ return false;+ }+}++// A null value deletes the key.+export const canvasStateSetInput = z.object({+ id: z.string().min(1),+ scope: canvasStateScopeSchema,+ key: z.string().min(1).max(200),+ value: z.unknown().refine(isStorableStateValue, {+ message: "value must not contain non-finite numbers (NaN or Infinity)",+ }),+});++// One registered action verb, as the host renders it before invoking.+export const canvasActionDefinitionSchema = z.object({+ verb: z.string(),+ summary: z.string(),+ destructive: z.boolean(),+});+export type CanvasActionDefinition = z.infer<+ typeof canvasActionDefinitionSchema+>;++export const canvasActionInvokeInput = z.object({+ id: z.string().min(1),+ verb: z.string().min(1).max(64),+ payload: z.record(z.string(), z.unknown()).default({}),+});++export const canvasActionResultSchema = z.object({+ verb: z.string(),+ result: z.record(z.string(), z.unknown()),+});+export type CanvasActionResult = z.infer<typeof canvasActionResultSchema>;diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.tsindex dacd10f06855..f25d539353d0 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts@@ -6,14 +6,22 @@ import {canvasBuildRecordSchema,} from "./canvasBuildSchemas";import type {+ CanvasActionDefinition,+ CanvasActionResult,CanvasDraft,CanvasSource,CanvasSourceProject,+ CanvasStateEntry,+ CanvasStateScope,CanvasVersion,DashboardRecord,} from "./dashboardSchemas";import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";-import { PROJECT_API_CLIENT, type ProjectApiClient } from "./projectApiClient";+import {+ PROJECT_API_CLIENT,+ type ProjectApiClient,+ ProjectApiError,+} from "./projectApiClient";// A canvas as the PostHog canvases API returns it.interface ApiCanvas {@@ -232,6 +240,102 @@ export class DashboardsService {}}+ // The canvas's readable ph.state entries: shared ones plus the caller's own+ // user-scoped ones. Optionally narrowed to one scope.+ async listState(input: {+ id: string;+ scope?: CanvasStateScope;+ }): Promise<CanvasStateEntry[]> {+ const suffix = input.scope+ ? `?scope=${encodeURIComponent(input.scope)}`+ : "";+ const body = await this.api.json<{+ entries: Array<{+ scope: CanvasStateScope;+ key: string;+ value: unknown;+ updated_at: string;+ }>;+ }>(+ `canvases/${encodeURIComponent(input.id)}/state/${suffix}`,+ "read canvas state",+ );+ return body.entries.map((entry) => ({+ scope: entry.scope,+ key: entry.key,+ value: entry.value,+ updatedAt: entry.updated_at,+ }));+ }++ // Write one ph.state key; a null value deletes it (the 204 path).+ async setState(input: {+ id: string;+ scope: CanvasStateScope;+ key: string;+ value: unknown;+ }): Promise<void> {+ const res = await this.api.fetch(+ `canvases/${encodeURIComponent(input.id)}/state/set/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: input.scope,+ key: input.key,+ value: input.value ?? null,+ }),+ },+ );+ if (!res.ok) {+ const detail = await res+ .json()+ .then((body) => (body as { detail?: string }).detail ?? null)+ .catch(() => null);+ throw new ProjectApiError(+ detail ?? `Failed to write canvas state (${res.status})`,+ res.status,+ );+ }+ }++ // The action registry: every verb a canvas may declare and invoke.+ async listActions(): Promise<CanvasActionDefinition[]> {+ const body = await this.api.json<{ actions: CanvasActionDefinition[] }>(+ `canvases/actions/`,+ "list canvas actions",+ );+ return body.actions;+ }++ // Invoke one registered action verb as the viewer.+ async invokeAction(input: {+ id: string;+ verb: string;+ payload: Record<string, unknown>;+ }): Promise<CanvasActionResult> {+ const res = await this.api.fetch(+ `canvases/${encodeURIComponent(input.id)}/actions/invoke/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ verb: input.verb, payload: input.payload }),+ },+ );+ const body = (await res.json().catch(() => ({}))) as {+ detail?: string;+ verb?: string;+ result?: Record<string, unknown>;+ };+ if (!res.ok) {+ throw new ProjectApiError(+ body.detail ?? `Failed to invoke canvas action (${res.status})`,+ res.status,+ );+ }+ return { verb: body.verb ?? input.verb, result: body.result ?? {} };+ }+rename(input: { id: string; name: string }): Promise<DashboardRecord> {return this.patch(input.id, { name: input.name }, "rename canvas");}diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.test.tsindex bdf544214ca1..c7dab37bc250 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts@@ -37,6 +37,23 @@ describe("canvasToHostMessageSchema", () => {);});+ // The bridge dispatches on `method` after this schema parse, so a method+ // missing from the enum is a bridge verb the host silently drops.+ it.each(["stateGet", "stateSet", "stateList", "actionInvoke"])(+ "accepts %s data requests",+ (method) => {+ expect(+ canvasToHostMessageSchema.safeParse({+ channel: "posthog-canvas",+ type: "data-request",+ id: "request-1",+ method,+ payload: {},+ }).success,+ ).toBe(true);+ },+ );+it("accepts a bounded text selection and rejects oversized selected text", () => {const selection = {channel: "posthog-canvas",diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex 0a47a10f761e..a04c89c3c370 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -265,7 +265,16 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [channel: z.literal(CANVAS_CHANNEL),type: z.literal("data-request"),id: z.string().min(1).max(128),- method: z.enum(["query", "loadInsight", "capture", "run"]),+ method: z.enum([+ "query",+ "loadInsight",+ "capture",+ "run",+ "stateGet",+ "stateSet",+ "stateList",+ "actionInvoke",+ ]),payload: z.unknown(),}),// A runtime/compile error from inside the iframe, surfaced so the host candiff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.tsindex 7a808bef7583..1ec4d98cb31b 100644--- a/products/desktop/packages/core/src/canvas/services.ts+++ b/products/desktop/packages/core/src/canvas/services.ts@@ -5,8 +5,12 @@ import type {} from "./canvasBuildSchemas";import type { ChannelTaskRecord } from "./channelTaskSchemas";import type {+ CanvasActionDefinition,+ CanvasActionResult,CanvasDraft,CanvasSource,+ CanvasStateEntry,+ CanvasStateScope,CanvasVersion,DashboardRecord,} from "./dashboardSchemas";@@ -48,6 +52,26 @@ export interface IDashboardsService {buildId: string;errorType: string;}): Promise<void>;+ // The canvas's readable ph.state entries (shared + the caller's own user rows).+ listState(input: {+ id: string;+ scope?: CanvasStateScope;+ }): Promise<CanvasStateEntry[]>;+ // Write one ph.state key; a null value deletes it.+ setState(input: {+ id: string;+ scope: CanvasStateScope;+ key: string;+ value: unknown;+ }): Promise<void>;+ // The action registry: every verb a canvas may declare and invoke.+ listActions(): Promise<CanvasActionDefinition[]>;+ // Invoke one registered action verb as the viewer.+ invokeAction(input: {+ id: string;+ verb: string;+ payload: Record<string, unknown>;+ }): Promise<CanvasActionResult>;// Read the canvas's source project (the head, or a historical version).getSource(input: { id: string; versionId?: string }): Promise<CanvasSource>;// The canvas's source-version history, newest first (metadata only).diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.tsindex 98d476d9690a..a77894b1463d 100644--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts@@ -4,10 +4,16 @@ import {canvasBuildRecordSchema,} from "@posthog/core/canvas/canvasBuildSchemas";import {+ canvasActionDefinitionSchema,+ canvasActionInvokeInput,+ canvasActionResultSchema,canvasBuildsInput,canvasDraftSchema,canvasSourceInput,canvasSourceSchema,+ canvasStateEntrySchema,+ canvasStateListInput,+ canvasStateSetInput,canvasVersionSchema,createDashboardInput,dashboardIdInput,@@ -134,6 +140,32 @@ export const dashboardsRouter = router({.get<IDashboardsService>(DASHBOARDS_SERVICE).reportError(input),),+ listState: publicProcedure+ .input(canvasStateListInput)+ .output(z.array(canvasStateEntrySchema))+ .query(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .listState(input),+ ),+ setState: publicProcedure+ .input(canvasStateSetInput)+ .mutation(({ ctx, input }) =>+ ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).setState(input),+ ),+ listActions: publicProcedure+ .output(z.array(canvasActionDefinitionSchema))+ .query(({ ctx }) =>+ ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).listActions(),+ ),+ invokeAction: publicProcedure+ .input(canvasActionInvokeInput)+ .output(canvasActionResultSchema)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .invokeAction(input),+ ),rename: publicProcedure.input(renameDashboardInput).output(dashboardRecordSchema)diff --git a/products/desktop/packages/shared/src/canvas-contracts.ts b/products/desktop/packages/shared/src/canvas-contracts.tsindex 46dc980e9969..18c20fd05bf3 100644--- a/products/desktop/packages/shared/src/canvas-contracts.ts+++ b/products/desktop/packages/shared/src/canvas-contracts.ts@@ -18,6 +18,12 @@ export const canvasCapabilitiesSchema = z.object({insights: z.array(z.string().min(1).max(128)).max(100),inlineQueries: z.boolean(),captureEvents: z.array(z.string().min(1).max(200)).max(100),+ // Defaulted so manifests built before these verbs parse unchanged.+ state: z+ .array(z.enum(["user", "shared"]))+ .max(2)+ .default([]),+ actions: z.array(z.string().min(1).max(64)).max(32).default([]),}),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.tsxindex aba817d25520..e6019e3afec5 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@@ -11,7 +11,13 @@ import { BuiltCanvas } from "./BuiltCanvas";describe("BuiltCanvas", () => {const capabilities = {- posthog: { insights: [], inlineQueries: false, captureEvents: [] },+ posthog: {+ insights: [],+ inlineQueries: false,+ captureEvents: [],+ state: [],+ actions: [],+ },network: { origins: [] },};const initialIsDarkMode = useThemeStore.getState().isDarkMode;diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex 9434ce0cfdd4..1ba8d8401144 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -546,8 +546,8 @@ export function FreeformCanvasView({// in BuiltCanvas via the `capabilities` prop below.const onDataRequest = useCallback((method: string, payload: unknown) =>- handleFreeformDataRequest(method, payload, queryClient),- [queryClient],+ handleFreeformDataRequest(method, payload, queryClient, { dashboardId }),+ [queryClient, dashboardId],);// Dedupes the runtime-error capture without a store dependency: readingdiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.tsnew file mode 100644index 000000000000..b971b1ac98e2--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from "vitest";+import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";++describe("createCanvasHostMessageRouter", () => {+ it.each([+ [false, false],+ [true, true],+ ])(+ "forwards action invocations only under a user gesture (activation: %s)",+ async (hasActivation, forwarded) => {+ const post = vi.fn();+ const onDataRequest = vi.fn().mockResolvedValue({ ok: true });+ const route = createCanvasHostMessageRouter({+ post,+ callbacks: () => ({ onDataRequest }),+ hasUserActivation: () => hasActivation,+ openExternal: vi.fn(),+ });++ await route({+ channel: "posthog-canvas",+ type: "data-request",+ id: "request-1",+ method: "actionInvoke",+ payload: { verb: "tasks.create", payload: { title: "t" } },+ });++ if (forwarded) {+ expect(onDataRequest).toHaveBeenCalledWith("actionInvoke", {+ verb: "tasks.create",+ payload: { title: "t" },+ });+ } else {+ expect(onDataRequest).not.toHaveBeenCalled();+ expect(post).toHaveBeenCalledWith(+ expect.objectContaining({+ id: "request-1",+ ok: false,+ error: "Canvas actions require a user action",+ }),+ );+ }+ },+ );++ it("does not gate state reads or writes on a user gesture", async () => {+ const post = vi.fn();+ const onDataRequest = vi.fn().mockResolvedValue(null);+ const route = createCanvasHostMessageRouter({+ post,+ callbacks: () => ({ onDataRequest }),+ hasUserActivation: () => false,+ openExternal: vi.fn(),+ });++ await route({+ channel: "posthog-canvas",+ type: "data-request",+ id: "request-2",+ method: "stateSet",+ payload: { scope: "user", key: "k", value: 1 },+ });++ expect(onDataRequest).toHaveBeenCalledWith("stateSet", {+ scope: "user",+ key: "k",+ value: 1,+ });+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.tsindex 44f896e38490..3686d402a92a 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts@@ -69,6 +69,18 @@ export function createCanvasHostMessageRouter(return async (message) => {switch (message.type) {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()) {+ options.post({+ channel: "posthog-canvas",+ type: "data-response",+ id: message.id,+ ok: false,+ error: "Canvas actions require a user action",+ });+ break;+ }if (activeDataRequests >= MAX_CONCURRENT_DATA_REQUESTS ||!isBoundedPayload(message.payload)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.tsindex c950e10c374e..bdf9e59ad429 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@@ -5,8 +5,18 @@ import { describe, expect, it, vi } from "vitest";import { handleFreeformDataRequest } from "./freeformDataBridge";const loadInsight = vi.fn();+const setState = vi.fn();+const listState = vi.fn();+const invokeAction = vi.fn();vi.mock("../hostClient", () => ({- hostClient: () => ({ canvasData: { loadInsight: { mutate: loadInsight } } }),+ hostClient: () => ({+ canvasData: { loadInsight: { mutate: loadInsight } },+ dashboards: {+ setState: { mutate: setState },+ listState: { query: listState },+ invokeAction: { mutate: invokeAction },+ },+ }),}));const capabilities: CanvasCapabilities = {@@ -14,6 +24,8 @@ const capabilities: CanvasCapabilities = {insights: ["allowed-insight"],inlineQueries: false,captureEvents: ["allowed-event"],+ state: ["user"],+ actions: ["tasks.create"],},network: { origins: [] },};@@ -23,6 +35,8 @@ describe("assertCanvasCapability", () => {["query", { hogql: "select 1" }],["loadInsight", { shortId: "other-insight" }],["capture", { event: "other-event" }],+ ["stateSet", { scope: "shared", key: "k", value: 1 }],+ ["actionInvoke", { verb: "annotations.create", payload: {} }],])("rejects undeclared %s access", (method, payload) => {expect(() => assertCanvasCapability(capabilities, method, payload)).toThrow("not allowed",@@ -32,6 +46,8 @@ describe("assertCanvasCapability", () => {it.each([["loadInsight", { shortId: "allowed-insight" }],["capture", { event: "allowed-event" }],+ ["stateGet", { scope: "user", key: "k" }],+ ["actionInvoke", { verb: "tasks.create", payload: {} }],])("allows declared %s access", (method, payload) => {expect(() =>assertCanvasCapability(capabilities, method, payload),@@ -52,6 +68,39 @@ describe("assertCanvasCapability", () => {});describe("handleFreeformDataRequest", () => {+ // State and actions are canvas-scoped writes: routing them without the canvas+ // identity would write one canvas's state under another's keys.+ it("routes state writes to the canvas passed in context", async () => {+ const queryClient = new QueryClient();+ setState.mockReset().mockResolvedValue(undefined);++ await handleFreeformDataRequest(+ "stateSet",+ { key: "k", value: 1, scope: "user" },+ queryClient,+ { dashboardId: "canvas-1" },+ );++ expect(setState).toHaveBeenCalledWith({+ id: "canvas-1",+ scope: "user",+ key: "k",+ value: 1,+ });+ });++ it.each([+ ["stateSet", { key: "k", value: 1 }],+ ["stateList", {}],+ ["actionInvoke", { verb: "tasks.create", payload: {} }],+ ])("%s without a canvas context is refused", async (method, payload) => {+ const queryClient = new QueryClient();++ await expect(+ handleFreeformDataRequest(method, payload, queryClient),+ ).rejects.toThrow("requires a canvas context");+ });+// Reads are cached by their content, so `variables` has to be part of the key. If// it isn't, one insight rendered per product resolves every product from the first// product's cache entry — a whole board of identical numbers, no error anywhere.diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.tsindex 118db8992ab4..f1b51f6e5a19 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts@@ -68,7 +68,16 @@ export async function handleFreeformDataRequest(method: string,payload: unknown,queryClient: QueryClient,+ // State and actions are canvas-scoped, unlike the content-keyed reads above,+ // so the caller passes the canvas identity in.+ context?: { dashboardId?: string },): Promise<unknown> {+ const requireDashboardId = (): string => {+ if (!context?.dashboardId) {+ throw new Error(`${method} requires a canvas context`);+ }+ return context.dashboardId;+ };switch (method) {case "query": {const input = payload as CanvasDataQueryInput;@@ -118,6 +127,58 @@ export async function handleFreeformDataRequest(properties: input.properties,});}+ case "stateGet": {+ const input = payload as { key?: string; scope?: "user" | "shared" };+ if (!input?.key || typeof input.key !== "string") {+ throw new Error("ph.state.get(key) requires a key");+ }+ // Never cached: state is the canvas's live memory, and a stale read+ // would undo the write the canvas just made.+ const entries = await hostClient().dashboards.listState.query({+ id: requireDashboardId(),+ scope: input.scope ?? "user",+ });+ return entries.find((entry) => entry.key === input.key)?.value ?? null;+ }+ case "stateSet": {+ const input = payload as {+ key?: string;+ value?: unknown;+ scope?: "user" | "shared";+ };+ if (!input?.key || typeof input.key !== "string") {+ throw new Error("ph.state.set(key, value) requires a key");+ }+ await hostClient().dashboards.setState.mutate({+ id: requireDashboardId(),+ scope: input.scope ?? "user",+ key: input.key,+ value: input.value ?? null,+ });+ return { ok: true };+ }+ case "stateList": {+ const input = payload as { scope?: "user" | "shared" };+ return hostClient().dashboards.listState.query({+ id: requireDashboardId(),+ scope: input?.scope,+ });+ }+ case "actionInvoke": {+ const input = payload as {+ verb?: string;+ payload?: Record<string, unknown>;+ };+ if (!input?.verb || typeof input.verb !== "string") {+ throw new Error("ph.actions.invoke(verb, payload) requires a verb");+ }+ // A write into PostHog, never cached.+ return hostClient().dashboards.invokeAction.mutate({+ id: requireDashboardId(),+ verb: input.verb,+ payload: input.payload ?? {},+ });+ }case "run":// Named, server-stored insights land in Phase 3 (the live published tier).throw new Error("ph.run is not available yet (named queries: Phase 3)");diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex e668b50772eb..d033573dbb01 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -264,6 +264,24 @@ export function buildSandboxDocument(}return call("capture", { event, properties: properties ?? {}, distinctId });},+ // Durable key-value memory, declared in capabilities.posthog.state.+ // Scope "user" (default) is private to this viewer; "shared" is one+ // value per canvas, visible to the whole team. Values are JSON, capped+ // at 64 KB serialized and 256 keys per scope; setting null deletes:+ // \`ph.state.set("board", { columns: 3 }, { scope: "shared" })\`.+ state: {+ get: (key, opts) => call("stateGet", { key, scope: (opts && opts.scope) || "user" }),+ set: (key, value, opts) =>+ call("stateSet", { key, value: value === undefined ? null : value, scope: (opts && opts.scope) || "user" }),+ list: (opts) => call("stateList", { scope: opts && opts.scope }),+ },+ // Write into PostHog as the viewer. Every verb must be declared in+ // capabilities.posthog.actions; wire invocations to explicit user+ // gestures (a button), never to load or render:+ // \`ph.actions.invoke("tasks.create", { title, description })\`.+ actions: {+ invoke: (verb, payload) => call("actionInvoke", { verb, payload: payload ?? {} }),+ },// 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 }),