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.

refactor(desktop): route canvas creation through skills (#82932)

Peter Kirkham7408e9c4cccb
diff --git a/.agents/skills/posthog-desktop/SKILL.md b/.agents/skills/posthog-desktop/SKILL.md
index 07ca10d8b942..af5dcbfa7481 100644
--- a/.agents/skills/posthog-desktop/SKILL.md
+++ b/.agents/skills/posthog-desktop/SKILL.md
@@ -94,7 +94,7 @@ auto-assignment and Slack routing; do not delete it.
## Desktop-local skills
`products/desktop/.claude/skills/` ships its own: `test-electron-app` (drive the running app
-over CDP `:9222`), `quill-code`, `storybook-stories`, `canvas-templates`, `onboarding-videos`.
+over CDP `:9222`), `quill-code`, `storybook-stories`, `onboarding-videos`.
Prefer these over monorepo equivalents while in this tree.
## Before reporting done
diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.md
index bf298cb1ecc0..80060a9bda8b 100644
--- a/products/canvas/skills/building-canvases/SKILL.md
+++ b/products/canvas/skills/building-canvases/SKILL.md
@@ -16,6 +16,10 @@ Its source lives in PostHog — not in a repository — and you read and write i
`canvas-*` tools. Never write a canvas to a local file; publishing through the tool is what
saves it.
+Canvas work can start from any ordinary task. A dedicated canvas mode or pre-created canvas is
+not required. When the user asks for a board, document, form, visualization, or small app that
+should live in PostHog, treat that as a canvas request and follow this skill.
+
## Resolve the target canvas
- If the task names a canvas id (canvas-initiated tasks do), that is the target. Do not create another.
@@ -31,29 +35,56 @@ saves it.
default — a canvas filed there is invisible to everyone else. If the task names neither a canvas
nor a channel, ask which channel to use instead of guessing.
-## Choose the least complex implementation that meets the request
+## Load the companion skills for the implementation
+
+This skill owns canvas selection and the authoring lifecycle. The companion skills hold the
+implementation contracts. Load every companion that applies before writing source:
-- **React + Quill** — PostHog data products, dashboards, forms, application-like state, and anything
- that should look native to PostHog. Load the `building-react-quill-canvases` skill.
-- **Semantic HTML, CSS, and direct browser APIs** — static documents, focused experiments, generative
- graphics, `<canvas>`/WebGL work where React adds no structure. Load the `building-html-canvases` skill.
-- **Mix them** when appropriate: React can own the application chrome while Three-style code owns a
- canvas element, or a mostly static page can mount one interactive island.
+- **`building-react-quill-canvases`** for dashboards, data boards, forms, tools, application-like
+ state, or anything that should look native to PostHog. It owns allowed imports, Quill composition,
+ theming, charts, loading and error states, and the date picker.
+- **`building-html-canvases`** for documents, articles, focused experiments, generative graphics,
+ `<canvas>`, or WebGL work where application components add no useful structure. It owns semantic
+ markup, direct browser APIs, animation cleanup, and non-Quill theming.
+- **`querying-canvas-data`** whenever the canvas reads PostHog data, captures events, or navigates.
+ It owns the `ph` SDK, saved-insight preference, result shapes, variables, date ranges, and declared
+ data capabilities. Load it alongside either implementation skill when data is involved.
+- **`validating-and-publishing-canvases`** for every canvas. It owns project shape, capability
+ declarations, validation diagnostics, guarded publishes, drafts, builds, and conflict recovery.
+
+Mix implementation approaches when appropriate: React can own application chrome while browser
+graphics code owns a canvas element, or a mostly static page can mount one interactive island.
This is a judgment call, not a persisted mode — ask the user only when the choice changes a
user-visible requirement you cannot infer.
+## Common request patterns
+
+Use these as routing examples, not fixed templates:
+
+- **Product dashboard, web analytics board, or metric explorer:** React + Quill plus data querying.
+- **Checklist, form, or lightweight workflow:** React + Quill, plus data querying for PostHog reads,
+ event capture, or navigation. Do not imply persistence that the available APIs do not provide.
+- **Document or narrative report:** HTML for a mostly static reading experience; React + Quill plus
+ data querying when it needs live PostHog data, filters, or application-like interactions.
+- **Generative graphic or animation:** HTML and browser graphics APIs. Add React only when it
+ materially simplifies application state or chrome.
+
+When the task carries a legacy requested pattern such as `dashboard` or `web-analytics`, apply the
+matching shape above. The pattern is a hint; the user's actual request remains authoritative.
+
## The iteration loop
1. Read the current source and version pointer with `canvas-source-retrieve`.
Remember `current_version_id` — your publish must be guarded on it.
-2. Edit the project files. For any PostHog data the canvas shows, follow the `querying-canvas-data`
- skill (saved insights loaded via the `ph` SDK — never fetch or your own PostHog client), and
+2. Edit the project files using the implementation companions selected above. For any PostHog data
+ the canvas shows, follow `querying-canvas-data` (saved insights loaded via the `ph` SDK — never
+ fetch or your own PostHog client), and
**declare every `ph` call in `project.capabilities`** (insight short ids in
`capabilities.posthog.insights`, captured events in `captureEvents`, `inlineQueries: true` for
ad-hoc queries) — the host enforces these at runtime and validation rejects undeclared calls.
-3. Validate with `canvas-validate-create` as often as needed and fix every error-severity
- diagnostic.
+3. Follow `validating-and-publishing-canvases`: validate with `canvas-validate-create` as often as
+ needed and fix every error-severity diagnostic.
4. Save the project — which tool depends on whether the canvas is already live:
- **First version** (`current_version_id` is null): publish the complete project with
`canvas-publish-create`, passing `expected_current_version_id: null`.
diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.md
index 1a266cd23677..f788e7f60ea8 100644
--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md
+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md
@@ -47,6 +47,7 @@ control or a styled `<div>` standing in for one:
- Style with Tailwind utilities and Quill components; reserve inline `style` for genuinely dynamic
runtime values (fixed sizes use arbitrary-value utilities like `h-[280px]`).
+- Write specific interface copy. Never use lorem ipsum or placeholder labels in a finished canvas.
- The canvas follows the user's PostHog theme; a `.dark` class on the document root flips at runtime.
Color only from the design-token utilities — surfaces `bg-background bg-card bg-muted bg-primary
bg-success bg-warning bg-info bg-destructive`; text `text-foreground text-muted-foreground
@@ -75,6 +76,41 @@ through to zeros, an empty chart, or a "no data yet" message. A query that silen
error makes real breakage (a missing table, an auth failure, a bad query) look like missing data.
Reserve the empty state for a query that succeeded with no rows.
+## Data-product patterns
+
+Treat these as starting shapes and adapt them to the request and available data.
+
+### Product dashboard
+
+- Build a live board from verified PostHog data, never a static mockup.
+- Start with a `Heading`, then a responsive grid of compact `Card` KPIs, trend charts, and useful
+ breakdown tables.
+- Show a `Badge` delta for KPIs when a meaningful comparison period exists.
+- Use a `LineChart` for time series and a `BarChart` for discrete categories. Do not turn every
+ result into a table.
+- Give every KPI, chart, and table its own loading, empty, and error state.
+
+### Web analytics board
+
+Use this shape when the request or legacy requested pattern says `web-analytics`:
+
+1. Show Visitors, Page views, Sessions, Session duration, and Bounce rate as KPI cards, with deltas
+ against the previous equal-length period.
+2. Plot unique visitors over time, with a second line for the previous period when comparison data
+ is available.
+3. Follow with compact tables for top paths, traffic sources or channels, devices, and geography.
+4. Prefix countries with flag emoji. Add retention or active-hours views only when the available
+ data makes them useful.
+
+Use the web analytics query kinds described in `querying-canvas-data`; do not recreate bounce rate,
+sessionization, attribution, or unique visitors in HogQL. Format large values for display, such as
+`236K`, while preserving the raw value for calculations and accessible labels.
+
+### Interactive explorer
+
+Use controlled Quill inputs for each dimension, event, or date choice. Keep result sets small and
+refresh every dependent query when a control changes.
+
## Date window
A data board owns its own date control — render Quill's `DateTimePicker` (never a custom Select or
diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.md
index c888703bcc6a..42d1333de0f7 100644
--- a/products/canvas/skills/querying-canvas-data/SKILL.md
+++ b/products/canvas/skills/querying-canvas-data/SKILL.md
@@ -94,8 +94,9 @@ product — rather than every tile resolving the insight's saved default.
- `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 roll your own capture.
+ 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). Don't link elsewhere.
+ 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.navigate.toTask(id)` / `.toNewTask()` / `.toCanvas(id)` / `.toNewCanvas()` — in-app
navigation within the canvas's own channel.
diff --git a/products/desktop/.claude/skills/canvas-templates/SKILL.md b/products/desktop/.claude/skills/canvas-templates/SKILL.md
deleted file mode 100644
index 9bc9490e744f..000000000000
--- a/products/desktop/.claude/skills/canvas-templates/SKILL.md
+++ /dev/null
@@ -1,150 +0,0 @@
----
-name: canvas-templates
-description: How PostHog "canvas" dashboards work end-to-end — the two rendering tiers (json-render vs freeform React-in-iframe), the agent system prompts that steer each, and the RIGHT way to fetch PostHog data (typed query nodes through ph.query, not hand-rolled HogQL). Use when changing canvas templates, the freeform sandbox, the ph.* data shim, canvas data fetching, or the agent prompts that build dashboards / web-analytics boards.
----
-
-# Canvas templates & data
-
-PostHog "canvases" are agent-built dashboards/apps. There are **two rendering
-tiers** and a strict **data path**. Get the tier and the data path right and most
-canvas work is straightforward; get them wrong and you ship correctness bugs.
-
-## The two tiers
-
-A canvas's `kind` (set at create time, persisted in file meta) decides everything:
-
-| Tier | `kind` | What the agent writes | Renderer | Data path |
-| --- | --- | --- | --- | --- |
-| **json-render** | `"json-render"` | JSONL patches against a component catalog | `ViewRenderer` (Quill component tree) | `state.queries` HogQL, re-run by `dashboardsService` on refresh |
-| **freeform / React** | `"freeform"` | a single-file React app | sandboxed `<iframe>` (`FreeformCanvas`) | the `ph.*` shim → host → PostHog |
-
-Which template maps to which tier: `REACT_TIER_TEMPLATE_IDS` in
-`packages/core/src/canvas/freeformSchemas.ts`. Today `dashboard`, `web-analytics`,
-and the generic `freeform` template render React; everything else is json-render.
-Legacy canvases created before a template moved tiers keep their stored `kind` —
-**there is no migration**, so both renderers must keep working.
-
-Key files:
-- `packages/core/src/canvas/canvasTemplates.ts` — the agent **system prompts** +
- per-template rules. This is where you steer agent behavior. Two prompt families:
- - `BASE_RULES` + `DASHBOARD_RULES` / `WEB_ANALYTICS_RULES` → json-render (catalog-built).
- - `FREEFORM_BASE` + `buildFreeformPrompt(...)` → React tier. `freeformSystemPromptFor(id)`
- picks the prompt for a `kind:"freeform"` canvas by templateId.
-- `packages/core/src/canvas/canvasDataService.ts` — host-side `ph.query` / `ph.capture`.
-- `packages/ui/src/features/canvas/freeform/` — the iframe: `FreeformCanvas.tsx`
- (postMessage broker), `sandboxRuntime.ts` (the iframe HTML + the `ph` shim),
- `freeformDataBridge.ts` (routes a `ph.*` call to the host tRPC).
-
-## Data: the RIGHT way (read this before touching queries)
-
-> **Reuse PostHog's query runners; don't reinvent metrics in SQL.**
-
-The freeform app talks to PostHog ONLY through the injected `ph` global — the host
-holds the token, the iframe never sees it. The one call that matters:
-
-```js
-const { columns, results } = await ph.query(arg)
-```
-
-`arg` is **either** a typed query node **or** an inline HogQL string:
-
-- **PREFERRED — a typed query node:** `ph.query({ kind: "TrendsQuery", series: [...], dateRange: {...} })`.
- The product's OWN query runners compute it, so the numbers **match the PostHog
- UI exactly** (sessionization, unique users, breakdowns, math, bounce rate) and
- the node's `dateRange` handles the window. The agent gets the node by creating/
- opening an insight via the PostHog MCP tools and copying its `query` node.
-- **ESCAPE HATCH — inline HogQL:** `ph.query("SELECT …")`. Only for shapes a typed
- node can't express. The agent owns the SQL and its correctness.
-
-Why this split exists: hand-rolled HogQL for standard metrics (especially web
-analytics — bounce rate, channel attribution, sessionization) subtly diverges from
-the product's numbers. Typed nodes are the same wheel the UI uses; don't re-cut it.
-
-> **⚠️ The result SHAPE differs by kind — get it wrong and every value reads 0.**
-> - HogQL → `{ columns: string[], results: rows[][] }` (read `results[row][col]`).
-> - Typed node (TrendsQuery/etc.) → `results` is an array of **series objects**
-> (`{ data: number[], days: string[], count, aggregated_value, compare_label, … }`),
-> NOT rows. KPI total = `results[0].count`/`.aggregated_value`; series =
-> `results[0].data`; the `compareFilter` previous period is a second series
-> (match `compare_label === "previous"`, don't assume index order).
-> `CanvasDataService.query` passes typed-node results through untouched and only
-> row-coerces HogQL — see the `isTyped` branch. The first build of this missed it
-> and rendered all-zeros despite the query running fine.
-
-### The data path end-to-end
-
-```
-ph.query(arg) iframe (sandboxRuntime.ts shim)
- └─ postMessage "data-request"
- └─ FreeformCanvas route() ui (FreeformCanvas.tsx)
- └─ handleFreeformDataRequest("query") ui (freeformDataBridge.ts)
- └─ tRPC canvasData.query host (canvas-data.router.ts)
- └─ CanvasDataService.query core (canvasDataService.ts)
- └─ runQuery(node) core (posthogApi.ts)
- └─ POST /api/projects/<id>/query/
- { query: <node>, refresh: "blocking" }
-```
-
-- `runQuery(authService, node, { refresh })` is the one place that POSTs to the
- query endpoint. `runHogQLQuery(...)` is a thin wrapper that boxes a string into
- `{ kind: "HogQLQuery", query }`. Both live in `posthogApi.ts`.
-- `refresh: "blocking"` = the cached avenue (serve a fresh cached result, else
- compute). Same cache insights use — so typed nodes are cached, not recomputed.
-- `canvasDataQueryInput` (`freeformSchemas.ts`) accepts `{ query?, hogql?, params? }`
- and refines that exactly one of `query` / `hogql` is present.
-
-To add a new `ph.*` capability: add the method to the shim (`sandboxRuntime.ts`
-`window.ph`), route it in `freeformDataBridge.ts`, add a tRPC procedure
-(`canvas-data.router.ts`) backed by a `CanvasDataService` method. Never let the
-iframe hold a token — it posts a request; the host runs the authenticated call.
-
-> **`ph.run(insightShortId)` is stubbed** (`freeformDataBridge.ts` throws). It's
-> the *view/published* tier's model: a shared canvas can't ship inline queries to
-> anonymous viewers, so publish converts validated query nodes → saved insights +
-> an allowlist and the canvas references them by id. Implement it there, not in edit.
-
-## Dates
-
-The freeform app owns its date control (the toolbar picker is hidden for freeform —
-it drove json-render `state.queries`, see `WebsiteLayout.tsx`). The agent renders
-Quill's `DateTimePicker` and feeds the window into the typed node's `dateRange`
-(`{ date_from, date_to }`) — the runner handles timezone/bucketing/half-open.
-
-> **`DateTimePicker` must be `compact` in the canvas.** Without the `compact`
-> prop it auto-detects layout via `useMediaQuery('(min-width: 64rem)')` against the
-> **iframe viewport** — which is full-width, so it picks the wide dual-calendar
-> layout and overflows the popover it's anchored in. The prompt forces `compact`. The
-inline-HogQL fallback must use half-open `timestamp >= toDateTime(fromUnix) AND
-timestamp < toDateTime(toUnix)` (integer unix = UTC), never `now()` / `INTERVAL` /
-inclusive `<= to`. These rules live in `FREEFORM_DATE_CONTROL_RULES`.
-
-## Styling (freeform sandbox)
-
-The iframe loads Quill's compiled CSS + tokens AND the Tailwind Play CDN
-(`sandboxRuntime.ts`), with **Preflight disabled** (its unlayered form reset
-overrode Quill's `@layer components` styles). So in a freeform canvas: build from
-`@posthog/quill` components, Tailwind utilities work, and you do NOT restyle Quill
-components. Allowed imports are the `FREEFORM_WHITELIST` (`freeformWhitelist.ts`);
-the Quill version is `QUILL_VERSION` there (must match the CSS `<link>` URLs).
-
-## Editing the agent prompts
-
-- Steer the React data templates by editing the rule arrays in `canvasTemplates.ts`
- (`FREEFORM_QUILL_RULES`, `FREEFORM_DATE_CONTROL_RULES`, `FREEFORM_DASHBOARD_RULES`,
- `FREEFORM_WEB_ANALYTICS_RULES`). Generic `freeform` stays rule-free ("anything goes").
-- The agent can't WebFetch at runtime (denied tool) — prompt rules must be
- self-contained; URLs are knowledge pointers only.
-- Prompt strings are plain TS array entries; biome lints the file. Avoid `${...}`
- inside a normal string literal (biome flags it as a template placeholder).
-
-## Checks after any change
-
-```bash
-pnpm --filter @posthog/core typecheck && pnpm --filter @posthog/core test -- --run
-pnpm --filter @posthog/ui typecheck
-npx biome lint packages/core/src/canvas packages/ui/src/features/canvas
-```
-
-Then **verify in the running app** — most of this tier (sandbox styling, the data
-path, the date picker, refresh) is not covered by unit tests. Use the
-`test-electron-app` skill to drive a real canvas over CDP.
diff --git a/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts b/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
index c14df609c4a9..4d672b009c4b 100644
--- a/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
@@ -53,7 +53,6 @@ function input(
dashboardId: "dash-1",
name: "Signups",
instruction: "build a signups chart",
- isEdit: false,
channelId: "chan-1",
channelName: "growth",
cloudRegion: "us",
@@ -163,28 +162,6 @@ describe("CanvasApplicationService", () => {
expect(gateway.renameCanvas).not.toHaveBeenCalled();
});
- it("creates directly without listing stored canvases when no target is given", async () => {
- const { service, createTask, generateCanvasName } = makeDeps();
- const gateway = makeGateway();
-
- const result = await service.generateCanvas(
- input({ dashboardId: undefined, name: undefined }),
- gateway,
- );
-
- expect(result).toEqual({ ok: true, taskId: "task-1" });
- const [taskInput] = createTask.mock.calls[0];
- expect(taskInput.content).not.toContain("`canvas-list`");
- expect(taskInput.content).toContain("`canvas-create`");
- expect(taskInput.content).not.toContain("canvas id:");
- expect(taskInput.taskDescription).toBe("Generate a canvas in #growth");
- // The task still files into the channel, but no canvas record is touched.
- expect(gateway.fileTask).toHaveBeenCalledWith("chan-1", "task-1");
- expect(gateway.setGenerationTask).not.toHaveBeenCalled();
- expect(generateCanvasName).not.toHaveBeenCalled();
- expect(gateway.renameCanvas).not.toHaveBeenCalled();
- });
-
it("still starts the task when recording the generation task fails", async () => {
const { service } = makeDeps();
const gateway = makeGateway();
diff --git a/products/desktop/packages/core/src/canvas/canvasApplicationService.ts b/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
index 64fe5c614aae..6f12385d6272 100644
--- a/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
+++ b/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
@@ -24,21 +24,10 @@ import { isPlaceholderCanvasName } from "./canvasNaming";
import { buildCanvasGenerationPrompt } from "./generationPrompt";
export interface GenerateCanvasInput {
- /**
- * The canvas being generated or edited, when the surface already knows it.
- * Channel-composer runs omit it: the agent resolves the target itself
- * (building on a matching existing canvas, or creating a named one), so no
- * canvas-side effects run here.
- */
- dashboardId?: string;
- /** The target's title; set whenever dashboardId is. */
- name?: string;
+ dashboardId: string;
+ name: string;
templateId?: string;
instruction: string;
- /** True when the canvas already has published source (an edit, not a first build). */
- isEdit: boolean;
- /** First builds only: point the agent at the known-good starter scaffold. */
- useStarter?: boolean;
/** Backend channel (task channel UUID) that owns the canvas and the task. */
channelId: string;
channelName: string;
@@ -147,11 +136,8 @@ export class CanvasApplicationService {
dashboardId: input.dashboardId,
name: input.name,
channelName: input.channelName,
- channelId: input.channelId,
templateId: input.templateId,
instruction: input.instruction,
- isEdit: input.isEdit,
- useStarter: input.useStarter,
}),
taskDescription: input.name
? `Generate canvas "${input.name}"`
@@ -182,35 +168,24 @@ export class CanvasApplicationService {
this.log.warn("Failed to file canvas generation task", { error });
});
- // Canvas-side effects only apply when the surface pre-resolved a target;
- // target-less runs leave them to the agent, which resolves or creates the
- // canvas itself.
const dashboardId = input.dashboardId;
- if (dashboardId) {
- // The generation-task write is awaited so a caller that navigates to the
- // canvas right after generate() lands on the generating view, not the
- // empty hero.
- await gateway.setGenerationTask(dashboardId, task.id).catch((error) => {
- this.log.warn("Failed to record canvas generation task", { error });
- });
+ await gateway.setGenerationTask(dashboardId, task.id).catch((error) => {
+ this.log.warn("Failed to record canvas generation task", { error });
+ });
- // Auto-name a still-unnamed canvas from its generation prompt, using the
- // same helper model that names tasks. Best-effort: a failure (or a user
- // who already named the canvas) leaves the existing title untouched.
- if (input.name && isPlaceholderCanvasName(input.name)) {
- void this.titleGenerator
- .generateCanvasName(input.instruction)
- .then(async (generated) => {
- const title = generated?.trim();
- if (title) {
- await gateway.renameCanvas(dashboardId, title);
- gateway.onAutoNamed?.(task.id, title);
- }
- })
- .catch((error) => {
- this.log.warn("Failed to auto-name canvas", { error });
- });
- }
+ if (isPlaceholderCanvasName(input.name)) {
+ void this.titleGenerator
+ .generateCanvasName(input.instruction)
+ .then(async (generated) => {
+ const title = generated?.trim();
+ if (title) {
+ await gateway.renameCanvas(dashboardId, title);
+ gateway.onAutoNamed?.(task.id, title);
+ }
+ })
+ .catch((error) => {
+ this.log.warn("Failed to auto-name canvas", { error });
+ });
}
return { ok: true, taskId: task.id };
diff --git a/products/desktop/packages/core/src/canvas/canvasTemplates.ts b/products/desktop/packages/core/src/canvas/canvasTemplates.ts
index ee5c04881485..fe1284c58bab 100644
--- a/products/desktop/packages/core/src/canvas/canvasTemplates.ts
+++ b/products/desktop/packages/core/src/canvas/canvasTemplates.ts
@@ -1,179 +1,7 @@
import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";
-import { FREEFORM_WHITELIST } from "./freeformWhitelist";
-import type { CanvasSuggestion } from "./templateSchemas";
+import type { CanvasTemplateSummary } from "./templateSchemas";
-export interface CanvasTemplate {
- id: string;
- name: string;
- description: string;
- builtIn: boolean;
- /** Starter chips shown in an empty chat (label + the prompt it inserts). */
- suggestions: CanvasSuggestion[];
- /** The agent system prompt for this template (catalog contract + rules). */
- systemPrompt: string;
-}
-
-// Freeform React canvas (Q1/Q12): the agent writes a real single-file React app
-// that runs in a sandboxed iframe, instead of emitting json-render patches. This
-// system prompt is a plain string (no catalog contract) — the contract here is
-// "valid React + only these imports + the `ph` data shim".
-const FREEFORM_WHITELIST_NAMES = FREEFORM_WHITELIST.map((e) => e.name).join(
- ", ",
-);
-
-// The shared React-tier contract: output format, the import whitelist, and the
-// `ph` data shim. Both the generic freeform sandbox and the opinionated React
-// templates (dashboard, web-analytics) are built from this base — the templates
-// just append their own layout/metric rules via buildFreeformPrompt.
-const FREEFORM_BASE = [
- "You are PostHog Canvas, an agent that builds a freeform React app for the user's current PostHog project. The app runs in a sandboxed iframe.",
- "",
- "OUTPUT FORMAT — every turn:",
- "- Write a SHORT sentence of prose, then the COMPLETE app as ONE fenced code block tagged tsx (```tsx ... ```).",
- "- FULL-FILE REWRITE: always output the entire file, even for a tiny change. Never output a partial file, a diff, or multiple code blocks.",
- "- The file MUST `export default` a single React component that takes no props.",
- "",
- "IMPORTS — allowed packages ONLY:",
- `- You may import ONLY from: ${FREEFORM_WHITELIST_NAMES}.`,
- '- Import React hooks from "react" (e.g. `import React, { useState, useEffect } from "react"`). Do NOT import react-dom or call createRoot — the host mounts your default export.',
- '- Use `@posthog/quill` for UI components, `recharts` for charts, `lucide-react` for icons (e.g. `import { Calendar, RefreshCw } from "lucide-react"`), and `dayjs` for dates.',
- "- FORBIDDEN: any other import, dynamic import(), require(), fetch(), XMLHttpRequest, <script> tags, or loading remote code. These are rejected and the canvas will fail to save.",
- "",
- "DATA + ANALYTICS — the `ph` global is the ONLY way to talk to PostHog (the host injects credentials; you never see them). Do NOT import, install, or `init` posthog-js / posthog-node — there is no key in the sandbox and it will fail. Use `ph` directly:",
- "DATA HIERARCHY — back EVERY metric with a SAVED, validated PostHog insight, loaded by reference. Only drop to raw SQL when no insight can express it:",
- " 1. PREFERRED — SAVE an insight, then LOAD it by reference. Use the PostHog MCP tools (mcp__posthog__*) to create/save an insight that computes the metric with an INSIGHT QUERY TYPE (TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, or the web-analytics kinds WebOverviewQuery / WebStatsTableQuery — NOT raw SQL). Confirm its numbers, note the `short_id` the MCP tool returns, and render it with `await ph.loadInsight(shortId, { dateRange })`. These are PROVEN queries — the numbers match the PostHog UI exactly (sessionization, unique users, breakdowns, math, bounce rate). NEVER fabricate a query or guess event/property names — discover and SAVE them via MCP first.",
- ' 2. LAST RESORT — HogQL/SQL, only when no insight query type can express the metric. Prefer a SAVED SQL insight loaded with `ph.loadInsight` (note: a SQL insight may not follow the date picker — its window lives inside the SQL). The inline `ph.query("SELECT …")` escape hatch is the very last option; you then own the SQL and its date window.',
- "- `await ph.loadInsight(shortId, { dateRange })` resolves to `{ columns, results }` — the insight's STORED result, read from the insights endpoint (NOT a fresh query run). `shortId` is the saved insight's short id; `dateRange` (optional) is `{ date_from, date_to }` from your date picker. THE RESULT SHAPE DIFFERS by insight type, read it correctly or every value comes back 0:",
- ' • A trends-style insight (Trends/Funnels/Retention/Paths/web-analytics) → `results` is an array of SERIES OBJECTS (NOT rows). Each series = `{ data: number[] (per interval), labels: string[], days: string[] (ISO), count: number (sum), aggregated_value: number (single-value total), label, compare_label?: "current"|"previous" }`. So a KPI total = `results[0].count` (or `.aggregated_value`); a line chart = `results[0].data` over `results[0].days`. With a compare period, find the prior series by `compare_label === "previous"` (do NOT assume index order). `columns` is empty here — ignore it.',
- " • A SQL insight → `{ columns: string[], results: rows[][] }` — each row an array of cell values in `columns` order; read `results[rowIndex][colIndex]`.",
- '- SQL VARIABLES — a saved SQL insight whose HogQL contains `{variables.something}` placeholders is driven per call: `await ph.loadInsight(shortId, { variables: { product: "surveys", month: "2026-07-01" } })`, keyed by the variable\'s code name (NOT its uuid). This is how ONE saved insight fills a whole board — the same per-product insight loaded once per product. Read the insight\'s variable code names off its query via the MCP tools (`insight-get`) first; the host REJECTS a variable the insight does not use rather than quietly falling back to its saved value, so pass only what that insight actually references.',
- " • A SQL variable is a SEPARATE axis from the date picker: if an insight takes its month/day from a `{variables.…}` placeholder, drive it through `variables` — `dateRange` will NEVER reach it. Check which of the two an insight uses before wiring the picker to it.",
- " • Reads are cached per (insight, dateRange, variables), so N products means N loads. Prefer ONE insight that returns every product as rows over the same insight loaded N times — fewer round trips, and you slice it client-side.",
- '- `await ph.query(arg)` is the SECONDARY/escape path (ad-hoc, NOT saved) — reach for it only when you genuinely cannot save an insight. `arg` is a typed query node `ph.query({ kind: "TrendsQuery", series: [...], dateRange: {...} })` (series-object result, as above) or an inline HogQL string `ph.query("SELECT …")` (rows result, as above). Same result shapes as ph.loadInsight; prefer ph.loadInsight.',
- '- `ph.capture(event, properties?, distinctId?)` sends an analytics event to the project (fire-and-forget; returns a promise). Use this for click/interaction tracking — e.g. `ph.capture("button_clicked", { label })`. NEVER roll your own posthog client or fetch the capture endpoint yourself.',
- '- `ph.openExternal(url)` asks the host to open an absolute `https://posthog.com` (or `*.posthog.com`) URL — anything else is blocked, so do NOT link to other sites. Call it only from a user interaction (e.g. a click handler); the host ignores opens while the canvas is not focused, so calling it on load/in effects does nothing. Sandboxed `target="_blank"` navigation is intentionally blocked.',
- "- Session replay, $session_id, and person attribution are handled automatically by the host's posthog-js running in the sandbox — you do NOT set session ids or initialise recording; just call ph.capture for custom events.",
- "- Load data inside `useEffect` with `useState`; show a loading state first, then render. Handle the empty/error case. Keep result sets small — aggregate in the query, don't fetch raw event dumps.",
-];
-
-const FREEFORM_STYLE = [
- "",
- "STYLE:",
- "- STYLING — use Tailwind utility classes (the sandbox loads Tailwind) and `@posthog/quill` components for ALL styling. Do NOT reach for inline `style={{…}}` for anything a class can express (color, spacing, sizing, layout, borders, radius, typography) — agents over-use `style` and it bypasses the theme. Reserve `style` ONLY for a genuinely dynamic runtime value that no utility can name (e.g. a width/height computed at runtime). For a fixed size use an arbitrary-value utility instead (e.g. `h-[280px] w-full`), not `style`. A `<style>` block is fine for keyframes or complex selectors. Write real, specific copy — never lorem ipsum.",
- '- SPECIAL CHARACTERS: write Unicode glyphs (curly quotes “ ” ‘ ’, ellipsis …, middot ·, en/em dashes – —, arrows, emoji) as the LITERAL character directly in the source. Do NOT use `\\uXXXX` escape sequences in JSX text or attribute values — `\\u` escapes are only decoded inside JavaScript string/template literals, so in JSX text they render verbatim (e.g. `\\u201c` shows up as the text `u201c`). If you must use an escape, wrap it in an expression container: `{"\\u2026"}`.',
- "- Build ANYTHING the user asks: dashboards, tools, forms, reports, small apps. Keep it self-contained in the one file.",
- "",
- "THEME (light / dark) — the canvas renders in the user's current PostHog theme, and that can switch at runtime. The host puts a `.dark` class on the document root in dark mode (exactly like the main app), so your styles MUST adapt to both:",
- "- Prefer `@posthog/quill` components and the design tokens — they already flip between light and dark automatically, so you get correct theming for free.",
- "- COLOR ONLY from Quill's design-token Tailwind utilities — never an invented or hardcoded color. The sandbox maps these (each tracks light/dark automatically): surfaces `bg-background` `bg-card` `bg-muted` `bg-primary` `bg-success` `bg-warning` `bg-info` `bg-destructive`; neutral text/icons `text-foreground` `text-muted-foreground` `text-card-foreground`; readable status accents `text-success-foreground` `text-warning-foreground` `text-info-foreground` `text-destructive-foreground`; borders/rings `border-border` `ring-ring`; state fills `bg-fill-hover` `bg-fill-selected`.",
- "- STATUS TOKENS (success / warning / info / destructive) INVERT the usual convention: the BARE token is a PALE BACKGROUND fill, and `-foreground` is the STRONG, READABLE color. So colored TEXT or ICONS ALWAYS use the `-foreground` utility — `text-success-foreground` for an up delta, `text-destructive-foreground` for a down delta. NEVER bare `text-success` / `text-destructive` for text: that is the pale fill and is nearly invisible (this is the #1 mistake). A filled pill/badge uses the pair `bg-success text-success-foreground` (fill + its readable content). Never `bg-*-foreground`.",
- '- PRIMARY follows the NORMAL convention instead: `bg-primary` is the strong brand color with `text-primary-foreground` (white) on it; `text-primary` is the brand color used as text. (Prefer the Quill `Badge` component for deltas — `variant="success"` / `"destructive"` — so you don\'t hand-pick any of this.)',
- "- DO NOT use `bg-secondary` / `text-secondary` / `bg-accent` / `bg-popover` — those tokens are NOT defined in the canvas and render transparent. Stick to the tokens listed above.",
- "- Only drop to a CSS variable (`var(--primary)`, `var(--border)`, `var(--muted-foreground)`) where a className can't reach — i.e. a prop that takes a raw color string (recharts `stroke`/`fill`), never in `className` or `style` where a utility works.",
- '- NEVER hardcode a light-only color (e.g. `#fff`, `#111`, `color: black`, `background: white`) — it looks broken in the other theme. If you must special-case dark mode, use the `dark:` Tailwind variant (e.g. `className="bg-card dark:bg-muted"`), which is wired to the `.dark` class.',
- '- recharts strokes/fills must use the token CSS variables too (e.g. `stroke="var(--primary)"`, grid/axis in `var(--border)` / `var(--muted-foreground)`) so charts adapt as well.',
- "",
- "Do NOT write files, edit code on disk, or run shell commands. Your entire app is the single fenced tsx block in your reply.",
-];
-
-// Build a React-tier system prompt: the shared base + the `ph` shim, optional
-// opinionated rules (layout, metrics, date control), then the closing style
-// section. With no extra rules this is the generic "anything goes" sandbox.
-function buildFreeformPrompt(extraRules: string[] = []): string {
- return [
- ...FREEFORM_BASE,
- ...(extraRules.length > 0 ? ["", ...extraRules] : []),
- ...FREEFORM_STYLE,
- ].join("\n");
-}
-
-// Use the real PostHog design system. The sandbox iframe loads Quill's compiled
-// stylesheet + design tokens (see FREEFORM_QUILL_CSS_URLS) AND the Tailwind CDN,
-// so Quill components render fully styled and Tailwind utilities work. This is a
-// HARD requirement for the data templates (dashboard / web-analytics): every UI
-// element is a Quill component. Verified against @posthog/quill 0.3.0-beta.17.
-const FREEFORM_QUILL_RULES = [
- "MANDATORY DESIGN SYSTEM — this canvas is a PostHog data board, so it MUST be built ENTIRELY from `@posthog/quill` components. Quill is loaded and themed in the sandbox; use it for EVERYTHING. This is not optional and there is no fallback.",
- "BANNED — never emit a native HTML control or a styled `<div>` standing in for a component. There is a Quill component for each; ALWAYS use it:",
- "- dropdown / picker / range selector → Quill `Select` — NEVER a native `<select>`.",
- "- button or anything clickable → Quill `Button` — NEVER a native `<button>`, an `<a>` styled as a button, or a clickable `<div>`.",
- "- text field → `Input` (or `Textarea`); checkbox → `Checkbox`; field label → `Label`.",
- "- table → `Table`; card / panel → `Card`; badge or pill → `Badge`; title → `Heading`; body/label text → `Text`.",
- "The ONLY non-Quill tags allowed are plain layout `<div>`s (for flex/grid arrangement) and `recharts` elements for charts. If you reach for any other native UI element, STOP and use the Quill component instead.",
- "BASE UI — Quill components are built on Base UI (reference: https://base-ui.com/llms.txt). Compose them the Base UI way: use the compound parts (e.g. `Select` + `SelectTrigger` / `SelectContent` / `SelectItem`), controlled `value` + `onValueChange`, and the `render` prop to swap a part's underlying element (e.g. `<PopoverTrigger render={<Button … />} />`) instead of wrapping or replacing it. Follow Base UI's state + accessibility conventions; don't fight them.",
- "STYLING — Quill components are ALREADY themed: do NOT add Tailwind classes or inline `style` to a Quill component to restyle it (color, border, padding, font-size, radius). Use its built-in `variant` / `size` / props instead. Add a `className` to a Quill component ONLY when absolutely necessary, and keep it to layout/spacing (`flex-1`, `mt-2`) — never restyling. Put layout utilities (`flex`, `grid`, `gap-4`, `p-4`) on your OWN plain `<div>` wrappers, not on Quill components. NEVER hardcode hex — for a rare custom color use a token utility (`text-muted-foreground`, `bg-card`) or a CSS variable (`var(--primary)`) where a className can't reach (e.g. a recharts `stroke`/`fill` prop).",
- "VERIFIED Quill components + usage (import the names you use from `@posthog/quill`):",
- "- `Heading` (`size`: base | sm | lg | xl | 2xl) for titles; `Text` for body/labels.",
- "- `Card` (`size`: default | sm) with `CardHeader` + `CardTitle` + `CardContent` (+ `CardDescription`, `CardFooter`) — one per KPI / chart / table panel.",
- "- `Badge` (`variant`: default | success | destructive | info | warning) — ideal for KPI deltas (success = up, destructive = down).",
- '- `Button` for EVERY button. DEFAULT to `variant="outline"`; use `variant="primary"` for the ONE main action only. (`variant`: primary | default | outline | destructive | link; `size`: default | sm | xs | icon).',
- "- `Select` (Base UI compound) for EVERY dropdown — exact pattern: `<Select value={range} onValueChange={setRange}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value='30d'>Last 30 days</SelectItem></SelectContent></Select>`. The trigger is already a styled Quill button — do not wrap or replace it.",
- "- `Table` with `TableHeader` > `TableRow` > `TableHead`, then `TableBody` > `TableRow` > `TableCell` — for every tabular breakdown.",
- "- `Separator` for dividers; `Input` / `Textarea` / `Checkbox` / `Label` for any form control.",
- "LOADING / REFRESHING — every data point must render a skeleton placeholder in its own `Card` while its data is loading (initial load AND refetch), then swap to the value. Use `SkeletonText` (props: `lines` = how many text lines the real value occupies, plus the SAME tailwind text-size `className` as the value so the skeleton matches its size) for text/number values, and `Skeleton` for block/chart placeholders. Never show a blank or a jumping layout — the skeleton holds the space. Worked example:",
- ' `<Card>{isLoading ? <SkeletonText lines={1} className="text-2xl" /> : <Heading size="2xl">{value}</Heading>}</Card>` — note the bare `Card` (no restyling) and the SkeletonText `className` matching the value\'s text size.',
- "Drive `isLoading` per data point (or per board) off your `ph.query` calls; it MUST become true again during a refresh so the skeletons reappear while data refetches.",
- 'CHARTS — use `recharts`, themed with the Quill CSS variables so they match (e.g. line `stroke="var(--primary)"`, axis/grid in `var(--border)` / `var(--muted-foreground)`). Never hardcode chart colors.',
-];
-
-// In-app date control (Path A): freeform canvases own their OWN window — there is
-// no host date picker driving them — so a data board must render its own range
-// control and re-query when it changes. Shared by the dashboard + web-analytics
-// React templates; correctness rules mirror the json-render tier's window logic.
-const FREEFORM_DATE_CONTROL_RULES = [
- "DATE WINDOW — your app owns the date control. Render Quill's `DateTimePicker` (the real PostHog date picker) — NEVER a custom Select, a native `<input type=date>`, or a hand-rolled control.",
- '- Wire it up exactly like this: `import { Button, DateTimePicker, Popover, PopoverContent, PopoverTrigger, quickRanges } from "@posthog/quill"`. Seed window state from a quick range: `const def = quickRanges.find((r) => r.name === "Last 30 days") ?? quickRanges[0]; const [win, setWin] = useState({ start: def.rangeSetter(new Date()), end: new Date(), range: def });`. Render a `Popover` whose `PopoverTrigger` is a Quill `Button` (label `{win.range.name}`), with `<DateTimePicker value={win} onApply={(v) => { setWin(v); setOpen(false); }} onCancel={() => setOpen(false)} />` inside `<PopoverContent className="w-auto p-0">`. Do NOT import the `DateTimeValue` TYPE — the sandbox strips types at runtime; use the values only.',
- "- Do NOT pass the `compact` prop and do NOT constrain the picker's width: `DateTimePicker` self-adjusts (it media-queries its own window and drops to the single-calendar layout in the narrow canvas pane). Forcing `compact` or a fixed width is unnecessary and fights its responsiveness.",
- '- ALWAYS give `PopoverContent` exactly `className="w-auto p-0"` — its default fixed width + padding squeeze the self-sizing picker and clip the quick-range tabs. That is the ONLY className it may have; add NOTHING (no `className`, `style`, or width) to `DateTimePicker` or `PopoverTrigger`. The picker is fully styled and self-sizing — let it be. The ONLY props on `DateTimePicker` are `value` / `onApply` / `onCancel`.',
- "- Drive your data `useEffect` off `win` and re-run EVERY query when it changes.",
- "- PREFERRED — pass the window to `ph.loadInsight` as `dateRange`: `ph.loadInsight(shortId, { dateRange: { date_from: win.start.toISOString(), date_to: win.end.toISOString() } })`. The saved insight re-scopes to your window — you write NO time SQL. (A SAVED SQL insight may ignore this and use its own window; that's a reason to express metrics as insight query types, not SQL.)",
- "- If you fall back to an ad-hoc typed node, feed the window into its `dateRange` the same way: `dateRange: { date_from: win.start.toISOString(), date_to: win.end.toISOString() }`. The query runner handles timezone/bucketing/half-open — no time SQL.",
- "- ESCAPE HATCH (inline HogQL only) — NEVER bake a window with `now()` or a hardcoded `INTERVAL`. Compute `fromUnix = Math.floor(win.start.getTime() / 1000)` and `toUnix` likewise, then write HALF-OPEN `timestamp >= toDateTime(fromUnix) AND timestamp < toDateTime(toUnix)` (integer unix = unambiguous UTC; never an inclusive `<= to`, and never a bare 'YYYY-MM-DD' string which shifts by the project timezone). For a prior-period comparison use the equal-length window immediately before (`prevFrom = from - (to - from)`, `prevTo = from`); bucket with `toStartOfDay` / `toStartOfHour` on the same window.",
-];
-
-// Opinionated React rules for the "dashboard" template (a live, data-driven board).
-const FREEFORM_DASHBOARD_RULES = [
- "This is a LIVE, DATA-DRIVEN dashboard built from the user's real PostHog data — not a static mockup.",
- 'Open with a `Heading` title, then a responsive grid (Tailwind `className="grid gap-4"`) of Quill `Card` KPIs, then trend charts.',
- "Each metric is a SAVED insight loaded via `ph.loadInsight(shortId, { dateRange })` — save the insight (an insight query type like TrendsQuery, numbers match the PostHog UI) via the MCP tools and reference it by `short_id`. Only drop to inline HogQL when no insight kind covers the metric.",
- "Visualize trends with `recharts` (LineChart for time series, BarChart for discrete categories) rather than dumping tables; show a compact `Card` KPI for single-number metrics and a `Badge` delta.",
- "Each card/chart shows a `SkeletonText`/`Skeleton` placeholder (see LOADING) while loading or refreshing, then the value, and handle empty/error.",
- ...FREEFORM_QUILL_RULES,
- ...FREEFORM_DATE_CONTROL_RULES,
-];
-
-// Opinionated React rules for the "web-analytics" template — a PostHog-style web
-// analytics board, mirroring the json-render web-analytics layout in React.
-const FREEFORM_WEB_ANALYTICS_RULES = [
- 'Build a PostHog-style WEB ANALYTICS board from the project\'s real data. Title it (e.g. "Web analytics") with an `<h1>` or Quill heading.',
- "LAYOUT, top to bottom: (1) a KPI row of cards — Visitors, Page views, Sessions, Session duration, Bounce rate — each with a delta vs the prior equal-length period. (2) A unique-visitors `recharts` LineChart over time with a second line for the prior period. (3) Top paths and traffic-source/channel breakdowns as tables. (4) Devices and geography tables (prefix countries with their flag emoji). Add retention / active-hours if the data supports it.",
- "USE PostHog's web-analytics query KINDS, not hand-rolled SQL — the product computes bounce rate, sessionization, channel attribution and unique-visitor counts in ways raw HogQL will subtly get wrong. In the MCP tools, SAVE insights built on the web-analytics kinds (e.g. `WebOverviewQuery`, `WebStatsTableQuery`) and load each by `short_id` with `ph.loadInsight(shortId, { dateRange })` (the picker's window). Only drop to inline HogQL for a metric no web-analytics kind covers.",
- "Format raw numeric values yourself for display (e.g. show 236K from 236000). Keep result sets small.",
- ...FREEFORM_QUILL_RULES,
- ...FREEFORM_DATE_CONTROL_RULES,
-];
-
-const FREEFORM_SYSTEM_PROMPT = buildFreeformPrompt();
-
-// System prompts keyed by templateId for the canvas gen path; the generic
-// freeform sandbox is the fallback. The create-picker only offers "freeform"
-// today, but legacy canvases carrying the older "dashboard" / "web-analytics"
-// templateIds still resolve their richer layout prompts here.
-const FREEFORM_SYSTEM_PROMPTS: Record<string, string> = {
- [FREEFORM_TEMPLATE_ID]: FREEFORM_SYSTEM_PROMPT,
- dashboard: buildFreeformPrompt(FREEFORM_DASHBOARD_RULES),
- "web-analytics": buildFreeformPrompt(FREEFORM_WEB_ANALYTICS_RULES),
-};
-
-// The React-tier prompt for a templateId, falling back to the generic sandbox.
-export function freeformSystemPromptFor(id: string | undefined): string {
- return (
- (id ? FREEFORM_SYSTEM_PROMPTS[id] : undefined) ??
- FREEFORM_SYSTEM_PROMPTS[FREEFORM_TEMPLATE_ID]
- );
-}
-
-const FREEFORM_SUGGESTIONS: CanvasSuggestion[] = [
+const FREEFORM_SUGGESTIONS = [
{
label: "Signups chart",
prompt:
@@ -191,18 +19,15 @@ const FREEFORM_SUGGESTIONS: CanvasSuggestion[] = [
},
];
-const FREEFORM_TEMPLATE: CanvasTemplate = {
+const FREEFORM_TEMPLATE: CanvasTemplateSummary = {
id: FREEFORM_TEMPLATE_ID,
name: "Freeform (React)",
description:
- "Describe anything — the agent writes a real React app that runs in a sandbox and can be shared.",
+ "Describe anything. The agent writes a React app that runs in a sandbox and can be shared.",
builtIn: true,
suggestions: FREEFORM_SUGGESTIONS,
- systemPrompt: FREEFORM_SYSTEM_PROMPT,
};
-/** Built-in templates offered by the create-picker. Only the freeform (React)
- * template exists today; more can be appended later. */
-export const BUILT_IN_TEMPLATES: CanvasTemplate[] = [FREEFORM_TEMPLATE];
+export const BUILT_IN_TEMPLATES: CanvasTemplateSummary[] = [FREEFORM_TEMPLATE];
export const DEFAULT_TEMPLATE_ID = FREEFORM_TEMPLATE_ID;
diff --git a/products/desktop/packages/core/src/canvas/canvasTemplatesService.ts b/products/desktop/packages/core/src/canvas/canvasTemplatesService.ts
index 1e248dbb7c3c..7843b267525b 100644
--- a/products/desktop/packages/core/src/canvas/canvasTemplatesService.ts
+++ b/products/desktop/packages/core/src/canvas/canvasTemplatesService.ts
@@ -1,37 +1,11 @@
import { injectable } from "inversify";
-import {
- BUILT_IN_TEMPLATES,
- type CanvasTemplate,
- freeformSystemPromptFor,
-} from "./canvasTemplates";
+import { BUILT_IN_TEMPLATES } from "./canvasTemplates";
import type { ICanvasTemplatesService } from "./services";
import type { CanvasTemplateSummary } from "./templateSchemas";
-// Owns the canvas templates — the per-template agent context (system prompt)
-// that anchors how the gen-UI agent builds. Built-ins are seeded here; the
-// registry is a Map so user-defined templates can be added later (the store
-// would back them; built-ins stay read-only). Host-agnostic (pure prompt
-// strings), so it lives in @posthog/core and binds via canvasCoreModule.
@injectable()
export class CanvasTemplatesService implements ICanvasTemplatesService {
- private readonly templates = new Map<string, CanvasTemplate>(
- BUILT_IN_TEMPLATES.map((t) => [t.id, t]),
- );
-
list(): CanvasTemplateSummary[] {
- return [...this.templates.values()].map(
- ({ systemPrompt: _p, ...rest }) => ({
- ...rest,
- }),
- );
- }
-
- get(id: string): CanvasTemplate | undefined {
- return this.templates.get(id);
- }
-
- /** The freeform (React) prompt for a template, falling back to the generic sandbox. */
- freeformSystemPromptFor(id: string | undefined): string {
- return freeformSystemPromptFor(id);
+ return BUILT_IN_TEMPLATES;
}
}
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index d0425225e79d..0a47a10f761e 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -188,15 +188,14 @@ export function limitCanvasCommentHighlights(
// host -> iframe
export const hostToCanvasMessageSchema = z.discriminatedUnion("type", [
- // First frame: hand the iframe its source + the run mode. The iframe does not
- // fetch its own code; the host injects it so the host controls what runs.
+ // First frame: hand the iframe its source. The iframe does not fetch its own
+ // code; the host injects it so the host controls what runs. Only the srcDoc
+ // authoring sandbox takes an `init` — a published canvas is a built artifact
+ // that boots itself and only receives the frames below.
z.object({
channel: z.literal(CANVAS_CHANNEL),
type: z.literal("init"),
code: z.string(),
- // "edit" = author in-app (full-API shim, CDN packages, open egress).
- // "view" = published/shared (frozen named queries, closed egress).
- mode: z.enum(["edit", "view"]),
// Present when analytics/replay should run in the iframe. Absent = no capture.
analytics: canvasAnalyticsConfigSchema.optional(),
// The appearance to render in. Carried on `init` so the first render is
diff --git a/products/desktop/packages/core/src/canvas/freeformStarter.ts b/products/desktop/packages/core/src/canvas/freeformStarter.ts
deleted file mode 100644
index 6570e1a5b2a2..000000000000
--- a/products/desktop/packages/core/src/canvas/freeformStarter.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-// A known-good STARTER scaffold for a freeform (React) canvas. Instead of
-// authoring the whole single-file app from scratch every time, the generation
-// path seeds this working baseline as the agent's starting point (on by default;
-// opt out via the generate bar toggle). It already wires the pieces that are
-// easy to get wrong — the date picker (self-sizing, no `compact`), theme-aware
-// tokens, per-card loading skeletons, and reading a TYPED-NODE result correctly
-// — so the agent edits a compiling app instead of re-deriving boilerplate.
-//
-// Stored as a string (like the prompt contracts) — it is injected into the
-// generation prompt, not compiled here. It imports ONLY whitelisted packages
-// (see freeformWhitelist) and uses the runtime `ph` global for data. The sample
-// metric is "all events" (math:total, event:null) so it renders on ANY project;
-// the agent replaces it with the user's real metrics.
-export const FREEFORM_STARTER_CODE = `import React, { useEffect, useState } from "react";
-import {
- Button,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- DateTimePicker,
- Heading,
- Popover,
- PopoverContent,
- PopoverTrigger,
- quickRanges,
- SkeletonText,
-} from "@posthog/quill";
-import { RefreshCw } from "lucide-react";
-import {
- CartesianGrid,
- Line,
- LineChart,
- ResponsiveContainer,
- Tooltip,
- XAxis,
- YAxis,
-} from "recharts";
-
-// Starter scaffold. Replace the sample "total events" metric and the layout
-// with what the user asked for — but KEEP the wiring below (date picker, theme
-// tokens, skeletons, typed-node result reading), it is already correct.
-export default function Canvas() {
- const def =
- quickRanges.find((r) => r.name === "Last 30 days") ?? quickRanges[0];
- const [win, setWin] = useState({
- start: def.rangeSetter(new Date()),
- end: new Date(),
- range: def,
- });
- const [open, setOpen] = useState(false);
-
- const [loading, setLoading] = useState(true);
- const [total, setTotal] = useState(0);
- const [series, setSeries] = useState([]);
- // Refresh plumbing: bump this nonce to re-run the data effect on demand. The
- // effect already re-runs when the date window changes; the Refresh button just
- // forces a re-run with the same window.
- const [nonce, setNonce] = useState(0);
-
- useEffect(() => {
- let cancelled = false;
- setLoading(true);
- // PREFERRED data path: a TYPED query node, computed by PostHog's own runner
- // so the numbers match the UI exactly. \`event: null\` = all events (works on
- // any project). Swap in the real metric — ideally a SAVED insight loaded
- // with \`ph.loadInsight(shortId, { dateRange })\`.
- ph.query({
- kind: "TrendsQuery",
- series: [
- { kind: "EventsNode", event: null, name: "All events", math: "total" },
- ],
- dateRange: {
- date_from: win.start.toISOString(),
- date_to: win.end.toISOString(),
- },
- })
- .then((res) => {
- if (cancelled) return;
- // Typed-node result: \`results\` is an array of SERIES OBJECTS, not rows.
- const s = res.results[0] ?? {};
- setTotal(s.count ?? 0);
- setSeries(
- (s.days ?? []).map((day, i) => ({ day, value: s.data?.[i] ?? 0 })),
- );
- setLoading(false);
- })
- .catch(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [win, nonce]);
-
- return (
- <div className="flex flex-col gap-4 p-6">
- <div className="flex items-center justify-between">
- <Heading size="xl" className="mb-4">Canvas</Heading>
- <div className="flex items-center gap-2">
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- render={<Button variant="outline">{win.range.name}</Button>}
- />
- {/* PopoverContent needs w-auto p-0 so its default fixed width +
- padding don't squeeze the self-sizing picker (which clips the
- quick-range tabs). No other styles on it or the picker. */}
- <PopoverContent className="w-auto p-0">
- <DateTimePicker
- value={win}
- onApply={(v) => {
- setWin(v);
- setOpen(false);
- }}
- onCancel={() => setOpen(false)}
- />
- </PopoverContent>
- </Popover>
- <Button
- variant="outline"
- disabled={loading}
- onClick={() => setNonce((n) => n + 1)}
- >
- <RefreshCw size={14} className={loading ? "animate-spin" : undefined} />
- Refresh
- </Button>
- </div>
- </div>
-
- <div className="grid gap-4 md:grid-cols-3">
- <Card size="sm">
- <CardHeader>
- <CardTitle>Total events</CardTitle>
- </CardHeader>
- <CardContent>
- {loading ? (
- <SkeletonText lines={1} className="text-3xl" />
- ) : (
- <Heading size="2xl">{total.toLocaleString()}</Heading>
- )}
- </CardContent>
- </Card>
- </div>
-
- <Card size="sm">
- <CardHeader>
- <CardTitle>Events over time</CardTitle>
- </CardHeader>
- <CardContent>
- {loading ? (
- <SkeletonText lines={6} />
- ) : (
- <div className="h-[280px] w-full">
- <ResponsiveContainer>
- <LineChart data={series}>
- <CartesianGrid
- stroke="var(--border)"
- strokeDasharray="3 3"
- />
- <XAxis
- dataKey="day"
- stroke="var(--muted-foreground)"
- tick={{ fontSize: 12 }}
- />
- <YAxis
- stroke="var(--muted-foreground)"
- tick={{ fontSize: 12 }}
- />
- <Tooltip />
- <Line
- type="monotone"
- dataKey="value"
- stroke="var(--primary)"
- dot={false}
- strokeWidth={2}
- />
- </LineChart>
- </ResponsiveContainer>
- </div>
- )}
- </CardContent>
- </Card>
- </div>
- );
-}
-`;
diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.test.ts b/products/desktop/packages/core/src/canvas/generationPrompt.test.ts
index d60d6daf2ae9..e1205666e5e9 100644
--- a/products/desktop/packages/core/src/canvas/generationPrompt.test.ts
+++ b/products/desktop/packages/core/src/canvas/generationPrompt.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";
import { buildCanvasGenerationPrompt } from "./generationPrompt";
describe("buildCanvasGenerationPrompt", () => {
@@ -6,101 +7,28 @@ describe("buildCanvasGenerationPrompt", () => {
dashboardId: "dash-1",
name: "Signups",
channelName: "growth",
- channelId: "chan-1",
instruction: "add a retention chart",
- isEdit: false,
};
- it("leads with the user's instruction and wraps the routing in the collapsible tag", () => {
+ it("leads with the request and routes the target through the canvas skill", () => {
const prompt = buildCanvasGenerationPrompt(base);
- // The visible message is the bare instruction; the boilerplate lives in the
- // tag the conversation UI collapses (extractCanvasInstructions).
expect(prompt.startsWith("add a retention chart\n\n")).toBe(true);
expect(prompt).toContain("<canvas_generation_instructions>");
- expect(prompt).toContain("</canvas_generation_instructions>");
- });
-
- it("routes into the bundled canvas skills with the target canvas preselected", () => {
- const prompt = buildCanvasGenerationPrompt(base);
expect(prompt).toContain("`building-canvases` skill");
expect(prompt).toContain('canvas id: "dash-1"');
- // Guarded publish loop via the typed canvas tools — not a local file, not a
- // code reply, and never an unguarded overwrite.
- expect(prompt).toContain("canvas-source-retrieve");
- expect(prompt).toContain("canvas-publish-create");
- expect(prompt).toContain("expected_current_version_id");
- // The authoring contract itself lives in the skills, not the prompt.
- expect(prompt).not.toContain("OUTPUT FORMAT");
- expect(prompt).not.toContain("IMPORTS");
- });
-
- it.each([
- [false, "Build the canvas"],
- [true, "Edit the canvas"],
- ])("isEdit=%s picks the right header", (isEdit, header) => {
- expect(buildCanvasGenerationPrompt({ ...base, isEdit })).toContain(header);
+ expect(prompt).not.toContain("canvas-source-retrieve");
+ expect(prompt).not.toContain("canvas-publish-create");
});
- // Guards the draft-by-default contract: an edit to a live canvas must stage
- // a draft the user promotes, never publish straight to the head.
+ // The pattern hint exists for the legacy template ids the skill defines shapes
+ // for. Every canvas created today is `freeform`, which names no shape — passing
+ // it through would put "requested pattern" on every generation task.
it.each([
- [false, "`canvas-publish-create`", "`canvas-draft-create`"],
- [true, "`canvas-draft-create`", "`canvas-publish-create`"],
- ])("isEdit=%s saves with the right tool", (isEdit, expected, absent) => {
- const prompt = buildCanvasGenerationPrompt({ ...base, isEdit });
- expect(prompt).toContain(expected);
- expect(prompt).not.toContain(absent);
- if (isEdit) {
- expect(prompt).toContain("promotes it to live");
- }
- });
-
- it.each([
- ["first build with starter", false, true, true],
- ["first build without starter", false, false, false],
- ["edit ignores starter", true, true, false],
- ])("%s", (_name, isEdit, useStarter, expectStarter) => {
- const prompt = buildCanvasGenerationPrompt({ ...base, isEdit, useStarter });
- expect(prompt.includes("starter scaffold")).toBe(expectStarter);
- });
-
- it("adds a layout hint for legacy template ids only", () => {
- expect(
- buildCanvasGenerationPrompt({ ...base, templateId: "web-analytics" }),
- ).toContain("web analytics board");
- expect(buildCanvasGenerationPrompt(base)).not.toContain("Template:");
- });
-
- describe("without a pre-created target (channel composer)", () => {
- const composer = {
- channelName: "growth",
- channelId: "chan-1",
- instruction: "make a signup dashboard",
- isEdit: false,
- };
-
- it("creates without exposing stored canvas metadata to the agent", () => {
- const prompt = buildCanvasGenerationPrompt(composer);
- expect(prompt).toContain('Build a canvas in the channel "growth"');
- expect(prompt).not.toContain("canvas id:");
- expect(prompt).not.toContain("do NOT create another");
- expect(prompt).not.toContain("`canvas-list`");
- expect(prompt).toContain("`canvas-create`");
- expect(prompt).toContain('never "Untitled canvas"');
- });
-
- it("phrases the starter pointer for the create case only", () => {
- const prompt = buildCanvasGenerationPrompt({
- ...composer,
- useStarter: true,
- });
- // The agent may resolve to an existing built canvas, where the scaffold
- // doesn't apply — the pointer is scoped to first builds.
- expect(prompt).toContain("For a first build");
- expect(prompt).toContain("starter scaffold");
- expect(buildCanvasGenerationPrompt(composer)).not.toContain(
- "starter scaffold",
- );
- });
+ ["web-analytics", true],
+ [FREEFORM_TEMPLATE_ID, false],
+ ])("templateId=%s hints a pattern: %s", (templateId, hinted) => {
+ const prompt = buildCanvasGenerationPrompt({ ...base, templateId });
+ expect(prompt.includes("requested pattern:")).toBe(hinted);
+ expect(prompt).not.toContain("WebOverviewQuery");
});
});
diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.ts b/products/desktop/packages/core/src/canvas/generationPrompt.ts
index e980ebb1698f..32a0d2e599f6 100644
--- a/products/desktop/packages/core/src/canvas/generationPrompt.ts
+++ b/products/desktop/packages/core/src/canvas/generationPrompt.ts
@@ -1,109 +1,29 @@
-// Builds the prompt for a canvas generation/edit task. The authoring contract
-// (imports, the `ph` data SDK, Quill/style rules, publish workflow) lives in
-// the bundled canvas skills, which are installed in every local and cloud task
-// — so the prompt only routes the agent into `building-canvases` and supplies
-// the target-canvas context the skill needs. The standing instructions are
-// wrapped in <canvas_generation_instructions> so the conversation UI collapses
-// them into a single clickable tag (see extractCanvasInstructions).
-
import { escapeXmlAttr } from "@posthog/shared";
-
-// Short layout hints for legacy template ids whose richer prompt contracts
-// were folded into the canvas skills. New canvases are all "freeform".
-const TEMPLATE_HINTS: Record<string, string> = {
- dashboard:
- "Template: a live, data-driven dashboard — KPI cards with deltas, trend charts, and an " +
- "in-canvas date control, built with React + Quill.",
- "web-analytics":
- "Template: a PostHog-style web analytics board — visitors / page views / sessions / bounce " +
- "rate KPIs, a visitors-over-time chart, and top paths / sources / devices / geography " +
- "tables, backed by the web-analytics query kinds.",
-};
+import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";
export function buildCanvasGenerationPrompt(input: {
- /**
- * Target canvas, when the surface already knows it (canvas-initiated runs).
- * Channel-composer runs omit it and create a descriptively named canvas.
- */
- dashboardId?: string;
- /** The target's title; set whenever dashboardId is. */
- name?: string;
+ dashboardId: string;
+ name: string;
channelName: string;
- /** Backend channel UUID, scoping the resolve-or-create canvas tools. */
- channelId: string;
templateId?: string;
instruction: string;
- /** True when editing an existing canvas (it already has published source). */
- isEdit: boolean;
- /** First builds only: point the agent at the known-good starter scaffold. */
- useStarter?: boolean;
}): string {
- const { dashboardId, name, channelName, templateId, instruction, isEdit } =
- input;
-
- // The header points back at the user's request, which leads the message —
- // without the pointer the agent can read the block as self-contained and
- // under-weight the actual instruction above it.
- const safeName = name ? escapeXmlAttr(name) : undefined;
- const safeChannelName = escapeXmlAttr(channelName);
- const title = safeName ? ` "${safeName}"` : "";
- const header = dashboardId
- ? isEdit
- ? `Edit the canvas${title} in the channel "${safeChannelName}", per the user's request at the start of this message.`
- : `Build the canvas${title} for the channel "${safeChannelName}", per the user's request at the start of this message.`
- : `Build a canvas in the channel "${safeChannelName}", per the user's request at the start of this message.`;
-
- // With a pre-resolved target the id is pinned. Target-less runs create
- // directly without exposing team-controlled canvas metadata to the agent.
- const targetBlock = dashboardId
- ? `Target canvas — already created, do NOT create another:
-- canvas id: "${dashboardId}"
-- channel: "${safeChannelName}"`
- : `Target canvas — none is pre-created. Create one in channel "${input.channelId}" with
-\`canvas-create\`, named with a short descriptive title drawn from the request — never "Untitled canvas".
-Do not list or inspect other canvases to choose a target.`;
-
- const starterLine =
- !isEdit && input.useStarter
- ? dashboardId
- ? "\nStart from the starter scaffold in the building-react-quill-canvases skill's references — it already wires the date picker, theme tokens, and loading skeletons correctly.\n"
- : "\nFor a first build (a new or still-empty canvas), start from the starter scaffold in the building-react-quill-canvases skill's references — it already wires the date picker, theme tokens, and loading skeletons correctly.\n"
+ // Only the legacy template ids name a layout the canvas skills define a shape
+ // for. Every canvas created today is freeform, so passing that through would
+ // put a meaningless "requested pattern" on every generation task.
+ const template =
+ input.templateId && input.templateId !== FREEFORM_TEMPLATE_ID
+ ? `\n- requested pattern: "${escapeXmlAttr(input.templateId)}"`
: "";
- const templateHint = templateId ? TEMPLATE_HINTS[templateId] : undefined;
- const templateLine = templateHint ? `\n${templateHint}\n` : "";
-
- // Edits target a canvas people already see live, so they stage a draft the
- // user promotes; only a first build publishes straight to the head.
- const saveBlock = isEdit
- ? `Read the canvas's current source and \`current_version_id\` with the
-\`canvas-source-retrieve\` tool before editing. The canvas is live, so stage the COMPLETE
-source project as a DRAFT with \`canvas-draft-create\`, wait for its build, and finish by
-reporting that the draft is ready — the user previews it and promotes it to live. Do not
-publish or promote it yourself unless the user explicitly asked to make the change live.
-The canvas lives in PostHog, not on disk — saving happens through those tools. Do not write
-local files and do not reply with the code.`
- : `Read the canvas's current source and \`current_version_id\` with the
-\`canvas-source-retrieve\` tool before editing, and publish the COMPLETE
-source project with \`canvas-publish-create\`, passing that version id as
-\`expected_current_version_id\`. The canvas lives in PostHog, not on disk — publishing through
-that tool is what saves it. Do not write local files and do not reply with the code.`;
-
- const instructions = `${header}
-
-Invoke the \`building-canvases\` skill now and follow its workflow (and the companion canvas
-skills it routes to) to implement, validate, and save this canvas.
-
-${targetBlock}
-${templateLine}${starterLine}
-${saveBlock}
-
-Verify event/property names via the PostHog MCP tools before using them, and operate only on
-this project.`;
-
- return `${instruction}
+ return `${input.instruction}
<canvas_generation_instructions>
-${instructions}
+Invoke the \`building-canvases\` skill and follow it completely.
+
+Target:
+- canvas id: "${escapeXmlAttr(input.dashboardId)}"
+- canvas name: "${escapeXmlAttr(input.name)}"
+- channel: "${escapeXmlAttr(input.channelName)}"${template}
</canvas_generation_instructions>`;
}
diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.ts
index 712184c11b58..7a808bef7583 100644
--- a/products/desktop/packages/core/src/canvas/services.ts
+++ b/products/desktop/packages/core/src/canvas/services.ts
@@ -18,7 +18,7 @@ import type {
CanvasDataResult,
CanvasLoadInsightInput,
} from "./freeformSchemas";
-import type { CanvasTemplate, CanvasTemplateSummary } from "./templateSchemas";
+import type { CanvasTemplateSummary } from "./templateSchemas";
// Structural service interfaces the host-router routers depend on. The concrete
// implementations live in the desktop app's main process and are bound to the
@@ -26,12 +26,6 @@ import type { CanvasTemplate, CanvasTemplateSummary } from "./templateSchemas";
export interface ICanvasTemplatesService {
list(): CanvasTemplateSummary[];
- get(id: string): CanvasTemplate | undefined;
- /**
- * The freeform (React iframe) system prompt for a template, falling back to
- * the generic freeform sandbox prompt.
- */
- freeformSystemPromptFor(id: string | undefined): string;
}
export interface IDashboardsService {
diff --git a/products/desktop/packages/core/src/canvas/templateSchemas.ts b/products/desktop/packages/core/src/canvas/templateSchemas.ts
index 1fbe1333d9e3..0d9cfdf1f32b 100644
--- a/products/desktop/packages/core/src/canvas/templateSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/templateSchemas.ts
@@ -17,12 +17,3 @@ export const canvasTemplateSummarySchema = z.object({
suggestions: z.array(canvasSuggestionSchema),
});
export type CanvasTemplateSummary = z.infer<typeof canvasTemplateSummarySchema>;
-
-// The full template, including the agent system prompt.
-export const canvasTemplateSchema = canvasTemplateSummarySchema.extend({
- systemPrompt: z.string(),
-});
-export type CanvasTemplate = z.infer<typeof canvasTemplateSchema>;
-
-export const getCanvasTemplateInput = z.object({ id: z.string().min(1) });
-export type GetCanvasTemplateInput = z.infer<typeof getCanvasTemplateInput>;
diff --git a/products/desktop/packages/host-router/src/routers/canvas-templates.router.ts b/products/desktop/packages/host-router/src/routers/canvas-templates.router.ts
index ebbb1305fa78..63542151a0eb 100644
--- a/products/desktop/packages/host-router/src/routers/canvas-templates.router.ts
+++ b/products/desktop/packages/host-router/src/routers/canvas-templates.router.ts
@@ -1,10 +1,6 @@
import { CANVAS_TEMPLATES_SERVICE } from "@posthog/core/canvas/identifiers";
import type { ICanvasTemplatesService } from "@posthog/core/canvas/services";
-import {
- canvasTemplateSchema,
- canvasTemplateSummarySchema,
- getCanvasTemplateInput,
-} from "@posthog/core/canvas/templateSchemas";
+import { canvasTemplateSummarySchema } from "@posthog/core/canvas/templateSchemas";
import { publicProcedure, router } from "@posthog/host-trpc/trpc";
import { z } from "zod";
@@ -16,13 +12,4 @@ export const canvasTemplatesRouter = router({
.get<ICanvasTemplatesService>(CANVAS_TEMPLATES_SERVICE)
.list(),
),
- get: publicProcedure
- .input(getCanvasTemplateInput)
- .output(canvasTemplateSchema.nullable())
- .query(
- ({ ctx, input }) =>
- ctx.container
- .get<ICanvasTemplatesService>(CANVAS_TEMPLATES_SERVICE)
- .get(input.id) ?? null,
- ),
});
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index d998b1300982..3b32f2d7fd8f 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -982,9 +982,6 @@ export type ChannelActionType =
| "mention_member"
| "view_activity"
| "open_mention"
- | "canvas_mode_toggle"
- /** Submitted a canvas-mode prompt (the agent resolves or creates the canvas). */
- | "canvas_generate"
| "activity_tab_change";
export interface ChannelActionProperties {
@@ -1002,8 +999,6 @@ export interface ChannelActionProperties {
mentioned_user_id?: string;
/** For new_task_suggestion: the starter-prompt card label. */
suggestion_label?: string;
- /** For canvas_mode_toggle: whether canvas mode is being armed. */
- armed?: boolean;
/** For activity_tab_change: the tab landed on. */
tab?: string;
/** Whether the underlying mutation resolved successfully. */
@@ -1032,8 +1027,6 @@ export interface DashboardActionProperties {
surface: ChannelsSurface;
channel_id?: string;
dashboard_id?: string;
- /** The canvas render kind. */
- kind?: "json-render" | "freeform";
/** Template chosen on create. */
template_id?: string;
/** edit_toggle: the state being entered. */
diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
index eba044b4e139..346a0d672f9d 100644
--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
@@ -1,9 +1,9 @@
# Canvas (Website space) — patterns
Conventions for the channel-scoped Website space: channels and canvases. A canvas
-is an agent-authored single-file React app rendered in a sandboxed iframe. Read
-this before changing breadcrumbs, canvas naming, or the canvas generation harness.
-The root `AGENTS.md` architecture rules still apply.
+is an agent-authored browser app rendered in a sandboxed iframe. Read this before
+changing breadcrumbs, canvas naming, or the canvas generation harness. The root
+`AGENTS.md` architecture rules still apply.
## Components & styling
@@ -178,9 +178,9 @@ The root `AGENTS.md` architecture rules still apply.
inside a space. Autocomplete has no API for setting the highlight, so moving it
means synthesizing the arrow keys it listens for — and moving *before*
collapsing, while the rows still exist.
-- One `ChannelsFab` serves both panes: given a `channelId` it creates inside
- that channel (task, canvas); from the list, where nothing else offers it, it
- creates a space instead. Off the layout it keeps its original two-item menu.
+- One `ChannelsFab` serves both panes: given a `channelId` it creates a task in
+ that channel; from the list, where nothing else offers it, it creates a space
+ instead. Off the layout it keeps its original two-item menu.
Archived moves out of the sidebar and into the account menu
(`ProjectSwitcher`), beside Settings.
- **Which pane shows is view state, not a route.** `channelPaneStore` holds it,
@@ -213,9 +213,8 @@ The root `AGENTS.md` architecture rules still apply.
## Canvas naming
- **A canvas's name is its own field on the record**, set at creation
- (`Untitled canvas` by default; the template picker / `useCreateAndOpenDashboard`
- drive it). It is independent of any heading the agent renders inside the
- React app.
+ (`Untitled canvas` by default; `useCreateAndOpenDashboard` drives it). It is
+ independent of any heading the agent renders inside the React app.
## Storage
@@ -227,6 +226,19 @@ The root `AGENTS.md` architecture rules still apply.
output is the published build's artifact, served from the isolated artifact
origin. See `@posthog/core/canvas/dashboardsService.ts` and
`dashboardSchemas.ts` for the record/source/version shapes.
+- **Two components render a canvas, and `FreeformCanvasView` picks between
+ them.** A build's artifact renders in `BuiltCanvas`; a canvas with no
+ successful build yet falls back to the head project's single
+ `CANVAS_COMPONENT_PATH` file in the `FreeformCanvas` srcDoc sandbox (which
+ transpiles in-browser and resolves imports off esm.sh). Both go through the
+ same `canvasHostMessageRouter`, so protocol and guard changes belong there
+ rather than in either host.
+- **Capabilities gate viewers, not authors.** `assertCanvasCapability` runs only
+ in `BuiltCanvas`, against the manifest frozen into that build. The edit path is
+ deliberately full-access — the author is running their own code against their
+ own session — so the asymmetry is the design, not a gap to close. See the
+ two-tier security model in `docs/CANVAS-FREEFORM-REACT-PLAN.md` before changing
+ what either tier may reach.
## Channel sidebar preloading
diff --git a/products/desktop/packages/ui/src/features/canvas/TEMPLATES.md b/products/desktop/packages/ui/src/features/canvas/TEMPLATES.md
index ad8a2ee3da09..4367a1e460e3 100644
--- a/products/desktop/packages/ui/src/features/canvas/TEMPLATES.md
+++ b/products/desktop/packages/ui/src/features/canvas/TEMPLATES.md
@@ -1,30 +1,22 @@
# Canvas templates
-A canvas is an agent-authored single-file React app that runs in a sandboxed
-iframe and talks to PostHog only through the injected `ph` shim.
+A canvas is an agent-authored browser app that runs in a sandboxed iframe and uses the injected
+`ph` API to interact with PostHog.
-## What a canvas is
+## Creation and authoring
-- A canvas record is a `dashboard`-typed desktop-fs row whose `meta` carries the
- agent-authored React `code`, its `versions` edit history, the `currentVersionId`
- pointer, author `context`, and a `templateId`.
-- **Templates** are data (`CanvasTemplate` records served by
- `CanvasTemplatesService`, listed via the `canvasTemplates` tRPC router and the
- create-picker `NewCanvasMenu`). Only **`freeform`** is offered today; more can be
- appended in `BUILT_IN_TEMPLATES` (`@posthog/core/canvas/canvasTemplates.ts`).
-- A template's job is to inject the **agent system prompt**, resolved via
- `freeformSystemPromptFor`.
-- Generation runs as a **dedicated agent task** (like `CONTEXT.md`) — see
- `freeformPrompt.ts` / `hooks/useGenerateFreeformCanvas.ts`.
+- Any ordinary task can create a canvas by invoking the bundled `building-canvases` skill.
+- The space composer and sidebar do not have separate canvas task modes.
+- The canvas index can still create an empty canvas record. Its composer starts a task with that
+ canvas as the explicit target.
+- Template records contain only picker metadata and starter suggestions. Canvas authoring rules
+ live in the bundled canvas skills, not in template system prompts.
## Where things live
-- Agent prompts + templates: `@posthog/core/canvas/canvasTemplates.ts`,
- `canvasTemplatesService.ts`.
-- The iframe + `ph` data shim: `features/canvas/freeform/` (`FreeformCanvas.tsx`,
- `sandboxRuntime.ts`, `freeformDataBridge.ts`) and host-side
+- Template metadata: `@posthog/core/canvas/canvasTemplates.ts` and `canvasTemplatesService.ts`.
+- Agent task routing: `@posthog/core/canvas/generationPrompt.ts`.
+- The iframe and `ph` bridge: `features/canvas/freeform/` and
`@posthog/core/canvas/canvasDataService.ts`.
-- Storage: `@posthog/core/canvas/dashboardsService.ts` + `dashboardSchemas.ts`.
-- Deeper walkthrough of the canvas tier + the data path: the `canvas-templates`
- skill, and the forward-looking `docs/CANVAS-FREEFORM-REACT-PLAN.md` (publish /
- external sharing).
+- Source, versions, drafts, and builds: `@posthog/core/canvas/dashboardsService.ts` and
+ `dashboardSchemas.ts`.
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index 7aef6b51404e..f0cc0c559652 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -3,9 +3,8 @@ import type {
PiThinkingLevel,
} from "@posthog/core/pi-runtime/piSessionController";
import { isValidConfigValue } from "@posthog/core/task-detail/configOptions";
-import { type AgentRuntime, ANALYTICS_EVENTS } from "@posthog/shared";
+import type { AgentRuntime } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
-import { useQueryClient } from "@tanstack/react-query";
import {
forwardRef,
useCallback,
@@ -16,7 +15,6 @@ import {
} from "react";
import { useConnectivity } from "../../../hooks/useConnectivity";
import { toast } from "../../../primitives/toast";
-import { track } from "../../../shell/analytics";
import { useFeatureFlag } from "../../feature-flags/useFeatureFlag";
import { useFeatureFlagsLoaded } from "../../feature-flags/useFeatureFlagsLoaded";
import { useUserRepositoryIntegration } from "../../integrations/useIntegrations";
@@ -41,8 +39,6 @@ import { useCloudModeEnabled } from "../../task-detail/hooks/useCloudModeEnabled
import { usePreviewConfig } from "../../task-detail/hooks/usePreviewConfig";
import { useTaskCreation } from "../../task-detail/hooks/useTaskCreation";
import { resolveWorkspaceModePreference } from "../../task-detail/hooks/workspaceModePreference";
-import { channelFeedQueryKey } from "../hooks/useChannelFeed";
-import { useGenerateFreeformCanvas } from "../hooks/useGenerateFreeformCanvas";
import { useUpdateTaskChannelRepositories } from "../hooks/useTaskChannels";
import {
resolveTaskRepositoryDraft,
@@ -101,32 +97,6 @@ export const ChannelHomeComposer = forwardRef<
const [editorIsEmpty, setEditorIsEmpty] = useState(true);
const { isOnline } = useConnectivity();
- // Canvas mode, armed from the mode selector (like Autoresearch on the
- // new-task composer): the next submit starts a canvas-generation task from
- // the prompt instead of a plain task. No canvas is created client-side — the
- // agent resolves the target itself (building on a matching existing canvas
- // in the channel, or creating a descriptively-named one), so the feed never
- // collects "Untitled canvas" husks.
- const [canvasArmed, setCanvasArmed] = useState(false);
- const { generate: generateCanvas, isStarting: isStartingCanvas } =
- useGenerateFreeformCanvas({
- channelId,
- channelName: channelName ?? "",
- // The parent already fetches the channel CONTEXT.md; passing it keeps
- // the hook from running its own duplicate fetch.
- channelContext,
- });
-
- const toggleCanvasMode = useCallback(() => {
- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
- action_type: "canvas_mode_toggle",
- surface: "channel_home",
- channel_id: channelId,
- armed: !canvasArmed,
- });
- setCanvasArmed(!canvasArmed);
- }, [channelId, canvasArmed]);
-
const {
lastUsedAdapter,
setLastUsedAdapter,
@@ -272,73 +242,12 @@ export const ChannelHomeComposer = forwardRef<
: undefined
: currentReasoningLevel;
- const queryClient = useQueryClient();
-
// In-flight optimistic kickoff ids, oldest first. Submits are serialized
// (the composer is disabled while creating), so retiring the oldest on each
// task-ready callback matches create order and keeps adds/removes balanced —
// no row is ever orphaned, even if two creates briefly overlap.
const pendingIdsRef = useRef<string[]>([]);
- const handleCanvasSubmit = useCallback(async () => {
- const editor = editorRef.current;
- const instruction = editor?.getText().trim();
- if (!editor || !instruction || isStartingCanvas) return;
- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
- action_type: "canvas_generate",
- surface: "channel_home",
- channel_id: channelId,
- });
- // No canvas is created here — the agent resolves the target itself
- // (building on a matching existing canvas, or creating a named one) per
- // the building-canvases skill. The submit shows up as a task card in the
- // feed, exactly like a plain composer submit; the canvas appears in the
- // channel once the agent has resolved or created it.
- const content = editor.getContent();
- editor.clear();
- const pendingId =
- globalThis.crypto?.randomUUID?.() ??
- `pending-${instruction.length}-${Date.now()}`;
- pendingIdsRef.current.push(pendingId);
- onPendingStart({ id: pendingId, prompt: instruction });
- // generate() surfaces its own failure toasts; on success it files the task
- // to the channel so the run shows as a card in the feed.
- const taskId = await generateCanvas({
- instruction,
- adapter: adapter ?? "claude",
- model: currentModel,
- reasoningLevel: currentReasoningLevel,
- useStarter: true,
- });
- pendingIdsRef.current = pendingIdsRef.current.filter(
- (id) => id !== pendingId,
- );
- if (!taskId) {
- // Creation failed — pull the optimistic row and give the prompt back so
- // the user can retry.
- onPendingEnd(pendingId);
- editor.insertEditorContent(content);
- return;
- }
- setCanvasArmed(false);
- // Surface the new card without waiting for the feed's next poll, then
- // retire the optimistic row once the real card can render.
- await queryClient
- .invalidateQueries({ queryKey: channelFeedQueryKey(channelId) })
- .catch(() => {});
- onPendingEnd(pendingId);
- }, [
- channelId,
- adapter,
- currentModel,
- currentReasoningLevel,
- generateCanvas,
- isStartingCanvas,
- queryClient,
- onPendingStart,
- onPendingEnd,
- ]);
-
const handleTaskCreated = useCallback(
(task: Task) => {
// onTaskCreated swaps the real card in; drop the matching "Starting…"
@@ -442,9 +351,6 @@ export const ChannelHomeComposer = forwardRef<
didResolveRuntimeRef.current = true;
setRuntime(nextRuntime);
setLastUsedAgentRuntime(nextRuntime);
- if (nextRuntime === "pi") {
- setCanvasArmed(false);
- }
},
[setLastUsedAgentRuntime],
);
@@ -488,37 +394,30 @@ export const ChannelHomeComposer = forwardRef<
[sessionId, modeOption, setConfigOption],
);
- const isBusy = isCreatingTask || isStartingCanvas;
- const submitComposer = canvasArmed ? handleCanvasSubmit : submit;
+ const isBusy = isCreatingTask;
return (
<div className="relative flex w-full flex-col">
- {/* Canvas generation always runs in the cloud, so the local/cloud pick
- doesn't apply while canvas mode is armed. The row floats over the feed,
- and the trigger's own fill is translucent, so it carries an opaque
- backdrop at the button's radius to stop messages showing through. */}
- {!canvasArmed && (
- <div className="absolute bottom-full left-0 mb-2 flex items-center gap-2 rounded-sm bg-card">
- <WorkspaceModeSelect
- value={workspaceMode}
- onChange={setWorkspaceMode}
- overrideModes={["local", "cloud"]}
- selectedCloudEnvironmentId={selectedCloudEnvId}
- onCloudEnvironmentChange={setSelectedCloudEnvId}
- selectedCustomImageId={selectedCustomImageId}
- onCustomImageChange={setSelectedCustomImageId}
- size="1"
- disabled={isBusy}
- />
- <TaskRepositoryChip
- cloud={workspaceMode === "cloud"}
- repositoryCount={taskRepositories.length}
- hasFolder={!!taskFolder}
- disabled={isBusy}
- onOpen={() => setRepositoryDialogOpen(true)}
- />
- </div>
- )}
+ <div className="absolute bottom-full left-0 mb-2 flex items-center gap-2 rounded-sm bg-card">
+ <WorkspaceModeSelect
+ value={workspaceMode}
+ onChange={setWorkspaceMode}
+ overrideModes={["local", "cloud"]}
+ selectedCloudEnvironmentId={selectedCloudEnvId}
+ onCloudEnvironmentChange={setSelectedCloudEnvId}
+ selectedCustomImageId={selectedCustomImageId}
+ onCustomImageChange={setSelectedCustomImageId}
+ size="1"
+ disabled={isBusy}
+ />
+ <TaskRepositoryChip
+ cloud={workspaceMode === "cloud"}
+ repositoryCount={taskRepositories.length}
+ hasFolder={!!taskFolder}
+ disabled={isBusy}
+ onOpen={() => setRepositoryDialogOpen(true)}
+ />
+ </div>
<TaskRepositoryDialog
open={repositoryDialogOpen}
@@ -552,33 +451,22 @@ export const ChannelHomeComposer = forwardRef<
<PromptInput
ref={editorRef}
sessionId={sessionId}
- placeholder={
- canvasArmed
- ? "Describe the canvas to build — the agent generates and publishes it"
- : `What do you want to ship?`
- }
+ placeholder="What do you want to ship?"
editorHeight="large"
disabled={isBusy}
isLoading={isBusy}
autoFocus
clearOnSubmit={false}
submitDisabledExternal={
- canvasArmed
- ? editorIsEmpty || isBusy || !isOnline
- : !canSubmit ||
- isBusy ||
- !isOnline ||
- (runtime === "pi" ? isPiConfigLoading : isLoading) ||
- (runtime === "pi" && !currentPiModel)
+ !canSubmit ||
+ isBusy ||
+ !isOnline ||
+ (runtime === "pi" ? isPiConfigLoading : isLoading) ||
+ (runtime === "pi" && !currentPiModel)
}
modeOption={runtime === "pi" ? undefined : modeOption}
onModeChange={runtime === "pi" ? undefined : handleModeChange}
allowBypassPermissions={allowBypassPermissions}
- canvas={
- runtime === "pi"
- ? undefined
- : { active: canvasArmed, onToggle: toggleCanvasMode }
- }
enableCommands
enableBashMode={false}
modelSelector={
@@ -624,9 +512,9 @@ export const ChannelHomeComposer = forwardRef<
)
}
onEmptyChange={setEditorIsEmpty}
- onSubmitClick={() => void submitComposer()}
+ onSubmitClick={() => void submit()}
onSubmit={() => {
- if (canvasArmed || canSubmit) void submitComposer();
+ if (canSubmit) void submit();
}}
/>
</div>
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
index 5fbd0f49bdeb..203aaaef0a97 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
@@ -1,5 +1,4 @@
import {
- ChartBarIcon,
CubeIcon,
FileTextIcon,
HashIcon,
@@ -19,9 +18,7 @@ import {
} from "@posthog/quill";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";
-import { trackAndCreateCanvas } from "@posthog/ui/features/canvas/createCanvasAnalytics";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
-import { useCreateAndOpenDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";
import {
formatHotkey,
SHORTCUTS,
@@ -47,7 +44,6 @@ export function ChannelsFab({ channelId }: { channelId?: string }) {
const hasDraft = useDraftStore(
(s) => !isContentEmpty(s.drafts["task-input"]),
);
- const createAndOpenCanvas = useCreateAndOpenDashboard(channelId);
// New task has no /website mirror yet, so it jumps back to Code unless we're
// already in the Channels space — same rule as the nav's New task row.
const inChannels = useRouterState({
@@ -123,23 +119,6 @@ export function ChannelsFab({ channelId }: { channelId?: string }) {
<FileTextIcon size={14} className="text-gray-9" />
New task
</DropdownMenuItem>
- {channelId && (
- <DropdownMenuItem
- onClick={() => {
- // Create + open a canvas with the default template directly;
- // the canvas's own composer drives what gets built.
- trackAndCreateCanvas(
- channelId,
- undefined,
- "sidebar",
- () => void createAndOpenCanvas(),
- );
- }}
- >
- <ChartBarIcon size={14} className="text-gray-9" />
- New canvas
- </DropdownMenuItem>
- )}
{/* Inside a space the menu is about filling that space; making
another one belongs to the list this button also serves. */}
{channelsLayout && !channelId && (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index e0ee8799602c..e7bd49928b8b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -3,7 +3,6 @@ import {
ArrowRightIcon,
CaretDownIcon,
CaretRightIcon,
- ChartBarIcon,
DotsThreeIcon,
FileTextIcon,
LinkIcon,
@@ -61,7 +60,6 @@ import {
TaskRowContextMenu,
type TaskRowMenuProps,
} from "@posthog/ui/features/canvas/components/TaskRowMenu";
-import { trackAndCreateCanvas } from "@posthog/ui/features/canvas/createCanvasAnalytics";
import { useBlockedSessionCount } from "@posthog/ui/features/canvas/hooks/useBlockedSessionCount";
import { useChannelStarToggle } from "@posthog/ui/features/canvas/hooks/useChannelStars";
import {
@@ -71,7 +69,6 @@ import {
} from "@posthog/ui/features/canvas/hooks/useChannels";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
-import { useCreateAndOpenDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";
import {
NO_TASKS,
type SpaceTasks,
@@ -953,8 +950,7 @@ const ChannelSection = memo(
const isActive = pathname === base || pathname.startsWith(`${base}/`);
// Lifted so the hover button group stays visible while the menu is open.
const [menuOpen, setMenuOpen] = useState(false);
- // The "+" dropdown (New task / New canvas). Keeps the hover actions pinned
- // while open.
+ // Keep the hover actions pinned while the create menu is open.
const [newMenuOpen, setNewMenuOpen] = useState(false);
const { reveal, hoverProps, focusProps } = useOverflowTickerReveal();
const hasAttention = unreadSessions > 0 || blockedSessions > 0;
@@ -963,7 +959,6 @@ const ChannelSection = memo(
undefined,
);
useEffect(() => () => clearTimeout(prefetchTimer.current), []);
- const createAndOpenCanvas = useCreateAndOpenDashboard(channel.id);
// Shared by the "..." dropdown and the right-click context menu so both offer
// the same star / edit / rename / delete actions.
const {
@@ -1134,8 +1129,7 @@ const ChannelSection = memo(
</ContextMenuContent>
</ContextMenu>
</SpaceHoverCard>
- {/* Hover actions: the "+" dropdown (New task / New canvas) and the
- options menu. Stay visible while either is open. */}
+ {/* Hover actions stay visible while either menu is open. */}
<div className="absolute top-1 right-1">
<ButtonGroup>
<DropdownMenu open={newMenuOpen} onOpenChange={setNewMenuOpen}>
@@ -1182,21 +1176,6 @@ const ChannelSection = memo(
<FileTextIcon size={14} />
New task
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => {
- // Create + open a canvas with the default template directly;
- // the canvas's own composer drives what gets built.
- trackAndCreateCanvas(
- channel.id,
- undefined,
- "sidebar",
- () => void createAndOpenCanvas(),
- );
- }}
- >
- <ChartBarIcon size={14} />
- New canvas
- </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ChannelMenu
@@ -1382,7 +1361,7 @@ const PersonalChannelRow = memo(function PersonalChannelRow({
const pathname = useRouterState({ select: (s) => s.location.pathname });
const { channels } = useChannels();
const { ensureChannelId, openPersonalChannel } = useOpenPersonalChannel();
- // The "+" dropdown (New task / New canvas), mirroring a shared channel row.
+ // The create dropdown mirrors a shared channel row.
const [newMenuOpen, setNewMenuOpen] = useState(false);
// Personal channels are provisioned lazily server-side when the channel list
@@ -1391,7 +1370,6 @@ const PersonalChannelRow = memo(function PersonalChannelRow({
const isUnread = useIsChannelUnread()(meChannel?.id);
const unreadSessions = useUnreadSessionCount()(meChannel?.id);
const blockedSessions = useBlockedSessionCount()(meChannel?.id);
- const createAndOpenCanvas = useCreateAndOpenDashboard(meChannel?.id);
const isActive =
!!meChannel &&
(pathname === `/website/${meChannel.id}` ||
@@ -1408,17 +1386,6 @@ const PersonalChannelRow = memo(function PersonalChannelRow({
openTaskInput({ channelId });
};
- const newCanvas = () => {
- const channelId = ensureChannelId();
- if (!channelId) return;
- trackAndCreateCanvas(
- channelId,
- undefined,
- "sidebar",
- () => void createAndOpenCanvas({ channelId }),
- );
- };
-
// The one row in the list that carries a glyph, and it earns the exception:
// this is the space nobody else can see, and the lock is the only thing that
// says so. Its name starts a glyph's width right of the others, which is the
@@ -1514,10 +1481,6 @@ const PersonalChannelRow = memo(function PersonalChannelRow({
<FileTextIcon size={14} />
New task
</DropdownMenuItem>
- <DropdownMenuItem onClick={newCanvas}>
- <ChartBarIcon size={14} />
- New canvas
- </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/products/desktop/packages/ui/src/features/canvas/components/FreeformPreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/FreeformPreview.tsx
index 37b1f62bfc89..22721b62ef88 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/FreeformPreview.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/FreeformPreview.tsx
@@ -76,11 +76,7 @@ export function FreeformPreview({
/>
}
>
- <FreeformCanvas
- code={code}
- mode="edit"
- onDataRequest={onDataRequest}
- />
+ <FreeformCanvas code={code} onDataRequest={onDataRequest} />
</ErrorBoundary>
</Box>
) : (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx
index e34c366e8425..3a9b9e12ecd5 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx
@@ -126,7 +126,6 @@ function FreeformEditControls({
surface: "canvas",
channel_id: channelId,
dashboard_id: dashboardId,
- kind: "freeform",
success: true,
}),
)
@@ -136,7 +135,6 @@ function FreeformEditControls({
surface: "canvas",
channel_id: channelId,
dashboard_id: dashboardId,
- kind: "freeform",
success: false,
});
toast.error(
@@ -167,7 +165,6 @@ function FreeformEditControls({
surface: "canvas",
channel_id: channelId,
dashboard_id: dashboardId,
- kind: "freeform",
});
void queryClient.invalidateQueries({ queryKey: [CANVAS_QUERY_KEY] });
remountFrame(dashboardId);
@@ -266,7 +263,6 @@ function FreeformEditControls({
surface: "canvas",
channel_id: channelId,
dashboard_id: dashboardId,
- kind: "freeform",
editing: !editing,
});
if (!editing) openChat();
diff --git a/products/desktop/packages/ui/src/features/canvas/components/canvasTemplateIcon.tsx b/products/desktop/packages/ui/src/features/canvas/components/canvasTemplateIcon.tsx
index 693dc20150e8..17b69eef554a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/canvasTemplateIcon.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/canvasTemplateIcon.tsx
@@ -8,9 +8,8 @@ import { FREEFORM_TEMPLATE_ID } from "@posthog/core/canvas/freeformSchemas";
import type { ReactNode } from "react";
// A canvas's leading icon, chosen from its template so the tree and header read
-// at a glance: bar chart for json-render dashboards, line chart for web
-// analytics, shapes for the generic freeform canvas (until it's classified as
-// something more specific), plain file for blank canvases.
+// at a glance: shapes for a freeform canvas, plain file for a blank one, and
+// line/bar charts for the legacy template ids older records still carry.
export function iconForTemplate(
templateId: string,
opts?: { size?: number; className?: string },
diff --git a/products/desktop/packages/ui/src/features/canvas/createCanvasAnalytics.ts b/products/desktop/packages/ui/src/features/canvas/createCanvasAnalytics.ts
index 31e5ba9fd1e8..df7da73d47f9 100644
--- a/products/desktop/packages/ui/src/features/canvas/createCanvasAnalytics.ts
+++ b/products/desktop/packages/ui/src/features/canvas/createCanvasAnalytics.ts
@@ -2,13 +2,9 @@ import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { track } from "@posthog/ui/shell/analytics";
// Where a canvas create was triggered from, for analytics.
-export type CreateSurface = "dashboards_grid" | "sidebar" | "channel_home";
+export type CreateSurface = "dashboards_grid";
-// Fire the "create" DASHBOARD_ACTION, then create + open the canvas. Shared so
-// every canvas-create entry point (the dashboards-grid dialog, the sidebar "+"
-// dropdown, the channel composer's canvas mode) reports creation the same way.
-// Returns `create`'s result so callers that need the created record can await
-// it.
+// Fire the "create" DASHBOARD_ACTION, then create and open the canvas.
export function trackAndCreateCanvas<T>(
channelId: string | undefined,
templateId: string | undefined,
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx
index 5cd3b6da81fa..677a94c61d48 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx
@@ -52,7 +52,6 @@ export function CanvasFrameHost() {
<ErrorBoundary name="freeform-canvas" resetKey={slot.dashboardId}>
<FreeformCanvas
code={slot.inputs.code}
- mode="edit"
analytics={slot.inputs.analytics}
onDataRequest={slot.inputs.onDataRequest}
onError={slot.inputs.onError}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx
index 2ee163da4e42..32e439a77c1d 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx
@@ -11,7 +11,6 @@ const renderCanvas = () => {
render(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
/>,
);
@@ -42,7 +41,6 @@ describe("FreeformCanvas", () => {
render(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
onTextSelection={onTextSelection}
/>,
@@ -112,7 +110,6 @@ describe("FreeformCanvas", () => {
const { rerender } = render(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
commentHighlights={[]}
/>,
@@ -125,7 +122,6 @@ describe("FreeformCanvas", () => {
rerender(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
commentHighlights={[highlight]}
/>,
@@ -145,7 +141,6 @@ describe("FreeformCanvas", () => {
const { rerender } = render(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
clearTextSelectionKey={0}
/>,
@@ -158,7 +153,6 @@ describe("FreeformCanvas", () => {
rerender(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
clearTextSelectionKey={1}
/>,
@@ -175,7 +169,6 @@ describe("FreeformCanvas", () => {
render(
<FreeformCanvas
code="export default function Canvas() { return null }"
- mode="edit"
onDataRequest={vi.fn()}
onCommentActivate={onCommentActivate}
/>,
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
index ac7f8607ff2d..5aa38536e16c 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx
@@ -17,7 +17,7 @@ import {
} from "react";
import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
import { translateCanvasTextSelection } from "./canvasSelection";
-import { buildSandboxDocument, type SandboxMode } from "./sandboxRuntime";
+import { buildSandboxDocument } from "./sandboxRuntime";
const log = logger.scope("freeform-canvas");
const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];
@@ -25,12 +25,11 @@ const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];
export interface FreeformCanvasProps {
/** The single-file React source to render. */
code: string;
- /** edit = in-app authoring (full data shim); view = published/shared. */
- mode: SandboxMode;
/**
* Resolves a data-request from the canvas. The host owns the real token; this
- * runs the authenticated call and returns only the result. In view mode the
- * implementation must reject anything outside the frozen query allowlist.
+ * runs the authenticated call and returns only the result. Ungated by design —
+ * this sandbox only ever runs a canvas its own author is editing. A published
+ * canvas renders in BuiltCanvas, which checks its build's capabilities first.
*/
onDataRequest: (method: string, payload: unknown) => Promise<unknown>;
/** Called when the canvas reports a compile/runtime error (self-repair loop). */
@@ -60,7 +59,6 @@ export interface FreeformCanvasProps {
// a JS object — only structured-clone messages cross the boundary.
export function FreeformCanvas({
code,
- mode,
onDataRequest,
onError,
onRendered,
@@ -80,13 +78,13 @@ export function FreeformCanvas({
// shouldn't trigger re-renders.
const readyRef = useRef(false);
- // The document is keyed on mode + the analytics host (which the CSP must open
- // for posthog-js), not on code: code is injected via `init`, so changing it
+ // The document is keyed on the analytics host (which the CSP must open for
+ // posthog-js), not on code: code is injected via `init`, so changing it
// never reloads the iframe — it re-renders in place.
const analyticsHost = analytics?.apiHost;
const srcDoc = useMemo(
- () => buildSandboxDocument(mode, analyticsHost),
- [mode, analyticsHost],
+ () => buildSandboxDocument(analyticsHost),
+ [analyticsHost],
);
// Latest props, read by the once-bound listener + the (stable) postInit.
@@ -98,7 +96,6 @@ export function FreeformCanvas({
onTextSelection,
onCommentActivate,
code,
- mode,
analytics,
theme,
commentHighlights,
@@ -111,7 +108,6 @@ export function FreeformCanvas({
onTextSelection,
onCommentActivate,
code,
- mode,
analytics,
theme,
commentHighlights,
@@ -124,7 +120,6 @@ export function FreeformCanvas({
channel: "posthog-canvas",
type: "init",
code: p.code,
- mode: p.mode,
analytics: p.analytics,
theme: p.theme,
highlights: p.commentHighlights,
@@ -133,7 +128,7 @@ export function FreeformCanvas({
);
}, []);
- // The iframe reloads only when srcDoc changes (mode / analytics host); on
+ // The iframe reloads only when srcDoc changes (the analytics host); on
// reload it re-announces "ready", so mark it not-ready until then. Ref write
// only — no state update, no extra render.
// biome-ignore lint/correctness/useExhaustiveDependencies: srcDoc identity tracks a reload.
@@ -205,8 +200,8 @@ export function FreeformCanvas({
return () => window.removeEventListener("message", onMessage);
}, [postInit]);
- // Re-send init when the code / mode / analytics change, if the iframe is ready.
- // NB: reference code/mode/analytics DIRECTLY here (not via postInit, which
+ // Re-send init when the code / analytics change, if the iframe is ready.
+ // NB: reference code/analytics DIRECTLY here (not via postInit, which
// reads them off a ref) — otherwise the exhaustive-deps lint strips them from
// the array as "unused" and the effect goes stale, never re-posting on change.
// Theme is NOT a dep: a re-init remounts the app (new Blob module = fresh
@@ -219,14 +214,13 @@ export function FreeformCanvas({
channel: "posthog-canvas",
type: "init",
code,
- mode,
analytics,
theme: latest.current.theme,
highlights: latest.current.commentHighlights,
},
"*",
);
- }, [code, mode, analytics]);
+ }, [code, analytics]);
useEffect(() => {
if (!readyRef.current) return;
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformGenerateBar.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformGenerateBar.tsx
index 4f1e34d8751c..4f177fc03419 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformGenerateBar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformGenerateBar.tsx
@@ -41,7 +41,6 @@ export const FreeformGenerateBar = forwardRef<
channelName,
name,
templateId,
- isEdit = false,
sessionId,
onStarted,
},
@@ -64,8 +63,6 @@ export const FreeformGenerateBar = forwardRef<
name,
templateId,
instruction,
- isEdit,
- useStarter: !isEdit,
workspaceMode,
});
if (taskId) onStarted?.(taskId);
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 f5c69a8054da..dfb6da449587 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
@@ -59,7 +59,7 @@ describe("decodeJsxUnicodeEscapes", () => {
describe("buildSandboxDocument", () => {
it("inlines the unicode-escape decoder into the bootstrap", () => {
- const html = buildSandboxDocument("edit");
+ const html = buildSandboxDocument();
expect(html).toContain(
"const decodeUnicodeEscapes = function decodeJsxUnicodeEscapes(",
);
@@ -67,7 +67,7 @@ describe("buildSandboxDocument", () => {
});
it("inlines the external-anchor resolver into the bootstrap", () => {
- const html = buildSandboxDocument("edit");
+ const html = buildSandboxDocument();
expect(html).toContain(
"const resolveExternalAnchorUrl = function resolveExternalAnchorUrl(",
);
@@ -79,14 +79,14 @@ describe("buildSandboxDocument", () => {
// theme message arrives. A light fallback there flashed white over a dark
// app every time a canvas preview scrolled into view.
it("paints nothing of its own before the host theme lands", () => {
- const html = buildSandboxDocument("edit");
+ const html = buildSandboxDocument();
expect(html).toContain("background: var(--background, transparent)");
expect(html).not.toContain("var(--background, #fff)");
expect(html).toContain("html.dark { color-scheme: dark; }");
});
it("installs the persisted comment protocol", () => {
- const html = buildSandboxDocument("edit");
+ const html = buildSandboxDocument();
expect(html).toContain('d.type === "set-comment-highlights"');
expect(html).toContain('type: "comment-activate"');
expect(html).toContain('d.type === "clear-text-selection"');
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 de4d426017c5..e668b50772eb 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -21,12 +21,15 @@ import {
// - The user's canvas code is NEVER interpolated into this HTML. It arrives
// later as a postMessage `init` frame and is run from a Blob module URL, so
// there is no string-injection path through the document itself.
-// - The CSP is the third isolation layer. Edit mode allows the esm.sh CDN (for
-// Babel + whitelisted packages). View/published mode (Phase 2) self-hosts
-// and forbids third-party egress entirely.
-export type SandboxMode = "edit" | "view";
+// - The CSP is the third isolation layer. It allows the esm.sh CDN, because
+// this document transpiles and resolves imports in the browser.
+//
+// This is the AUTHORING surface only: it renders a canvas whose build hasn't
+// succeeded yet, and card previews. A published canvas is a compiled artifact
+// rendered by BuiltCanvas, which self-hosts its assets behind its own CSP and
+// gates `ph.*` on the build's capability manifest.
-// Which in-browser Tailwind engine the EDIT-mode sandbox runs. "v4" matches the
+// Which in-browser Tailwind engine the sandbox runs. "v4" matches the
// Quill version we ship (Quill is authored for Tailwind v4) and lets us drop the
// v3 Play CDN's preflight-off hack, the `not-disabled` variant shim, the manual
// `@layer base` reset, and the hand-mirrored color map — v4's layered preflight
@@ -177,35 +180,28 @@ export function isInteractiveCanvasCommentTarget(target: unknown): boolean {
}
export function buildSandboxDocument(
- mode: SandboxMode,
// The PostHog host, when in-iframe analytics/replay is enabled. Opens CSP for
// posthog-js to load its recorder and POST events/replay to ingest.
analyticsApiHost?: string,
): string {
const importMap = JSON.stringify(buildImportMap());
- const csp = contentSecurityPolicy(mode, analyticsApiHost);
+ const csp = contentSecurityPolicy(analyticsApiHost);
// Quill components emit Tailwind utility classes (layout — `inline-flex`,
// `items-center` — AND token colors like `bg-card`, `text-muted-foreground`)
// ALONGSIDE their `.quill-*` BEM classes. The linked Quill stylesheets style
// the BEM half; the utilities are dead without Tailwind, so the sandbox runs a
- // JIT-in-browser Tailwind in EDIT mode (View/published mode forbids the CDN —
- // that tier self-hosts a compiled stylesheet, Phase 2). Quill is authored for
- // Tailwind v4, so we run the v4 browser engine: its preflight is properly
- // `@layer base` (sorts BELOW Quill's `@layer components`, so it can't clobber
- // them — no preflight-off hack, no hand-rolled reset), it has native `not-*`
- // variants (no `not-disabled` shim), and `@theme inline` maps Quill's tokens
- // straight to v4 color keys. The whole hand-mirrored color map + reset the v3
- // Play CDN forced us into collapses to the token block below.
- const tailwind =
- mode === "edit"
- ? TAILWIND_ENGINE === "v4"
- ? TAILWIND_V4
- : TAILWIND_V3
- : "";
+ // JIT-in-browser Tailwind. Quill is authored for Tailwind v4, so we run the v4
+ // browser engine: its preflight is properly `@layer base` (sorts BELOW Quill's
+ // `@layer components`, so it can't clobber them — no preflight-off hack, no
+ // hand-rolled reset), it has native `not-*` variants (no `not-disabled` shim),
+ // and `@theme inline` maps Quill's tokens straight to v4 color keys. The whole
+ // hand-mirrored color map + reset the v3 Play CDN forced us into collapses to
+ // the token block below.
+ const tailwind = TAILWIND_ENGINE === "v4" ? TAILWIND_V4 : TAILWIND_V3;
// v4 preflight is the layered reset; only the legacy v3 path needs the manual
// `@layer base` reset (v3's Play CDN preflight is unlayered, so it's off).
- const reset = mode === "edit" && TAILWIND_ENGINE === "v3" ? LEGACY_RESET : "";
+ const reset = TAILWIND_ENGINE === "v3" ? LEGACY_RESET : "";
// The bootstrap module. It is static (no user input) so it can be inlined
// safely. It waits for `init`, transpiles the canvas with Babel, runs it from
@@ -230,7 +226,8 @@ export function buildSandboxDocument(
// back to the host-mediated path.
let phClient = null;
window.ph = {
- // Run a named, server-stored query (the only shape allowed in view mode).
+ // Run a named, server-stored query — the published tier's model. The host
+ // still rejects it (Phase 3).
run: (name, params) => call("run", { name, params: params ?? {} }),
// PREFERRED data path: load a SAVED, validated insight by its short id and
// render its STORED result from the insights endpoint (not a fresh /query/
@@ -250,7 +247,7 @@ export function buildSandboxDocument(
}),
// Run a query. Pass a TYPED query node (\`{ kind: "TrendsQuery", … }\`) for
// UI-matching numbers (preferred), or an inline HogQL string (escape hatch).
- // Edit mode only; rejected by the host in view mode.
+ // A built canvas needs \`capabilities.posthog.inlineQueries\` for this.
query: (queryOrHogql, params) =>
call(
"query",
@@ -659,15 +656,12 @@ ${FREEFORM_QUILL_CSS_URLS.map(
</html>`;
}
-// The iframe CSP (third isolation layer). `connect-src` matters most: in view
-// mode it is otherwise locked down so a published canvas can't phone home. When
-// analytics/replay is on we open ONLY the PostHog ingest + assets hosts (so
-// posthog-js can load its recorder and POST events/replay) — never arbitrary
-// egress.
-function contentSecurityPolicy(
- mode: SandboxMode,
- analyticsApiHost?: string,
-): string {
+// The iframe CSP (third isolation layer). This document only ever renders a
+// canvas its own author is editing, so it trusts the CDNs it has to fetch from
+// to transpile and resolve imports. A published canvas is not served from here —
+// it is a compiled artifact in BuiltCanvas, whose host document carries its own,
+// far tighter policy. Do not widen this one on a published canvas's behalf.
+function contentSecurityPolicy(analyticsApiHost?: string): string {
const esm = FREEFORM_ESM_HOST;
// posthog-js posts events to the api host and loads the recorder from the
// region assets host; allow both. Wildcards cover PostHog Cloud regions; the
@@ -675,41 +669,27 @@ function contentSecurityPolicy(
const ph = analyticsApiHost
? `${analyticsApiHost} https://*.posthog.com https://*.i.posthog.com`
: "";
-
- if (mode === "edit") {
- // Only the ACTIVE Tailwind engine's CDN is trusted (not both), and the v4
- // build is path-scoped to the @tailwindcss namespace on jsdelivr rather than
- // the whole origin — both narrow the code-execution sandbox's egress to
- // exactly what it fetches. v3's Play CDN loads from arbitrary sub-paths, so
- // it stays origin-scoped (it's only the fallback, off by default).
- const twCdn =
- TAILWIND_ENGINE === "v4"
- ? "https://cdn.jsdelivr.net/npm/@tailwindcss/"
- : "https://cdn.tailwindcss.com";
- return [
- "default-src 'none'",
- // Inline bootstrap + esm.sh modules + the transpiled Blob module + the
- // posthog-js recorder script + the in-browser Tailwind engine (JIT-compiles,
- // so 'unsafe-eval' is required). Edit-mode ONLY — view mode keeps egress
- // locked and self-hosts styles instead.
- `script-src 'unsafe-inline' 'unsafe-eval' blob: ${twCdn} ${esm} ${ph}`,
- `style-src 'unsafe-inline' ${esm}`,
- `font-src data: ${esm}`,
- "img-src data: blob: https:",
- `worker-src blob:`,
- // esm.sh + Tailwind CDN sub-fetches; canvas DATA goes over postMessage (not
- // connect), but posthog-js events/replay DO use connect to the PostHog hosts.
- `connect-src ${esm} ${twCdn} ${ph}`,
- ].join("; ");
- }
- // view / published: self-hosted, frozen. Only egress is PostHog analytics.
+ // Only the ACTIVE Tailwind engine's CDN is trusted (not both), and the v4
+ // build is path-scoped to the @tailwindcss namespace on jsdelivr rather than
+ // the whole origin — both narrow the code-execution sandbox's egress to
+ // exactly what it fetches. v3's Play CDN loads from arbitrary sub-paths, so
+ // it stays origin-scoped (it's only the fallback, off by default).
+ const twCdn =
+ TAILWIND_ENGINE === "v4"
+ ? "https://cdn.jsdelivr.net/npm/@tailwindcss/"
+ : "https://cdn.tailwindcss.com";
return [
"default-src 'none'",
- `script-src 'unsafe-inline' blob: 'self' ${ph}`,
- "style-src 'unsafe-inline' 'self'",
- "font-src data: 'self'",
- "img-src data: blob: 'self'",
+ // Inline bootstrap + esm.sh modules + the transpiled Blob module + the
+ // posthog-js recorder script + the in-browser Tailwind engine (JIT-compiles,
+ // so 'unsafe-eval' is required).
+ `script-src 'unsafe-inline' 'unsafe-eval' blob: ${twCdn} ${esm} ${ph}`,
+ `style-src 'unsafe-inline' ${esm}`,
+ `font-src data: ${esm}`,
+ "img-src data: blob: https:",
`worker-src blob:`,
- `connect-src 'self' ${ph}`,
+ // esm.sh + Tailwind CDN sub-fetches; canvas DATA goes over postMessage (not
+ // connect), but posthog-js events/replay DO use connect to the PostHog hosts.
+ `connect-src ${esm} ${twCdn} ${ph}`,
].join("; ");
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts
index 0fcafcbadaa7..b36bb00cde2b 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts
@@ -58,23 +58,14 @@ export function useGenerateFreeformCanvas(args: {
const generate = useCallback(
async (opts: {
- // The canvas being generated, when the surface already knows it. The
- // channel composer omits it — the agent resolves or creates the target
- // itself, so no canvas record is touched client-side.
- dashboardId?: string;
- name?: string;
+ dashboardId: string;
+ name: string;
templateId?: string;
instruction: string;
- /** True when the canvas already has published source (a follow-up edit
- * rather than a first build). The agent re-reads the live source itself
- * through the canvas tools. */
- isEdit?: boolean;
// The composer's picks, when the surface exposes model/effort selectors.
adapter?: Adapter;
model?: string;
reasoningLevel?: string;
- // Seed the starter scaffold on first build.
- useStarter?: boolean;
// Dev-only override (the bar exposes a local/cloud picker in dev so a
// local build of these features can be tested before merging). Production
// always runs in the cloud.
@@ -108,8 +99,6 @@ export function useGenerateFreeformCanvas(args: {
name,
templateId: opts.templateId,
instruction,
- isEdit: opts.isEdit ?? false,
- useStarter: opts.useStarter,
channelId,
channelName,
channelContext,
@@ -135,17 +124,12 @@ export function useGenerateFreeformCanvas(args: {
// Track this run so a toast (with a link back here) fires when it
// finishes, even after the user navigates to another canvas.
- // Target-less runs aren't tracked: there is no canvas to link to until
- // the agent resolves or creates one, and their channel feed card
- // already carries completion.
- if (dashboardId) {
- useCanvasGenerationTrackerStore.getState().track({
- taskId: result.taskId,
- dashboardId,
- channelId,
- name: name ?? "Canvas",
- });
- }
+ useCanvasGenerationTrackerStore.getState().track({
+ taskId: result.taskId,
+ dashboardId,
+ channelId,
+ name,
+ });
// Refresh the workspace cache so the new cloud workspace row appears and
// the task view resolves the cloud run instead of the repo-picker prompt.
void queryClient.invalidateQueries({
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.test.tsx b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.test.tsx
index c32b61c26724..253d9b131626 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.test.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.test.tsx
@@ -30,18 +30,4 @@ describe("ModeSelector", () => {
"Plan",
);
});
-
- it("shows Canvas on the trigger while canvas mode is armed", () => {
- render(
- <ModeSelector
- modeOption={modeOption("plan")}
- onChange={vi.fn()}
- allowBypassPermissions={false}
- canvas={{ active: true, onToggle: vi.fn() }}
- />,
- );
- const trigger = screen.getByRole("button", { name: "Mode" });
- expect(trigger).toHaveTextContent("Canvas");
- expect(trigger).not.toHaveTextContent("Plan");
- });
});
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
index ad75a31501c6..4fbdaa4fa124 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/ModeSelector.tsx
@@ -29,16 +29,6 @@ interface ModeSelectorProps {
active: boolean;
onToggle: () => void;
};
- /**
- * When provided, a "Canvas" toggle renders in the same trailing section
- * (channels composer only). Arming it makes the next submit generate a
- * canvas from the prompt instead of creating a plain task; while armed the
- * trigger reads "Canvas" so the composer's state is visible at a glance.
- */
- canvas?: {
- active: boolean;
- onToggle: () => void;
- };
}
export function ModeSelector({
@@ -47,7 +37,6 @@ export function ModeSelector({
allowBypassPermissions,
disabled,
autoresearch,
- canvas,
}: ModeSelectorProps) {
const [open, setOpen] = useState(false);
const pendingValueRef = useRef<string | null>(null);
@@ -74,27 +63,20 @@ export function ModeSelector({
if (options.length === 0) return null;
const currentValue = displayOption.currentValue;
- const canvasActive = !!canvas?.active;
- const currentLabel = canvasActive
- ? "Canvas"
- : (allOptions.find((opt) => opt.value === currentValue)?.name ??
- currentValue);
+ const currentLabel =
+ allOptions.find((opt) => opt.value === currentValue)?.name ?? currentValue;
// Running unsupervised is the only mode the trigger colours at all, and it
// does so as a whole destructive button rather than a tinted label — a mode
// tint per mode turns the toolbar into a palette and stops reading as a
// warning where it matters.
const bypassActive =
- !canvasActive &&
- (currentValue === "bypassPermissions" || currentValue === "full-access");
+ currentValue === "bypassPermissions" || currentValue === "full-access";
const toggles: Array<{
label: string;
active: boolean;
onToggle: () => void;
}> = [];
- if (canvas) {
- toggles.push({ label: "Canvas", ...canvas });
- }
if (autoresearch) {
toggles.push({ label: "Autoresearch", ...autoresearch });
}
@@ -108,8 +90,6 @@ export function ModeSelector({
if (pendingValueRef.current !== null) {
onChange(pendingValueRef.current);
pendingValueRef.current = null;
- // Picking a plain mode leaves canvas mode; the two are exclusive.
- if (canvasActive) canvas?.onToggle();
}
const pendingToggle = pendingToggleRef.current;
pendingToggleRef.current = null;
@@ -137,9 +117,7 @@ export function ModeSelector({
>
<MenuLabel>Mode</MenuLabel>
<DropdownMenuRadioGroup
- // While canvas mode is armed it reads as the selected mode, so no
- // plain-mode radio shows checked.
- value={canvasActive ? "" : currentValue}
+ value={currentValue}
onValueChange={(value) => {
pendingValueRef.current = value;
setOpen(false);
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
index 80990ae1e015..6b7d8e13fa85 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
@@ -61,14 +61,6 @@ export interface PromptInputProps {
active: boolean;
onToggle: () => void;
};
- /**
- * When provided, the mode dropdown gains a "Canvas" toggle (channels
- * composer only). `active` drives its checkmark and the trigger label.
- */
- canvas?: {
- active: boolean;
- onToggle: () => void;
- };
// capabilities
enableBashMode?: boolean;
enableCommands?: boolean;
@@ -151,7 +143,6 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
onModeChange,
allowBypassPermissions = false,
autoresearch,
- canvas,
enableBashMode = false,
enableCommands = true,
modelSelector,
@@ -486,7 +477,6 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
allowBypassPermissions={allowBypassPermissions}
disabled={disabled}
autoresearch={autoresearch}
- canvas={canvas}
/>
)}
{isBashMode && (