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(canvas): prefill cloud tasks and open github pr links (#99024)

Peter Kirkhamf3c2c937cd77
diff --git a/docs/internal/canvas-connectors.md b/docs/internal/canvas-connectors.md
index fa6ae0c19538..01d46902b041 100644
--- a/docs/internal/canvas-connectors.md
+++ b/docs/internal/canvas-connectors.md
@@ -2,6 +2,27 @@
Canvases can read third-party data with the current viewer's connection. Calls require the `canvas-connectors` team feature flag. The flag fails closed.
+## PR card actions
+
+From a user click, `ph.navigate.toNewTask({ prompt, repository })` opens a task form in a new tab.
+Both fields are optional. The prompt has a 16,000-character limit; the repository is an `owner/repo` name.
+A repository prefill selects cloud mode for this task only. The task stays in the canvas's space,
+but does not change the space's repository settings. The viewer must have access to the repository
+and must submit the form before a run starts. Omitting both fields opens the usual empty task form.
+Do not use `tasks.create_and_run` for a repository override: that action inherits the space settings.
+
+`ph.openExternal(url)` accepts HTTPS GitHub PR links as well as PostHog HTTPS URLs. GitHub links
+must use `github.com`, with no credentials, custom port, or query string. PR overview, files,
+commits, and checks paths are allowed, including fragment links. The host opens these PR links
+without a confirmation dialog, but still requires a user click and applies its existing rate limit.
+Other GitHub paths and other external domains remain blocked.
+
+These APIs require the updated Desktop host and canvas builder. Republish older canvases after
+deployment to include the new runtime. An older artifact can have no `ph.navigate`; show an update
+message rather than silently creating a task with the space's default repository.
+Prefilled forms use a separate `compose-task` navigation intent so older hosts reject the request
+instead of dropping its fields and opening a task with the wrong repository.
+
## Declare tools
Declare each provider and tool in the source project's capabilities:
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 37729f2843e0..646386820e8d 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -32,7 +32,7 @@ const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);const github=url.hostname==="github.com"&&!url.username&&!url.password&&!url.port&&!url.search&&new RegExp("^/[a-z0-9-]+/[a-z0-9_.-]+/pull/[1-9][0-9]*(/(files|commits|checks))?/?$","i").test(url.pathname);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")||github))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,navigate:{toTask:(taskId)=>post({type:"navigate",nav:{target:"task",taskId}}),toNewTask:(options)=>{if(!navigator.userActivation?.isActive)throw new Error("Opening a task requires a user action");post({type:"navigate",nav:{target:options?"compose-task":"new-task",prompt:options?.prompt,repository:options?.repository}})},toCanvas:(dashboardId)=>post({type:"navigate",nav:{target:"canvas",dashboardId}}),toNewCanvas:()=>post({type:"navigate",nav:{target:"new-canvas"}})},agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
// Notebook source remains arbitrary JavaScript, and its separate AI review is advisory.
// The cross-origin sandbox, CSP, host authorization, and frame allow-list are
// load-bearing controls. Navigation interception is defense in depth: the Navigation
diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.md
index 8c74b7afd506..11fe27b71015 100644
--- a/products/canvas/skills/querying-canvas-data/SKILL.md
+++ b/products/canvas/skills/querying-canvas-data/SKILL.md
@@ -305,8 +305,14 @@ useEffect(() => {
- `ph.capture(event, properties?, distinctId?)` — analytics events for interactions
(fire-and-forget). Session replay, `$session_id`, and person attribution are handled by the
host automatically; never initialize recording, set session ids, or roll your own capture.
-- `ph.openExternal(url)` — opens `https://posthog.com` / `*.posthog.com` URLs only, and only from
- a user interaction (opens outside focus are ignored). Sandboxed `target="_blank"` navigation is
- blocked, so do not use it as a fallback or link elsewhere.
+- `ph.openExternal(url)` — opens PostHog HTTPS URLs and `https://github.com/<owner>/<repo>/pull/<number>`
+ links from a user click. GitHub PR links open without a confirmation dialog. Files, commits, checks,
+ and fragment links are allowed; credentials, custom ports, query strings, and other domains are not.
+ Sandboxed `target="_blank"` navigation is blocked, so use the bridge rather than a browser fallback.
- `ph.navigate.toTask(id)` / `.toNewTask()` / `.toCanvas(id)` / `.toNewCanvas()` — in-app
navigation within the canvas's own channel.
+- `ph.navigate.toNewTask({ prompt, repository })` — opens a prefilled task form in a new tab from
+ a user click. `prompt` is at most 16,000 characters; `repository` is an `owner/repo` name. Both are
+ optional. Setting a repository selects cloud mode for this task without changing the space.
+ The viewer reviews and sends the prompt; opening the form does not start a run. Check for
+ `ph.navigate` in older published artifacts and ask for a rebuild after deployment if it is missing.
diff --git a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts
index dedeab1236db..8a52c9b4f38a 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
@@ -154,7 +154,7 @@ export interface CanvasAgent {
/** In-app navigation. Only these four targets exist. */
export interface CanvasNavigate {
toTask(taskId: string): void
- toNewTask(): void
+ toNewTask(options?: { prompt?: string; repository?: string }): void
toCanvas(canvasId: string): void
toNewCanvas(): void
}
@@ -180,7 +180,7 @@ export interface CanvasSdk {
* each event name in `capabilities.posthog.captureEvents`.
*/
capture(event: string, properties?: Record<string, unknown>, distinctId?: string): Promise<{ ok: boolean }>
- /** Open a PostHog URL externally. https://posthog.com / *.posthog.com only. */
+ /** Open a PostHog HTTPS URL or a GitHub PR HTTPS URL from a user click. */
openExternal(url: string): void
state: CanvasState
actions: CanvasActions
@@ -191,7 +191,7 @@ export interface CanvasSdk {
* only; undefined in the edit-mode preview.
*/
config?: Readonly<Record<string, unknown>>
- /** Preview runtime only today; undefined in a published canvas. */
+ /** Available in current preview and published runtimes; older builds may omit it. */
navigate?: CanvasNavigate
}
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts
index 8bf231cf9373..d8ae4bac339c 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts
@@ -6,6 +6,38 @@ import {
limitCanvasCommentHighlights,
} from "./freeformSchemas";
+describe("task composer navigation", () => {
+ it("preserves bounded task input without accepting a channel override", () => {
+ expect(
+ canvasNavIntentSchema.parse({
+ target: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ channelId: "another-channel",
+ }),
+ ).toEqual({
+ target: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ });
+ expect(canvasNavIntentSchema.parse({ target: "new-task" })).toEqual({
+ target: "new-task",
+ });
+ });
+
+ it.each([
+ { repository: "https://github.com/example/app" },
+ { repository: "../app" },
+ { repository: "example/app/extra" },
+ { prompt: "x".repeat(16_001) },
+ ])("rejects invalid composer input %j", (input) => {
+ expect(
+ canvasNavIntentSchema.safeParse({ target: "compose-task", ...input })
+ .success,
+ ).toBe(false);
+ });
+});
+
describe("canvasToHostMessageSchema", () => {
const message = (url: string) => ({
channel: "posthog-canvas",
@@ -17,6 +49,8 @@ describe("canvasToHostMessageSchema", () => {
"https://posthog.com/docs",
"https://us.posthog.com/project/2",
"https://app.posthog.com",
+ "https://github.com/example/app/pull/42",
+ "https://github.com/example/app/pull/42/files#diff-example",
])("accepts %s", (url) => {
expect(canvasToHostMessageSchema.safeParse(message(url)).success).toBe(
true,
@@ -25,6 +59,11 @@ describe("canvasToHostMessageSchema", () => {
it.each([
"https://example.com",
+ "https://github.com/login",
+ "https://github.com.evil.com/example/app/pull/42",
+ "https://user:[email protected]/example/app/pull/42",
+ "https://github.com:8443/example/app/pull/42",
+ "https://github.com/example/app/pull/42?redirect=https://example.com",
"http://posthog.com",
"https://posthog.com.evil.com",
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index d65e55cf6271..3e50c89dd137 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -1,4 +1,4 @@
-import { isSafePostHogUrl } from "@posthog/shared";
+import { isSafeGitHubPullRequestUrl, isSafePostHogUrl } from "@posthog/shared";
import { z } from "zod";
import { textCommentAnchorDataSchema } from "../comments/anchors";
@@ -281,6 +281,15 @@ export type HostToCanvasMessage = z.infer<typeof hostToCanvasMessageSchema>;
export const canvasNavIntentSchema = z.discriminatedUnion("target", [
z.object({ target: z.literal("task"), taskId: z.string().min(1) }),
z.object({ target: z.literal("new-task") }),
+ z.object({
+ target: z.literal("compose-task"),
+ prompt: z.string().max(16_000).optional(),
+ repository: z
+ .string()
+ .max(200)
+ .regex(/^[a-z0-9-]+\/[a-z0-9_.-]+$/i)
+ .optional(),
+ }),
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
@@ -342,12 +351,16 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [
type: z.literal("navigate"),
nav: canvasNavIntentSchema,
}),
- // Open a URL outside the sandbox. The PostHog-only https allowlist is part
+ // Open a URL outside the sandbox. The HTTPS allowlist is part
// of the schema, so no consumer can forward an unvalidated URL.
z.object({
channel: z.literal(CANVAS_CHANNEL),
type: z.literal("open-external"),
- url: z.string().refine(isSafePostHogUrl),
+ url: z
+ .string()
+ .refine(
+ (url) => isSafePostHogUrl(url) || isSafeGitHubPullRequestUrl(url),
+ ),
}),
z.object({
channel: z.literal(CANVAS_CHANNEL),
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 757eefedba8f..f6ceb2d0a87f 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -375,7 +375,11 @@ export {
} from "./tool-meta";
export { isTranscriptNeutralNotificationMethod } from "./transcript-neutral-notifications";
export { TypedEventEmitter } from "./typed-event-emitter";
-export { isSafeExternalUrl, isSafePostHogUrl } from "./url";
+export {
+ isSafeExternalUrl,
+ isSafeGitHubPullRequestUrl,
+ isSafePostHogUrl,
+} from "./url";
export { getCloudUrlFromRegion } from "./urls";
export {
buildVideoDataUrl,
diff --git a/products/desktop/packages/shared/src/url.ts b/products/desktop/packages/shared/src/url.ts
index 458688f266ac..9f0b4848ec46 100644
--- a/products/desktop/packages/shared/src/url.ts
+++ b/products/desktop/packages/shared/src/url.ts
@@ -38,3 +38,23 @@ export function isSafePostHogUrl(url: string): boolean {
parsed.hostname.endsWith(".posthog.com"))
);
}
+
+export function isSafeGitHubPullRequestUrl(url: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ return (
+ parsed.protocol === "https:" &&
+ parsed.hostname === "github.com" &&
+ !parsed.username &&
+ !parsed.password &&
+ !parsed.port &&
+ !parsed.search &&
+ /^\/[a-z0-9-]+\/[a-z0-9_.-]+\/pull\/[1-9]\d*(?:\/(?:files|commits|checks))?\/?$/i.test(
+ parsed.pathname,
+ )
+ );
+}
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 2771e40aaa24..94c6dd255cd3 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
@@ -1,3 +1,4 @@
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import {
act,
@@ -9,6 +10,8 @@ import {
import { afterEach, describe, expect, it, vi } from "vitest";
import { BuiltCanvas } from "./BuiltCanvas";
+vi.mock("@posthog/ui/shell/openExternal", () => ({ openExternalUrl: vi.fn() }));
+
describe("BuiltCanvas", () => {
const capabilities = {
posthog: {
@@ -25,6 +28,50 @@ describe("BuiltCanvas", () => {
const initialIsDarkMode = useThemeStore.getState().isDarkMode;
afterEach(() => useThemeStore.setState({ isDarkMode: initialIsDarkMode }));
+ it("opens a GitHub PR without a confirmation dialog", async () => {
+ const confirm = vi.spyOn(window, "confirm");
+ Object.defineProperty(navigator, "userActivation", {
+ configurable: true,
+ value: { isActive: true },
+ });
+ try {
+ render(
+ <BuiltCanvas
+ artifactUrl="https://usercontent.example/build/index.html"
+ capabilities={capabilities}
+ onDataRequest={vi.fn()}
+ />,
+ );
+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;
+ if (!iframe.contentWindow) throw new Error("Canvas iframe has no window");
+ const postMessage = vi
+ .spyOn(iframe.contentWindow, "postMessage")
+ .mockImplementation(() => undefined);
+ fireEvent.load(iframe);
+ const calls = postMessage.mock.calls as unknown as [
+ unknown,
+ string,
+ Transferable[],
+ ][];
+ const port = calls.at(-1)?.[2]?.[0] as MessagePort;
+ port.postMessage({
+ channel: "posthog-canvas",
+ type: "open-external",
+ url: "https://github.com/example/app/pull/42",
+ });
+ await waitFor(() =>
+ expect(openExternalUrl).toHaveBeenCalledWith(
+ "https://github.com/example/app/pull/42",
+ ),
+ );
+ expect(confirm).not.toHaveBeenCalled();
+ } finally {
+ confirm.mockRestore();
+ Reflect.deleteProperty(navigator, "userActivation");
+ vi.mocked(openExternalUrl).mockClear();
+ }
+ });
+
it("loads an immutable artifact without granting origin or popup access", () => {
render(
<BuiltCanvas
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
index f41123ff019b..02df13866397 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
@@ -7,6 +7,7 @@ import {
canvasToHostMessageSchema,
} from "@posthog/core/canvas/freeformSchemas";
import type { CanvasCapabilities } from "@posthog/shared";
+import { isSafeGitHubPullRequestUrl } from "@posthog/shared";
import { logger } from "@posthog/ui/shell/logger";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
@@ -205,10 +206,12 @@ export function BuiltCanvas({
onCommentActivate: (id) => latest.current.onCommentActivate?.(id),
}),
hasUserActivation: () => navigator.userActivation?.isActive === true,
- // Built artifacts run arbitrary published code, so an external open asks
- // first even after the activation + throttle gates pass.
+ // Only validated GitHub PR links skip confirmation after the gesture gate.
openExternal: (url) => {
- if (window.confirm(`Open this link in your browser?\n\n${url}`)) {
+ if (
+ isSafeGitHubPullRequestUrl(url) ||
+ window.confirm(`Open this link in your browser?\n\n${url}`)
+ ) {
openExternalUrl(url);
}
},
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 d842239727c2..f97b4a0ccdc5 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,53 @@ import { describe, expect, it, vi } from "vitest";
import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
describe("createCanvasHostMessageRouter", () => {
+ it.each([false, true])(
+ "requires activation for task composition (%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: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ },
+ });
+ expect(onNavigate).toHaveBeenCalledTimes(active ? 1 : 0);
+ if (active)
+ expect(onNavigate).toHaveBeenCalledWith({
+ target: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ });
+ },
+ );
+
+ it.each([false, true])(
+ "opens GitHub PR links only after a click (%s)",
+ async (active) => {
+ const openExternal = vi.fn();
+ const route = createCanvasHostMessageRouter({
+ post: vi.fn(),
+ callbacks: () => ({ onDataRequest: vi.fn() }),
+ hasUserActivation: () => active,
+ openExternal,
+ });
+ await route({
+ channel: "posthog-canvas",
+ type: "open-external",
+ url: "https://github.com/example/app/pull/42",
+ });
+ expect(openExternal).toHaveBeenCalledTimes(active ? 1 : 0);
+ },
+ );
it.each([false, true])(
"requires activation for connector navigation (%s)",
async (active) => {
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 c6a930ce56aa..ae918d858032 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -4,7 +4,7 @@ import type {
CanvasToHostMessage,
HostToCanvasMessage,
} from "@posthog/core/canvas/freeformSchemas";
-import { isSafePostHogUrl } from "@posthog/shared";
+import { isSafeGitHubPullRequestUrl, isSafePostHogUrl } from "@posthog/shared";
// Canvas code can post open-external without a gesture, so opens are limited.
const EXTERNAL_OPEN_MIN_INTERVAL_MS = 1_000;
@@ -184,7 +184,12 @@ export function createCanvasHostMessageRouter(
options.callbacks().onRendered?.();
break;
case "navigate":
- if (message.nav.target === "connect" && !options.hasUserActivation())
+ if (
+ (message.nav.target === "connect" ||
+ message.nav.target === "compose-task" ||
+ message.nav.target === "new-task") &&
+ !options.hasUserActivation()
+ )
break;
// message.nav is already allowlist-validated by the schema parse.
options.callbacks().onNavigate?.(message.nav);
@@ -200,7 +205,10 @@ export function createCanvasHostMessageRouter(
break;
case "open-external":
// Re-checks the schema's allowlist refine in case it ever drifts.
- if (!isSafePostHogUrl(message.url)) {
+ if (
+ !isSafePostHogUrl(message.url) &&
+ !isSafeGitHubPullRequestUrl(message.url)
+ ) {
options.onExternalOpenBlocked?.(message.url, "unsafe-url");
} else if (!options.hasUserActivation()) {
options.onExternalOpenBlocked?.(message.url, "no-interaction");
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts
index edf8b0c8fd30..32f889b3cd0b 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
@@ -2,7 +2,8 @@ import {
CANVAS_SDK_MODULE_SOURCE,
CANVAS_SDK_SPECIFIER,
} from "@posthog/shared";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import builderSource from "../../../../../../../canvas/packages/canvas_builder/build.mjs?raw";
import {
buildSandboxDocument,
decodeJsxUnicodeEscapes,
@@ -103,6 +104,76 @@ describe("decodeJsxUnicodeEscapes", () => {
});
describe("buildSandboxDocument", () => {
+ it("publishes navigation and the same GitHub URL restriction as the host", () => {
+ const source = builderSource.match(/const runtime = `([^`]*)`/)?.[1];
+ if (!source) throw new Error("Published runtime not found");
+ const listeners = new Map<string, (event: unknown) => void>();
+ const postMessage = vi.fn();
+ const frame = {
+ ph: undefined as unknown as {
+ navigate: {
+ toNewTask: (options: { prompt: string; repository: string }) => void;
+ };
+ openExternal: (url: string) => void;
+ },
+ };
+ const userActivation = { isActive: true };
+ const parent = {};
+ new Function(
+ "window",
+ "document",
+ "location",
+ "parent",
+ "navigator",
+ "addEventListener",
+ source,
+ )(
+ frame,
+ document,
+ { hash: "" },
+ parent,
+ { userActivation },
+ (name: string, listener: (event: unknown) => void) =>
+ listeners.set(name, listener),
+ );
+ listeners.get("message")?.({
+ source: parent,
+ data: { channel: "posthog-canvas", type: "connect" },
+ ports: [{ postMessage, addEventListener: vi.fn(), start: vi.fn() }],
+ });
+ frame.ph.navigate.toNewTask({
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ });
+ expect(postMessage).toHaveBeenCalledWith({
+ channel: "posthog-canvas",
+ type: "navigate",
+ nav: {
+ target: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ },
+ });
+ frame.ph.openExternal("https://github.com/example/app/pull/42");
+ expect(postMessage).toHaveBeenLastCalledWith({
+ channel: "posthog-canvas",
+ type: "open-external",
+ url: "https://github.com/example/app/pull/42",
+ });
+ expect(() => frame.ph.openExternal("https://github.com/login")).toThrow(
+ "not allowed",
+ );
+ expect(() =>
+ frame.ph.openExternal("https://github.com.evil.com/example/app/pull/42"),
+ ).toThrow("not allowed");
+ userActivation.isActive = false;
+ expect(() =>
+ frame.ph.navigate.toNewTask({
+ prompt: "Inspect",
+ repository: "example/app",
+ }),
+ ).toThrow("user action");
+ });
it("inlines the unicode-escape decoder into the bootstrap", () => {
const html = buildSandboxDocument();
expect(html).toContain(
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
index f5a6d31ccc77..3dd86a9b0bc4 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -307,7 +307,7 @@ export function buildSandboxDocument(
agent: {
request: (prompt) => call("agentRequest", { prompt }),
},
- // Brokered by the host: PostHog-only https URLs, rate-limited, and
+ // Brokered by the host: PostHog and GitHub PR HTTPS URLs, rate-limited, and
// ignored while the canvas is unfocused (no auto-opens on load).
openExternal: (url) => post({ type: "open-external", url }),
// Navigate the host app. Fire-and-forget: the host validates the intent
@@ -315,7 +315,10 @@ export function buildSandboxDocument(
// cannot pick the channel or an arbitrary path — only these four targets.
navigate: {
toTask: (taskId) => post({ type: "navigate", nav: { target: "task", taskId } }),
- toNewTask: () => post({ type: "navigate", nav: { target: "new-task" } }),
+ toNewTask: (options) => {
+ if (!navigator.userActivation?.isActive) throw new Error("Opening a task requires a user action");
+ post({ type: "navigate", nav: { target: options ? "compose-task" : "new-task", prompt: options?.prompt, repository: options?.repository } });
+ },
toCanvas: (dashboardId) => post({ type: "navigate", nav: { target: "canvas", dashboardId } }),
toNewCanvas: () => post({ type: "navigate", nav: { target: "new-canvas" } }),
},
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.test.ts
new file mode 100644
index 000000000000..2f7f6cdc7f53
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.test.ts
@@ -0,0 +1,35 @@
+import { openTaskInput } from "@posthog/ui/router/useOpenTask";
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { useCanvasNavigation } from "./useCanvasNavigation";
+
+vi.mock("@posthog/ui/router/useOpenTask", () => ({ openTaskInput: vi.fn() }));
+vi.mock("@posthog/ui/router/navigationBridge", () => ({
+ navigateToChannelDashboard: vi.fn(),
+ navigateToChannelTask: vi.fn(),
+ navigateToSettings: vi.fn(),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useDashboards", () => ({
+ useCreateAndOpenDashboard: () => vi.fn(),
+}));
+
+describe("useCanvasNavigation", () => {
+ it("prefills a cloud repository within the existing space, then clears it for an empty form", () => {
+ const { result } = renderHook(() => useCanvasNavigation("canvas-space"));
+ result.current({
+ target: "compose-task",
+ prompt: "Inspect this PR",
+ repository: "example/app",
+ });
+ expect(openTaskInput).toHaveBeenLastCalledWith({
+ channelId: "canvas-space",
+ initialPrompt: "Inspect this PR",
+ initialCloudRepository: "example/app",
+ newTab: true,
+ });
+ result.current({ target: "new-task" });
+ expect(openTaskInput).toHaveBeenLastCalledWith({
+ channelId: "canvas-space",
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts
index ace2b8fdc7c6..614f69ee5ef5 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/useCanvasNavigation.ts
@@ -39,6 +39,14 @@ export function useCanvasNavigation(
// Via openTaskInput so a stale prefill can't leak into the composer.
openTaskInput({ channelId });
break;
+ case "compose-task":
+ openTaskInput({
+ channelId,
+ initialPrompt: intent.prompt,
+ initialCloudRepository: intent.repository,
+ newTab: true,
+ });
+ break;
case "canvas":
navigateToChannelDashboard(channelId, intent.dashboardId);
break;