: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(canvas): expose ph.connectors in the canvas SDK and desktop host (#94581)
Peter Kirkham213d4d90b8e2
diff --git a/docs/internal/canvas-connectors.md b/docs/internal/canvas-connectors.mdindex 1d91c7f4de3e..9ad08272654a 100644--- a/docs/internal/canvas-connectors.md+++ b/docs/internal/canvas-connectors.md@@ -48,8 +48,8 @@ When a connection is missing or needs authorization, `connect_path` identifies t## Host safety-The canvas host must ask the viewer before it sends connector calls. Consent must be limited to the canvas version, provider, and tool. The prompt must explain that the canvas can receive private data and that declared network access can send it outside PostHog.+The canvas host asks the viewer before it sends connector calls. Consent is limited to the canvas version, provider, and tool. The prompt explains that the canvas can receive private data and share it through its declared capabilities. A denied call stays blocked until the viewer retries from a user action.-Connector caches must be authentication-scoped. Remove them when the viewer, organization, or project changes. Never write connector results into shared canvas state.+Connector results and consent use authentication-scoped caches. Account, organization, and project changes clear these caches. Results are also separated by canvas version. Never write connector results into shared canvas state.Keep the feature flag off until the backend and a host with these checks are deployed. Verify connection failures, cancellation, account changes, and the connector activity log before increasing the rollout.diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex f6f59de804fb..0033c9a2bb07 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -157,6 +157,12 @@ That field is the only valid link to a canvas — never construct one yourself;`canvases-actions-retrieve` tool and follow each verb's `usage` (payload/result shape,behavior, and the confirmation copy it warrants) before wiring it.+- **`ph.connectors.call(provider, tool, args)`** — read live third-party data (GitHub, or any+ MCP store server) with the VIEWER's own connection at view time. Never call GitHub, Calendly,+ or another service yourself and paste the result into the source: that snapshot is stale on+ publish and shows every viewer the author's data. Declare each provider and tool in+ `capabilities.connectors`; discover them with the `canvas-connectors-retrieve` tool. See+ `querying-canvas-data` for the result and not-connected handling.- **`ph.agent.request(prompt)`** — ask the canvas's authoring agent for a change, with the viewer'sapproval. Declare `agentRequests: true` in `capabilities.posthog`. Call it only from a directclick or form submission — the host shows the exact prompt and asks the viewer to accept beforediff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.mdindex 814ce0310c4b..8c74b7afd506 100644--- a/products/canvas/skills/querying-canvas-data/SKILL.md+++ b/products/canvas/skills/querying-canvas-data/SKILL.md@@ -2,11 +2,13 @@name: querying-canvas-datadescription: >Get PostHog data into a canvas correctly: the host-injected `ph` SDK (loadInsight, query,- capture, state, openExternal, navigate), the data hierarchy (saved insights first, typed query nodes+ capture, state, connectors, openExternal, navigate), the data hierarchy (saved insights first, typed query nodessecond, inline HogQL last), verifiability (insight-backed metrics link their saved insight inPostHog; ad-hoc queries expose the exact query that ran), per-insight-type result shapes,- progressive per-query loading, date-range wiring, and event capture from a canvas. Use whenever a- canvas shows metrics, charts, tables, or any PostHog data, or needs to send analytics events.+ progressive per-query loading, date-range wiring, live third-party data through the viewer's own+ connections (ph.connectors), and event capture from a canvas. Use whenever a canvas shows+ metrics, charts, tables, any PostHog data, or data from GitHub or an MCP server, or needs to send+ analytics events.---# Querying canvas data@@ -255,6 +257,49 @@ canvas) differ in payload shape, auth, and behavior. Invoking looks like:const { result } = await ph.actions.invoke('tasks.create', { title, description })```+## Live third-party data — ph.connectors++`ph.connectors.call(provider, tool, args, { refresh? })` reads data from a third-party service+with the **viewer's** own connection, at view time. Use it for anything that must stay fresh+per person: open pull requests, today's meetings, assigned issues. Never fetch such data+yourself while authoring and bake the result into the source — that snapshot is stale the moment+it is published, and it shows every viewer the author's data.++- Providers are `github` (native, over the viewer's personal GitHub connection) or+ `mcp:<server host>` for any server the viewer has connected in the MCP store (for example+ `mcp:mcp.calendly.com`). Discover providers, tools, argument schemas, and per-tool `usage`+ with the `canvas-connectors-retrieve` tool; pass `mcp_hosts` to inspect a server the current+ user has not connected. Call only tools whose catalog entry has `is_read_only: true`.+ MCP tools need an explicit read-only hint and a name that passes the local read-verb check.+- **Declare every provider and tool** in `capabilities.connectors` as+ `[{ "provider": "github", "tools": ["list_pull_requests"] }]`. Validation rejects an+ undeclared `ph.connectors.call` literal, and the host refuses undeclared calls at runtime.+- The call resolves to `{ status, result, detail, truncated, connect_path }`. Branch on `status`:+ - `ok` — `result` holds the tool output. Native tools return their documented shape; MCP+ tools return `{ content, structured_content, is_error }` (MCP content blocks).+ - `not_connected` / `needs_reauth` — this viewer has no usable connection. Render a+ "Connect GitHub" (or the server's name) button that calls `ph.connectors.connect(provider)`+ from the click; the host opens the right settings page. Never treat this as empty data.+ - `blocked`, `write_blocked`, `tool_missing`, `upstream_error` — show `detail` with a retry.+- `truncated: true` means the result exceeded 256 KB and was cut to a preview; narrow the call+ (a smaller `limit`, one repository) instead of paging client-side.+- Calls can start on mount, but the host asks the viewer for access before it reads connector data.+ Consent applies to one canvas version, provider, and tool. A refusal rejects the call; show the error and a retry button.+- Results are cached per canvas version for `refresh` seconds (default 60, range 30–86400).+ Account, organization, and project changes clear both results and consent.+- Keep connector results in component state or `ph.state` scope `"user"`.+ A canvas with connectors cannot declare shared state. Validation and the API reject this combination.++```tsx+const [prs, setPrs] = useState<{ loading: boolean; status?: string; rows?: PullRequest[] }>({ loading: true })+useEffect(() => {+ ph.connectors+ .call('github', 'list_pull_requests', { repository: 'example/app', state: 'open' }, { refresh: 60 })+ .then((res) => setPrs({ loading: false, status: res.status, rows: res.result?.pull_requests ?? [] }))+ .catch((error) => setPrs({ loading: false, status: 'error', rows: [] }))+}, [])+```+## Side effects- `ph.capture(event, properties?, distinctId?)` — analytics events for interactionsdiff --git a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.tsindex b917a20a9617..dedeab1236db 100644--- a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts+++ b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts@@ -5,8 +5,8 @@// products/canvas/packages/canvas_builder/canvas-sdk.mjs.//// A published canvas is held to `project.capabilities` at runtime: every insight-// short id, capture event name, state scope, and action verb must be declared,-// and ad-hoc `ph.query` needs `inlineQueries: true`.+// short id, capture event name, state scope, action verb, and connector tool must+// be declared, and ad-hoc `ph.query` needs `inlineQueries: true`./*** One trends-style series. `ph.loadInsight` and a typed query node return these@@ -94,6 +94,49 @@ export interface CanvasActions {invoke(verb: string, payload?: Record<string, unknown>): Promise<unknown>}+export type CanvasConnectorCallStatus =+ | 'ok'+ | 'not_connected'+ | 'needs_reauth'+ | 'blocked'+ | 'tool_missing'+ | 'write_blocked'+ | 'upstream_error'++export interface CanvasConnectorCallResult {+ status: CanvasConnectorCallStatus+ /** The tool output when status is "ok"; MCP tools return { content, structured_content, is_error }. */+ result: Record<string, unknown> | null+ /** Human-readable explanation for a non-ok status. */+ detail: string+ /** True when the result exceeded the size cap and was cut to a preview. */+ truncated: boolean+ /** Settings path where the viewer connects the provider, when that would help. */+ connect_path: string | null+}++export interface CanvasConnectorCallOptions {+ /** Cache lifetime in whole seconds, 30–86400. Defaults to 60. */+ refresh?: number+}++export interface CanvasConnectors {+ /**+ * Read live third-party data with the viewer's own connection. `provider` is+ * "github" or "mcp:<server host>"; declare every provider and tool in+ * `capabilities.connectors`. Never rejects for a missing connection: check+ * `status` and offer `connect(provider)`.+ */+ call(+ provider: string,+ tool: string,+ args?: Record<string, unknown>,+ options?: CanvasConnectorCallOptions+ ): Promise<CanvasConnectorCallResult>+ /** Open the settings page where the viewer connects the provider. Call from a click. */+ connect(provider: string): void+}+export interface CanvasAgentRequestResult {requestOutcome: 'signaled' | 'new_run' | 'already_queued' | 'reported'taskId: string@@ -142,6 +185,7 @@ export interface CanvasSdk {state: CanvasStateactions: CanvasActionsagent: CanvasAgent+ connectors: CanvasConnectors/*** Frozen per-placement config parsed at boot. Published/component runtime* only; undefined in the edit-mode preview.diff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.mdindex aa832f73b3de..d9ef7b44ffb8 100644--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md@@ -39,6 +39,12 @@ then dies in the rendered canvas. Declare:- `capabilities.posthog.captureEvents` — every event name it passes to `ph.capture`.- `capabilities.posthog.inlineQueries: true` — when it calls `ph.query` at all.- `capabilities.posthog.agentRequests: true` — when it calls `ph.agent.request`.+- `capabilities.connectors` — one `{ "provider", "tools" }` entry per third-party provider the+ canvas reads through `ph.connectors.call`, listing every tool it calls on that provider. A+ provider is a native id (`github`) or `mcp:<server host>` (`mcp:mcp.calendly.com`). Unknown+ providers, unregistered native tools, and private MCP hosts fail validation; every declared+ tool must have `is_read_only: true` in the catalog. An upstream hint alone does not grant access.+ A canvas with connectors cannot declare shared state.- `capabilities.network.origins` — each exact HTTPS origin used by `fetch`, `XMLHttpRequest`, or anexternal stylesheet, image, font, media file, or frame. Remote scripts remain blocked.Do not include paths, credentials, queries, fragments, or wildcards. The host must be public:diff --git a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts b/products/desktop/packages/core/src/canvas/canvasCapabilities.tsindex fe2532fb855a..5344bce288af 100644--- a/products/desktop/packages/core/src/canvas/canvasCapabilities.ts+++ b/products/desktop/packages/core/src/canvas/canvasCapabilities.ts@@ -63,6 +63,19 @@ export function assertCanvasCapability(throw new Error("Agent requests are not allowed by this canvas");}return;+ case "connectorCall": {+ const { provider, tool } =+ (payload as { provider?: string; tool?: string }) ?? {};+ const declared = (capabilities.connectors ?? []).find(+ (entry) => entry.provider === provider,+ );+ if (!provider || !tool || !declared?.tools.includes(tool)) {+ throw new Error(+ `Connector tool "${provider ?? ""}/${tool ?? ""}" 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.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.tsindex 43c6bf4b6641..eb4ae28334b5 100644--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts@@ -240,3 +240,31 @@ export type CanvasActionResult = z.infer<typeof canvasActionResultSchema>;export const requestCanvasAgentInput = canvasAgentRequestInputSchema.extend({id: z.string().min(1),});++export const canvasConnectorCallServiceInput = z.object({+ id: z.string().min(1),+ provider: z.string().min(1).max(300),+ tool: z.string().min(1).max(200),+ arguments: z.record(z.string(), z.unknown()).default({}),+});++// Mirrors the API's connector call result. `status` is "ok" when `result`+// holds the tool output; every other status explains itself in `detail`.+export const canvasConnectorCallResultSchema = z.object({+ status: z.enum([+ "ok",+ "not_connected",+ "needs_reauth",+ "blocked",+ "tool_missing",+ "write_blocked",+ "upstream_error",+ ]),+ result: z.record(z.string(), z.unknown()).nullable(),+ detail: z.string(),+ truncated: z.boolean(),+ connect_path: z.string().nullable(),+});+export type CanvasConnectorCallResult = z.infer<+ typeof canvasConnectorCallResultSchema+>;diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.tsindex 2c33187e3dc4..4384c8bbf3f9 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts@@ -8,6 +8,7 @@ import {import type {CanvasActionDefinition,CanvasActionResult,+ CanvasConnectorCallResult,CanvasCreator,CanvasDraft,CanvasSource,@@ -453,6 +454,43 @@ export class DashboardsService {return { verb: body.verb ?? input.verb, result: body.result ?? {} };}+ // Call one declared connector tool as the viewer.+ async callConnector(input: {+ id: string;+ provider: string;+ tool: string;+ arguments: Record<string, unknown>;+ }): Promise<CanvasConnectorCallResult> {+ const res = await this.api.fetch(+ `canvases/${encodeURIComponent(input.id)}/connectors/call/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ provider: input.provider,+ tool: input.tool,+ arguments: input.arguments,+ }),+ },+ );+ const body = (await res.json().catch(() => ({}))) as {+ detail?: string;+ } & Partial<CanvasConnectorCallResult>;+ if (!res.ok) {+ throw new ProjectApiError(+ body.detail ?? `Failed to call canvas connector (${res.status})`,+ res.status,+ );+ }+ return {+ status: body.status ?? "upstream_error",+ result: body.result ?? null,+ detail: body.detail ?? "",+ truncated: body.truncated ?? false,+ connect_path: body.connect_path ?? null,+ };+ }+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 c7dab37bc250..8bf231cf9373 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import {+ canvasNavIntentSchema,canvasToHostMessageSchema,hostToCanvasMessageSchema,limitCanvasCommentHighlights,@@ -39,20 +40,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.each([+ "stateGet",+ "stateSet",+ "stateList",+ "actionInvoke",+ "connectorCall",+ ])("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 = {@@ -159,3 +163,18 @@ describe("canvasToHostMessageSchema", () => {});});});++describe("connector navigation", () => {+ it.each([+ ["github", true],+ ["mcp:mcp.example.com", true],+ ["slack", false],+ ["githbu", false],+ ["mcp:", false],+ ["mcp:https://example.com", false],+ ])("validates provider %s", (provider, allowed) => {+ expect(+ canvasNavIntentSchema.safeParse({ target: "connect", provider }).success,+ ).toBe(allowed);+ });+});diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex 4ed181d10b71..fb7c27c80be9 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -96,6 +96,25 @@ export type CanvasCaptureInput = z.infer<typeof canvasCaptureInput>;export const canvasCaptureResultSchema = z.object({ ok: z.boolean() });export type CanvasCaptureResult = z.infer<typeof canvasCaptureResultSchema>;+// Connector-call avenue behind the `ph.connectors.call` shim. The host resolves+// the viewer's own connection server-side; the iframe names only the provider,+// the tool, and its arguments.+export const canvasConnectorProviderSchema = z.union([+ z.literal("github"),+ z+ .string()+ .max(300)+ .regex(/^mcp:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i),+]);++export const canvasConnectorCallInput = z.object({+ provider: canvasConnectorProviderSchema,+ tool: z.string().min(1).max(200),+ arguments: z.record(z.string().max(128), z.unknown()).default({}),+ refresh: z.number().int().min(30).max(86_400).optional(),+});+export type CanvasConnectorCallInput = z.infer<typeof canvasConnectorCallInput>;+export const canvasAgentRequestInputSchema = z.object({prompt: z.string().min(1).max(10_000),});@@ -259,6 +278,12 @@ export const canvasNavIntentSchema = z.discriminatedUnion("target", [z.object({ target: z.literal("new-task") }),z.object({ target: z.literal("canvas"), dashboardId: z.string().min(1) }),z.object({ target: z.literal("new-canvas") }),+ // ph.connectors.connect(provider): the host maps the provider to its own+ // settings page, so the iframe never names a route.+ z.object({+ target: z.literal("connect"),+ provider: canvasConnectorProviderSchema,+ }),]);export type CanvasNavIntent = z.infer<typeof canvasNavIntentSchema>;@@ -286,6 +311,7 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", ["stateList","actionInvoke","agentRequest",+ "connectorCall",]),payload: z.unknown(),}),diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.tsindex fcdb8e88fd30..f6a414302792 100644--- a/products/desktop/packages/core/src/canvas/services.ts+++ b/products/desktop/packages/core/src/canvas/services.ts@@ -7,6 +7,7 @@ import type { ChannelTaskRecord } from "./channelTaskSchemas";import type {CanvasActionDefinition,CanvasActionResult,+ CanvasConnectorCallResult,CanvasDraft,CanvasSource,CanvasStateEntry,@@ -102,6 +103,13 @@ export interface IDashboardsService {verb: string;payload: Record<string, unknown>;}): Promise<CanvasActionResult>;+ // Call one declared connector tool with the viewer's own connection.+ callConnector(input: {+ id: string;+ provider: string;+ tool: string;+ arguments: Record<string, unknown>;+ }): Promise<CanvasConnectorCallResult>;// 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 208dd8b35b41..fcbaef5537d4 100644--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts@@ -8,6 +8,8 @@ import {canvasActionInvokeInput,canvasActionResultSchema,canvasBuildsInput,+ canvasConnectorCallResultSchema,+ canvasConnectorCallServiceInput,canvasDraftSchema,canvasSourceInput,canvasSourceSchema,@@ -216,6 +218,14 @@ export const dashboardsRouter = router({.get<IDashboardsService>(DASHBOARDS_SERVICE).invokeAction(input),),+ callConnector: publicProcedure+ .input(canvasConnectorCallServiceInput)+ .output(canvasConnectorCallResultSchema)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .callConnector(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 d4a3f6448bff..79dd46c78650 100644--- a/products/desktop/packages/shared/src/canvas-contracts.ts+++ b/products/desktop/packages/shared/src/canvas-contracts.ts@@ -41,6 +41,17 @@ export const canvasCapabilitiesSchema = z.object({origins: z.array(z.string().url().max(2_048)).max(20).default([]),}).default({ origins: [] }),+ // Third-party providers the canvas reads through ph.connectors, each with+ // the tools it may call. Every call runs with the viewer's own connection.+ connectors: z+ .array(+ z.object({+ provider: z.string().min(1).max(300),+ tools: z.array(z.string().min(1).max(200)).min(1).max(64),+ }),+ )+ .max(20)+ .default([]),});export type CanvasCapabilities = z.infer<typeof canvasCapabilitiesSchema>;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 a7fe6acd080d..8901a62ecf99 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@@ -20,6 +20,7 @@ describe("BuiltCanvas", () => {agentRequests: false,},network: { origins: [] },+ connectors: [],};const initialIsDarkMode = useThemeStore.getState().isDarkMode;afterEach(() => useThemeStore.setState({ isDarkMode: initialIsDarkMode }));diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex f7fc10485f93..471f5ab7646c 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -615,6 +615,7 @@ export function FreeformCanvasView({if (method !== "agentRequest") {return handleFreeformDataRequest(method, payload, queryClient, {dashboardId,+ sourceVersionId: displayedVersionId ?? undefined,});}const input = canvasAgentRequestInputSchema.parse(payload);@@ -630,7 +631,7 @@ export function FreeformCanvasView({agentRequestPromiseRef.current = { resolve, reject };});},- [queryClient, dashboardId],+ [queryClient, dashboardId, displayedVersionId],);const cancelAgentRequest = useCallback(() => {agentRequestPromiseRef.current?.reject(new Error("Agent request canceled"));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.tsindex 4efff015ea8b..0e1b5ff2140f 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@@ -2,6 +2,24 @@ import { describe, expect, it, vi } from "vitest";import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";describe("createCanvasHostMessageRouter", () => {+ it.each([false, true])(+ "requires activation for connector navigation (%s)",+ async (active) => {+ const onNavigate = vi.fn();+ const route = createCanvasHostMessageRouter({+ post: vi.fn(),+ callbacks: () => ({ onDataRequest: vi.fn(), onNavigate }),+ hasUserActivation: () => active,+ openExternal: vi.fn(),+ });+ await route({+ channel: "posthog-canvas",+ type: "navigate",+ nav: { target: "connect", provider: "github" },+ });+ expect(onNavigate).toHaveBeenCalledTimes(active ? 1 : 0);+ },+ );it.each([[false, false],[true, true],diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.tsindex 0fd8fffa01b0..bdec2db79d48 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts@@ -180,6 +180,8 @@ export function createCanvasHostMessageRouter(options.callbacks().onRendered?.();break;case "navigate":+ if (message.nav.target === "connect" && !options.hasUserActivation())+ break;// message.nav is already allowlist-validated by the schema parse.options.callbacks().onNavigate?.(message.nav);break;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 6362b22fa47e..1ca1b36d4460 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@@ -1,13 +1,14 @@import { assertCanvasCapability } from "@posthog/core/canvas/canvasCapabilities";import type { CanvasCapabilities } from "@posthog/shared";import { QueryClient } from "@tanstack/react-query";-import { describe, expect, it, vi } from "vitest";+import { afterEach, 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();+const callConnector = vi.fn();vi.mock("../hostClient", () => ({hostClient: () => ({canvasData: { loadInsight: { mutate: loadInsight } },@@ -15,6 +16,7 @@ vi.mock("../hostClient", () => ({setState: { mutate: setState },listState: { query: listState },invokeAction: { mutate: invokeAction },+ callConnector: { mutate: callConnector },},}),}));@@ -29,6 +31,7 @@ const capabilities: CanvasCapabilities = {actions: ["tasks.create"],},network: { origins: [] },+ connectors: [{ provider: "github", tools: ["list_pull_requests"] }],};describe("assertCanvasCapability", () => {@@ -39,6 +42,15 @@ describe("assertCanvasCapability", () => {["stateSet", { scope: "shared", key: "k", value: 1 }],["actionInvoke", { verb: "annotations.create", payload: {} }],["agentRequest", { prompt: "Change it" }],+ // Declaring a provider does not declare every tool on it.+ [+ "connectorCall",+ { provider: "github", tool: "search_issues", arguments: {} },+ ],+ [+ "connectorCall",+ { provider: "mcp:mcp.example.com", tool: "list_pull_requests" },+ ],])("rejects undeclared %s access", (method, payload) => {expect(() => assertCanvasCapability(capabilities, method, payload)).toThrow("not allowed",@@ -50,6 +62,10 @@ describe("assertCanvasCapability", () => {["capture", { event: "allowed-event" }],["stateGet", { scope: "user", key: "k" }],["actionInvoke", { verb: "tasks.create", payload: {} }],+ [+ "connectorCall",+ { provider: "github", tool: "list_pull_requests", arguments: {} },+ ],])("allows declared %s access", (method, payload) => {expect(() =>assertCanvasCapability(capabilities, method, payload),@@ -83,6 +99,90 @@ describe("assertCanvasCapability", () => {});describe("handleFreeformDataRequest", () => {+ it.each([true, false])(+ "requires viewer consent before fetching (allowed: %s)",+ async (allowed) => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(allowed);+ callConnector.mockReset().mockResolvedValue({ status: "ok", result: {} });+ const read = () =>+ handleFreeformDataRequest(+ "connectorCall",+ { provider: "github", tool: "list_pull_requests" },+ queryClient,+ { dashboardId: "canvas-1", sourceVersionId: "version-1" },+ );+ for (let attempt = 0; attempt < 2; attempt += 1) {+ if (allowed) await read();+ else await expect(read()).rejects.toThrow("not granted");+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(callConnector).toHaveBeenCalledTimes(allowed ? 1 : 0);+ }+ if (!allowed) {+ vi.stubGlobal("navigator", { userActivation: { isActive: true } });+ confirm.mockReturnValue(true);+ await read();+ expect(confirm).toHaveBeenCalledTimes(2);+ expect(callConnector).toHaveBeenCalledTimes(1);+ }+ queryClient.clear();+ },+ );++ it("removes connector results and consent on an authentication change", async () => {+ const queryClient = new QueryClient();+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(true);+ callConnector+ .mockReset()+ .mockResolvedValueOnce({ status: "ok", result: { viewer: "first" } })+ .mockResolvedValueOnce({ status: "ok", result: { viewer: "second" } });+ const read = () =>+ handleFreeformDataRequest(+ "connectorCall",+ { provider: "github", tool: "list_pull_requests" },+ queryClient,+ { dashboardId: "canvas-1", sourceVersionId: "version-1" },+ );+ await expect(read()).resolves.toMatchObject({+ result: { viewer: "first" },+ });+ queryClient.removeQueries({+ predicate: (query) => query.meta?.authScoped === true,+ });+ await expect(read()).resolves.toMatchObject({+ result: { viewer: "second" },+ });+ expect(confirm).toHaveBeenCalledTimes(2);+ queryClient.clear();+ });++ it("requests consent again for a different canvas version or tool", async () => {+ const queryClient = new QueryClient();+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(true);+ callConnector.mockReset().mockResolvedValue({ status: "ok", result: {} });+ for (const [sourceVersionId, tool] of [+ ["version-1", "list_pull_requests"],+ ["version-2", "list_pull_requests"],+ ["version-2", "get_file_contents"],+ ]) {+ await handleFreeformDataRequest(+ "connectorCall",+ { provider: "github", tool },+ queryClient,+ { dashboardId: "canvas-1", sourceVersionId },+ );+ }+ expect(confirm).toHaveBeenCalledTimes(3);+ expect(callConnector).toHaveBeenCalledTimes(3);+ queryClient.clear();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });// 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 () => {@@ -108,6 +208,7 @@ describe("handleFreeformDataRequest", () => {["stateSet", { key: "k", value: 1 }],["stateList", {}],["actionInvoke", { verb: "tasks.create", payload: {} }],+ ["connectorCall", { provider: "github", tool: "list_pull_requests" }],])("%s without a canvas context is refused", async (method, payload) => {const queryClient = new QueryClient();@@ -116,6 +217,46 @@ describe("handleFreeformDataRequest", () => {).rejects.toThrow("requires a canvas context");});+ // The capability check that admits a connector call is per canvas, so a cached+ // result must not be served to a second canvas that made the same call.+ it("does not share a cached connector result across canvases", async () => {+ vi.spyOn(window, "confirm").mockReturnValue(true);+ const queryClient = new QueryClient();+ callConnector.mockReset().mockResolvedValue({+ status: "ok",+ result: { pull_requests: [] },+ detail: "",+ truncated: false,+ connect_path: null,+ });+ const payload = {+ provider: "github",+ tool: "list_pull_requests",+ arguments: { repository: "app" },+ };++ await handleFreeformDataRequest("connectorCall", payload, queryClient, {+ dashboardId: "canvas-1",+ sourceVersionId: "version-1",+ });+ await handleFreeformDataRequest("connectorCall", payload, queryClient, {+ dashboardId: "canvas-1",+ sourceVersionId: "version-1",+ });+ await handleFreeformDataRequest("connectorCall", payload, queryClient, {+ dashboardId: "canvas-2",+ sourceVersionId: "version-1",+ });++ expect(callConnector).toHaveBeenCalledTimes(2);+ expect(callConnector).toHaveBeenLastCalledWith({+ id: "canvas-2",+ provider: "github",+ tool: "list_pull_requests",+ arguments: { repository: "app" },+ });+ });+// 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 d850629ddb5e..06124a5cd18b 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts@@ -1,8 +1,10 @@import type {CanvasCaptureInput,+ CanvasConnectorCallInput,CanvasDataQueryInput,CanvasLoadInsightInput,} from "@posthog/core/canvas/freeformSchemas";+import { canvasConnectorCallInput } from "@posthog/core/canvas/freeformSchemas";import type { QueryClient } from "@tanstack/react-query";import { hostClient } from "../hostClient";@@ -54,6 +56,7 @@ function cachedRead<T>(return queryClient.fetchQuery({queryKey: [CANVAS_QUERY_KEY, method, stableStringify(input)] as const,queryFn: run,+ meta: method === "connectorCall" ? { authScoped: true } : undefined,staleTime: (refreshSeconds ?? 5 * 60) * 1_000,// At least the refresh interval, or GC would evict an inactive entry// before it goes stale and force an early backend re-read.@@ -61,6 +64,46 @@ function cachedRead<T>(});}+// Connector results describe live external state (open pull requests, today's+// meetings), so they go stale faster than a saved insight.+const CONNECTOR_DEFAULT_REFRESH_SECONDS = 60;++async function requireConnectorConsent(+ queryClient: QueryClient,+ dashboardId: string,+ sourceVersionId: string,+ input: CanvasConnectorCallInput,+): Promise<void> {+ const queryKey = [+ "canvasData/connectorConsent",+ dashboardId,+ sourceVersionId,+ input.provider,+ input.tool,+ ] as const;+ if (+ queryClient.getQueryData(queryKey) === false &&+ navigator.userActivation?.isActive === true+ ) {+ queryClient.removeQueries({ queryKey, exact: true });+ }+ const allowed = await queryClient.fetchQuery({+ queryKey,+ queryFn: async () =>+ window.confirm(+ `Allow this canvas to read ${JSON.stringify(input.tool)} from ${JSON.stringify(input.provider)} with your connection?\n\nThe canvas can receive private data and share it through its declared capabilities. Only allow canvases you trust.`,+ ),+ staleTime: Infinity,+ gcTime: 10 * 60 * 1_000,+ meta: { authScoped: true },+ });+ if (!allowed) {+ throw new Error(+ "Connector access was not granted. Click in the canvas to try again.",+ );+ }+}+function refreshSeconds(value: unknown): number | undefined {if (value === undefined) return undefined;if (@@ -85,7 +128,7 @@ export async function handleFreeformDataRequest(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 },+ context?: { dashboardId?: string; sourceVersionId?: string },): Promise<unknown> {const requireDashboardId = (): string => {if (!context?.dashboardId) {@@ -202,6 +245,35 @@ export async function handleFreeformDataRequest(payload: input.payload ?? {},});}+ case "connectorCall": {+ const dashboardId = requireDashboardId();+ const input = canvasConnectorCallInput.parse(payload);+ if (!context?.sourceVersionId) {+ throw new Error("Connector calls require a saved canvas version");+ }+ await requireConnectorConsent(+ queryClient,+ dashboardId,+ context.sourceVersionId,+ input,+ );+ // Keyed by canvas as well as content: the capability check that admitted+ // the call is per canvas, so a result must not leak into a canvas that+ // did not declare the tool.+ const args = {+ id: requireDashboardId(),+ provider: input.provider,+ tool: input.tool,+ arguments: input.arguments ?? {},+ };+ return cachedRead(+ queryClient,+ "connectorCall",+ { ...args, sourceVersionId: context.sourceVersionId },+ () => hostClient().dashboards.callConnector.mutate(args),+ refreshSeconds(input.refresh) ?? CONNECTOR_DEFAULT_REFRESH_SECONDS,+ );+ }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.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.tsindex 1d68ab3c99c4..edf8b0c8fd30 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@@ -123,6 +123,10 @@ describe("buildSandboxDocument", () => {expect(imports["react/jsx-runtime"]).toContain("esm.sh");});+ it("treats null connector options as an omitted refresh value", () => {+ expect(buildSandboxDocument()).toContain("refresh: options?.refresh");+ });+it("inlines the external-anchor resolver 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.tsindex 9f08b848b281..f5a6d31ccc77 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -287,6 +287,20 @@ export function buildSandboxDocument(actions: {invoke: (verb, payload) => call("actionInvoke", { verb, payload: payload ?? {} }),},+ // Read live third-party data with the viewer's own connection. Every+ // provider and tool must be declared in capabilities.connectors; the+ // result is cached per canvas for \`refresh\` seconds (default 60):+ // \`ph.connectors.call("github", "list_pull_requests", { repository: "app" })\`.+ // A "not_connected" status carries a connect_path; \`connect(provider)\`+ // opens that settings page from a click.+ 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 } });+ },+ },// 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")\`.diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.tsindex ed45b5977842..ace2b8fdc7c6 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts@@ -1,12 +1,25 @@-import type { CanvasNavIntent } from "@posthog/core/canvas/freeformSchemas";+import {+ type CanvasNavIntent,+ canvasConnectorProviderSchema,+} from "@posthog/core/canvas/freeformSchemas";import { useCreateAndOpenDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";+import type { SettingsCategory } from "@posthog/ui/features/settings/types";import {navigateToChannelDashboard,navigateToChannelTask,+ navigateToSettings,} from "@posthog/ui/router/navigationBridge";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { useCallback } from "react";+/** The settings page where a viewer connects a connector provider. */+export function connectorSettingsCategory(+ provider: string,+): SettingsCategory | null {+ if (!canvasConnectorProviderSchema.safeParse(provider).success) return null;+ return provider === "github" ? "github" : "mcp-servers";+}+/*** Routes a canvas's allowlisted nav intent to real host navigation. channelId is* host-supplied (never from the iframe), so the canvas can only move within its@@ -32,6 +45,11 @@ export function useCanvasNavigation(case "new-canvas":void createAndOpen();break;+ case "connect": {+ const category = connectorSettingsCategory(intent.provider);+ if (category) navigateToSettings(category);+ break;+ }}},[channelId, createAndOpen],diff --git a/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsxindex a9fb19b68df5..70fa1eecc557 100644--- a/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx+++ b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx@@ -50,8 +50,9 @@ export function ComponentFrame({ placement }: { placement: GridPlacement }) {(method: string, payload: unknown) =>handleFreeformDataRequest(method, payload, queryClient, {dashboardId: componentId,+ sourceVersionId: renderedBuild?.sourceVersionId,}),- [queryClient, componentId],+ [queryClient, componentId, renderedBuild?.sourceVersionId],);const capabilities = renderedBuild?.manifest