Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): grid canvas renderer, editor, and home tab (#83549)

Peter Kirkham93034dcf2e62
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 44338b648b1e..6c78b392b892 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -27,7 +27,7 @@ const runtimePath = 'assets/canvas-runtime.js'
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
// A published canvas runs the runtime baked into its artifact by this builder,
// while an unpublished one runs the desktop's sandbox document — two copies of
// the same selection behavior. The pair below is ported from the desktop's
diff --git a/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts b/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
index 4d672b009c4b..f750de7116cd 100644
--- a/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasApplicationService.test.ts
@@ -68,16 +68,18 @@ describe("CanvasApplicationService", () => {
const result = await service.generateCanvas(input(), gateway);
expect(result).toEqual({ ok: true, taskId: "task-1" });
+ // No caller pick: prefer Sonnet 5 over the gateway's default, validated
+ // by the resolver against the gateway's model list.
expect(resolveDefaultModel).toHaveBeenCalledWith(
"https://us.posthog.com",
"claude",
- undefined,
+ "claude-sonnet-5",
);
const [taskInput] = createTask.mock.calls[0];
expect(taskInput.content).toContain("`building-canvases` skill");
expect(taskInput.content).toContain('canvas id: "dash-1"');
expect(taskInput).toMatchObject({
- executionMode: "auto",
+ executionMode: "bypassPermissions",
workspaceMode: "cloud",
adapter: "claude",
model: "model-1",
@@ -87,6 +89,76 @@ describe("CanvasApplicationService", () => {
expect(gateway.setGenerationTask).toHaveBeenCalledWith("dash-1", "task-1");
});
+ it("scopes a placement fill to its tile: skill routing, no canvas-level generation state", async () => {
+ const { service, createTask, generateCanvasName } = makeDeps();
+ const gateway = makeGateway();
+
+ const result = await service.generateCanvas(
+ input({
+ name: "Untitled canvas",
+ placement: { placementId: "p-1", w: 2, h: 1 },
+ }),
+ gateway,
+ );
+
+ expect(result).toEqual({ ok: true, taskId: "task-1" });
+ const [taskInput] = createTask.mock.calls[0];
+ expect(taskInput.content).toContain("`composing-grid-canvases` skill");
+ expect(taskInput.content).toContain('placement id: "p-1"');
+ // Named after the widget, not the canvas — every fill on the same canvas
+ // would otherwise share one "Generate canvas ..." title.
+ expect(taskInput.taskDescription).toBe(
+ "Generate widget: build a signups chart",
+ );
+ expect(gateway.fileTask).toHaveBeenCalledWith("chan-1", "task-1");
+ // The placement row carries the task id; the canvas itself is not
+ // generating and must not be renamed from one widget's prompt.
+ expect(gateway.setGenerationTask).not.toHaveBeenCalled();
+ expect(generateCanvasName).not.toHaveBeenCalled();
+ });
+
+ it("routes a whole-grid-canvas run to the grid skill and records it on the canvas", async () => {
+ const { service, createTask } = makeDeps();
+ const gateway = makeGateway();
+
+ const result = await service.generateCanvas(
+ input({
+ name: "Home",
+ instruction: "fix the weather widget's query",
+ canvasKind: "grid",
+ }),
+ gateway,
+ );
+
+ expect(result).toEqual({ ok: true, taskId: "task-1" });
+ const [taskInput] = createTask.mock.calls[0];
+ expect(taskInput.content).toContain("`composing-grid-canvases` skill");
+ expect(taskInput.content).toContain("WHOLE grid canvas");
+ expect(taskInput.taskDescription).toBe(
+ 'Update canvas "Home": fix the weather widget\'s query',
+ );
+ // The whole-canvas conversation is recorded so it can be reopened.
+ expect(gateway.setGenerationTask).toHaveBeenCalledWith("dash-1", "task-1");
+ });
+
+ // The effort default must follow the model: "high" sent alongside a
+ // fallback model that doesn't support it makes the task API reject the run.
+ it.each([
+ ["claude-sonnet-5", "high"],
+ ["model-1", undefined],
+ ])(
+ "defaults reasoning effort only when the preferred model resolved (%s)",
+ async (resolved, expectedEffort) => {
+ const { service, createTask } = makeDeps({
+ resolveDefaultModel: vi.fn().mockResolvedValue(resolved),
+ });
+
+ await service.generateCanvas(input(), makeGateway());
+
+ expect(createTask.mock.calls[0][0].reasoningLevel).toBe(expectedEffort);
+ },
+ );
+
it.each([
["no signed-in region", input({ cloudRegion: null })],
["resolver returns nothing", input(), vi.fn().mockResolvedValue(undefined)],
diff --git a/products/desktop/packages/core/src/canvas/canvasApplicationService.ts b/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
index 6f12385d6272..d7401bfd5067 100644
--- a/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
+++ b/products/desktop/packages/core/src/canvas/canvasApplicationService.ts
@@ -21,13 +21,24 @@ import {
} from "@posthog/shared";
import { inject, injectable } from "inversify";
import { isPlaceholderCanvasName } from "./canvasNaming";
-import { buildCanvasGenerationPrompt } from "./generationPrompt";
+import {
+ buildCanvasGenerationPrompt,
+ buildGridCanvasGenerationPrompt,
+ buildPlacementGenerationPrompt,
+} from "./generationPrompt";
export interface GenerateCanvasInput {
dashboardId: string;
name: string;
templateId?: string;
instruction: string;
+ /** When set, the run fills ONE placement on a grid canvas instead of
+ * authoring the canvas itself (composing-grid-canvases skill routing). */
+ placement?: { placementId: string; w: number; h: number };
+ /** "grid" routes a whole-canvas run (no placement) to the grid skill:
+ * the agent edits the layout and its components instead of authoring a
+ * freeform canvas app. */
+ canvasKind?: "grid";
/** Backend channel (task channel UUID) that owns the canvas and the task. */
channelId: string;
channelName: string;
@@ -59,6 +70,24 @@ export interface CanvasGenerationGateway {
onAutoNamed?(taskId: string, title: string): void;
}
+// Unattended canvas runs default to Claude Sonnet 5 at high reasoning effort.
+// The resolver validates the id against the gateway's model list, so when it's
+// absent the run falls back to the server default instead of failing — and the
+// effort default follows the model: it only applies when the preferred model
+// actually resolved, because other models may not support that effort tier.
+const CANVAS_PREFERRED_ADAPTER = "claude" as const;
+const CANVAS_PREFERRED_MODEL = "claude-sonnet-5";
+const CANVAS_PREFERRED_REASONING = "high";
+
+const TASK_TITLE_MAX = 80;
+
+function truncateForTitle(text: string): string {
+ const flattened = text.replace(/\s+/g, " ").trim();
+ return flattened.length > TASK_TITLE_MAX
+ ? `${flattened.slice(0, TASK_TITLE_MAX - 1)}…`
+ : flattened;
+}
+
export type GenerateCanvasResult =
| { ok: true; taskId: string }
| { ok: false; reason: "no-model" }
@@ -105,7 +134,7 @@ export class CanvasApplicationService {
gateway: CanvasGenerationGateway,
): Promise<GenerateCanvasResult> {
const {
- adapter = "claude",
+ adapter = CANVAS_PREFERRED_ADAPTER,
// Defaults to a cloud run — canvas generation should never tie up (or
// depend on) the local machine. The dev-only picker can override to
// "local" to test a local build of these features before merging.
@@ -122,7 +151,12 @@ export class CanvasApplicationService {
? await this.modelResolver.resolveDefaultModel(
getCloudUrlFromRegion(input.cloudRegion),
adapter,
- input.model,
+ input.model ??
+ // The preferred id only fits its own adapter; a caller-picked
+ // other adapter resolves to that adapter's server default.
+ (adapter === CANVAS_PREFERRED_ADAPTER
+ ? CANVAS_PREFERRED_MODEL
+ : null),
)
: undefined;
if (!model) {
@@ -132,23 +166,66 @@ export class CanvasApplicationService {
const result = await this.taskService.createTask(
{
- content: buildCanvasGenerationPrompt({
- dashboardId: input.dashboardId,
- name: input.name,
- channelName: input.channelName,
- templateId: input.templateId,
- instruction: input.instruction,
- }),
- taskDescription: input.name
- ? `Generate canvas "${input.name}"`
- : `Generate a canvas in ${channelDisplayReference(input.channelName)}`,
- // Unattended generation: run in auto mode so it doesn't stall on
- // edit-approval prompts.
- executionMode: "auto" as const,
+ content: input.placement
+ ? buildPlacementGenerationPrompt({
+ dashboardId: input.dashboardId,
+ name: input.name,
+ channelName: input.channelName,
+ instruction: input.instruction,
+ placementId: input.placement.placementId,
+ boxWidth: input.placement.w,
+ boxHeight: input.placement.h,
+ })
+ : input.canvasKind === "grid"
+ ? buildGridCanvasGenerationPrompt({
+ dashboardId: input.dashboardId,
+ name: input.name,
+ channelName: input.channelName,
+ instruction: input.instruction,
+ })
+ : buildCanvasGenerationPrompt({
+ dashboardId: input.dashboardId,
+ name: input.name,
+ channelName: input.channelName,
+ templateId: input.templateId,
+ instruction: input.instruction,
+ }),
+ // A placement fill is named after its widget — every fill on the same
+ // canvas would otherwise share one useless "Generate canvas Home" title.
+ taskDescription: input.placement
+ ? `Generate widget: ${truncateForTitle(input.instruction)}`
+ : input.canvasKind === "grid"
+ ? `Update canvas "${input.name}": ${truncateForTitle(input.instruction)}`
+ : input.name
+ ? `Generate canvas "${input.name}"`
+ : `Generate a canvas in ${channelDisplayReference(input.channelName)}`,
+ // Unattended generation: auto mode relays every MCP approval to the
+ // desktop and blocks the run until someone answers. What still applies
+ // in bypass mode: do_not_use tools stay denied, tools on MCP servers
+ // relayed to the user's machine still need their approval, and PostHog
+ // exec sub-tools matching the run's permission regex are still relayed
+ // for one. It does NOT contain the run to the canvas API.
+ //
+ // TODO(canvas mcp scopes): bypassing is only defensible once this run's
+ // token is narrowed. A client-created run sends runSource "manual",
+ // which resolves to "full" PostHog MCP scopes in
+ // products/tasks/backend/facade/api.py (insight, dashboard and flag
+ // writes, plus SQL), while the prompt carries channel context and canvas
+ // comments other people wrote. ReviewHog's sandbox passes an explicit
+ // scope list for exactly this reason (see REVIEW_MCP_SCOPES), but the
+ // REST run-create surface exposes no scope field, so a client cannot ask
+ // for one. Both canvas surfaces CAN answer an approval today
+ // (CanvasPermissionDialog on freeform, Review request on a grid tile),
+ // so this mode also switches off a gate that works.
+ executionMode: "bypassPermissions" as const,
workspaceMode,
adapter,
model,
- reasoningLevel: input.reasoningLevel,
+ reasoningLevel:
+ input.reasoningLevel ??
+ (model === CANVAS_PREFERRED_MODEL
+ ? CANVAS_PREFERRED_REASONING
+ : undefined),
allowNoRepo: true,
channelContext: input.channelContext,
channelName: input.channelName,
@@ -169,6 +246,12 @@ export class CanvasApplicationService {
});
const dashboardId = input.dashboardId;
+ // A placement fill is scoped to one tile: the placement row carries the
+ // task id, so the whole canvas must not read as "generating" (nor get
+ // auto-renamed from a single widget's prompt).
+ if (input.placement) {
+ return { ok: true, taskId: task.id };
+ }
await gateway.setGenerationTask(dashboardId, task.id).catch((error) => {
this.log.warn("Failed to record canvas generation task", { error });
});
diff --git a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
index 9caa7168f9ac..aaefda2b3a4e 100644
--- a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
@@ -2,10 +2,12 @@ import { describe, expect, it, vi } from "vitest";
import {
type CanvasBuildLifecycle,
type CanvasBuildRecord,
+ canvasBuildRecordSchema,
currentHeadBuildFailure,
hasActiveCanvasBuild,
historicalCanvasBuild,
latestFinishedCanvasBuild,
+ placementComponentBuild,
publishedCanvasBuild,
} from "./canvasBuildSchemas";
import { DashboardsService } from "./dashboardsService";
@@ -37,6 +39,32 @@ function lifecycle(builds: CanvasBuildRecord[]): CanvasBuildLifecycle {
}
describe("canvas build lifecycle", () => {
+ // The builder freezes project.capabilities into the manifest verbatim, and
+ // a project declares only the capabilities it uses. A partial manifest must
+ // parse with deny-by-default fills — an unparseable record is silently
+ // dropped, which rendered a ready build as "failed to build" on grid tiles.
+ it("parses a manifest declaring only the capabilities the project uses", () => {
+ const parsed = canvasBuildRecordSchema.parse({
+ ...build("b1", "ready"),
+ manifest: {
+ entryHtml: "index.html",
+ assets: [],
+ dependencies: { react: "19.0.0" },
+ canvasSdkVersion: "0.1.0",
+ capabilities: {
+ posthog: { state: ["user"] },
+ network: { origins: [] },
+ },
+ },
+ });
+ expect(parsed.manifest?.capabilities.posthog).toMatchObject({
+ insights: [],
+ inlineQueries: false,
+ captureEvents: [],
+ state: ["user"],
+ });
+ });
+
// hasActiveCanvasBuild drives the polling interval: a wrong answer either
// polls forever or stops while a build is still running.
it.each([
@@ -101,6 +129,36 @@ describe("canvas build lifecycle", () => {
).toBeNull();
});
+ // A pinned placement's config and size were written against the version it
+ // names, so rendering the live build instead would feed the widget a
+ // contract nobody validated it for.
+ it("renders a pinned placement from the pinned version's own build", () => {
+ const pinned = build("pinned", "ready");
+ pinned.sourceVersionId = "version-1";
+ const value = lifecycle([build("live", "ready"), pinned]);
+ value.publishedBuildId = "live";
+
+ expect(placementComponentBuild(value, "version-1")).toBe(pinned);
+ });
+
+ // Build retention can sweep a pinned version's artifact (only an explicit
+ // pin action protects a build), and falling back to the live build would
+ // silently render a different widget than the placement asked for.
+ it("resolves no build when the pinned version's artifact is gone", () => {
+ const value = lifecycle([build("live", "ready")]);
+ value.publishedBuildId = "live";
+
+ expect(placementComponentBuild(value, "version-1")).toBeNull();
+ });
+
+ it("follows the published pointer when the placement pins nothing", () => {
+ const live = build("live", "ready");
+ const value = lifecycle([live, build("older", "ready")]);
+ value.publishedBuildId = "live";
+
+ expect(placementComponentBuild(value, null)).toBe(live);
+ });
+
it("surfaces a failed build of the current head even when an older published build is also ready", () => {
// b_old (sv-old) is the pinned/published live build; a newer publish (b_new,
// sv-new = current head) failed. latestFinishedCanvasBuild returns the first
diff --git a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts
index 9ec9e9cdfa5a..9c7fddd3c978 100644
--- a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts
@@ -56,6 +56,27 @@ export function historicalCanvasBuild(
);
}
+/**
+ * The build a grid placement renders: the component's live build when the
+ * placement follows the latest version, or the pinned version's own retained
+ * artifact. A pin resolves to nothing rather than falling back to the live
+ * build — the placement's config was written against the version it names, and
+ * retention can sweep an unpinned artifact, so the caller must say the pinned
+ * version is unavailable instead of quietly rendering a different widget.
+ */
+export function placementComponentBuild(
+ lifecycle: CanvasBuildLifecycle,
+ pinnedVersionId: string | null,
+): CanvasBuildRecord | null {
+ if (pinnedVersionId) {
+ return historicalCanvasBuild(lifecycle, pinnedVersionId);
+ }
+ return (
+ lifecycle.builds.find((build) => build.id === lifecycle.publishedBuildId) ??
+ null
+ );
+}
+
export const canvasBuildLifecycleSchema = z.object({
/** The live (last successful, still-eligible) build, null until one completes. */
publishedBuildId: z.string().nullable(),
diff --git a/products/desktop/packages/core/src/canvas/channelItems.test.ts b/products/desktop/packages/core/src/canvas/channelItems.test.ts
index 6dfe239ece69..ffe4c3415653 100644
--- a/products/desktop/packages/core/src/canvas/channelItems.test.ts
+++ b/products/desktop/packages/core/src/canvas/channelItems.test.ts
@@ -36,6 +36,8 @@ function canvas(over: Partial<DashboardRecord> = {}): DashboardRecord {
id: "d1",
channelId: "c1",
name: "Canvas",
+ kind: "freeform" as const,
+ description: "",
templateId: "freeform",
context: "",
createdAt: 0,
diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
index d01385c7d962..90b9df677d3d 100644
--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
@@ -4,16 +4,27 @@ import {
} from "@posthog/shared";
import { z } from "zod";
import { canvasAgentRequestInputSchema } from "./freeformSchemas";
+import { componentMetaSchema } from "./gridLayoutSchemas";
// A canvas record from the PostHog canvases API, normalized to camelCase and
// epoch-ms timestamps. Source code and version history are NOT part of the
// record — they live behind the source/versions endpoints, and the rendered
// output behind the build lifecycle.
+export const canvasKindSchema = z.enum(["freeform", "grid", "component"]);
+export type CanvasKind = z.infer<typeof canvasKindSchema>;
+
export const dashboardRecordSchema = z.object({
id: z.string(),
// The backend channel (task channel UUID) this canvas belongs to.
channelId: z.string(),
name: z.string(),
+ // freeform: a standalone app. component: a reusable widget grids place.
+ // grid: a composition of components (its source is a layout document).
+ kind: canvasKindSchema.default("freeform"),
+ // Short prose describing the canvas; for components, the store-search text.
+ description: z.string().default(""),
+ // For components: the head version's placement contract (size, configSchema).
+ componentMeta: componentMetaSchema.nullish(),
templateId: z.string().default("freeform"),
// The live author-written context (markdown) passed to the agent.
context: z.string().default(""),
@@ -82,6 +93,12 @@ export type CanvasSource = z.infer<typeof canvasSourceSchema>;
export const listDashboardsInput = z.object({ channelId: z.string().min(1) });
+// The component store: component-kind canvases across every channel visible to
+// the caller, optionally narrowed by a name/description search.
+export const listComponentsInput = z.object({
+ search: z.string().optional(),
+});
+
export const createDashboardInput = z.object({
channelId: z.string().min(1),
name: z.string().min(1),
diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.ts
index 59a41c5cac0a..13708f327180 100644
--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts
@@ -21,6 +21,12 @@ import {
canvasAgentRequestResultSchema,
FREEFORM_TEMPLATE_ID,
} from "./freeformSchemas";
+import {
+ type CanvasLayout,
+ type CanvasLayoutResult,
+ componentMetaSchema,
+ type LayoutOperation,
+} from "./gridLayoutSchemas";
import {
PROJECT_API_CLIENT,
type ProjectApiClient,
@@ -31,6 +37,9 @@ import {
interface ApiCanvas {
id: string;
name: string;
+ kind?: "freeform" | "grid" | "component";
+ description?: string;
+ component_meta?: unknown;
channel: string;
template_id: string;
context: string;
@@ -82,10 +91,16 @@ function toEpoch(value: string | null | undefined): number | undefined {
}
function toRecord(api: ApiCanvas): DashboardRecord {
+ // Fail-soft on the contract shape: a meta this client doesn't understand
+ // renders as "not placeable", never a crashed record list.
+ const meta = componentMetaSchema.safeParse(api.component_meta);
return {
id: api.id,
channelId: api.channel,
name: api.name,
+ kind: api.kind ?? "freeform",
+ description: api.description ?? "",
+ componentMeta: meta.success ? meta.data : null,
templateId: api.template_id || FREEFORM_TEMPLATE_ID,
context: api.context ?? "",
generationTaskId: api.generation_task_id,
@@ -154,6 +169,20 @@ export class DashboardsService {
return toRecord((await res.json()) as ApiCanvas);
}
+ // The component store: component-kind canvases across every channel visible
+ // to the caller, optionally narrowed by a name/description search.
+ async listComponents(input: { search?: string }): Promise<DashboardRecord[]> {
+ const search = input.search
+ ? `&search=${encodeURIComponent(input.search)}`
+ : "";
+ const rows = await this.api.listPaginated<ApiCanvas>(
+ `canvases/?kind=component${search}`,
+ "list canvas components",
+ { limit: 200 },
+ );
+ return rows.map(toRecord);
+ }
+
async create(input: {
channelId: string;
name: string;
@@ -171,6 +200,90 @@ export class DashboardsService {
return toRecord(api);
}
+ // Get-or-create the caller's home canvas: a grid canvas in their personal
+ // channel, pointed at by their home preference. Idempotent.
+ async home(): Promise<DashboardRecord> {
+ const api = await this.api.json<ApiCanvas>(
+ `canvases/home/`,
+ "provision home canvas",
+ { method: "POST" },
+ );
+ return toRecord(api);
+ }
+
+ // Read a grid canvas's layout document — the head, or a historical version.
+ async getLayout(input: {
+ id: string;
+ versionId?: string;
+ }): Promise<CanvasLayoutResult> {
+ const suffix = input.versionId
+ ? `?version_id=${encodeURIComponent(input.versionId)}`
+ : "";
+ const body = await this.api.json<{
+ layout: CanvasLayout;
+ current_version_id: string | null;
+ }>(
+ `canvases/${encodeURIComponent(input.id)}/layout/${suffix}`,
+ "load canvas layout",
+ );
+ return { layout: body.layout, currentVersionId: body.current_version_id };
+ }
+
+ // Publish a complete layout document as the grid canvas's new head. Live
+ // immediately — layout is data, no build runs.
+ async publishLayout(input: {
+ id: string;
+ layout: CanvasLayout;
+ prompt?: string;
+ expectedCurrentVersionId: string | null;
+ }): Promise<CanvasLayoutResult> {
+ const body = await this.api.json<{
+ layout: CanvasLayout;
+ current_version_id: string;
+ }>(
+ `canvases/${encodeURIComponent(input.id)}/layout/publish/`,
+ "publish canvas layout",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ layout: input.layout,
+ prompt: input.prompt,
+ expected_current_version_id: input.expectedCurrentVersionId,
+ }),
+ },
+ );
+ return { layout: body.layout, currentVersionId: body.current_version_id };
+ }
+
+ // Apply surgical operations to the grid canvas's current layout — the
+ // default write path, guarded so concurrent edits conflict (409) instead of
+ // silently merging.
+ async patchLayout(input: {
+ id: string;
+ operations: LayoutOperation[];
+ prompt?: string;
+ expectedCurrentVersionId: string | null;
+ }): Promise<CanvasLayoutResult> {
+ const body = await this.api.json<{
+ layout: CanvasLayout;
+ current_version_id: string;
+ }>(
+ `canvases/${encodeURIComponent(input.id)}/layout/patch/`,
+ "patch canvas layout",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ operations: input.operations,
+ prompt: input.prompt,
+ expected_current_version_id: input.expectedCurrentVersionId,
+ }),
+ },
+ );
+ return { layout: body.layout, currentVersionId: body.current_version_id };
+ }
+
private async patch(
id: string,
body: Record<string, unknown>,
diff --git a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts b/products/desktop/packages/core/src/canvas/freeformWhitelist.ts
index 0a3d631db78c..ee69ee03581e 100644
--- a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts
+++ b/products/desktop/packages/core/src/canvas/freeformWhitelist.ts
@@ -43,7 +43,12 @@ export const FREEFORM_WHITELIST: WhitelistEntry[] = [
{
name: "@posthog/quill",
version: QUILL_VERSION,
- esm: `${ESM}/@posthog/quill@${QUILL_VERSION}?external=react,react-dom`,
+ // `deps` pins quill's Base UI to the version the canvas builder bundles.
+ // Left floating (quill declares ^1.4.0), esm.sh resolves the newest Base
+ // UI, and its 1.7.0 build emits literal `#prehydration/...` specifiers
+ // that browsers read as URL fragments — the esm.sh homepage comes back as
+ // text/html and the whole quill module graph fails to load.
+ esm: `${ESM}/@posthog/quill@${QUILL_VERSION}?external=react,react-dom&deps=@base-ui/[email protected]`,
},
// One charting library (the conventional React pick).
{
diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.ts b/products/desktop/packages/core/src/canvas/generationPrompt.ts
index 32a0d2e599f6..ef6d91125df2 100644
--- a/products/desktop/packages/core/src/canvas/generationPrompt.ts
+++ b/products/desktop/packages/core/src/canvas/generationPrompt.ts
@@ -1,6 +1,71 @@
import { escapeXmlAttr } from "@posthog/shared";
import { FREEFORM_TEMPLATE_ID } from "./freeformSchemas";
+// A generation task scoped to one placement on a grid canvas: the agent fills
+// the drawn box by placing a store component or building a new one, following
+// the composing-grid-canvases skill rather than the freeform one.
+export function buildPlacementGenerationPrompt(input: {
+ dashboardId: string;
+ name: string;
+ channelName: string;
+ instruction: string;
+ placementId: string;
+ boxWidth: number;
+ boxHeight: number;
+}): string {
+ return `${input.instruction}
+
+<canvas_generation_instructions>
+Invoke the \`composing-grid-canvases\` skill and follow it completely.
+
+You are filling ONE placement on a grid canvas. Resolve it with the skill's
+ladder: search the component store first, fork when close, build a new
+component only when nothing fits. When the placement is ready, patch it to
+status "live" with the component id and config, keeping its prompt intact.
+On failure, patch it to status "failed" instead of leaving it generating.
+
+Target:
+- grid canvas id: "${escapeXmlAttr(input.dashboardId)}"
+- grid canvas name: "${escapeXmlAttr(input.name)}"
+- channel: "${escapeXmlAttr(input.channelName)}"
+- placement id: "${escapeXmlAttr(input.placementId)}"
+- drawn box: ${input.boxWidth}x${input.boxHeight} grid units (a small box wants a glanceable tile; a large one a full app surface)
+</canvas_generation_instructions>`;
+}
+
+// A task scoped to a whole grid canvas: the agent edits the layout itself and
+// the placed components, following the composing-grid-canvases skill.
+export function buildGridCanvasGenerationPrompt(input: {
+ dashboardId: string;
+ name: string;
+ channelName: string;
+ instruction: string;
+}): string {
+ return `${input.instruction}
+
+<canvas_generation_instructions>
+Invoke the \`composing-grid-canvases\` skill and follow it completely.
+
+You are working on the WHOLE grid canvas: add, fill, move, resize, or remove
+placements as the instruction requires, and edit the placed component
+canvases themselves when a widget needs fixing. One instruction often calls
+for SEVERAL widgets (e.g. "a canvas summarizing work in progress" wants a
+tile per concern): plan the full set first, resolve each with the skill's
+ladder (place from the store, fork, or build new), and lay them all out
+without overlap. Use the guarded patch loop, and never leave a placement in
+the generating state when you finish.
+
+Users leave feedback as comments on this canvas, attached to this task. List
+them with the task comment tools (e.g. \`tasks-comments-list\`) before and
+after making changes, and address the open ones.
+
+Target:
+- grid canvas id: "${escapeXmlAttr(input.dashboardId)}"
+- grid canvas name: "${escapeXmlAttr(input.name)}"
+- channel: "${escapeXmlAttr(input.channelName)}"
+</canvas_generation_instructions>`;
+}
+
export function buildCanvasGenerationPrompt(input: {
dashboardId: string;
name: string;
diff --git a/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts b/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts
new file mode 100644
index 000000000000..173dba5c1d49
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts
@@ -0,0 +1,123 @@
+import { z } from "zod";
+
+// A grid canvas's layout document — its entire "source". Layout is data:
+// publishes and patches are live immediately, with no build. The server
+// validates authoritatively (geometry, overlaps, component references); these
+// schemas are the transport shapes.
+
+export const gridDefinitionSchema = z.object({
+ columns: z.number().int(),
+ rowHeight: z.number().int(),
+ gap: z.number().int(),
+});
+export type GridDefinition = z.infer<typeof gridDefinitionSchema>;
+
+export const placementStatusSchema = z.enum([
+ "pending",
+ "generating",
+ "live",
+ "failed",
+]);
+export type PlacementStatus = z.infer<typeof placementStatusSchema>;
+
+export const gridPlacementSchema = z.object({
+ id: z.string(),
+ status: placementStatusSchema,
+ // The component canvas this placement renders (required once live).
+ component: z.string().nullish(),
+ // "latest" (default) or a pinned source version id of the component.
+ version: z.string().nullish(),
+ x: z.number().int(),
+ y: z.number().int(),
+ w: z.number().int(),
+ h: z.number().int(),
+ // Per-placement settings, validated server-side against the component's
+ // configSchema and delivered to the widget as ph.config.
+ config: z.record(z.string(), z.unknown()).nullish(),
+ // For pending/generating/failed placements: what the user asked the box to be.
+ prompt: z.string().nullish(),
+ // The agent task currently filling this placement, when one is running.
+ generationTaskId: z.string().nullish(),
+});
+export type GridPlacement = z.infer<typeof gridPlacementSchema>;
+
+const LATEST_COMPONENT_VERSION = "latest";
+
+/** The component source version a placement pins, or null when it follows the
+ * component's latest published build. */
+export function pinnedComponentVersion(
+ placement: Pick<GridPlacement, "version">,
+): string | null {
+ return placement.version && placement.version !== LATEST_COMPONENT_VERSION
+ ? placement.version
+ : null;
+}
+
+export const canvasLayoutSchema = z.object({
+ schemaVersion: z.number(),
+ grid: gridDefinitionSchema,
+ placements: z.array(gridPlacementSchema),
+});
+export type CanvasLayout = z.infer<typeof canvasLayoutSchema>;
+
+export const canvasLayoutResultSchema = z.object({
+ layout: canvasLayoutSchema,
+ // The head layout version — pass as expectedCurrentVersionId on writes.
+ currentVersionId: z.string().nullish(),
+});
+export type CanvasLayoutResult = z.infer<typeof canvasLayoutResultSchema>;
+
+// Fields an update op may merge into a placement (id is immutable).
+export const placementChangesSchema = gridPlacementSchema
+ .omit({ id: true })
+ .partial();
+export type PlacementChanges = z.infer<typeof placementChangesSchema>;
+
+export const layoutOperationSchema = z.discriminatedUnion("op", [
+ z.object({ op: z.literal("set_grid"), grid: gridDefinitionSchema }),
+ z.object({ op: z.literal("add_placement"), placement: gridPlacementSchema }),
+ z.object({
+ op: z.literal("update_placement"),
+ id: z.string(),
+ changes: placementChangesSchema,
+ }),
+ z.object({ op: z.literal("remove_placement"), id: z.string() }),
+]);
+export type LayoutOperation = z.infer<typeof layoutOperationSchema>;
+
+export const canvasLayoutInput = z.object({
+ id: z.string().min(1),
+ versionId: z.string().optional(),
+});
+
+export const publishLayoutInput = z.object({
+ id: z.string().min(1),
+ layout: canvasLayoutSchema,
+ prompt: z.string().optional(),
+ expectedCurrentVersionId: z.string().nullable(),
+});
+
+export const patchLayoutInput = z.object({
+ id: z.string().min(1),
+ operations: z.array(layoutOperationSchema).min(1),
+ prompt: z.string().optional(),
+ expectedCurrentVersionId: z.string().nullable(),
+});
+
+// A component's placement contract, snapshotted onto its head version and
+// frozen into its build manifest.
+export const componentSizeSchema = z.object({
+ defaultW: z.number().int(),
+ defaultH: z.number().int(),
+ minW: z.number().int(),
+ minH: z.number().int(),
+ maxW: z.number().int().optional(),
+ maxH: z.number().int().optional(),
+});
+export type ComponentSize = z.infer<typeof componentSizeSchema>;
+
+export const componentMetaSchema = z.object({
+ size: componentSizeSchema,
+ configSchema: z.record(z.string(), z.unknown()).optional(),
+});
+export type ComponentMeta = z.infer<typeof componentMetaSchema>;
diff --git a/products/desktop/packages/core/src/canvas/projectApiClient.ts b/products/desktop/packages/core/src/canvas/projectApiClient.ts
index 9debb9b4d483..3cccefa0f476 100644
--- a/products/desktop/packages/core/src/canvas/projectApiClient.ts
+++ b/products/desktop/packages/core/src/canvas/projectApiClient.ts
@@ -24,6 +24,36 @@ export function apiErrorStatus(error: unknown): number | null {
return error instanceof ProjectApiError ? error.status : null;
}
+// A DRF error body carries the actual cause ("detail", plus canvas validation
+// "diagnostics"); without it a 400 is undiagnosable from the client. Cap the
+// diagnostics so one broken layout doesn't produce a screen-length message.
+const MAX_ERROR_DIAGNOSTICS = 5;
+
+async function errorBodyDetail(res: Response): Promise<string> {
+ try {
+ const body: unknown = await res.json();
+ if (typeof body !== "object" || body === null) return "";
+ const parts: string[] = [];
+ const { detail, diagnostics } = body as {
+ detail?: unknown;
+ diagnostics?: unknown;
+ };
+ if (typeof detail === "string" && detail) parts.push(detail);
+ if (Array.isArray(diagnostics)) {
+ for (const diagnostic of diagnostics.slice(0, MAX_ERROR_DIAGNOSTICS)) {
+ const message = (diagnostic as { message?: unknown } | null)?.message;
+ if (typeof message === "string" && message) parts.push(message);
+ }
+ if (diagnostics.length > MAX_ERROR_DIAGNOSTICS) {
+ parts.push(`(+${diagnostics.length - MAX_ERROR_DIAGNOSTICS} more)`);
+ }
+ }
+ return parts.length > 0 ? `: ${parts.join(" ")}` : "";
+ } catch {
+ return "";
+ }
+}
+
/**
* Thin shared client for the current PostHog project's REST API. Resolves the
* project + auth, then forwards to authenticated fetch. Owners of typed
@@ -54,7 +84,7 @@ export class ProjectApiClient {
const res = await this.fetch(path, init);
if (!res.ok)
throw new ProjectApiError(
- `Failed to ${errorLabel} (${res.status})`,
+ `Failed to ${errorLabel} (${res.status})${await errorBodyDetail(res)}`,
res.status,
);
return (await res.json()) as T;
diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.ts
index 50bad68cf19c..939ed69fec22 100644
--- a/products/desktop/packages/core/src/canvas/services.ts
+++ b/products/desktop/packages/core/src/canvas/services.ts
@@ -23,6 +23,11 @@ import type {
CanvasDataResult,
CanvasLoadInsightInput,
} from "./freeformSchemas";
+import type {
+ CanvasLayout,
+ CanvasLayoutResult,
+ LayoutOperation,
+} from "./gridLayoutSchemas";
import type { CanvasTemplateSummary } from "./templateSchemas";
// Structural service interfaces the host-router routers depend on. The concrete
@@ -35,12 +40,35 @@ export interface ICanvasTemplatesService {
export interface IDashboardsService {
list(channelId: string): Promise<DashboardRecord[]>;
+ // The component store: component-kind canvases visible to the caller.
+ listComponents(input: { search?: string }): Promise<DashboardRecord[]>;
get(id: string): Promise<DashboardRecord | null>;
create(input: {
channelId: string;
name: string;
templateId?: string;
}): Promise<DashboardRecord>;
+ // Get-or-create the caller's home grid canvas. Idempotent.
+ home(): Promise<DashboardRecord>;
+ // Read a grid canvas's layout (the head, or a historical version).
+ getLayout(input: {
+ id: string;
+ versionId?: string;
+ }): Promise<CanvasLayoutResult>;
+ // Publish a complete layout as the new head (live immediately, no build).
+ publishLayout(input: {
+ id: string;
+ layout: CanvasLayout;
+ prompt?: string;
+ expectedCurrentVersionId: string | null;
+ }): Promise<CanvasLayoutResult>;
+ // Apply surgical, guarded operations to the current layout.
+ patchLayout(input: {
+ id: string;
+ operations: LayoutOperation[];
+ prompt?: string;
+ expectedCurrentVersionId: string | null;
+ }): Promise<CanvasLayoutResult>;
saveContext(input: { id: string; context: string }): Promise<DashboardRecord>;
setGenerationTask(input: {
id: string;
diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
index fe6e0b09def6..6ed8175ad12e 100644
--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts
+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
@@ -18,6 +18,7 @@ import {
createDashboardInput,
dashboardIdInput,
dashboardRecordSchema,
+ listComponentsInput,
listDashboardsInput,
promoteCanvasInput,
renameDashboardInput,
@@ -28,6 +29,12 @@ import {
setGenerationTaskInput,
setPinnedInput,
} from "@posthog/core/canvas/dashboardSchemas";
+import {
+ canvasLayoutInput,
+ canvasLayoutResultSchema,
+ patchLayoutInput,
+ publishLayoutInput,
+} from "@posthog/core/canvas/gridLayoutSchemas";
import { DASHBOARDS_SERVICE } from "@posthog/core/canvas/identifiers";
import type { IDashboardsService } from "@posthog/core/canvas/services";
import { publicProcedure, router } from "@posthog/host-trpc/trpc";
@@ -42,12 +49,51 @@ export const dashboardsRouter = router({
.get<IDashboardsService>(DASHBOARDS_SERVICE)
.list(input.channelId),
),
+ listComponents: publicProcedure
+ .input(listComponentsInput)
+ .output(z.array(dashboardRecordSchema))
+ .query(({ ctx, input }) =>
+ ctx.container
+ .get<IDashboardsService>(DASHBOARDS_SERVICE)
+ .listComponents(input),
+ ),
get: publicProcedure
.input(dashboardIdInput)
.output(dashboardRecordSchema.nullable())
.query(({ ctx, input }) =>
ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).get(input.id),
),
+ // A query despite the POST underneath: home is an idempotent get-or-create,
+ // and query semantics give the surface caching and dedupe for free.
+ home: publicProcedure
+ .output(dashboardRecordSchema)
+ .query(({ ctx }) =>
+ ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).home(),
+ ),
+ layout: publicProcedure
+ .input(canvasLayoutInput)
+ .output(canvasLayoutResultSchema)
+ .query(({ ctx, input }) =>
+ ctx.container
+ .get<IDashboardsService>(DASHBOARDS_SERVICE)
+ .getLayout(input),
+ ),
+ publishLayout: publicProcedure
+ .input(publishLayoutInput)
+ .output(canvasLayoutResultSchema)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<IDashboardsService>(DASHBOARDS_SERVICE)
+ .publishLayout(input),
+ ),
+ patchLayout: publicProcedure
+ .input(patchLayoutInput)
+ .output(canvasLayoutResultSchema)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<IDashboardsService>(DASHBOARDS_SERVICE)
+ .patchLayout(input),
+ ),
source: publicProcedure
.input(canvasSourceInput)
.output(canvasSourceSchema)
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 3b32f2d7fd8f..a5806ff19dcf 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -258,6 +258,7 @@ export interface CommandMenuActionProperties {
}
export type SidebarNavItem =
+ | "home"
| "new_task"
| "search"
| "inbox"
diff --git a/products/desktop/packages/shared/src/canvas-contracts.ts b/products/desktop/packages/shared/src/canvas-contracts.ts
index 2c6789e065fa..4b49a40190f5 100644
--- a/products/desktop/packages/shared/src/canvas-contracts.ts
+++ b/products/desktop/packages/shared/src/canvas-contracts.ts
@@ -13,22 +13,37 @@ export const CANVAS_ENTRY_HTML = "index.html";
// compatibility adapter.
export const CANVAS_COMPONENT_PATH = "src/canvas.tsx";
+// Every field is defaulted: the builder freezes project.capabilities into the
+// manifest VERBATIM, and a project declares only the capabilities it uses — a
+// required field here makes the whole build record unparseable client-side,
+// which reads as "this canvas has no build". Absent means deny at runtime, so
+// defaulting is the fail-closed direction.
export const canvasCapabilitiesSchema = z.object({
- posthog: z.object({
- insights: z.array(z.string().min(1).max(128)).max(100),
- inlineQueries: z.boolean(),
- captureEvents: z.array(z.string().min(1).max(200)).max(100),
- // Defaulted so manifests built before these verbs parse unchanged.
- state: z
- .array(z.enum(["user", "shared"]))
- .max(2)
- .default([]),
- actions: z.array(z.string().min(1).max(64)).max(32).default([]),
- agentRequests: z.boolean().default(false),
- }),
- network: z.object({
- origins: z.array(z.string().url().max(2_048)).max(20),
- }),
+ posthog: z
+ .object({
+ insights: z.array(z.string().min(1).max(128)).max(100).default([]),
+ inlineQueries: z.boolean().default(false),
+ captureEvents: z.array(z.string().min(1).max(200)).max(100).default([]),
+ state: z
+ .array(z.enum(["user", "shared"]))
+ .max(2)
+ .default([]),
+ actions: z.array(z.string().min(1).max(64)).max(32).default([]),
+ agentRequests: z.boolean().default(false),
+ })
+ .default({
+ insights: [],
+ inlineQueries: false,
+ captureEvents: [],
+ state: [],
+ actions: [],
+ agentRequests: false,
+ }),
+ network: z
+ .object({
+ origins: z.array(z.string().url().max(2_048)).max(20).default([]),
+ })
+ .default({ origins: [] }),
});
export type CanvasCapabilities = z.infer<typeof canvasCapabilitiesSchema>;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx
index c0a07f916289..95ced96dde07 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx
@@ -24,6 +24,7 @@ vi.mock("@posthog/ui/router/useAppView", () => ({
}));
vi.mock("@posthog/ui/router/navigationBridge", () => ({
navigateToActivity: vi.fn(),
+ navigateToHome: vi.fn(),
navigateToInbox: vi.fn(),
navigateToWebsiteCommandCenter: vi.fn(),
}));
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.tsx
index 2e5da710b4b5..dcf9d3f28468 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.tsx
@@ -2,6 +2,7 @@ import {
BellIcon,
EnvelopeSimple,
GearSix,
+ HouseSimple,
Lightning,
} from "@phosphor-icons/react";
import {
@@ -33,6 +34,7 @@ import { CountBadge } from "@posthog/ui/primitives/CountBadge";
import { LoopIcon } from "@posthog/ui/primitives/LoopIcon";
import {
navigateToActivity,
+ navigateToHome,
navigateToInbox,
navigateToLoops,
navigateToWebsiteCommandCenter,
@@ -200,6 +202,7 @@ export function ChannelNav() {
action();
};
+ const isHome = view.type === "home";
const isInbox = view.type === "inbox";
const isActivity = view.type === "activity";
const isCommandCenter = view.type === "command-center";
@@ -212,6 +215,12 @@ export function ChannelNav() {
// providers never share it.
<TooltipProvider delay={400}>
<div className="flex shrink-0 gap-2 p-2">
+ <NavIcon
+ icon={<HouseSimple size={16} weight={isHome ? "fill" : "regular"} />}
+ label="Home"
+ isActive={isHome}
+ onClick={withTrack("home", navigateToHome)}
+ />
<NavIcon
icon={
<EnvelopeSimple size={16} weight={isInbox ? "fill" : "regular"} />
diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteDashboard.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteDashboard.tsx
index 2b27918e8aca..3ab22d0eab6c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteDashboard.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteDashboard.tsx
@@ -1,12 +1,19 @@
import { FreeformCanvasView } from "@posthog/ui/features/canvas/freeform/FreeformCanvasView";
+import { GridCanvasView } from "@posthog/ui/features/canvas/grid/GridCanvasView";
+import { useDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";
import { useIsDashboardEditing } from "@posthog/ui/features/canvas/stores/dashboardEditStore";
// Renders a canvas's app in a sandboxed iframe (view + edit). Edit mode adds
// the chat panel + version controls; generation runs as a dedicated task. The
// view fetches its own record/source/build lifecycle — including the author
// context, which the side panel edits against the saved record directly.
+// Grid-kind canvases render the widget-grid surface instead of the single app.
export function WebsiteDashboard({ dashboardId }: { dashboardId: string }) {
const editing = useIsDashboardEditing(dashboardId);
+ const { dashboard } = useDashboard(dashboardId);
+ if (dashboard?.kind === "grid") {
+ return <GridCanvasView canvasId={dashboardId} interactive={editing} />;
+ }
return (
<FreeformCanvasView
threadId={`dashboard:${dashboardId}`}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
index e470d4fbc97d..f41123ff019b 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx
@@ -20,14 +20,20 @@ const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];
function buildArtifactHostDocument(
artifactUrl: string,
theme: CanvasTheme,
+ config?: Record<string, unknown>,
): string {
const artifactOrigin = new URL(artifactUrl).origin;
// The theme rides the fragment so the artifact runtime (a synchronous head
// script) applies `.dark` before first paint — the bridge port only connects
// at the load event, far too late to prevent a light flash. Fragments don't
- // reach the server, so signed artifact URLs stay valid.
+ // reach the server, so signed artifact URLs stay valid. Placement config
+ // rides the same fragment: the runtime freezes it as ph.config at boot.
+ const fragment = new URLSearchParams({ theme });
+ if (config && Object.keys(config).length > 0) {
+ fragment.set("config", JSON.stringify(config));
+ }
const themedUrl = new URL(artifactUrl);
- themedUrl.hash = `theme=${theme}`;
+ themedUrl.hash = fragment.toString();
const serializedArtifactUrl = JSON.stringify(themedUrl.href).replaceAll(
"<",
"\\u003c",
@@ -90,6 +96,9 @@ export interface BuiltCanvasProps {
* data requests. */
capabilities: CanvasCapabilities | undefined;
onDataRequest: (method: string, payload: unknown) => Promise<unknown>;
+ /** Per-placement settings, exposed to the artifact as ph.config (frozen at
+ * boot). A changed config remounts the artifact. */
+ config?: Record<string, unknown>;
onError?: (message: string, stack?: string) => void;
/** The artifact's runtime booted and posted "ready" — proof the signed URL
* actually loaded (an expired URL never gets this far). */
@@ -106,6 +115,7 @@ export function BuiltCanvas({
artifactUrl,
capabilities,
onDataRequest,
+ config,
onError,
onReady,
onRendered,
@@ -125,7 +135,11 @@ export function BuiltCanvas({
// The srcDoc bakes in the mount-time theme only — folding the live theme in
// would reload the artifact on every toggle. Live changes go over the port.
const initialTheme = useRef(theme).current;
- const hostDocument = buildArtifactHostDocument(artifactUrl, initialTheme);
+ const hostDocument = buildArtifactHostDocument(
+ artifactUrl,
+ initialTheme,
+ config,
+ );
const latest = useRef({
capabilities,
onDataRequest,
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 1d19a1268021..18e0a40dc89c 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -613,7 +613,16 @@ export function buildSandboxDocument(
} catch (err) {
// Only the latest snapshot reports — a superseded partial's parse error
// must not surface as the canvas's error or flicker the host banner.
- if (seq === mountSeq) reportError(err && err.message, err && err.stack);
+ if (seq !== mountSeq) return;
+ let message = err && err.message;
+ // Chrome reports a failed CDN fetch of the code's imports as an opaque
+ // error naming the blob module; name the real dependency instead.
+ if (message && message.indexOf("Failed to fetch dynamically imported module") !== -1) {
+ message = "Couldn't load the canvas libraries from esm.sh. " +
+ "Previewing an unbuilt canvas needs network access to https://esm.sh; " +
+ "published canvases are unaffected.";
+ }
+ reportError(message, err && err.stack);
}
};
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx
new file mode 100644
index 000000000000..a864329f12c1
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/ComponentFrame.tsx
@@ -0,0 +1,135 @@
+import { placementComponentBuild } from "@posthog/core/canvas/canvasBuildSchemas";
+import {
+ type GridPlacement,
+ pinnedComponentVersion,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import { Button, Spinner, Text } from "@posthog/quill";
+import type { CanvasCapabilities } from "@posthog/shared";
+import { useCanvasBuilds } from "@posthog/ui/features/canvas/hooks/useCanvasBuilds";
+import { useQueryClient } from "@tanstack/react-query";
+import { useCallback, useMemo } from "react";
+import { BuiltCanvas } from "../freeform/BuiltCanvas";
+import { handleFreeformDataRequest } from "../freeform/freeformDataBridge";
+import { usePinnedArtifact } from "../freeform/usePinnedArtifact";
+
+/**
+ * One live placement's widget: the component canvas's built artifact in its own
+ * sandboxed frame. Data requests, state, and capabilities are all scoped to the
+ * COMPONENT canvas — each widget is held to the contract its own build shipped
+ * with, independent of its neighbors.
+ */
+export function ComponentFrame({ placement }: { placement: GridPlacement }) {
+ const componentId = placement.component ?? "";
+ const queryClient = useQueryClient();
+ // A pinned placement asks for one specific source version: request it by id
+ // so the endpoint includes its build even when newer builds pushed it out of
+ // the lifecycle window.
+ const pinnedVersion = pinnedComponentVersion(placement);
+ const { lifecycle, isError, dataUpdatedAt, refetch } = useCanvasBuilds(
+ componentId || undefined,
+ { versionId: pinnedVersion ?? undefined },
+ );
+ const renderedBuild = useMemo(
+ () =>
+ lifecycle ? placementComponentBuild(lifecycle, pinnedVersion) : null,
+ [lifecycle, pinnedVersion],
+ );
+ const { artifact, refreshKey, onReady } = usePinnedArtifact({
+ dashboardId: componentId,
+ publishedBuild: renderedBuild,
+ lifecycle,
+ mintedAt: dataUpdatedAt,
+ suspended: false,
+ });
+
+ const onDataRequest = useCallback(
+ (method: string, payload: unknown) =>
+ handleFreeformDataRequest(method, payload, queryClient, {
+ dashboardId: componentId,
+ }),
+ [queryClient, componentId],
+ );
+
+ const capabilities = renderedBuild?.manifest
+ ? ((renderedBuild.manifest as { capabilities?: CanvasCapabilities })
+ .capabilities ?? undefined)
+ : undefined;
+ const config = useMemo(
+ () => (placement.config as Record<string, unknown> | null) ?? undefined,
+ [placement.config],
+ );
+
+ if (!artifact) {
+ // The lifecycle loaded and the pinned version has no artifact in it: build
+ // retention can sweep one, and rendering the component's latest build
+ // instead would silently swap the widget. Refetching cannot bring it back,
+ // so this state offers no retry.
+ if (pinnedVersion && lifecycle && !renderedBuild) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-1 overflow-hidden p-3 text-center">
+ <Text size="sm">This widget's pinned version isn't available.</Text>
+ <Text size="xs" variant="muted">
+ Point the widget at the component's latest version to bring it back.
+ </Text>
+ </div>
+ );
+ }
+ // No artifact and no build coming: an endless spinner here hides a broken
+ // widget — the checklist a fresh home seeds hits this when its build fails.
+ const newestBuild = lifecycle?.builds[0];
+ const buildDead =
+ lifecycle &&
+ !renderedBuild &&
+ (!newestBuild || newestBuild.buildStatus === "failed");
+ if (buildDead) {
+ const failure = newestBuild?.diagnostics.find(
+ (entry) => entry.severity === "error",
+ )?.message;
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-1 overflow-hidden p-3 text-center">
+ <Text size="sm">This widget failed to build.</Text>
+ {failure ? (
+ <Text size="xs" variant="muted" className="line-clamp-3">
+ {failure}
+ </Text>
+ ) : null}
+ <Text size="xs" variant="muted">
+ Open the component canvas to fix and republish.
+ </Text>
+ </div>
+ );
+ }
+ // The build lifecycle fetch failed for good (retries exhausted) and there's
+ // no data to fall back on — a permanent failure like a deleted component
+ // canvas. Without this the tile spins forever with no way out.
+ if (isError && !lifecycle) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-1 overflow-hidden p-3 text-center">
+ <Text size="sm">This widget couldn't load.</Text>
+ <Text size="xs" variant="muted">
+ It may have been removed, or the connection dropped.
+ </Text>
+ <Button variant="outline" size="sm" onClick={refetch}>
+ Retry
+ </Button>
+ </div>
+ );
+ }
+ return (
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ return (
+ <BuiltCanvas
+ key={`${artifact.buildId}:${refreshKey}`}
+ artifactUrl={artifact.url}
+ capabilities={capabilities}
+ config={config}
+ onDataRequest={onDataRequest}
+ onReady={onReady}
+ onRendered={onReady}
+ />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
new file mode 100644
index 000000000000..b799459f7db4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
@@ -0,0 +1,472 @@
+import {
+ ChatCircleIcon,
+ SidebarSimpleIcon,
+ SquaresFourIcon,
+} from "@phosphor-icons/react";
+import type {
+ GridPlacement,
+ LayoutOperation,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import {
+ Button,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Spinner,
+ Text,
+} from "@posthog/quill";
+import { canvasCommentTaskId } from "@posthog/ui/features/canvas/freeform/canvasCommentTask";
+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
+import {
+ useCanvasVersions,
+ useDashboard,
+} from "@posthog/ui/features/canvas/hooks/useDashboards";
+import { useGenerateFreeformCanvas } from "@posthog/ui/features/canvas/hooks/useGenerateFreeformCanvas";
+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
+import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { GridChatPanel, type GridChatTarget } from "./GridChatPanel";
+import {
+ GridPlacementTile,
+ type PlacementTileActions,
+} from "./GridPlacementTile";
+import { collides, type GridRect, surfaceRows } from "./gridGeometry";
+import { type GridDragOutcome, useGridDrag } from "./useGridDrag";
+import { useGridLayout, usePatchLayout } from "./useGridLayout";
+
+const DEFAULT_GRID = { columns: 6, rowHeight: 96, gap: 8 };
+
+// Outer radius of a lattice dot's fade (the gradient's transparent stop).
+const DOT_FADE_RADIUS = 4;
+
+function gridItemStyle(rect: GridRect): React.CSSProperties {
+ return {
+ gridColumn: `${rect.x + 1} / span ${rect.w}`,
+ gridRow: `${rect.y + 1} / span ${rect.h}`,
+ };
+}
+
+// Where the how-to tile sits on an empty grid: centered, wide enough to read,
+// one row down so it looks placed rather than docked to the top edge.
+function emptyHintRect(columns: number): GridRect {
+ const w = Math.min(4, columns);
+ return { x: Math.floor((columns - w) / 2), y: 1, w, h: 3 };
+}
+
+// The dot lattice needs the surface's real pixel width: columns are fractional
+// (1fr), so corner positions can't be expressed in pure CSS background math.
+function useMeasuredWidth(element: HTMLDivElement | null): number {
+ const [width, setWidth] = useState(0);
+ useEffect(() => {
+ if (!element) return;
+ const observer = new ResizeObserver((entries) => {
+ const entry = entries[0];
+ if (entry) setWidth(entry.contentRect.width);
+ });
+ observer.observe(element);
+ setWidth(element.clientWidth);
+ return () => observer.disconnect();
+ }, [element]);
+ return width;
+}
+
+/**
+ * A grid canvas: a composition of component widgets on a fixed-column grid.
+ * Viewing renders each live placement's built artifact in its own sandboxed
+ * frame; edit mode adds draw-to-create (drag an empty area, describe the box),
+ * move (drag a tile), and resize (drag the corner handle). Every edit is a
+ * surgical, version-guarded layout patch, so a user and an agent editing the
+ * same canvas conflict loudly instead of overwriting each other.
+ */
+export function GridCanvasView({
+ canvasId,
+ interactive,
+}: {
+ canvasId: string;
+ interactive: boolean;
+}) {
+ const { dashboard } = useDashboard(canvasId);
+ const { layout, currentVersionId, isLoading } = useGridLayout(canvasId);
+ const { patch, isPatching } = usePatchLayout(canvasId);
+ // Resolve the channel's display name from the shared channels query, like the
+ // freeform view does, so a started run names its channel in the agent prompt
+ // (an empty name drops the whole channel-context instruction).
+ const channelId = dashboard?.channelId ?? "";
+ const { channels } = useChannels();
+ const channelName = useMemo(
+ () => channels.find((channel) => channel.id === channelId)?.name ?? "",
+ [channels, channelId],
+ );
+ const { generate } = useGenerateFreeformCanvas({ channelId, channelName });
+
+ const surfaceRef = useRef<HTMLDivElement>(null);
+ // The surface mounts only after loading, so a plain ref never retriggers the
+ // measurement effect; a state-backed element does.
+ const [surfaceEl, setSurfaceEl] = useState<HTMLDivElement | null>(null);
+ const setSurfaceRef = useCallback((el: HTMLDivElement | null) => {
+ surfaceRef.current = el;
+ setSurfaceEl(el);
+ }, []);
+ const surfaceWidth = useMeasuredWidth(surfaceEl);
+ const placements = layout?.placements;
+
+ // The right-hand dock, sharing the freeform panel's persisted collapse and
+ // width so the two canvas kinds feel like one surface. Edit mode opens it
+ // on the canvas's own conversation; a widget's chat affordances refocus it.
+ const collapsed = useCanvasChatPanelStore((s) => s.collapsed);
+ const setCollapsed = useCanvasChatPanelStore((s) => s.setCollapsed);
+ const panelWidth = useCanvasChatPanelStore((s) => s.width);
+ const setPanelWidth = useCanvasChatPanelStore((s) => s.setWidth);
+ // Comments opened from view mode (the breadcrumb's Comments button) hold the
+ // dock open without edit mode, exactly like the freeform panel.
+ const viewOpen = useCanvasChatPanelStore((s) => s.viewOpen);
+ const [isResizingPanel, setIsResizingPanel] = useState(false);
+ const [widgetTarget, setWidgetTarget] = useState<GridChatTarget | null>(null);
+ // Canvas-wide task started this session, until the record catches up.
+ const [startedCanvasTaskId, setStartedCanvasTaskId] = useState<string | null>(
+ null,
+ );
+
+ // The layout version the grid is on, in the freeform toolbar's vocabulary.
+ const { versions } = useCanvasVersions(canvasId);
+ const versionText = useMemo(() => {
+ if (!currentVersionId || versions.length === 0) return null;
+ const index = versions.findIndex(
+ (version) => version.id === currentVersionId,
+ );
+ if (index === -1) return null;
+ return `v${versions.length - index}/${versions.length} · Live`;
+ }, [versions, currentVersionId]);
+ const commentVersionLabel = useCallback(
+ (versionId: string) => {
+ const index = versions.findIndex((version) => version.id === versionId);
+ return index === -1 ? null : `V${versions.length - index}`;
+ },
+ [versions],
+ );
+
+ const onDragComplete = useCallback(
+ (outcome: GridDragOutcome) => {
+ if (!placements) return;
+ if (outcome.kind === "draw") {
+ if (collides(outcome.rect, placements)) return;
+ void patch([
+ {
+ op: "add_placement",
+ placement: {
+ id: `p-${crypto.randomUUID().slice(0, 8)}`,
+ status: "pending",
+ ...outcome.rect,
+ },
+ },
+ ]);
+ return;
+ }
+ const { rect, origin, placementId } = outcome;
+ if (!origin || !placementId) return;
+ const moved =
+ rect.x !== origin.x ||
+ rect.y !== origin.y ||
+ rect.w !== origin.w ||
+ rect.h !== origin.h;
+ if (!moved || collides(rect, placements, placementId)) return;
+ void patch([{ op: "update_placement", id: placementId, changes: rect }]);
+ },
+ [placements, patch],
+ );
+
+ const {
+ drag,
+ onSurfacePointerDown,
+ onPointerMove,
+ onPointerUp,
+ onPointerCancel,
+ startMove,
+ startResize,
+ } = useGridDrag({
+ surfaceRef,
+ grid: layout?.grid ?? DEFAULT_GRID,
+ interactive,
+ onComplete: onDragComplete,
+ });
+
+ const describe = useCallback(
+ async (placement: GridPlacement, prompt: string) => {
+ if (!dashboard) return;
+ // Flip the tile to its generating state before dispatching the task —
+ // task creation takes seconds, and a silent describe box reads as broken.
+ const staged = await patch(
+ [
+ {
+ op: "update_placement",
+ id: placement.id,
+ changes: { status: "generating", prompt },
+ },
+ ],
+ prompt,
+ );
+ if (!staged) return;
+ const taskId = await generate({
+ dashboardId: canvasId,
+ name: dashboard.name,
+ instruction: prompt,
+ placement: {
+ placementId: placement.id,
+ w: placement.w,
+ h: placement.h,
+ },
+ });
+ const record: LayoutOperation[] = [
+ {
+ op: "update_placement",
+ id: placement.id,
+ // Dispatch failed (already toasted): back to pending so the box
+ // offers the prompt again instead of spinning forever.
+ changes: taskId
+ ? { generationTaskId: taskId }
+ : { status: "pending" },
+ },
+ ];
+ // The task is already running and its id is known only here, so losing
+ // this write leaves a tile generating forever with nothing to open. The
+ // queue rebases after a failure, so one retry clears a lost race.
+ if (!(await patch(record))) await patch(record);
+ },
+ [dashboard, generate, patch, canvasId],
+ );
+
+ const reset = useCallback(
+ (placement: GridPlacement) => {
+ // Back to the describe box with the prompt intact; the stale task id is
+ // ignored outside the generating state and overwritten on re-dispatch.
+ void patch([
+ {
+ op: "update_placement",
+ id: placement.id,
+ changes: { status: "pending" },
+ },
+ ]);
+ },
+ [patch],
+ );
+
+ const remove = useCallback(
+ (placement: GridPlacement) => {
+ void patch([{ op: "remove_placement", id: placement.id }]);
+ },
+ [patch],
+ );
+
+ const discuss = useCallback(
+ (placement: GridPlacement) => {
+ setWidgetTarget({
+ taskId: placement.generationTaskId ?? null,
+ title: placement.prompt ?? "Widget",
+ });
+ setCollapsed(false);
+ },
+ [setCollapsed],
+ );
+
+ const actions: PlacementTileActions = {
+ describe,
+ reset,
+ remove,
+ discuss,
+ };
+
+ if (isLoading || !layout || !placements || !dashboard) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ const { grid } = layout;
+ // Cell pitch in px: cell size plus one gap. Vertical pitch is fixed by the
+ // layout; horizontal comes from the measured surface width (1fr columns).
+ const pitchX = (surfaceWidth + grid.gap) / grid.columns;
+ const pitchY = grid.rowHeight + grid.gap;
+
+ return (
+ <div className="flex h-full">
+ <div className="flex min-w-0 flex-1 flex-col">
+ {interactive ? (
+ // The freeform canvas's toolbar shape: version info on the left,
+ // panel controls on the right, in the bar rather than floating.
+ <div className="flex h-10 shrink-0 items-center justify-between border-(--gray-5) border-b px-3">
+ <div className="flex items-center gap-1">
+ {versionText ? (
+ <Text size="sm" className="text-(--gray-9)">
+ {versionText}
+ </Text>
+ ) : null}
+ </div>
+ {collapsed && !widgetTarget ? (
+ <Button
+ variant="default"
+ size="icon"
+ aria-label="Show chat"
+ onClick={() => setCollapsed(false)}
+ >
+ <SidebarSimpleIcon size={16} />
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ <div className="min-h-0 flex-1 overflow-y-auto p-4">
+ <div
+ ref={setSurfaceRef}
+ className="relative grid"
+ style={{
+ gridTemplateColumns: `repeat(${grid.columns}, minmax(0, 1fr))`,
+ gridAutoRows: `${grid.rowHeight}px`,
+ gap: `${grid.gap}px`,
+ // Fill the viewport even when the content needs fewer rows, so the
+ // whole visible page is drawable (and dotted) rather than a strip.
+ minHeight: `max(100%, ${surfaceRows(placements) * pitchY}px)`,
+ cursor: interactive ? "crosshair" : undefined,
+ }}
+ onPointerDown={onSurfacePointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerCancel}
+ onLostPointerCapture={onPointerCancel}
+ >
+ {interactive && surfaceWidth > 0 ? (
+ // Edit mode reveals the lattice: a soft dot (the fade to transparent
+ // is the blur) on each cell corner, where tiles snap and drawing
+ // starts, gently pulsing to invite a drag. The overlay's top edge
+ // starts at the first interior corner row so no clipped dots hug the
+ // top of the page.
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 animate-pulse opacity-60"
+ style={{
+ top: pitchY - grid.gap / 2 - DOT_FADE_RADIUS,
+ backgroundImage:
+ "radial-gradient(circle, var(--gray-7) 1px, transparent 4px)",
+ backgroundSize: `${pitchX}px ${pitchY}px`,
+ backgroundPosition: `${pitchX / 2 - grid.gap / 2}px ${DOT_FADE_RADIUS - pitchY / 2}px`,
+ }}
+ />
+ ) : null}
+ {placements.length === 0 && !drag ? (
+ // How-to placed on the grid as a tile of its own, instead of a
+ // full-width overlay that looks like broken chrome. Pointer events
+ // pass through so the user can draw right over it.
+ <div
+ className="pointer-events-none flex items-center justify-center rounded-(--radius-3) border border-(--gray-6) border-dashed bg-(--gray-2)"
+ style={gridItemStyle(emptyHintRect(grid.columns))}
+ >
+ <Empty className="border-0 bg-transparent">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <SquaresFourIcon size={24} />
+ </EmptyMedia>
+ <EmptyTitle>
+ {interactive
+ ? "Draw your first widget"
+ : "An empty canvas"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {interactive
+ ? "Click and drag on the dotted grid to draw a box, then describe what should go there."
+ : "Select Edit to draw your first widget."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ ) : null}
+ {placements.map((placement) => {
+ const dragged =
+ drag &&
+ drag.kind !== "draw" &&
+ drag.placementId === placement.id
+ ? drag.rect
+ : placement;
+ return (
+ <div
+ key={placement.id}
+ className="group relative overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)"
+ style={gridItemStyle(dragged)}
+ >
+ {interactive ? (
+ <div
+ className="absolute inset-x-0 top-0 z-10 h-5 cursor-move bg-(--gray-3) opacity-0 transition-opacity group-hover:opacity-100"
+ onPointerDown={startMove(placement)}
+ />
+ ) : null}
+ <GridPlacementTile
+ placement={placement}
+ interactive={interactive}
+ patching={isPatching}
+ actions={actions}
+ />
+ {interactive && placement.generationTaskId ? (
+ // Opens the widget's own conversation in the side panel so a
+ // broken query or tweak goes straight back to its agent.
+ <Button
+ variant="outline"
+ size="icon"
+ className="absolute top-1 right-1 z-20 opacity-0 transition-opacity group-hover:opacity-100"
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={() => actions.discuss(placement)}
+ >
+ <ChatCircleIcon size={14} />
+ </Button>
+ ) : null}
+ {interactive ? (
+ <div
+ className="absolute right-0 bottom-0 z-10 h-4 w-4 cursor-nwse-resize bg-(--gray-6) opacity-0 transition-opacity group-hover:opacity-100"
+ onPointerDown={startResize(placement)}
+ />
+ ) : null}
+ </div>
+ );
+ })}
+ {drag ? (
+ <div
+ className="pointer-events-none rounded-(--radius-3) border-(--accent-8) border-2 border-dashed bg-(--accent-3) opacity-70"
+ style={gridItemStyle(drag.rect)}
+ />
+ ) : null}
+ </div>
+ </div>
+ </div>
+ {interactive || widgetTarget || viewOpen ? (
+ <ResizableSidebar
+ open={!collapsed || !!widgetTarget}
+ width={panelWidth}
+ setWidth={setPanelWidth}
+ isResizing={isResizingPanel}
+ setIsResizing={setIsResizingPanel}
+ side="right"
+ >
+ <GridChatPanel
+ target={widgetTarget}
+ canvasTaskId={dashboard.generationTaskId ?? startedCanvasTaskId}
+ commentTaskId={canvasCommentTaskId(
+ dashboard.generationTaskId ?? startedCanvasTaskId,
+ versions,
+ )}
+ canvasVersionId={currentVersionId ?? null}
+ commentVersionLabel={commentVersionLabel}
+ canvasId={canvasId}
+ canvasName={dashboard.name}
+ channelId={dashboard.channelId}
+ channelName={channelName}
+ onBack={() => setWidgetTarget(null)}
+ onMinimize={() => {
+ setCollapsed(true);
+ setWidgetTarget(null);
+ }}
+ onStarted={setStartedCanvasTaskId}
+ />
+ </ResizableSidebar>
+ ) : null}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx
new file mode 100644
index 000000000000..99a7b83a5b72
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridChatPanel.tsx
@@ -0,0 +1,313 @@
+import { CaretLeftIcon, SidebarSimpleIcon } from "@phosphor-icons/react";
+import {
+ Button,
+ Input,
+ Spinner,
+ Tabs,
+ TabsList,
+ TabsTrigger,
+ Text,
+} from "@posthog/quill";
+import type { Task } from "@posthog/shared/domain-types";
+import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";
+import { useGenerateFreeformCanvas } from "@posthog/ui/features/canvas/hooks/useGenerateFreeformCanvas";
+import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";
+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
+import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";
+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+
+/** A widget conversation the panel is temporarily focused on. */
+export interface GridChatTarget {
+ taskId: string | null;
+ title: string;
+}
+
+/**
+ * The grid canvas's right-hand dock, mirroring the freeform canvas panel:
+ * edit mode opens it on the canvas's own conversation (with a comments tab
+ * beside it), and a widget's chat affordances refocus it on that widget's
+ * fill task — follow-ups, steering, and permission approvals all in place.
+ * The version the grid is on shows in the canvas toolbar, like freeform.
+ */
+export function GridChatPanel({
+ target,
+ canvasTaskId,
+ commentTaskId,
+ canvasVersionId,
+ commentVersionLabel,
+ canvasId,
+ canvasName,
+ channelId,
+ channelName,
+ onBack,
+ onMinimize,
+ onStarted,
+}: {
+ /** Widget focus, or null for the canvas's own conversation. */
+ target: GridChatTarget | null;
+ /** The recorded canvas-wide conversation, if one has been started. */
+ canvasTaskId: string | null;
+ /** The task canvas comments anchor to (the canvas conversation, or the run
+ * that produced the current layout). Null disables the comments tab. */
+ commentTaskId: string | null;
+ /** The layout version currently shown, for labeling new comments. */
+ canvasVersionId: string | null;
+ commentVersionLabel: (versionId: string) => string | null;
+ canvasId: string;
+ canvasName: string;
+ channelId: string;
+ /** The channel's display name, so a started run names its channel. */
+ channelName: string;
+ /** Return from a widget's conversation to the canvas's. */
+ onBack: () => void;
+ onMinimize: () => void;
+ /** A canvas-wide task was started from the panel's composer. */
+ onStarted: (taskId: string) => void;
+}) {
+ const tab = useCanvasChatPanelStore((state) => state.tab);
+ const setTab = useCanvasChatPanelStore((state) => state.setTab);
+ const minimize = (
+ <Button
+ variant="default"
+ size="icon"
+ aria-label="Hide panel"
+ onClick={onMinimize}
+ >
+ <SidebarSimpleIcon size={14} />
+ </Button>
+ );
+
+ if (target) {
+ return (
+ <div className="flex h-full flex-col border-(--gray-5) border-l">
+ <div className="flex h-10 shrink-0 items-center gap-1 border-(--gray-5) border-b px-2">
+ <Button
+ variant="default"
+ size="icon"
+ aria-label="Back to canvas chat"
+ onClick={onBack}
+ >
+ <CaretLeftIcon size={14} />
+ </Button>
+ <Text size="sm" weight="medium" className="min-w-0 flex-1 truncate">
+ {target.title}
+ </Text>
+ {minimize}
+ </div>
+ {target.taskId ? (
+ <TaskChat taskId={target.taskId} />
+ ) : (
+ <div className="flex flex-1 items-center justify-center p-4">
+ <Text size="sm">This widget has no conversation yet.</Text>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full flex-col border-(--gray-5) border-l">
+ <div className="flex h-10 shrink-0 items-center justify-between border-(--gray-5) border-b pr-2 pl-3">
+ <Tabs
+ value={tab}
+ onValueChange={(value) => setTab(value as "chat" | "comments")}
+ >
+ <TabsList variant="line" className="h-10 gap-1 p-0">
+ <TabsTrigger value="chat" className="px-2.5">
+ Chat
+ </TabsTrigger>
+ <TabsTrigger
+ value="comments"
+ disabled={!commentTaskId}
+ className="px-2.5"
+ >
+ Comments
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ {minimize}
+ </div>
+ {tab === "comments" && commentTaskId ? (
+ <CanvasComments
+ taskId={commentTaskId}
+ canvasId={canvasId}
+ canvasName={canvasName}
+ canvasVersionId={canvasVersionId}
+ commentVersionLabel={commentVersionLabel}
+ />
+ ) : canvasTaskId ? (
+ <TaskChat taskId={canvasTaskId} />
+ ) : (
+ <CanvasChatComposer
+ canvasId={canvasId}
+ canvasName={canvasName}
+ channelId={channelId}
+ channelName={channelName}
+ onStarted={onStarted}
+ />
+ )}
+ </div>
+ );
+}
+
+// Resolves the task (shared react-query cache) and renders its live chat —
+// follow-ups, steering, and permission approvals all happen in here.
+function TaskChat({ taskId }: { taskId: string }) {
+ const { data: task } = useQuery(taskDetailQuery(taskId));
+ if (!task) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ // Constrain the chat body like the comments branch beside it: a shrinkable
+ // flex child below the fixed header needs min-h-0 so it fills the remaining
+ // height instead of growing past the panel.
+ return (
+ <div className="min-h-0 flex-1">
+ <EmbeddedSessionView task={task} />
+ </div>
+ );
+}
+
+// The canvas's comment threads, anchored to its conversation task: read,
+// reply, resolve, and add new ones. The agent reads the same threads.
+function CanvasComments({
+ taskId,
+ canvasId,
+ canvasName,
+ canvasVersionId,
+ commentVersionLabel,
+}: {
+ taskId: string;
+ canvasId: string;
+ canvasName: string;
+ canvasVersionId: string | null;
+ commentVersionLabel: (versionId: string) => string | null;
+}) {
+ const { data: task } = useQuery(taskDetailQuery(taskId));
+ if (!task) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ return (
+ <div className="min-h-0 flex-1">
+ <GridCanvasComments
+ task={task}
+ canvasId={canvasId}
+ canvasName={canvasName}
+ canvasVersionId={canvasVersionId}
+ commentVersionLabel={commentVersionLabel}
+ />
+ </div>
+ );
+}
+
+// Its own component so useThreadConversation runs only once the task exists.
+function GridCanvasComments({
+ task,
+ canvasId,
+ canvasName,
+ canvasVersionId,
+ commentVersionLabel,
+}: {
+ task: Task;
+ canvasId: string;
+ canvasName: string;
+ canvasVersionId: string | null;
+ commentVersionLabel: (versionId: string) => string | null;
+}) {
+ const { timeline } = useThreadConversation(task, {
+ surface: "activity_panel",
+ });
+ return (
+ <TaskCommentsList
+ task={task}
+ timeline={timeline}
+ onlySource={{
+ kind: "canvas",
+ name: canvasName,
+ target: { scope: "desktop_canvas", itemId: canvasId },
+ url: null,
+ }}
+ canvasVersionId={canvasVersionId}
+ commentVersionLabel={commentVersionLabel}
+ />
+ );
+}
+
+// No canvas-wide conversation yet: a one-field composer that starts one.
+function CanvasChatComposer({
+ canvasId,
+ canvasName,
+ channelId,
+ channelName,
+ onStarted,
+}: {
+ canvasId: string;
+ canvasName: string;
+ channelId: string;
+ channelName: string;
+ onStarted: (taskId: string) => void;
+}) {
+ const [instruction, setInstruction] = useState("");
+ const [isStarting, setIsStarting] = useState(false);
+ const { generate } = useGenerateFreeformCanvas({
+ channelId,
+ channelName,
+ });
+
+ const submit = async () => {
+ if (!instruction.trim() || isStarting) return;
+ setIsStarting(true);
+ try {
+ const taskId = await generate({
+ dashboardId: canvasId,
+ name: canvasName,
+ instruction: instruction.trim(),
+ canvasKind: "grid",
+ });
+ if (taskId) onStarted(taskId);
+ } finally {
+ setIsStarting(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-1 flex-col justify-center gap-2 p-4">
+ <Text size="sm">
+ Ask the agent to change anything on this canvas: add or fix widgets,
+ rearrange the grid, or clean it up.
+ </Text>
+ <form
+ className="flex items-center gap-1"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <Input
+ autoFocus
+ value={instruction}
+ onChange={(event) => setInstruction(event.target.value)}
+ placeholder="What should change?"
+ disabled={isStarting}
+ />
+ <Button
+ type="submit"
+ size="sm"
+ loading={isStarting}
+ disabled={!instruction.trim() || isStarting}
+ >
+ Start
+ </Button>
+ </form>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
new file mode 100644
index 000000000000..46d5cbb8af19
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
@@ -0,0 +1,258 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import { Button, Input, Spinner, Text } from "@posthog/quill";
+import { isTerminalStatus } from "@posthog/shared/domain-types";
+import { useSessionStore } from "@posthog/ui/features/sessions/sessionStore";
+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { ComponentFrame } from "./ComponentFrame";
+
+// Poll cadence for the fill task's run status while a tile is generating —
+// matches the canvas generation poll elsewhere.
+const FILL_TASK_POLL_MS = 5_000;
+
+export interface PlacementTileActions {
+ /** Dispatch an agent task to fill this placement with the given ask. */
+ describe: (placement: GridPlacement, prompt: string) => Promise<void>;
+ /** Put a stalled placement back to pending so it can be re-described. */
+ reset: (placement: GridPlacement) => void;
+ /** Remove this placement from the layout. */
+ remove: (placement: GridPlacement) => void;
+ /** Open this placement's task conversation in the canvas's side panel. */
+ discuss: (placement: GridPlacement) => void;
+}
+
+/**
+ * One placement on the grid, rendered by lifecycle status: a live widget, a
+ * drawn box awaiting its description, an agent filling it, or a failed fill
+ * offering a retry.
+ */
+export function GridPlacementTile({
+ placement,
+ interactive,
+ patching,
+ actions,
+}: {
+ placement: GridPlacement;
+ interactive: boolean;
+ /** A layout write is in flight; the tile's edit buttons stay disabled until
+ * it lands, so a second click can't fire a patch against the same head. */
+ patching: boolean;
+ actions: PlacementTileActions;
+}) {
+ if (placement.status === "live" && placement.component) {
+ return <ComponentFrame placement={placement} />;
+ }
+ if (placement.status === "generating") {
+ return (
+ <GeneratingTile
+ placement={placement}
+ interactive={interactive}
+ patching={patching}
+ actions={actions}
+ />
+ );
+ }
+ return (
+ <DescribeTile
+ placement={placement}
+ failed={placement.status === "failed"}
+ interactive={interactive}
+ patching={patching}
+ actions={actions}
+ />
+ );
+}
+
+function GeneratingTile({
+ placement,
+ interactive,
+ patching,
+ actions,
+}: {
+ placement: GridPlacement;
+ interactive: boolean;
+ patching: boolean;
+ actions: PlacementTileActions;
+}) {
+ const taskId = placement.generationTaskId ?? null;
+ const { data: task } = useQuery({
+ ...taskDetailQuery(taskId ?? ""),
+ enabled: !!taskId,
+ refetchInterval: FILL_TASK_POLL_MS,
+ });
+ // The agent owns moving the placement to live or failed. A terminal run
+ // with the placement still generating means it never did (crashed, missing
+ // skill, gave up) — spinning forever would hide that.
+ const stalled =
+ !!task?.latest_run && isTerminalStatus(task.latest_run.status);
+ // A run blocked on a permission request looks identical to one that's
+ // working — from this tile, forever. Surface the wait so the user knows
+ // the next move is theirs.
+ const runId = useSessionStore((s) =>
+ taskId ? s.taskIdIndex[taskId] : undefined,
+ );
+ const pendingApprovals = useSessionStore((s) =>
+ runId ? (s.sessions[runId]?.pendingPermissions?.size ?? 0) : 0,
+ );
+
+ const viewTask = taskId ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => actions.discuss(placement)}
+ >
+ {stalled ? "View task" : "View progress"}
+ </Button>
+ ) : null;
+
+ if (stalled) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 p-3 text-center">
+ <Text size="sm" className="line-clamp-2">
+ The agent finished without updating this widget.
+ </Text>
+ <div className="flex items-center gap-1">
+ {interactive ? (
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={patching}
+ onClick={() => actions.reset(placement)}
+ >
+ Try again
+ </Button>
+ ) : null}
+ {viewTask}
+ </div>
+ </div>
+ );
+ }
+
+ if (pendingApprovals > 0) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 p-3 text-center">
+ <Text size="sm" className="line-clamp-2">
+ The agent is waiting for your approval.
+ </Text>
+ <div className="flex items-center gap-1">
+ {taskId ? (
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={() => actions.discuss(placement)}
+ >
+ Review request
+ </Button>
+ ) : null}
+ {interactive ? (
+ <Button
+ variant="default"
+ size="sm"
+ disabled={patching}
+ onClick={() => actions.remove(placement)}
+ >
+ Remove
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 p-3 text-center">
+ <Spinner />
+ <Text size="sm" className="line-clamp-2">
+ {placement.prompt ?? "Building this widget…"}
+ </Text>
+ <div className="flex items-center gap-1">
+ {viewTask}
+ {interactive ? (
+ <Button
+ variant="default"
+ size="sm"
+ disabled={patching}
+ onClick={() => actions.remove(placement)}
+ >
+ Remove
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function DescribeTile({
+ placement,
+ failed,
+ interactive,
+ patching,
+ actions,
+}: {
+ placement: GridPlacement;
+ failed: boolean;
+ interactive: boolean;
+ patching: boolean;
+ actions: PlacementTileActions;
+}) {
+ const [prompt, setPrompt] = useState(placement.prompt ?? "");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ if (!interactive) {
+ return (
+ <div className="flex h-full w-full items-center justify-center p-3">
+ <Text size="sm">
+ {failed ? "This widget failed to build." : "An empty widget."}
+ </Text>
+ </div>
+ );
+ }
+ const submit = async () => {
+ if (!prompt.trim() || isSubmitting) return;
+ setIsSubmitting(true);
+ try {
+ await actions.describe(placement, prompt.trim());
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 p-3 text-center">
+ {failed ? (
+ <Text size="sm">This widget failed to build. Describe it again:</Text>
+ ) : null}
+ <form
+ className="flex w-full items-center gap-1"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <Input
+ autoFocus
+ value={prompt}
+ onChange={(event) => setPrompt(event.target.value)}
+ placeholder="What should go here?"
+ disabled={isSubmitting}
+ />
+ <Button
+ type="submit"
+ size="sm"
+ loading={isSubmitting}
+ disabled={!prompt.trim() || isSubmitting}
+ >
+ {failed ? "Retry" : "Create"}
+ </Button>
+ </form>
+ <Button
+ variant="default"
+ size="sm"
+ disabled={patching}
+ onClick={() => actions.remove(placement)}
+ >
+ Remove
+ </Button>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.test.tsx b/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.test.tsx
new file mode 100644
index 000000000000..1c25ad56ba2d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.test.tsx
@@ -0,0 +1,67 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const HOME_KEY = ["dashboards", "home"];
+
+const mocks = vi.hoisted(() => ({ home: vi.fn() }));
+
+vi.mock("@posthog/host-router/react", () => ({
+ useHostTRPC: () => ({
+ dashboards: {
+ home: {
+ queryOptions: (_input: unknown, options: Record<string, unknown>) => ({
+ queryKey: HOME_KEY,
+ queryFn: () => mocks.home(),
+ ...options,
+ }),
+ },
+ },
+ }),
+}));
+
+// The home canvas itself is another surface's concern; this file is about the
+// query that resolves which canvas Home shows.
+vi.mock("./GridCanvasView", () => ({ GridCanvasView: () => null }));
+
+import { WebsiteHome } from "./WebsiteHome";
+
+let queryClient: QueryClient;
+
+function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+describe("WebsiteHome", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ // Home's provisioning query takes no input, so every account on the machine
+ // shares one cache key, and staleTime Infinity means nothing refetches it. The
+ // auth-scoped meta is what makes a logout, org switch, or project switch evict
+ // it — without it the next user's Home renders the previous user's personal
+ // canvas.
+ it("caches the home canvas under a query an account change evicts", async () => {
+ mocks.home.mockResolvedValue({ id: "canvas-1", name: "Home" });
+
+ render(<WebsiteHome />, { wrapper });
+ await screen.findByText("Home");
+ expect(queryClient.getQueryData(HOME_KEY)).toMatchObject({
+ id: "canvas-1",
+ });
+
+ // The predicate clearAuthScopedQueries runs on every account change.
+ queryClient.removeQueries({
+ predicate: (query) => query.meta?.authScoped === true,
+ });
+
+ expect(queryClient.getQueryData(HOME_KEY)).toBeUndefined();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.tsx b/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.tsx
new file mode 100644
index 000000000000..6c992b83f77e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/WebsiteHome.tsx
@@ -0,0 +1,109 @@
+import { WarningIcon } from "@phosphor-icons/react";
+import { useHostTRPC } from "@posthog/host-router/react";
+import {
+ Button,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Heading,
+ Spinner,
+} from "@posthog/quill";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { GridCanvasView } from "./GridCanvasView";
+
+/**
+ * The user's home tab: a personal grid canvas, provisioned on first open
+ * (idempotent get-or-create) and composed like any other grid canvas — draw a
+ * box and describe it.
+ */
+export function WebsiteHome() {
+ const trpc = useHostTRPC();
+ const [editing, setEditing] = useState(false);
+ // Entering edit opens the canvas chat dock, like the freeform Edit button.
+ const openChat = useCanvasChatPanelStore((state) => state.openChat);
+ const {
+ data: home,
+ isError,
+ isFetching,
+ refetch,
+ } = useQuery(
+ // Provisioning is an idempotent get-or-create, so query semantics are
+ // safe and give caching + dedupe across remounts for free.
+ //
+ // The auth-scoped meta is load-bearing rather than tidy here: this query
+ // takes no input, so every account on the machine shares one cache key,
+ // and `staleTime: Infinity` (which keeps a mounted Home from re-running
+ // provisioning) means nothing else would ever refresh it. Without the meta
+ // a logout, org switch, or project switch leaves the previous user's
+ // personal home canvas id in the cache for the next one.
+ trpc.dashboards.home.queryOptions(undefined, {
+ meta: AUTH_SCOPED_QUERY_META,
+ staleTime: Infinity,
+ }),
+ );
+
+ // Provisioning is a live round trip (it get-or-creates the canvas) and can
+ // fail — offline, or a backend error. Without this the failed query looks
+ // identical to a slow one and Home dead-ends on the spinner below.
+ if (isError && !home) {
+ return (
+ <Empty className="h-full border-0">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <WarningIcon size={24} />
+ </EmptyMedia>
+ <EmptyTitle>Couldn't load Home</EmptyTitle>
+ <EmptyDescription>
+ Setting up your home canvas failed. Check your connection and try
+ again.
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button
+ variant="primary"
+ size="default"
+ loading={isFetching}
+ disabled={isFetching}
+ onClick={() => void refetch()}
+ >
+ Try again
+ </Button>
+ </EmptyContent>
+ </Empty>
+ );
+ }
+
+ if (!home) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 items-center justify-between border-(--gray-4) border-b px-4 py-2">
+ <Heading size="lg">Home</Heading>
+ <Button
+ variant={editing ? "primary" : "outline"}
+ size="sm"
+ onClick={() => {
+ if (!editing) openChat();
+ setEditing(!editing);
+ }}
+ >
+ {editing ? "Done" : "Edit"}
+ </Button>
+ </div>
+ <div className="relative min-h-0 flex-1">
+ <GridCanvasView canvasId={home.id} interactive={editing} />
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.test.ts b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.test.ts
new file mode 100644
index 000000000000..f346685c62d8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.test.ts
@@ -0,0 +1,71 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import { describe, expect, it } from "vitest";
+import {
+ cellFromPoint,
+ clampRect,
+ collides,
+ rectFromCells,
+} from "./gridGeometry";
+
+function placement(overrides: Partial<GridPlacement>): GridPlacement {
+ return { id: "p1", status: "pending", x: 0, y: 0, w: 2, h: 1, ...overrides };
+}
+
+describe("gridGeometry", () => {
+ it.each([
+ ["separate columns", { x: 2, y: 0, w: 2, h: 1 }, false],
+ ["exact overlap", { x: 0, y: 0, w: 2, h: 1 }, true],
+ ["partial overlap", { x: 1, y: 0, w: 2, h: 1 }, true],
+ ["touching edges do not overlap", { x: 0, y: 1, w: 2, h: 1 }, false],
+ ])("collides: %s", (_name, rect, expected) => {
+ expect(collides(rect, [placement({})])).toBe(expected);
+ });
+
+ it("collides ignores the placement being moved", () => {
+ expect(collides({ x: 0, y: 0, w: 2, h: 1 }, [placement({})], "p1")).toBe(
+ false,
+ );
+ });
+
+ it.each([
+ [
+ "oversized width shrinks to grid",
+ { x: 0, y: 0, w: 9, h: 1 },
+ { x: 0, y: 0, w: 6, h: 1 },
+ ],
+ [
+ "right overflow slides left",
+ { x: 5, y: 0, w: 2, h: 1 },
+ { x: 4, y: 0, w: 2, h: 1 },
+ ],
+ [
+ "negative origin clamps to zero",
+ { x: -1, y: -2, w: 1, h: 1 },
+ { x: 0, y: 0, w: 1, h: 1 },
+ ],
+ [
+ "zero size becomes one cell",
+ { x: 0, y: 0, w: 0, h: 0 },
+ { x: 0, y: 0, w: 1, h: 1 },
+ ],
+ ])("clampRect: %s", (_name, rect, expected) => {
+ expect(clampRect(rect, 6)).toEqual(expected);
+ });
+
+ it("cellFromPoint maps pointer positions to cells including the gap", () => {
+ const grid = { columns: 6, rowHeight: 96, gap: 8 };
+ const surface = { left: 0, top: 0, width: 616 };
+ expect(cellFromPoint(0, 0, surface, grid)).toEqual({ col: 0, row: 0 });
+ expect(cellFromPoint(110, 105, surface, grid)).toEqual({ col: 1, row: 1 });
+ expect(cellFromPoint(9999, 0, surface, grid)).toEqual({ col: 5, row: 0 });
+ });
+
+ it("rectFromCells normalizes a drag in any direction", () => {
+ expect(rectFromCells({ col: 3, row: 2 }, { col: 1, row: 4 })).toEqual({
+ x: 1,
+ y: 2,
+ w: 3,
+ h: 3,
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts
new file mode 100644
index 000000000000..ab668b0dd5d9
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts
@@ -0,0 +1,83 @@
+import type {
+ GridDefinition,
+ GridPlacement,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+
+export interface GridRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+// Server-enforced height cap for a single placement.
+export const MAX_PLACEMENT_HEIGHT = 40;
+
+export function rectsOverlap(a: GridRect, b: GridRect): boolean {
+ return (
+ a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
+ );
+}
+
+export function collides(
+ candidate: GridRect,
+ placements: GridPlacement[],
+ ignoreId?: string,
+): boolean {
+ return placements.some(
+ (placement) =>
+ placement.id !== ignoreId && rectsOverlap(candidate, placement),
+ );
+}
+
+// Clamp a rect into the grid: sizes to at least 1x1 (and the height cap), then
+// position so the rect stays inside the columns.
+export function clampRect(rect: GridRect, columns: number): GridRect {
+ const w = Math.min(Math.max(1, rect.w), columns);
+ const h = Math.min(Math.max(1, rect.h), MAX_PLACEMENT_HEIGHT);
+ const x = Math.min(Math.max(0, rect.x), columns - w);
+ const y = Math.max(0, rect.y);
+ return { x, y, w, h };
+}
+
+// The grid cell under a pointer position, given the surface's bounding rect.
+export function cellFromPoint(
+ pointerX: number,
+ pointerY: number,
+ surface: { left: number; top: number; width: number },
+ grid: GridDefinition,
+): { col: number; row: number } {
+ const cellWidth = (surface.width + grid.gap) / grid.columns;
+ const col = Math.floor((pointerX - surface.left) / cellWidth);
+ const row = Math.floor(
+ (pointerY - surface.top) / (grid.rowHeight + grid.gap),
+ );
+ return {
+ col: Math.min(Math.max(0, col), grid.columns - 1),
+ row: Math.max(0, row),
+ };
+}
+
+// The normalized rect spanned by two cells (a drag's anchor and current cell).
+export function rectFromCells(
+ anchor: { col: number; row: number },
+ current: { col: number; row: number },
+): GridRect {
+ const x = Math.min(anchor.col, current.col);
+ const y = Math.min(anchor.row, current.row);
+ return {
+ x,
+ y,
+ w: Math.abs(anchor.col - current.col) + 1,
+ h: Math.abs(anchor.row - current.row) + 1,
+ };
+}
+
+// Rows the grid surface must render: content, plus room to draw below it.
+export function surfaceRows(placements: GridPlacement[], minimum = 8): number {
+ const bottom = placements.reduce(
+ (lowest, placement) => Math.max(lowest, placement.y + placement.h),
+ 0,
+ );
+ return Math.max(minimum, bottom + 4);
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts b/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts
new file mode 100644
index 000000000000..0caa54384776
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts
@@ -0,0 +1,165 @@
+import type {
+ GridDefinition,
+ GridPlacement,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import { type RefObject, useState } from "react";
+import {
+ cellFromPoint,
+ clampRect,
+ type GridRect,
+ rectFromCells,
+} from "./gridGeometry";
+
+export type GridDragState =
+ | { kind: "draw"; anchor: { col: number; row: number }; rect: GridRect }
+ | {
+ kind: "move";
+ placementId: string;
+ grabbed: { col: number; row: number };
+ origin: GridRect;
+ rect: GridRect;
+ }
+ | { kind: "resize"; placementId: string; origin: GridRect; rect: GridRect };
+
+export interface GridDragOutcome {
+ kind: GridDragState["kind"];
+ rect: GridRect;
+ placementId?: string;
+ origin?: GridRect;
+}
+
+/**
+ * The pointer state machine behind the grid editor: draw a new box on the
+ * empty surface, move a tile, or resize one from its corner handle. Cells are
+ * snapped as the pointer moves (move/resize rects stay clamped to the grid);
+ * the caller decides what a completed drag means.
+ */
+export function useGridDrag({
+ surfaceRef,
+ grid,
+ interactive,
+ onComplete,
+}: {
+ surfaceRef: RefObject<HTMLDivElement | null>;
+ grid: GridDefinition;
+ interactive: boolean;
+ onComplete: (outcome: GridDragOutcome) => void;
+}) {
+ const [drag, setDrag] = useState<GridDragState | null>(null);
+
+ const cellAt = (event: React.PointerEvent) => {
+ const surface = surfaceRef.current?.getBoundingClientRect();
+ if (!surface) return { col: 0, row: 0 };
+ return cellFromPoint(event.clientX, event.clientY, surface, grid);
+ };
+
+ const capture = (event: React.PointerEvent) =>
+ surfaceRef.current?.setPointerCapture(event.pointerId);
+
+ const onSurfacePointerDown = (event: React.PointerEvent) => {
+ if (!interactive || event.button !== 0) return;
+ // Only a press on the empty surface starts a draw; tiles own their presses.
+ if (event.target !== surfaceRef.current) return;
+ const anchor = cellAt(event);
+ capture(event);
+ setDrag({ kind: "draw", anchor, rect: rectFromCells(anchor, anchor) });
+ };
+
+ const startMove =
+ (placement: GridPlacement) => (event: React.PointerEvent) => {
+ if (!interactive || event.button !== 0) return;
+ event.stopPropagation();
+ capture(event);
+ setDrag({
+ kind: "move",
+ placementId: placement.id,
+ grabbed: cellAt(event),
+ origin: placement,
+ rect: {
+ x: placement.x,
+ y: placement.y,
+ w: placement.w,
+ h: placement.h,
+ },
+ });
+ };
+
+ const startResize =
+ (placement: GridPlacement) => (event: React.PointerEvent) => {
+ if (!interactive || event.button !== 0) return;
+ event.stopPropagation();
+ capture(event);
+ setDrag({
+ kind: "resize",
+ placementId: placement.id,
+ origin: placement,
+ rect: {
+ x: placement.x,
+ y: placement.y,
+ w: placement.w,
+ h: placement.h,
+ },
+ });
+ };
+
+ const onPointerMove = (event: React.PointerEvent) => {
+ if (!drag) return;
+ const cell = cellAt(event);
+ if (drag.kind === "draw") {
+ setDrag({ ...drag, rect: rectFromCells(drag.anchor, cell) });
+ } else if (drag.kind === "move") {
+ const rect = clampRect(
+ {
+ ...drag.origin,
+ x: drag.origin.x + (cell.col - drag.grabbed.col),
+ y: drag.origin.y + (cell.row - drag.grabbed.row),
+ },
+ grid.columns,
+ );
+ setDrag({ ...drag, rect });
+ } else {
+ const rect = clampRect(
+ {
+ ...drag.origin,
+ w: cell.col - drag.origin.x + 1,
+ h: cell.row - drag.origin.y + 1,
+ },
+ grid.columns,
+ );
+ setDrag({ ...drag, rect });
+ }
+ };
+
+ const onPointerUp = () => {
+ if (!drag) return;
+ setDrag(null);
+ onComplete({
+ kind: drag.kind,
+ // Move/resize rects are clamped on every pointer move; only a drawn
+ // rect still needs it.
+ rect:
+ drag.kind === "draw" ? clampRect(drag.rect, grid.columns) : drag.rect,
+ placementId: drag.kind === "draw" ? undefined : drag.placementId,
+ origin: drag.kind === "draw" ? undefined : drag.origin,
+ });
+ };
+
+ // A preempted pointer (a trackpad or touch gesture the browser cancels, or
+ // lost capture) drops the gesture WITHOUT committing it — clearing drag snaps
+ // the tile back to its real position. Skipping this leaves a stale drag that
+ // tracks the cursor with no button held and persists an unmade edit on the
+ // next click.
+ const onPointerCancel = () => {
+ setDrag(null);
+ };
+
+ return {
+ drag,
+ onSurfacePointerDown,
+ onPointerMove,
+ onPointerUp,
+ onPointerCancel,
+ startMove,
+ startResize,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx
new file mode 100644
index 000000000000..d0bce84bd1d0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx
@@ -0,0 +1,126 @@
+import type {
+ CanvasLayoutResult,
+ LayoutOperation,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const LAYOUT_KEY = ["dashboards", "layout", "canvas-1"];
+
+const mocks = vi.hoisted(() => ({
+ patchLayout: vi.fn(),
+ toastError: vi.fn(),
+}));
+
+vi.mock("@posthog/host-router/react", () => ({
+ useHostTRPC: () => ({
+ dashboards: {
+ layout: { queryKey: () => LAYOUT_KEY },
+ patchLayout: {
+ mutationOptions: (options: Record<string, unknown>) => ({
+ mutationFn: (input: unknown) => mocks.patchLayout(input),
+ ...options,
+ }),
+ },
+ },
+ }),
+}));
+
+vi.mock("@posthog/ui/features/notifications/errorDetails", () => ({
+ toastError: mocks.toastError,
+}));
+
+import { usePatchLayout } from "./useGridLayout";
+
+const MOVE: LayoutOperation[] = [
+ { op: "update_placement", id: "p1", changes: { x: 1 } },
+];
+
+function layoutAt(versionId: string): CanvasLayoutResult {
+ return {
+ layout: {
+ schemaVersion: 1,
+ grid: { columns: 6, rowHeight: 96, gap: 8 },
+ placements: [],
+ },
+ currentVersionId: versionId,
+ };
+}
+
+let queryClient: QueryClient;
+
+function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+describe("usePatchLayout", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ queryClient.setQueryData(LAYOUT_KEY, layoutAt("v1"));
+ });
+
+ // Two gestures can finish before the first patch answers. Sending both
+ // against the same head means the server rejects the second as a conflict and
+ // the drag or resize silently disappears on the rebase refetch.
+ it("bases a queued patch on the version the previous patch created", async () => {
+ const expected: unknown[] = [];
+ let releaseFirst = (): void => {};
+ const firstInFlight = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ mocks.patchLayout
+ .mockImplementationOnce(async (input: Record<string, unknown>) => {
+ expected.push(input.expectedCurrentVersionId);
+ await firstInFlight;
+ return layoutAt("v2");
+ })
+ .mockImplementationOnce(async (input: Record<string, unknown>) => {
+ expected.push(input.expectedCurrentVersionId);
+ return layoutAt("v3");
+ });
+
+ const { result } = renderHook(() => usePatchLayout("canvas-1"), {
+ wrapper,
+ });
+ await act(async () => {
+ const first = result.current.patch(MOVE);
+ const second = result.current.patch(MOVE);
+ releaseFirst();
+ await Promise.all([first, second]);
+ });
+
+ expect(expected).toEqual(["v1", "v2"]);
+ expect(queryClient.getQueryData(LAYOUT_KEY)).toEqual(layoutAt("v3"));
+ });
+
+ // A rejected patch must not wedge the queue: the next gesture still runs.
+ it("reports a rejected patch as null and keeps accepting later ones", async () => {
+ mocks.patchLayout
+ .mockRejectedValueOnce(new Error("version_conflict"))
+ .mockResolvedValueOnce(layoutAt("v2"));
+
+ const { result } = renderHook(() => usePatchLayout("canvas-1"), {
+ wrapper,
+ });
+ let rejected: CanvasLayoutResult | null = layoutAt("unset");
+ let accepted: CanvasLayoutResult | null = null;
+ await act(async () => {
+ rejected = await result.current.patch(MOVE);
+ accepted = await result.current.patch(MOVE);
+ });
+
+ expect(rejected).toBeNull();
+ expect(accepted).toEqual(layoutAt("v2"));
+ expect(mocks.toastError).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
new file mode 100644
index 000000000000..3e11f97fe1c0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
@@ -0,0 +1,120 @@
+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
+import type {
+ CanvasLayoutResult,
+ LayoutOperation,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import { useHostTRPC } from "@posthog/host-router/react";
+import { toastError } from "@posthog/ui/features/notifications/errorDetails";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useRef } from "react";
+
+// Poll fast while any placement is being agent-filled (the agent patches the
+// layout server-side), otherwise slowly — other viewers/agents can still edit.
+const GENERATING_POLL_MS = 3_000;
+const IDLE_POLL_MS = 20_000;
+
+export function useGridLayout(canvasId: string | undefined): {
+ layout: CanvasLayoutResult["layout"] | undefined;
+ currentVersionId: string | null;
+ isLoading: boolean;
+} {
+ const trpc = useHostTRPC();
+ const { data, isLoading } = useQuery(
+ trpc.dashboards.layout.queryOptions(
+ { id: canvasId ?? "" },
+ {
+ enabled: !!canvasId,
+ staleTime: GENERATING_POLL_MS,
+ refetchInterval: (query) =>
+ query.state.data?.layout.placements.some(
+ (placement) => placement.status === "generating",
+ )
+ ? GENERATING_POLL_MS
+ : IDLE_POLL_MS,
+ },
+ ),
+ );
+ return {
+ layout: data?.layout,
+ currentVersionId: data?.currentVersionId ?? null,
+ isLoading,
+ };
+}
+
+/**
+ * Guarded surgical writes to a grid canvas's layout. On success the layout
+ * cache adopts the server's document; on any failure (including a 409 from a
+ * concurrent edit) the layout is refetched so the surface rebases on the real
+ * head instead of retrying blind.
+ *
+ * Patches run one at a time, each reading the head from the layout cache when
+ * it is actually sent. Two gestures can finish before the first patch answers,
+ * and sending both against the same head would have the server reject the
+ * second as a conflict — losing that drag or resize on the rebase refetch.
+ */
+export function usePatchLayout(canvasId: string): {
+ patch: (
+ operations: LayoutOperation[],
+ prompt?: string,
+ ) => Promise<CanvasLayoutResult | null>;
+ isPatching: boolean;
+} {
+ const trpc = useHostTRPC();
+ const queryClient = useQueryClient();
+ const layoutKey = trpc.dashboards.layout.queryKey({ id: canvasId });
+ const { mutateAsync, isPending } = useMutation(
+ trpc.dashboards.patchLayout.mutationOptions({
+ onSuccess: (result) => {
+ queryClient.setQueryData(layoutKey, result);
+ },
+ }),
+ );
+ // The tail of the patch queue. It never rejects, so one failed patch cannot
+ // wedge the gestures behind it.
+ const queue = useRef<Promise<CanvasLayoutResult | null>>(
+ Promise.resolve(null),
+ );
+ const patch = useCallback(
+ (operations: LayoutOperation[], prompt?: string) => {
+ const key = trpc.dashboards.layout.queryKey({ id: canvasId });
+ const queued = queue.current.then(async () => {
+ const head = queryClient.getQueryData<CanvasLayoutResult>(key);
+ try {
+ return await mutateAsync({
+ id: canvasId,
+ operations,
+ prompt,
+ expectedCurrentVersionId: head?.currentVersionId ?? null,
+ });
+ } catch (error) {
+ toastError("Couldn't update the canvas layout", error);
+ // Rebase before the next queued gesture is sent, and let callers
+ // treat null as "this edit didn't land".
+ await queryClient.invalidateQueries({ queryKey: key });
+ return null;
+ }
+ });
+ queue.current = queued;
+ return queued;
+ },
+ [mutateAsync, canvasId, queryClient, trpc],
+ );
+ return { patch, isPatching: isPending };
+}
+
+export function useComponentStore(
+ search: string,
+ options?: { enabled?: boolean },
+): {
+ components: DashboardRecord[];
+ isLoading: boolean;
+} {
+ const trpc = useHostTRPC();
+ const { data, isLoading } = useQuery(
+ trpc.dashboards.listComponents.queryOptions(
+ { search: search || undefined },
+ { staleTime: 30_000, enabled: options?.enabled ?? true },
+ ),
+ );
+ return { components: data ?? [], isLoading };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts
index d5bc2ac2e3ed..967d5e9103c6 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts
@@ -25,13 +25,19 @@ export function useCanvasBuilds(
): {
lifecycle: CanvasBuildLifecycle | undefined;
isLoading: boolean;
+ /** True once the fetch has failed after its retries — lets a caller tell a
+ * permanently broken request (e.g. a deleted component canvas) from a slow
+ * one, so it can show an error instead of an endless spinner. */
+ isError: boolean;
/** Epoch ms the current lifecycle data was fetched — signed artifact URLs
* are minted per fetch, so this is the pinned URL's mint time. */
dataUpdatedAt: number;
+ /** Re-run the fetch, for a retry control on the error state. */
+ refetch: () => void;
} {
const trpc = useHostTRPC();
const generating = options?.generating ?? false;
- const { data, isLoading, dataUpdatedAt } = useQuery(
+ const { data, isLoading, isError, dataUpdatedAt, refetch } = useQuery(
trpc.dashboards.builds.queryOptions(
{ id: dashboardId ?? "", versionId: options?.versionId },
{
@@ -46,5 +52,13 @@ export function useCanvasBuilds(
},
),
);
- return { lifecycle: data, isLoading, dataUpdatedAt };
+ return {
+ lifecycle: data,
+ isLoading,
+ isError,
+ dataUpdatedAt,
+ refetch: () => {
+ void refetch();
+ },
+ };
}
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 b36bb00cde2b..fd96f9bdea1e 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useGenerateFreeformCanvas.ts
@@ -62,6 +62,12 @@ export function useGenerateFreeformCanvas(args: {
name: string;
templateId?: string;
instruction: string;
+ // When set, the run fills ONE placement on a grid canvas (the agent
+ // follows the composing-grid-canvases skill instead of building-canvases).
+ placement?: { placementId: string; w: number; h: number };
+ // "grid" routes a whole-canvas run to the grid skill (edit the layout
+ // and its components) instead of freeform canvas authoring.
+ canvasKind?: "grid";
// The composer's picks, when the surface exposes model/effort selectors.
adapter?: Adapter;
model?: string;
@@ -99,6 +105,8 @@ export function useGenerateFreeformCanvas(args: {
name,
templateId: opts.templateId,
instruction,
+ placement: opts.placement,
+ canvasKind: opts.canvasKind,
channelId,
channelName,
channelContext,
@@ -123,13 +131,18 @@ 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.
- useCanvasGenerationTrackerStore.getState().track({
- taskId: result.taskId,
- dashboardId,
- channelId,
- name,
- });
+ // finishes, even after the user navigates to another canvas. Placement
+ // fills are excluded: the completion toast judges the canvas's build
+ // health, and a grid canvas has no builds — the empty lifecycle would
+ // read as "finished with a failed build". The tile shows the progress.
+ if (!opts.placement && opts.canvasKind !== "grid") {
+ 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/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.ts
index 1992d0fd8a03..824f1018c00e 100644
--- a/products/desktop/packages/ui/src/router/navigationBridge.ts
+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts
@@ -44,6 +44,10 @@ export function navigateToActivity(): void {
void getRouterOrNull()?.navigate({ to: "/website/activity" });
}
+export function navigateToHome(): void {
+ void getRouterOrNull()?.navigate({ to: "/website/home" });
+}
+
export function navigateToChannel(channelId: string): void {
void getRouterOrNull()?.navigate({
to: "/website/$channelId",
diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.ts
index 98bd7a2d28d1..c98153ebe31d 100644
--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts
+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts
@@ -21,6 +21,7 @@ import { Route as CodeIndexRouteImport } from './routes/code/index'
import { Route as WebsiteSkillsRouteImport } from './routes/website/skills'
import { Route as WebsiteNewRouteImport } from './routes/website/new'
import { Route as WebsiteMcpServersRouteImport } from './routes/website/mcp-servers'
+import { Route as WebsiteHomeRouteImport } from './routes/website/home'
import { Route as WebsiteCommandCenterRouteImport } from './routes/website/command-center'
import { Route as WebsiteActivityRouteImport } from './routes/website/activity'
import { Route as SettingsCategoryRouteImport } from './routes/settings/$category'
@@ -140,6 +141,11 @@ const WebsiteMcpServersRoute = WebsiteMcpServersRouteImport.update({
path: '/mcp-servers',
getParentRoute: () => WebsiteRoute,
} as any)
+const WebsiteHomeRoute = WebsiteHomeRouteImport.update({
+ id: '/home',
+ path: '/home',
+ getParentRoute: () => WebsiteRoute,
+} as any)
const WebsiteCommandCenterRoute = WebsiteCommandCenterRouteImport.update({
id: '/command-center',
path: '/command-center',
@@ -468,6 +474,7 @@ export interface FileRoutesByFullPath {
'/settings/$category': typeof SettingsCategoryRoute
'/website/activity': typeof WebsiteActivityRoute
'/website/command-center': typeof WebsiteCommandCenterRoute
+ '/website/home': typeof WebsiteHomeRoute
'/website/mcp-servers': typeof WebsiteMcpServersRoute
'/website/new': typeof WebsiteNewRoute
'/website/skills': typeof WebsiteSkillsRoute
@@ -537,6 +544,7 @@ export interface FileRoutesByTo {
'/settings/$category': typeof SettingsCategoryRoute
'/website/activity': typeof WebsiteActivityRoute
'/website/command-center': typeof WebsiteCommandCenterRoute
+ '/website/home': typeof WebsiteHomeRoute
'/website/mcp-servers': typeof WebsiteMcpServersRoute
'/website/new': typeof WebsiteNewRoute
'/website/skills': typeof WebsiteSkillsRoute
@@ -601,6 +609,7 @@ export interface FileRoutesById {
'/settings/$category': typeof SettingsCategoryRoute
'/website/activity': typeof WebsiteActivityRoute
'/website/command-center': typeof WebsiteCommandCenterRoute
+ '/website/home': typeof WebsiteHomeRoute
'/website/mcp-servers': typeof WebsiteMcpServersRoute
'/website/new': typeof WebsiteNewRoute
'/website/skills': typeof WebsiteSkillsRoute
@@ -675,6 +684,7 @@ export interface FileRouteTypes {
| '/settings/$category'
| '/website/activity'
| '/website/command-center'
+ | '/website/home'
| '/website/mcp-servers'
| '/website/new'
| '/website/skills'
@@ -744,6 +754,7 @@ export interface FileRouteTypes {
| '/settings/$category'
| '/website/activity'
| '/website/command-center'
+ | '/website/home'
| '/website/mcp-servers'
| '/website/new'
| '/website/skills'
@@ -807,6 +818,7 @@ export interface FileRouteTypes {
| '/settings/$category'
| '/website/activity'
| '/website/command-center'
+ | '/website/home'
| '/website/mcp-servers'
| '/website/new'
| '/website/skills'
@@ -973,6 +985,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof WebsiteMcpServersRouteImport
parentRoute: typeof WebsiteRoute
}
+ '/website/home': {
+ id: '/website/home'
+ path: '/home'
+ fullPath: '/website/home'
+ preLoaderRoute: typeof WebsiteHomeRouteImport
+ parentRoute: typeof WebsiteRoute
+ }
'/website/command-center': {
id: '/website/command-center'
path: '/command-center'
@@ -1385,6 +1404,7 @@ declare module '@tanstack/react-router' {
interface WebsiteRouteChildren {
WebsiteActivityRoute: typeof WebsiteActivityRoute
WebsiteCommandCenterRoute: typeof WebsiteCommandCenterRoute
+ WebsiteHomeRoute: typeof WebsiteHomeRoute
WebsiteMcpServersRoute: typeof WebsiteMcpServersRoute
WebsiteNewRoute: typeof WebsiteNewRoute
WebsiteSkillsRoute: typeof WebsiteSkillsRoute
@@ -1403,6 +1423,7 @@ interface WebsiteRouteChildren {
const WebsiteRouteChildren: WebsiteRouteChildren = {
WebsiteActivityRoute: WebsiteActivityRoute,
WebsiteCommandCenterRoute: WebsiteCommandCenterRoute,
+ WebsiteHomeRoute: WebsiteHomeRoute,
WebsiteMcpServersRoute: WebsiteMcpServersRoute,
WebsiteNewRoute: WebsiteNewRoute,
WebsiteSkillsRoute: WebsiteSkillsRoute,
diff --git a/products/desktop/packages/ui/src/router/routes/website/home.tsx b/products/desktop/packages/ui/src/router/routes/website/home.tsx
new file mode 100644
index 000000000000..3e2d681619ab
--- /dev/null
+++ b/products/desktop/packages/ui/src/router/routes/website/home.tsx
@@ -0,0 +1,6 @@
+import { WebsiteHome } from "@posthog/ui/features/canvas/grid/WebsiteHome";
+import { createFileRoute } from "@tanstack/react-router";
+
+export const Route = createFileRoute("/website/home")({
+ component: WebsiteHome,
+});
diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.ts
index ca75364a3afe..8452e7de6e1f 100644
--- a/products/desktop/packages/ui/src/router/useAppView.ts
+++ b/products/desktop/packages/ui/src/router/useAppView.ts
@@ -12,6 +12,7 @@ export type AppViewType =
| "task-input"
| "folder-settings"
| "activity"
+ | "home"
| "inbox"
| "agents"
| "loops"
@@ -64,6 +65,8 @@ function deriveFromMatches(matches: Match[]): AppView {
return { type: "folder-settings", folderId: last.params.folderId };
case "/website/activity":
return { type: "activity" };
+ case "/website/home":
+ return { type: "home" };
case "/code/inbox":
return { type: "inbox" };
case "/code/agents":