:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(comments): canvas commenting and historical version replay (#78691)
Shy Alterb528bc1d3231
diff --git a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.tsindex 12e20ef04cd7..9caa7168f9ac 100644--- a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts+++ b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts@@ -4,6 +4,7 @@ import {type CanvasBuildRecord,currentHeadBuildFailure,hasActiveCanvasBuild,+ historicalCanvasBuild,latestFinishedCanvasBuild,publishedCanvasBuild,} from "./canvasBuildSchemas";@@ -74,6 +75,32 @@ describe("canvas build lifecycle", () => {expect(publishedCanvasBuild(value)).toBe(ready);});+ it("selects a retained ready artifact for a historical version", () => {+ const ready = build("historical", "ready");+ ready.sourceVersionId = "version-1";++ expect(+ historicalCanvasBuild(+ lifecycle([build("latest", "ready"), ready]),+ "version-1",+ ),+ ).toBe(ready);+ });++ it.each([+ ["an unfinished build", build("historical", "building")],+ [+ "a ready build without a retained artifact",+ { ...build("historical", "ready"), artifactUrl: null },+ ],+ ])("rejects %s for a historical version", (_name, candidate) => {+ candidate.sourceVersionId = "version-1";++ expect(+ historicalCanvasBuild(lifecycle([candidate]), "version-1"),+ ).toBeNull();+ });+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@@ -136,7 +163,7 @@ describe("canvas build lifecycle", () => {},} as unknown as ProjectApiClient);- const result = await service.getBuilds("canvas-1");+ const result = await service.getBuilds({ id: "canvas-1" });expect(result.publishedBuildId).toBe("b0");expect(result.builds[0]).toMatchObject({diff --git a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.tsindex fe779d1a9221..9ec9e9cdfa5a 100644--- a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts+++ b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.ts@@ -42,6 +42,20 @@ export function publishedCanvasBuild();}+export function historicalCanvasBuild(+ lifecycle: CanvasBuildLifecycle,+ versionId: string,+): CanvasBuildRecord | null {+ return (+ lifecycle.builds.find(+ (build) =>+ build.sourceVersionId === versionId &&+ build.buildStatus === "ready" &&+ !!build.artifactUrl,+ ) ?? 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/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.tsindex 2d5fb978f1cb..094291d39d59 100644--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts@@ -73,6 +73,11 @@ export const createDashboardInput = z.object({export const dashboardIdInput = z.object({ id: z.string().min(1) });+export const canvasBuildsInput = z.object({+ id: z.string().min(1),+ versionId: z.string().min(1).optional(),+});+export const canvasSourceInput = z.object({id: z.string().min(1),// Read a historical version's files instead of the head.diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.test.ts b/products/desktop/packages/core/src/canvas/dashboardsService.test.tsindex 9d13b489af6b..fac1b52b0d56 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.test.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.test.ts@@ -77,7 +77,7 @@ describe("DashboardsService.list", () => {describe("DashboardsService.getBuilds", () => {it("normalizes the lifecycle payload", async () => {const { api } = fakeApi({- "canvases/c1/builds/": {+ "canvases/c1/builds/?version_id=v1": {published_build_id: "b1",current_version_id: "v1",builds: [@@ -97,7 +97,7 @@ describe("DashboardsService.getBuilds", () => {});const service = new DashboardsService(api);- const lifecycle = await service.getBuilds("c1");+ const lifecycle = await service.getBuilds({ id: "c1", versionId: "v1" });expect(lifecycle.publishedBuildId).toBe("b1");expect(lifecycle.currentVersionId).toBe("v1");diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.tsindex 2a6e186e75db..d21830ba9502 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts@@ -258,12 +258,21 @@ export class DashboardsService {// Read a canvas's build lifecycle (pointers + recent builds). Publishing// queues a build server-side; callers poll this until it settles.- async getBuilds(id: string): Promise<CanvasBuildLifecycle> {+ async getBuilds(input: {+ id: string;+ versionId?: string;+ }): Promise<CanvasBuildLifecycle> {+ const suffix = input.versionId+ ? `?version_id=${encodeURIComponent(input.versionId)}`+ : "";const body = await this.api.json<{published_build_id: string | null;current_version_id: string | null;builds: Record<string, unknown>[];- }>(`canvases/${encodeURIComponent(id)}/builds/`, "load canvas builds");+ }>(+ `canvases/${encodeURIComponent(input.id)}/builds/${suffix}`,+ "load canvas builds",+ );// Each build row is already validated by tryToBuildRecord; this endpoint is// polled every couple of seconds during builds, so don't re-run the whole// lifecycle schema (which would zod-parse every record a second time).diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.test.tsindex 7f1a8381e79c..bdf544214ca1 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.test.ts@@ -1,7 +1,11 @@import { describe, expect, it } from "vitest";-import { canvasToHostMessageSchema } from "./freeformSchemas";+import {+ canvasToHostMessageSchema,+ hostToCanvasMessageSchema,+ limitCanvasCommentHighlights,+} from "./freeformSchemas";-describe("canvasToHostMessageSchema open-external", () => {+describe("canvasToHostMessageSchema", () => {const message = (url: string) => ({channel: "posthog-canvas",type: "open-external",@@ -32,4 +36,109 @@ describe("canvasToHostMessageSchema open-external", () => {false,);});++ it("accepts a bounded text selection and rejects oversized selected text", () => {+ const selection = {+ channel: "posthog-canvas",+ type: "text-selection",+ selection: {+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ rect: { top: 10, right: 80, bottom: 30, left: 20 },+ },+ };++ expect(canvasToHostMessageSchema.safeParse(selection).success).toBe(true);+ expect(+ canvasToHostMessageSchema.safeParse({+ ...selection,+ selection: { ...selection.selection, quote: "x".repeat(10_001) },+ }).success,+ ).toBe(false);+ });++ it("accepts an explicit selection-cleared event", () => {+ expect(+ canvasToHostMessageSchema.safeParse({+ channel: "posthog-canvas",+ type: "text-selection-cleared",+ }).success,+ ).toBe(true);+ });++ it("accepts a bounded comment activation", () => {+ expect(+ canvasToHostMessageSchema.safeParse({+ channel: "posthog-canvas",+ type: "comment-activate",+ id: "comment-1",+ }).success,+ ).toBe(true);+ });++ it("accepts bounded comment highlights", () => {+ expect(+ hostToCanvasMessageSchema.safeParse({+ channel: "posthog-canvas",+ type: "set-comment-highlights",+ highlights: [+ {+ id: "comment-1",+ active: false,+ anchor: {+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ },+ },+ ],+ }).success,+ ).toBe(true);+ });++ it.each([+ {+ name: "protocol item limit",+ count: 501,+ quote: "x",+ expected: 500,+ },+ {+ name: "aggregate anchor text budget",+ count: 11,+ quote: "x".repeat(10_000),+ expected: 10,+ },+ ])("limits highlights by $name", ({ count, quote, expected }) => {+ const highlights = Array.from({ length: count }, (_, index) => ({+ id: `comment-${index}`,+ active: false,+ anchor: {+ quote,+ prefix: "",+ suffix: "",+ start: 0,+ end: quote.length,+ },+ }));++ expect(limitCanvasCommentHighlights(highlights)).toHaveLength(expected);+ });++ it("accepts a host request to clear native text selection", () => {+ expect(+ hostToCanvasMessageSchema.parse({+ channel: "posthog-canvas",+ type: "clear-text-selection",+ }),+ ).toEqual({+ channel: "posthog-canvas",+ type: "clear-text-selection",+ });+ });});diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex b5ee108a51a8..721f428fde23 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -1,5 +1,6 @@import { isSafePostHogUrl } from "@posthog/shared";import { z } from "zod";+import { textCommentAnchorDataSchema } from "../comments/anchors";// The template id for freeform-React canvases. Stored on a canvas's meta so the// generation path can resolve the right system prompt.@@ -126,6 +127,54 @@ export type CanvasAnalyticsConfig = z.infer<typeof canvasAnalyticsConfigSchema>;export const canvasThemeSchema = z.enum(["light", "dark"]);export type CanvasTheme = z.infer<typeof canvasThemeSchema>;+const canvasTextSelectionDataSchema = textCommentAnchorDataSchema.extend({+ rect: z.object({+ top: z.number().finite(),+ right: z.number().finite(),+ bottom: z.number().finite(),+ left: z.number().finite(),+ }),+});+export const canvasTextSelectionSchema = canvasTextSelectionDataSchema.refine(+ ({ start, end }) => end > start,+);+export type CanvasTextSelection = z.infer<typeof canvasTextSelectionSchema>;++export const canvasCommentHighlightSchema = z.object({+ id: z.string().min(1).max(128),+ active: z.boolean(),+ anchor: textCommentAnchorDataSchema.refine(({ start, end }) => end > start),+});+export type CanvasCommentHighlight = z.infer<+ typeof canvasCommentHighlightSchema+>;++export const MAX_CANVAS_COMMENT_HIGHLIGHTS = 500;+export const MAX_CANVAS_COMMENT_HIGHLIGHT_TEXT_LENGTH = 100_000;++export function limitCanvasCommentHighlights(+ highlights: CanvasCommentHighlight[],+): CanvasCommentHighlight[] {+ const limited: CanvasCommentHighlight[] = [];+ let textLength = 0;+ for (const highlight of highlights) {+ const nextTextLength =+ textLength ++ highlight.anchor.quote.length ++ highlight.anchor.prefix.length ++ highlight.anchor.suffix.length;+ if (+ limited.length >= MAX_CANVAS_COMMENT_HIGHLIGHTS ||+ nextTextLength > MAX_CANVAS_COMMENT_HIGHLIGHT_TEXT_LENGTH+ ) {+ break;+ }+ limited.push(highlight);+ textLength = nextTextLength;+ }+ return limited;+}+// host -> iframeexport const hostToCanvasMessageSchema = z.discriminatedUnion("type", [// First frame: hand the iframe its source + the run mode. The iframe does not@@ -143,6 +192,10 @@ export const hostToCanvasMessageSchema = z.discriminatedUnion("type", [// already correct; live theme changes use the `set-theme` frame below// (which re-themes without remounting). Absent = light.theme: canvasThemeSchema.optional(),+ highlights: z+ .array(canvasCommentHighlightSchema)+ .max(MAX_CANVAS_COMMENT_HIGHLIGHTS)+ .optional(),}),// Live theme change: re-apply light/dark WITHOUT remounting the app. Sent on// its own (not folded into `init`) so toggling the host theme — or an OS@@ -152,6 +205,17 @@ export const hostToCanvasMessageSchema = z.discriminatedUnion("type", [type: z.literal("set-theme"),theme: canvasThemeSchema,}),+ z.object({+ channel: z.literal(CANVAS_CHANNEL),+ type: z.literal("set-comment-highlights"),+ highlights: z+ .array(canvasCommentHighlightSchema)+ .max(MAX_CANVAS_COMMENT_HIGHLIGHTS),+ }),+ z.object({+ channel: z.literal(CANVAS_CHANNEL),+ type: z.literal("clear-text-selection"),+ }),// Reply to a data-request, correlated by `id`.z.object({channel: z.literal(CANVAS_CHANNEL),@@ -223,5 +287,19 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [type: z.literal("open-external"),url: z.string().refine(isSafePostHogUrl),}),+ z.object({+ channel: z.literal(CANVAS_CHANNEL),+ type: z.literal("text-selection"),+ selection: canvasTextSelectionSchema,+ }),+ z.object({+ channel: z.literal(CANVAS_CHANNEL),+ type: z.literal("text-selection-cleared"),+ }),+ z.object({+ channel: z.literal(CANVAS_CHANNEL),+ type: z.literal("comment-activate"),+ id: z.string().min(1).max(128),+ }),]);export type CanvasToHostMessage = z.infer<typeof canvasToHostMessageSchema>;diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.tsindex 640344b6253e..061c2bd6cdcb 100644--- a/products/desktop/packages/core/src/canvas/services.ts+++ b/products/desktop/packages/core/src/canvas/services.ts@@ -57,8 +57,11 @@ export interface IDashboardsService {versionId: string;expectedCurrentVersionId: string | null;}): Promise<CanvasBuildRecord>;- // Read a canvas's build lifecycle (pointers + recent builds).- getBuilds(id: string): Promise<CanvasBuildLifecycle>;+ // Read a canvas's build lifecycle, optionally including a historical build.+ getBuilds(input: {+ id: string;+ versionId?: string;+ }): Promise<CanvasBuildLifecycle>;actOnBuild(input: CanvasBuildActionInput): Promise<CanvasBuildRecord>;rename(input: { id: string; name: string }): Promise<DashboardRecord>;delete(id: string): Promise<void>;diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.tsindex 7603b889ea0d..723d084a9375 100644--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts@@ -4,6 +4,7 @@ import {canvasBuildRecordSchema,} from "@posthog/core/canvas/canvasBuildSchemas";import {+ canvasBuildsInput,canvasSourceInput,canvasSourceSchema,canvasVersionSchema,@@ -62,12 +63,12 @@ export const dashboardsRouter = router({.revertToVersion(input),),builds: publicProcedure- .input(dashboardIdInput)+ .input(canvasBuildsInput).output(canvasBuildLifecycleSchema).query(({ ctx, input }) =>ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE)- .getBuilds(input.id),+ .getBuilds(input),),actOnBuild: publicProcedure.input(canvasBuildActionInputSchema)diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.test.tsxindex a0017fb932c8..f81e49815b74 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.test.tsx@@ -1,19 +1,25 @@import { Theme } from "@radix-ui/themes";-import { render, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({useChannelsLayout: () => false,}));+vi.mock("@posthog/host-router/react", () => ({+ useHostTRPC: () => ({+ dashboards: { saveContext: { mutationKey: () => ["save-context"] } },+ }),+}));-const { useChannelTasks, useParams, usePathname, useTasks } = vi.hoisted(- () => ({+const { useChannelTasks, useDashboard, useParams, usePathname, useTasks } =+ vi.hoisted(() => ({useChannelTasks: vi.fn(),+ useDashboard: vi.fn(),useParams: vi.fn(),usePathname: vi.fn(),useTasks: vi.fn(),- }),-);+ }));vi.mock("@tanstack/react-router", () => ({Outlet: () => null,@@ -45,8 +51,35 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({}),}));vi.mock("@posthog/ui/features/canvas/hooks/useDashboards", () => ({- useDashboard: () => ({ dashboard: undefined }),+ useDashboard,useDashboardMutations: () => ({}),+ useCanvasVersions: () => ({ versions: [{ taskId: "version-task" }] }),+}));+vi.mock("@posthog/ui/features/sessions/components/useComments", () => ({+ useCommentsQuery: () => ({+ data: [+ {+ id: "comment-1",+ created_at: "2026-01-01T00:00:00Z",+ content: "First",+ item_id: "canvas-1",+ item_context: { anchor: { kind: "document" } },+ scope: "desktop_canvas",+ source_comment: null,+ completed_at: null,+ },+ {+ id: "comment-2",+ created_at: "2026-01-01T00:01:00Z",+ content: "Second",+ item_id: "canvas-1",+ item_context: { anchor: { kind: "document" } },+ scope: "desktop_canvas",+ source_comment: null,+ completed_at: null,+ },+ ],+ }),}));vi.mock("@posthog/ui/features/canvas/stores/dashboardEditStore", () => ({useDashboardEditStore: (sel: (s: unknown) => unknown) =>@@ -60,6 +93,7 @@ vi.mock("@posthog/ui/features/canvas/freeform/CanvasFrameHost", () => ({CanvasFrameHost: () => null,}));+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import { useHeaderStore } from "@posthog/ui/shell/headerStore";import { WebsiteLayout } from "./WebsiteLayout";@@ -68,11 +102,17 @@ function renderLayout({params,tasks = [{ id: "task-1", title: "Fix the bug" }],channelTaskIds = tasks.map((task) => task.id),+ dashboard,}: {pathname: string;params: Record<string, string>;tasks?: { id: string; title: string }[];channelTaskIds?: string[];+ dashboard?: {+ name: string;+ templateId: string;+ generationTaskId: string | null;+ };}) {usePathname.mockReturnValue(pathname);useParams.mockReturnValue(params);@@ -81,15 +121,46 @@ function renderLayout({tasks: channelTaskIds.map((taskId) => ({ taskId })),isLoading: false,});+ useDashboard.mockReturnValue({ dashboard });useHeaderStore.setState({ content: <span>crumb</span> });render(- <Theme>- <WebsiteLayout />- </Theme>,+ <QueryClientProvider client={new QueryClient()}>+ <Theme>+ <WebsiteLayout />+ </Theme>+ </QueryClientProvider>,);}describe("WebsiteLayout task header actions", () => {+ it.each([+ ["while generating", "task-1"],+ ["after generation", null],+ ])(+ "shows the comment count and opens comments %s",+ (_label, generationTaskId) => {+ renderLayout({+ pathname: "/website/chan-1/dashboards/canvas-1",+ params: { channelId: "chan-1", dashboardId: "canvas-1" },+ dashboard: {+ name: "Launch",+ templateId: "freeform",+ generationTaskId,+ },+ });++ expect(+ screen.getByRole("button", { name: /Comments/ }),+ ).toHaveTextContent("Comments2");+ useCanvasChatPanelStore.setState({ collapsed: true, tab: "chat" });+ fireEvent.click(screen.getByRole("button", { name: /Comments/ }));+ expect(useCanvasChatPanelStore.getState()).toMatchObject({+ collapsed: false,+ tab: "comments",+ });+ },+ );+it("renders the task action row on a channel task detail", () => {renderLayout({pathname: "/website/chan-1/tasks/task-1",diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsxindex 172df777217a..67a53f9117ce 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteLayout.tsx@@ -1,5 +1,6 @@import {ArrowClockwiseIcon,+ ChatCircleIcon,DotsThreeIcon,LinkIcon,PencilSimpleIcon,@@ -28,20 +29,29 @@ import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTeimport { NewCanvasMenu } from "@posthog/ui/features/canvas/components/NewCanvasMenu";import { deleteCanvasWithUndo } from "@posthog/ui/features/canvas/deleteCanvasWithUndo";import { CanvasFrameHost } from "@posthog/ui/features/canvas/freeform/CanvasFrameHost";+import { canvasCommentTaskId } from "@posthog/ui/features/canvas/freeform/canvasCommentTask";import { useCanvasFrameStore } from "@posthog/ui/features/canvas/freeform/canvasFrameStore";import { CANVAS_QUERY_KEY } from "@posthog/ui/features/canvas/freeform/freeformDataBridge";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useChannelTasks } from "@posthog/ui/features/canvas/hooks/useChannelTasks";import {+ useCanvasVersions,useDashboard,useDashboardMutations,} from "@posthog/ui/features/canvas/hooks/useDashboards";+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import {useDashboardEditStore,useIsDashboardEditing,} from "@posthog/ui/features/canvas/stores/dashboardEditStore";import { copyCanvasLink } from "@posthog/ui/features/canvas/utils/copyCanvasLink";+import { buildCommentThreads } from "@posthog/ui/features/sessions/components/commentViewTypes";+import { useCommentsQuery } from "@posthog/ui/features/sessions/components/useComments";+import {+ MentionAvailabilityProvider,+ PRIVATE_SPACE_MENTIONS_DISABLED,+} from "@posthog/ui/features/sessions/mentionAvailability";import { TaskHeaderActions } from "@posthog/ui/features/task-detail/components/TaskHeaderActions";import { useTasks } from "@posthog/ui/features/tasks/useTasks";import { toast } from "@posthog/ui/primitives/toast";@@ -278,8 +288,26 @@ function CanvasBreadcrumb({trailing?: ReactNode;}) {const { dashboard } = useDashboard(dashboardId);+ const { versions } = useCanvasVersions(dashboardId);const { renameDashboard } = useDashboardMutations();+ const openComments = useCanvasChatPanelStore((state) => state.openComments);const name = dashboard?.name ?? "Canvas";+ const commentTarget = {+ scope: "desktop_canvas" as const,+ itemId: dashboardId,+ };+ const commentTaskId = canvasCommentTaskId(+ dashboard?.generationTaskId,+ versions,+ );+ const comments = useCommentsQuery(+ commentTaskId ? commentTarget : null,+ commentTaskId ?? "",+ { live: true },+ );+ const openCommentCount = buildCommentThreads(comments.data ?? []).filter(+ (thread) => !thread.resolved,+ ).length;return (<ChannelBreadcrumb@@ -294,7 +322,20 @@ function CanvasBreadcrumb({leafLabel={name}editScopeKey={dashboardId}onRename={(next) => void renameDashboard(dashboardId, next)}- trailing={trailing}+ trailing={+ <>+ {commentTaskId && (+ <Button size="sm" variant="outline" onClick={openComments}>+ <ChatCircleIcon />+ Comments+ {openCommentCount > 0 && (+ <span className="tabular-nums">{openCommentCount}</span>+ )}+ </Button>+ )}+ {trailing}+ </>+ }/>);}@@ -325,6 +366,11 @@ export function WebsiteLayout() {: undefined;const { channels } = useChannels();+ const mentionsDisabledReason =+ channels.find((channel) => channel.id === channelId)?.channelType ===+ "personal"+ ? PRIVATE_SPACE_MENTIONS_DISABLED+ : null;const channelName = channelId? (channels.find((c) => c.id === channelId)?.name ??(spacesLayout ? "Space" : "Channel"))@@ -397,7 +443,9 @@ export function WebsiteLayout() {</Flex>)}<Box flexGrow="1" overflow="hidden">- <Outlet />+ <MentionAvailabilityProvider disabledReason={mentionsDisabledReason}>+ <Outlet />+ </MentionAvailabilityProvider></Box>{/* Warm-iframe pool for canvases. Mounted once here so it persists acrossevery in-space navigation; overlays itself onto the active canvas'sdiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsxindex b9c217c1d867..aba817d25520 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx@@ -157,25 +157,105 @@ describe("BuiltCanvas", () => {Transferable[],][];const canvasPort = calls.at(-1)?.[2]?.[0] as MessagePort;- const frames: unknown[] = [];- canvasPort.addEventListener("message", (event) =>- frames.push((event as MessageEvent).data),- );+ const themeFrames: unknown[] = [];+ canvasPort.addEventListener("message", (event) => {+ const frame = (event as MessageEvent).data as { type?: string };+ if (frame.type === "set-theme") themeFrames.push(frame);+ });canvasPort.start();- await waitFor(() => expect(frames).toHaveLength(1));- expect(frames[0]).toEqual({+ await waitFor(() => expect(themeFrames).toHaveLength(1));+ expect(themeFrames[0]).toEqual({channel: "posthog-canvas",type: "set-theme",theme: "dark",});act(() => useThemeStore.setState({ isDarkMode: false }));- await waitFor(() => expect(frames).toHaveLength(2));- expect(frames[1]).toEqual({+ await waitFor(() => expect(themeFrames).toHaveLength(2));+ expect(themeFrames[1]).toEqual({channel: "posthog-canvas",type: "set-theme",theme: "light",});});++ it("opens a comment selected inside the built artifact", async () => {+ const onCommentActivate = vi.fn();+ render(+ <BuiltCanvas+ artifactUrl="https://usercontent.example/build/index.html"+ capabilities={capabilities}+ onDataRequest={vi.fn()}+ onCommentActivate={onCommentActivate}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;+ if (!iframe.contentWindow) throw new Error("Canvas iframe has no window");+ const postMessage = vi+ .spyOn(iframe.contentWindow, "postMessage")+ .mockImplementation(() => undefined);++ fireEvent.load(iframe);+ const calls = postMessage.mock.calls as unknown as [+ unknown,+ string,+ Transferable[],+ ][];+ const canvasPort = calls.at(-1)?.[2]?.[0] as MessagePort;+ canvasPort.postMessage({+ channel: "posthog-canvas",+ type: "comment-activate",+ id: "comment-1",+ });++ await waitFor(() =>+ expect(onCommentActivate).toHaveBeenCalledWith("comment-1"),+ );+ });++ it("clears native artifact selection when the host dismisses it", async () => {+ const { rerender } = render(+ <BuiltCanvas+ artifactUrl="https://usercontent.example/build/index.html"+ capabilities={capabilities}+ onDataRequest={vi.fn()}+ clearTextSelectionKey={0}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;+ if (!iframe.contentWindow) throw new Error("Canvas iframe has no window");+ const postMessage = vi+ .spyOn(iframe.contentWindow, "postMessage")+ .mockImplementation(() => undefined);++ fireEvent.load(iframe);+ const calls = postMessage.mock.calls as unknown as [+ unknown,+ string,+ Transferable[],+ ][];+ const canvasPort = calls.at(-1)?.[2]?.[0] as MessagePort;+ const messages: unknown[] = [];+ canvasPort.addEventListener("message", (event) =>+ messages.push((event as MessageEvent).data),+ );+ canvasPort.start();++ rerender(+ <BuiltCanvas+ artifactUrl="https://usercontent.example/build/index.html"+ capabilities={capabilities}+ onDataRequest={vi.fn()}+ clearTextSelectionKey={1}+ />,+ );++ await waitFor(() =>+ expect(messages).toContainEqual({+ channel: "posthog-canvas",+ type: "clear-text-selection",+ }),+ );+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsxindex 15d89d2939d6..e470d4fbc97d 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.tsx@@ -1,6 +1,8 @@import { assertCanvasCapability } from "@posthog/core/canvas/canvasCapabilities";import {+ type CanvasCommentHighlight,type CanvasNavIntent,+ type CanvasTextSelection,type CanvasTheme,canvasToHostMessageSchema,} from "@posthog/core/canvas/freeformSchemas";@@ -10,8 +12,10 @@ import { openExternalUrl } from "@posthog/ui/shell/openExternal";import { useThemeStore } from "@posthog/ui/shell/themeStore";import { useEffect, useLayoutEffect, useRef } from "react";import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";+import { translateCanvasTextSelection } from "./canvasSelection";const log = logger.scope("built-canvas");+const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];function buildArtifactHostDocument(artifactUrl: string,@@ -92,6 +96,10 @@ export interface BuiltCanvasProps {onReady?: () => void;onRendered?: () => void;onNavigate?: (intent: CanvasNavIntent) => void;+ onTextSelection?: (selection: CanvasTextSelection | null) => void;+ onCommentActivate?: (id: string) => void;+ commentHighlights?: CanvasCommentHighlight[];+ clearTextSelectionKey?: number;}export function BuiltCanvas({@@ -102,6 +110,10 @@ export function BuiltCanvas({onReady,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,+ commentHighlights = EMPTY_COMMENT_HIGHLIGHTS,+ clearTextSelectionKey = 0,}: BuiltCanvasProps) {const iframeRef = useRef<HTMLIFrameElement>(null);// Mirrors the host's light/dark theme, like FreeformCanvas — sent over the@@ -122,6 +134,9 @@ export function BuiltCanvas({onRendered,onNavigate,theme,+ onTextSelection,+ onCommentActivate,+ commentHighlights,});latest.current = {capabilities,@@ -131,6 +146,9 @@ export function BuiltCanvas({onRendered,onNavigate,theme,+ onTextSelection,+ onCommentActivate,+ commentHighlights,};// biome-ignore lint/correctness/useExhaustiveDependencies: a new host document needs a fresh bridge even though the effect reads it only through the iframe.@@ -150,9 +168,27 @@ export function BuiltCanvas({log.warn("Built canvas error", { message });latest.current.onError?.(message, stack);},- onReady: () => latest.current.onReady?.(),+ onReady: () => {+ artifactPortRef.current?.postMessage({+ channel: "posthog-canvas",+ type: "set-comment-highlights",+ highlights: latest.current.commentHighlights,+ });+ latest.current.onReady?.();+ },onRendered: () => latest.current.onRendered?.(),onNavigate: (intent) => latest.current.onNavigate?.(intent),+ onTextSelection: (selection) => {+ if (!selection) {+ latest.current.onTextSelection?.(null);+ return;+ }+ const frame = iframeRef.current?.getBoundingClientRect();+ latest.current.onTextSelection?.(+ translateCanvasTextSelection(selection, frame),+ );+ },+ onCommentActivate: (id) => latest.current.onCommentActivate?.(id),}),hasUserActivation: () => navigator.userActivation?.isActive === true,// Built artifacts run arbitrary published code, so an external open asks@@ -221,6 +257,22 @@ export function BuiltCanvas({});}, [theme]);+ useEffect(() => {+ artifactPortRef.current?.postMessage({+ channel: "posthog-canvas",+ type: "set-comment-highlights",+ highlights: commentHighlights,+ });+ }, [commentHighlights]);++ useEffect(() => {+ if (clearTextSelectionKey === 0) return;+ artifactPortRef.current?.postMessage({+ channel: "posthog-canvas",+ type: "clear-text-selection",+ });+ }, [clearTextSelectionKey]);+return (<iframeref={iframeRef}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasBuildStatus.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasBuildStatus.tsxindex f38301b9e349..819194490a0b 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasBuildStatus.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasBuildStatus.tsx@@ -7,6 +7,7 @@ import {XIcon,} from "@phosphor-icons/react";import {+ type CanvasBuildLifecycle,currentHeadBuildFailure,latestFinishedCanvasBuild,} from "@posthog/core/canvas/canvasBuildSchemas";@@ -20,7 +21,6 @@ import {TooltipTrigger,} from "@posthog/quill";import type { CanvasDiagnostic } from "@posthog/shared";-import { useCanvasBuilds } from "@posthog/ui/features/canvas/hooks/useCanvasBuilds";import { toast } from "@posthog/ui/primitives/toast";import { useMutation, useQueryClient } from "@tanstack/react-query";import { useEffect, useState } from "react";@@ -57,9 +57,11 @@ function topErrors(diagnostics: CanvasDiagnostic[]): string[] {// diagnostics, mirroring the runtime-error self-repair affordance.export function CanvasBuildStatus({dashboardId,+ lifecycle,onAskAgentToFix,}: {dashboardId: string;+ lifecycle: CanvasBuildLifecycle | undefined;onAskAgentToFix?: (prompt: string) => void;}) {const trpc = useHostTRPC();@@ -76,8 +78,6 @@ export function CanvasBuildStatus({}),}),);- const { lifecycle } = useCanvasBuilds(dashboardId);-const active = lifecycle?.builds.find((build) =>build.buildStatus === "queued" || build.buildStatus === "building",diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsxindex d64bf9d90c82..5cd3b6da81fa 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFrameHost.tsx@@ -58,6 +58,10 @@ export function CanvasFrameHost() {onError={slot.inputs.onError}onRendered={slot.inputs.onRendered}onNavigate={slot.inputs.onNavigate}+ onTextSelection={slot.inputs.onTextSelection}+ onCommentActivate={slot.inputs.onCommentActivate}+ commentHighlights={slot.inputs.commentHighlights}+ clearTextSelectionKey={slot.inputs.clearTextSelectionKey}/></ErrorBoundary></div>diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFramePlaceholder.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFramePlaceholder.tsxindex b3c1105f8276..91bbe3508ea9 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFramePlaceholder.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasFramePlaceholder.tsx@@ -1,6 +1,8 @@import type {CanvasAnalyticsConfig,+ CanvasCommentHighlight,CanvasNavIntent,+ CanvasTextSelection,} from "@posthog/core/canvas/freeformSchemas";import { useLayoutEffect, useMemo, useRef } from "react";import { useCanvasFrameStore } from "./canvasFrameStore";@@ -18,6 +20,10 @@ export function CanvasFramePlaceholder({onError,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,+ commentHighlights,+ clearTextSelectionKey,}: {dashboardId: string;code: string;@@ -26,6 +32,10 @@ export function CanvasFramePlaceholder({onError?: (message: string, stack?: string) => void;onRendered?: () => void;onNavigate?: (intent: CanvasNavIntent) => void;+ onTextSelection?: (selection: CanvasTextSelection | null) => void;+ onCommentActivate?: (id: string) => void;+ commentHighlights?: CanvasCommentHighlight[];+ clearTextSelectionKey?: number;}) {const ref = useRef<HTMLDivElement>(null);@@ -42,8 +52,23 @@ export function CanvasFramePlaceholder({onError,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,+ commentHighlights,+ clearTextSelectionKey,}),- [code, analytics, onDataRequest, onError, onRendered, onNavigate],+ [+ code,+ analytics,+ onDataRequest,+ onError,+ onRendered,+ onNavigate,+ onTextSelection,+ onCommentActivate,+ commentHighlights,+ clearTextSelectionKey,+ ],);// Layout effect (not passive) and declared first, so the slot exists before thediff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsxnew file mode 100644index 000000000000..3c22b24ca81f--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.test.tsx@@ -0,0 +1,90 @@+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { CanvasSelectionCommentAction } from "./CanvasSelectionCommentAction";++const { mutateAsync } = vi.hoisted(() => ({ mutateAsync: vi.fn() }));++vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({+ useOrgMembers: () => ({ members: [] }),+}));+vi.mock("@posthog/ui/features/sessions/components/useComments", () => ({+ useCreateComment: () => ({ mutateAsync }),+}));+vi.mock(+ "@posthog/ui/features/code-editor/components/SelectionCommentOverlay",+ () => ({+ SelectionCommentOverlay: ({+ open,+ onSubmit,+ }: {+ open: boolean;+ onSubmit: (+ start: number,+ end: number,+ content: string,+ mentions: number[],+ ) => void;+ }) =>+ open ? (+ <button+ type="button"+ onClick={() => onSubmit(0, 0, "Please revise this", [4])}+ >+ Submit selection comment+ </button>+ ) : null,+ }),+);++describe("CanvasSelectionCommentAction", () => {+ beforeEach(() => {+ mutateAsync.mockReset();+ useCanvasChatPanelStore.setState({ collapsed: true, tab: "chat" });+ });++ it("creates the text-anchored comment and opens the comments tab", async () => {+ mutateAsync.mockResolvedValue({ id: "comment-1" });+ render(+ <CanvasSelectionCommentAction+ selection={{+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ rect: { top: 10, right: 80, bottom: 30, left: 20 },+ }}+ taskId="task-1"+ dashboardId="canvas-1"+ canvasName="Launch canvas"+ versionId="version-2"+ onDismiss={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText("Submit selection comment"));++ expect(mutateAsync).toHaveBeenCalledWith({+ content: "Please revise this",+ context: {+ anchor: {+ kind: "text",+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ },+ canvasVersionId: "version-2",+ },+ mentions: [4],+ });+ await waitFor(() => {+ expect(useCanvasChatPanelStore.getState()).toMatchObject({+ collapsed: false,+ tab: "comments",+ });+ });+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsxnew file mode 100644index 000000000000..2b238bcebc33--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSelectionCommentAction.tsx@@ -0,0 +1,82 @@+import type { CanvasTextSelection } from "@posthog/core/canvas/freeformSchemas";+import type { TextCommentAnchor } from "@posthog/core/comments/anchors";+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";+import { useCreateComment } from "@posthog/ui/features/sessions/components/useComments";++export function CanvasSelectionCommentAction({+ selection,+ taskId,+ dashboardId,+ canvasName,+ versionId,+ onDismiss,+}: {+ selection: CanvasTextSelection | null;+ taskId: string | null;+ dashboardId: string;+ canvasName: string;+ versionId: string | null;+ onDismiss: () => void;+}) {+ const { members } = useOrgMembers();+ const openComments = useCanvasChatPanelStore((state) => state.openComments);+ const target = { scope: "desktop_canvas" as const, itemId: dashboardId };+ const createComment = useCreateComment(target, taskId ?? undefined);++ const anchor: TextCommentAnchor | null = selection+ ? {+ kind: "text",+ quote: selection.quote,+ prefix: selection.prefix,+ suffix: selection.suffix,+ start: selection.start,+ end: selection.end,+ }+ : null;++ return (+ <SelectionCommentOverlay+ selection={+ selection+ ? {+ text: selection.quote,+ fromLine: selection.start + 1,+ toLine: selection.end + 1,+ anchor: {+ top: selection.rect.bottom,+ left: Math.max(+ 8,+ Math.min(selection.rect.right, window.innerWidth - 440),+ ),+ },+ }+ : null+ }+ open={!!selection && !!taskId}+ filePath={canvasName}+ actionLabel="Add comment"+ placeholder="Add a comment about this selection"+ showActionText+ members={members}+ onDismiss={onDismiss}+ onSubmit={async (_start, _end, content, mentions) => {+ if (!anchor || !taskId) return;+ const comment = await createComment.mutateAsync({+ content,+ context: {+ anchor,+ ...(versionId ? { canvasVersionId: versionId } : {}),+ },+ mentions,+ });+ openComments();+ useCommentNavigationStore+ .getState()+ .requestCommentFocus(taskId, target, comment.id);+ }}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsxnew file mode 100644index 000000000000..410ffa051265--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx@@ -0,0 +1,63 @@+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { CanvasSidePanel } from "./CanvasSidePanel";++vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: () => ({ data: { id: "task-1", title: "Build canvas" } }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useThreadConversation", () => ({+ useThreadConversation: () => ({ timeline: [{ kind: "message" }] }),+}));+vi.mock("@posthog/ui/features/canvas/components/TaskCommentsList", () => ({+ TaskCommentsList: ({+ task,+ onlySource,+ }: {+ task: { id: string };+ onlySource: { target: { itemId: string } };+ }) => (+ <div data-testid="task-comments">+ {task.id}:{onlySource.target.itemId}+ </div>+ ),+}));+vi.mock("@posthog/ui/features/sessions/components/EmbeddedSessionView", () => ({+ EmbeddedSessionView: () => <div data-testid="task-chat" />,+}));+vi.mock("@posthog/ui/features/canvas/freeform/FreeformGenerateBar", () => ({+ FreeformGenerateBar: () => null,+}));+vi.mock("@posthog/ui/features/canvas/freeform/ContextEditor", () => ({+ CanvasContextEditor: () => null,+}));++describe("CanvasSidePanel", () => {+ beforeEach(() => {+ useCanvasChatPanelStore.setState({ tab: "chat", collapsed: false });+ });++ it("switches from canvas chat to comments for this canvas", () => {+ render(+ <CanvasSidePanel+ effectiveTaskId="task-1"+ commentTaskId="task-1"+ onMinimize={vi.fn()}+ dashboardId="canvas-1"+ channelId="channel-1"+ channelName="General"+ name="Launch canvas"+ displayedVersionId="version-2"+ commentVersionLabel={(versionId) => versionId}+ onCommentOpen={vi.fn()}+ />,+ );++ expect(screen.getByTestId("task-chat")).toBeInTheDocument();+ fireEvent.click(screen.getByText("Comments"));+ expect(screen.getByTestId("task-comments")).toHaveTextContent(+ "task-1:canvas-1",+ );+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsxindex 2e5b98af51aa..6194c5147c61 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx@@ -1,18 +1,25 @@+import { SidebarSimpleIcon, SpinnerGapIcon } from "@phosphor-icons/react";import {- ChatCircleIcon,- PencilSimpleIcon,- SidebarSimpleIcon,- SpinnerGapIcon,-} from "@phosphor-icons/react";-import { Button } from "@posthog/quill";+ Button,+ Tabs,+ TabsList,+ TabsTrigger,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@posthog/quill";+import type { Task } from "@posthog/shared/domain-types";+import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";import { CanvasContextEditor } from "@posthog/ui/features/canvas/freeform/ContextEditor";import { FreeformGenerateBar } from "@posthog/ui/features/canvas/freeform/FreeformGenerateBar";+import { useThreadConversation } from "@posthog/ui/features/canvas/hooks/useThreadConversation";+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import type { EditorHandle } from "@posthog/ui/features/message-editor/types";import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";-import { Flex, Text, Tooltip } from "@radix-ui/themes";import { useQuery } from "@tanstack/react-query";-import type { Ref } from "react";+import { type Ref, useEffect, useRef } from "react";// The canvas's right-hand dock. While a generation/edit run is in flight it// shows that run's live chat (steering/queue included); otherwise it shows the@@ -20,22 +27,30 @@ import type { Ref } from "react";// collapses the panel to a thin rail (handled by the parent).export function CanvasSidePanel({effectiveTaskId,+ commentTaskId,onMinimize,dashboardId,channelId,channelName,name,+ displayedVersionId,+ commentVersionLabel,+ onCommentOpen,templateId,isEdit,editorRef,onStarted,}: {effectiveTaskId: string | null;+ commentTaskId: string | null;onMinimize: () => void;dashboardId: string;channelId: string;channelName: string;name: string;+ displayedVersionId: string | null;+ commentVersionLabel: (versionId: string) => string | null;+ onCommentOpen: (versionId: string | null) => void;templateId?: string;/** Whether the canvas already has published source (a follow-up edit rather* than a first build) — the agent re-reads the live source itself. */@@ -44,42 +59,68 @@ export function CanvasSidePanel({editorRef?: Ref<EditorHandle>;onStarted?: (taskId: string) => void;}) {- const isChat = !!effectiveTaskId;+ const tab = useCanvasChatPanelStore((state) => state.tab);+ const setTab = useCanvasChatPanelStore((state) => state.setTab);+ const previousTaskId = useRef(effectiveTaskId);++ useEffect(() => {+ if (effectiveTaskId && effectiveTaskId !== previousTaskId.current) {+ setTab("chat");+ }+ previousTaskId.current = effectiveTaskId;+ }, [effectiveTaskId, setTab]);return (- <Flex direction="column" className="h-full min-w-0 bg-gray-1">- <Flex- align="center"- justify="between"- className="h-10 shrink-0 items-center border-b bg-chrome px-3"- >- <Flex align="center" gap="2" className="min-w-0">- {isChat ? (- <ChatCircleIcon size={15} className="shrink-0 text-gray-10" />- ) : (- <PencilSimpleIcon size={15} className="shrink-0 text-gray-10" />- )}- <Text size="2" weight="medium" className="truncate text-gray-12">- {isChat ? "Chat" : "Edit canvas"}- </Text>- </Flex>- <Tooltip content="Minimize panel">- <Button- size="icon"- variant="default"- aria-label="Minimize panel"- onClick={onMinimize}- >- <SidebarSimpleIcon size={16} />- </Button>+ <div className="flex h-full min-w-0 flex-col bg-gray-1">+ <div className="flex h-10 shrink-0 items-center justify-between border-b bg-chrome 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>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon"+ variant="default"+ aria-label="Minimize panel"+ onClick={onMinimize}+ >+ <SidebarSimpleIcon size={16} />+ </Button>+ }+ />+ <TooltipContent>Minimize panel</TooltipContent></Tooltip>- </Flex>+ </div><div className="min-h-0 flex-1">- {effectiveTaskId ? (+ {tab === "comments" && commentTaskId ? (+ <CanvasCommentsLoader+ taskId={commentTaskId}+ dashboardId={dashboardId}+ name={name}+ displayedVersionId={displayedVersionId}+ commentVersionLabel={commentVersionLabel}+ onCommentOpen={onCommentOpen}+ />+ ) : effectiveTaskId ? (<CanvasChatLoader taskId={effectiveTaskId} />) : (- <Flex direction="column" gap="3" className="h-full min-h-0 p-3">+ <div className="flex h-full min-h-0 flex-col gap-3 p-3"><FreeformGenerateBarref={editorRef}sessionId={`canvas:${dashboardId}`}@@ -94,18 +135,18 @@ export function CanvasSidePanel({{/* The author context (markdown): background the agent reads onevery generation. Edits against the saved record, autosavingon blur. */}- <Flex direction="column" gap="1" className="min-h-0 flex-1">- <Text size="1" className="shrink-0 text-gray-10">- Context — notes the agent reads on every generation+ <div className="flex min-h-0 flex-1 flex-col gap-1">+ <Text size="xs" variant="muted" className="shrink-0">+ Context: notes the agent reads on every generation</Text><div className="min-h-0 flex-1 overflow-hidden rounded-md border"><CanvasContextEditor dashboardId={dashboardId} /></div>- </Flex>- </Flex>+ </div>+ </div>)}</div>- </Flex>+ </div>);}@@ -116,11 +157,83 @@ function CanvasChatLoader({ taskId }: { taskId: string }) {if (!task) {return (- <Flex align="center" justify="center" className="h-full">+ <div className="flex h-full items-center justify-center"><SpinnerGapIcon size={18} className="animate-spin text-gray-9" />- </Flex>+ </div>);}return <EmbeddedSessionView task={task} />;}++function CanvasCommentsLoader({+ taskId,+ dashboardId,+ name,+ displayedVersionId,+ commentVersionLabel,+ onCommentOpen,+}: {+ taskId: string;+ dashboardId: string;+ name: string;+ displayedVersionId: string | null;+ commentVersionLabel: (versionId: string) => string | null;+ onCommentOpen: (versionId: string | null) => void;+}) {+ const { data: task } = useQuery(taskDetailQuery(taskId));++ if (!task) {+ return (+ <div className="flex h-full items-center justify-center">+ <SpinnerGapIcon size={18} className="animate-spin text-gray-9" />+ </div>+ );+ }++ return (+ <CanvasTaskComments+ task={task}+ dashboardId={dashboardId}+ name={name}+ displayedVersionId={displayedVersionId}+ commentVersionLabel={commentVersionLabel}+ onCommentOpen={onCommentOpen}+ />+ );+}++function CanvasTaskComments({+ task,+ dashboardId,+ name,+ displayedVersionId,+ commentVersionLabel,+ onCommentOpen,+}: {+ task: Task;+ dashboardId: string;+ name: string;+ displayedVersionId: string | null;+ commentVersionLabel: (versionId: string) => string | null;+ onCommentOpen: (versionId: string | null) => void;+}) {+ const { timeline } = useThreadConversation(task, {+ surface: "activity_panel",+ });+ return (+ <TaskCommentsList+ task={task}+ timeline={timeline}+ onlySource={{+ kind: "canvas",+ name,+ target: { scope: "desktop_canvas", itemId: dashboardId },+ url: null,+ }}+ canvasVersionId={displayedVersionId}+ commentVersionLabel={commentVersionLabel}+ onCanvasCommentOpen={onCommentOpen}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsxindex e6bb12afe495..2ee163da4e42 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.test.tsx@@ -1,5 +1,5 @@import { openExternalUrl } from "@posthog/ui/shell/openExternal";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { FreeformCanvas } from "./FreeformCanvas";@@ -37,6 +37,165 @@ describe("FreeformCanvas", () => {);});+ it("forwards a validated text selection in viewport coordinates", () => {+ const onTextSelection = vi.fn();+ render(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ onTextSelection={onTextSelection}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;+ vi.spyOn(iframe, "getBoundingClientRect").mockReturnValue({+ top: 100,+ left: 200,+ right: 800,+ bottom: 700,+ width: 600,+ height: 600,+ x: 200,+ y: 100,+ toJSON: () => ({}),+ });++ window.dispatchEvent(+ new MessageEvent("message", {+ source: iframe.contentWindow,+ data: {+ channel: "posthog-canvas",+ type: "text-selection",+ selection: {+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ rect: { top: 10, right: 80, bottom: 30, left: 20 },+ },+ },+ }),+ );++ expect(onTextSelection).toHaveBeenCalledWith(+ expect.objectContaining({+ quote: "selected text",+ rect: { top: 110, right: 280, bottom: 130, left: 220 },+ }),+ );++ window.dispatchEvent(+ new MessageEvent("message", {+ source: iframe.contentWindow,+ data: {+ channel: "posthog-canvas",+ type: "text-selection-cleared",+ },+ }),+ );+ expect(onTextSelection).toHaveBeenLastCalledWith(null);+ });++ it("forwards persisted comment highlights into the running sandbox", () => {+ const highlight = {+ id: "comment-1",+ active: false,+ anchor: {+ quote: "selected text",+ prefix: "before ",+ suffix: " after",+ start: 7,+ end: 20,+ },+ };+ const { rerender } = render(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ commentHighlights={[]}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;+ const postMessage = vi.spyOn(iframe.contentWindow as Window, "postMessage");+ fireEvent.load(iframe);+ postMessage.mockClear();++ rerender(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ commentHighlights={[highlight]}+ />,+ );++ expect(postMessage).toHaveBeenCalledWith(+ {+ channel: "posthog-canvas",+ type: "set-comment-highlights",+ highlights: [highlight],+ },+ "*",+ );+ });++ it("clears native iframe selection when the host dismisses it", () => {+ const { rerender } = render(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ clearTextSelectionKey={0}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;+ const postMessage = vi.spyOn(iframe.contentWindow as Window, "postMessage");+ fireEvent.load(iframe);+ postMessage.mockClear();++ rerender(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ clearTextSelectionKey={1}+ />,+ );++ expect(postMessage).toHaveBeenCalledWith(+ { channel: "posthog-canvas", type: "clear-text-selection" },+ "*",+ );+ });++ it("opens a comment selected inside the canvas", () => {+ const onCommentActivate = vi.fn();+ render(+ <FreeformCanvas+ code="export default function Canvas() { return null }"+ mode="edit"+ onDataRequest={vi.fn()}+ onCommentActivate={onCommentActivate}+ />,+ );+ const iframe = screen.getByTitle("Canvas") as HTMLIFrameElement;++ window.dispatchEvent(+ new MessageEvent("message", {+ source: iframe.contentWindow,+ data: {+ channel: "posthog-canvas",+ type: "comment-activate",+ id: "comment-1",+ },+ }),+ );++ expect(onCommentActivate).toHaveBeenCalledWith("comment-1");+ });+describe("open-external", () => {let userActivationIsActive = true;diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsxindex fa4248f15211..ac7f8607ff2d 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvas.tsx@@ -1,6 +1,8 @@import {type CanvasAnalyticsConfig,+ type CanvasCommentHighlight,type CanvasNavIntent,+ type CanvasTextSelection,canvasToHostMessageSchema,} from "@posthog/core/canvas/freeformSchemas";import { logger } from "@posthog/ui/shell/logger";@@ -14,9 +16,11 @@ import {useRef,} from "react";import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";+import { translateCanvasTextSelection } from "./canvasSelection";import { buildSandboxDocument, type SandboxMode } from "./sandboxRuntime";const log = logger.scope("freeform-canvas");+const EMPTY_COMMENT_HIGHLIGHTS: CanvasCommentHighlight[] = [];export interface FreeformCanvasProps {/** The single-file React source to render. */@@ -39,6 +43,10 @@ export interface FreeformCanvasProps {* just forwards it — the caller maps it to actual routing.*/onNavigate?: (intent: CanvasNavIntent) => void;+ onTextSelection?: (selection: CanvasTextSelection | null) => void;+ onCommentActivate?: (id: string) => void;+ commentHighlights?: CanvasCommentHighlight[];+ clearTextSelectionKey?: number;/*** Bootstrap config for in-iframe posthog-js (analytics + session replay).* Absent = no capture/replay. Only the PUBLIC key is here; the private token@@ -57,6 +65,10 @@ export function FreeformCanvas({onError,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,+ commentHighlights = EMPTY_COMMENT_HIGHLIGHTS,+ clearTextSelectionKey = 0,analytics,}: FreeformCanvasProps) {const iframeRef = useRef<HTMLIFrameElement>(null);@@ -83,20 +95,26 @@ export function FreeformCanvas({onError,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,code,mode,analytics,theme,+ commentHighlights,});latest.current = {onDataRequest,onError,onRendered,onNavigate,+ onTextSelection,+ onCommentActivate,code,mode,analytics,theme,+ commentHighlights,};const postInit = useCallback(() => {@@ -109,6 +127,7 @@ export function FreeformCanvas({mode: p.mode,analytics: p.analytics,theme: p.theme,+ highlights: p.commentHighlights,},"*",);@@ -145,6 +164,17 @@ export function FreeformCanvas({},onRendered: () => latest.current.onRendered?.(),onNavigate: (intent) => latest.current.onNavigate?.(intent),+ onTextSelection: (selection) => {+ if (!selection) {+ latest.current.onTextSelection?.(null);+ return;+ }+ const frame = iframeRef.current?.getBoundingClientRect();+ latest.current.onTextSelection?.(+ translateCanvasTextSelection(selection, frame),+ );+ },+ onCommentActivate: (id) => latest.current.onCommentActivate?.(id),}),hasUserActivation: () => navigator.userActivation?.isActive === true,openExternal: openExternalUrl,@@ -192,11 +222,32 @@ export function FreeformCanvas({mode,analytics,theme: latest.current.theme,+ highlights: latest.current.commentHighlights,},"*",);}, [code, mode, analytics]);+ useEffect(() => {+ if (!readyRef.current) return;+ iframeRef.current?.contentWindow?.postMessage(+ {+ channel: "posthog-canvas",+ type: "set-comment-highlights",+ highlights: commentHighlights,+ },+ "*",+ );+ }, [commentHighlights]);++ useEffect(() => {+ if (!readyRef.current || clearTextSelectionKey === 0) return;+ iframeRef.current?.contentWindow?.postMessage(+ { channel: "posthog-canvas", type: "clear-text-selection" },+ "*",+ );+ }, [clearTextSelectionKey]);+// Live theme change: re-theme the running canvas in place (no remount), so a// host theme toggle — or an OS light/dark flip under "system" — preserves all// canvas state (filters, forms, scroll). Skipped until the iframe is ready;diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex 427638f9f1b2..25fb443ee471 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -10,10 +10,16 @@ import {import {currentHeadBuildFailure,hasActiveCanvasBuild,+ historicalCanvasBuild,latestFinishedCanvasBuild,publishedCanvasBuild,} from "@posthog/core/canvas/canvasBuildSchemas";-import type { CanvasAnalyticsConfig } from "@posthog/core/canvas/freeformSchemas";+import {+ type CanvasAnalyticsConfig,+ type CanvasCommentHighlight,+ type CanvasTextSelection,+ limitCanvasCommentHighlights,+} from "@posthog/core/canvas/freeformSchemas";import { useHostTRPC } from "@posthog/host-router/react";import {Button,@@ -44,6 +50,12 @@ import {useFreeformThread,} from "@posthog/ui/features/canvas/stores/freeformChatStore";import type { EditorHandle } from "@posthog/ui/features/message-editor/types";+import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";+import {+ buildCommentThreads,+ readCommentContext,+} from "@posthog/ui/features/sessions/components/commentViewTypes";+import { useCommentsQuery } from "@posthog/ui/features/sessions/components/useComments";import { useSessionForTask } from "@posthog/ui/features/sessions/useSession";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";@@ -65,7 +77,9 @@ import { CanvasBuildStatus } from "./CanvasBuildStatus";import { CanvasFramePlaceholder } from "./CanvasFramePlaceholder";import { CanvasGenerateHero } from "./CanvasGenerateHero";import { CanvasPermissionDialog } from "./CanvasPermissionDialog";+import { CanvasSelectionCommentAction } from "./CanvasSelectionCommentAction";import { CanvasSidePanel } from "./CanvasSidePanel";+import { canvasCommentTaskId } from "./canvasCommentTask";import {canvasVersionNavigation,shouldClearCanvasBrowse,@@ -75,7 +89,7 @@ import { useCanvasNavigation } from "./useCanvasNavigation";import { usePinnedArtifact } from "./usePinnedArtifact";// A freeform (React-in-iframe) canvas. The rendered output is, in priority-// order: a historical version being browsed (edit mode), the published build's+// order: a historical version being browsed, the published build's// artifact, or — before the first build lands — the head source client-rendered// through the warm-frame pool when it's a single-file project. Edit mode adds// the chat panel, version navigation (browse/revert over the server-side@@ -98,7 +112,15 @@ export function FreeformCanvasView({// local bridge so the composer floats to the side immediately on submit,// before the canvas record's polled generationTaskId catches up.const [startedTaskId, setStartedTaskId] = useState<string | null>(null);+ const [textSelection, setTextSelection] =+ useState<CanvasTextSelection | null>(null);+ const [clearTextSelectionKey, setClearTextSelectionKey] = useState(0);+ const dismissTextSelection = useCallback(() => {+ setTextSelection(null);+ setClearTextSelectionKey((key) => key + 1);+ }, []);const collapsed = useCanvasChatPanelStore((s) => s.collapsed);+ const panelTab = useCanvasChatPanelStore((s) => s.tab);const setCollapsed = useCanvasChatPanelStore((s) => s.setCollapsed);const panelWidth = useCanvasChatPanelStore((s) => s.width);const setPanelWidth = useCanvasChatPanelStore((s) => s.setWidth);@@ -124,15 +146,9 @@ export function FreeformCanvasView({const genTaskId = dashboard?.generationTaskId ?? null;const channelId = dashboard?.channelId ?? "";- // Reconcile the optimistic bridge against the polled record during render- // (not via an effect, which would flash a stale frame): once the record- // reports its own generationTaskId, drop the bridge so the panel reverts to- // the composer when the run later clears the association.- const [prevGenTaskId, setPrevGenTaskId] = useState(genTaskId);- if (genTaskId !== prevGenTaskId) {- setPrevGenTaskId(genTaskId);+ useEffect(() => {if (genTaskId) setStartedTaskId(null);- }+ }, [genTaskId]);// The run whose chat the panel shows: the record's id, or the optimistic// bridge until the poll catches up.@@ -203,17 +219,24 @@ export function FreeformCanvasView({// Build lifecycle, polled while a build is active or a generation is in// flight (the agent's publish queues the build server-side — without the// `generating` signal the client would never observe it start).+ const browsing = !!browseVersionId;const {lifecycle,isLoading: buildsLoading,dataUpdatedAt: buildsUpdatedAt,- } = useCanvasBuilds(dashboardId, { generating: isSyncing });+ } = useCanvasBuilds(dashboardId, {+ generating: isSyncing,+ versionId: browsing ? (browseVersionId ?? undefined) : undefined,+ });const publishedBuild = lifecycle ? publishedCanvasBuild(lifecycle) : null;+ const historicalBuild =+ lifecycle && browseVersionId+ ? historicalCanvasBuild(lifecycle, browseVersionId)+ : null;// The published build's artifact, pinned to one signed URL per build (so the// 2s builds poll can't reload the iframe), with expired-URL recovery via the// refresh-key remount. The whole lifecycle machine lives in the hook.- const browsing = interactive && !!browseVersionId;const {artifact: pinnedArtifact,refreshKey: artifactRefreshKey,@@ -225,11 +248,22 @@ export function FreeformCanvasView({mintedAt: buildsUpdatedAt,suspended: browsing,});+ const {+ artifact: pinnedHistoricalArtifact,+ refreshKey: historicalArtifactRefreshKey,+ onReady: onHistoricalArtifactReady,+ } = usePinnedArtifact({+ dashboardId,+ publishedBuild: historicalBuild,+ lifecycle,+ mintedAt: buildsUpdatedAt,+ suspended: !browsing,+ });// Server-side version history (newest first), for the undo/redo navigation.- const { versions, isLoading: versionsLoading } = useCanvasVersions(- interactive ? dashboardId : undefined,- );+ const { versions, isLoading: versionsLoading } =+ useCanvasVersions(dashboardId);+ const commentTaskId = canvasCommentTaskId(genTaskId, versions);// Clear a browse that points at a version the history no longer contains// (e.g. it was pruned server-side while this canvas was open).@@ -291,6 +325,66 @@ export function FreeformCanvasView({// Migrated single-file canvases have no version pointer, but the source// endpoint exposes their stored code as a synthetic project.const headVersionId = dashboard?.currentVersionId ?? null;+ const displayedVersionId = browsing+ ? browseVersionId+ : (publishedBuild?.sourceVersionId ?? headVersionId);+ const commentTarget = useMemo(+ () => ({ scope: "desktop_canvas" as const, itemId: dashboardId }),+ [dashboardId],+ );+ const commentsQuery = useCommentsQuery(+ commentTaskId ? commentTarget : null,+ commentTaskId ?? "",+ );+ const focusedCommentId = useCommentNavigationStore(+ (state) => state.focusByTask[commentTaskId ?? ""]?.threadId ?? null,+ );+ const activateComment = useCallback(+ (id: string) => {+ if (!commentTaskId) return;+ useCanvasChatPanelStore.getState().openComments();+ useCommentNavigationStore+ .getState()+ .requestCommentFocus(commentTaskId, commentTarget, id);+ },+ [commentTaskId, commentTarget],+ );+ const commentHighlights = useMemo<CanvasCommentHighlight[]>(() => {+ const threads = buildCommentThreads(commentsQuery.data ?? []);+ return limitCanvasCommentHighlights(+ threads.flatMap((thread) => {+ if (thread.resolved) return [];+ const context = readCommentContext(thread.root);+ if (+ context?.anchor.kind !== "text" ||+ (context.canvasVersionId &&+ context.canvasVersionId !== displayedVersionId)+ ) {+ return [];+ }+ return [+ {+ id: thread.root.id,+ active: thread.root.id === focusedCommentId,+ anchor: context.anchor,+ },+ ];+ }),+ );+ }, [commentsQuery.data, displayedVersionId, focusedCommentId]);+ const selectionVersionRef = useRef(displayedVersionId);+ useEffect(() => {+ if (selectionVersionRef.current === displayedVersionId) return;+ selectionVersionRef.current = displayedVersionId;+ dismissTextSelection();+ }, [displayedVersionId, dismissTextSelection]);+ const commentVersionLabel = useCallback(+ (versionId: string) => {+ const index = versions.findIndex((version) => version.id === versionId);+ return index === -1 ? null : `V${versions.length - index}`;+ },+ [versions],+ );const wantHeadSource =!!dashboard && lifecycle !== undefined && !publishedBuild;const { source: headSource, isLoading: headSourceLoading } = useCanvasSource({@@ -299,14 +393,6 @@ export function FreeformCanvasView({});const headCode = headSource?.project.files[CANVAS_COMPONENT_PATH];- // The browsed version's source (edit mode only).- const { source: browseSource, isLoading: browseSourceLoading } =- useCanvasSource({- id: browsing ? dashboardId : undefined,- versionId: browseVersionId ?? undefined,- });- const browseCode = browseSource?.project.files[CANVAS_COMPONENT_PATH];-const trpcCapture = trpc.canvasData.captureConfig.queryOptions(undefined, {staleTime: 5 * 60_000,});@@ -345,6 +431,10 @@ export function FreeformCanvasView({onArtifactReady();setRuntimeError(threadId, null);}, [threadId, setRuntimeError, onArtifactReady]);+ const clearHistoricalArtifactError = useCallback(() => {+ onHistoricalArtifactReady();+ setRuntimeError(threadId, null);+ }, [threadId, setRuntimeError, onHistoricalArtifactReady]);// Routes the canvas's allowlisted nav intents within this channel.const onNavigate = useCanvasNavigation(channelId);@@ -393,13 +483,9 @@ export function FreeformCanvasView({// always starts open, while a minimize still sticks for this visit.const [generatingPanelDismissed, setGeneratingPanelDismissed] =useState(false);- // A dismissal is per-run: a later run on this same mounted canvas opens the- // panel again. Reconciled during render, like the genTaskId bridge above.- const [dismissedForTaskId, setDismissedForTaskId] = useState(effectiveTaskId);- if (effectiveTaskId !== dismissedForTaskId) {- setDismissedForTaskId(effectiveTaskId);+ useEffect(() => {if (effectiveTaskId) setGeneratingPanelDismissed(false);- }+ }, [effectiveTaskId]);const generatingPanelOpen =isGenerating &&!!effectiveTaskId &&@@ -410,6 +496,8 @@ export function FreeformCanvasView({// or while the generating default holds (any mode).const showPanel =(interactive && (hasContent || !!effectiveTaskId)) || generatingPanelOpen;+ const showCommentsPanel =+ panelTab === "comments" && !collapsed && !!commentTaskId;// Build failures/progress surface in view mode too — the toolbar renders// there only while it has something to say.const hasBuildSignal =@@ -485,6 +573,7 @@ export function FreeformCanvasView({<Flex align="center" gap="2"><CanvasBuildStatusdashboardId={dashboardId}+ lifecycle={lifecycle}onAskAgentToFix={interactive ? prefillComposer : undefined}/>{interactive &&@@ -555,11 +644,7 @@ export function FreeformCanvasView({}/>{browsing ? (- browseSourceLoading ? (- <ScrollArea className="h-full">- <LoadingState />- </ScrollArea>- ) : browseCode ? (+ pinnedHistoricalArtifact ? (<Flex direction="column" className="h-full"><Flexalign="center"@@ -568,32 +653,49 @@ export function FreeformCanvasView({><Flex align="center" gap="1" className="text-accent-11"><ClockCounterClockwiseIcon size={14} />- <Text size="1">- Viewing version — revert to make it live- </Text>+ <Text size="1">Viewing a previous version</Text>+ </Flex>+ <Flex align="center" gap="2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setBrowseVersion(threadId, null)}+ >+ Back to latest+ </Button>+ {interactive && (+ <Button+ size="sm"+ variant="primary"+ disabled={isReverting}+ onClick={() => void onRevert()}+ >+ {isReverting ? "Reverting…" : "Revert"}+ </Button>+ )}</Flex>- <Button- size="sm"- variant="primary"- disabled={isReverting}- onClick={() => void onRevert()}- >- {isReverting ? "Reverting…" : "Revert"}- </Button></Flex><Box className="min-h-0 flex-1">- {/* Reuses the canvas's warm frame with the browsed code. */}- <CanvasFramePlaceholder- dashboardId={dashboardId}- code={browseCode}- analytics={analytics}+ <BuiltCanvas+ key={`${pinnedHistoricalArtifact.buildId}:${historicalArtifactRefreshKey}`}+ artifactUrl={pinnedHistoricalArtifact.url}+ capabilities={historicalBuild?.manifest?.capabilities}onDataRequest={onDataRequest}onError={onError}- onRendered={onRendered}+ onReady={clearHistoricalArtifactError}+ onRendered={clearHistoricalArtifactError}onNavigate={onNavigate}+ onTextSelection={setTextSelection}+ onCommentActivate={activateComment}+ commentHighlights={commentHighlights}+ clearTextSelectionKey={clearTextSelectionKey}/></Box></Flex>+ ) : buildsLoading ? (+ <ScrollArea className="h-full">+ <LoadingState />+ </ScrollArea>) : (<ScrollArea className="h-full"><Empty className="h-full border-0">@@ -601,22 +703,27 @@ export function FreeformCanvasView({<EmptyMedia variant="icon"><ClockCounterClockwiseIcon size={24} /></EmptyMedia>- <EmptyTitle>Multi-file version</EmptyTitle>+ <EmptyTitle>Preview unavailable</EmptyTitle><EmptyDescription>- This version has multiple source files, which render only- after a build — revert to make it live and rebuild it.+ {interactive+ ? "This version does not have a saved preview. Revert to rebuild and view it."+ : "This version does not have a saved preview. Go back to the latest version to continue."}</EmptyDescription></EmptyHeader><EmptyContent><Flex align="center" gap="2">- <Button- variant="primary"- size="default"- disabled={isReverting}- onClick={() => void onRevert()}- >- {isReverting ? "Reverting…" : "Revert to this version"}- </Button>+ {interactive && (+ <Button+ variant="primary"+ size="default"+ disabled={isReverting}+ onClick={() => void onRevert()}+ >+ {isReverting+ ? "Reverting…"+ : "Revert to this version"}+ </Button>+ )}<Buttonvariant="outline"size="default"@@ -640,6 +747,10 @@ export function FreeformCanvasView({onReady={onArtifactReady}onRendered={onRendered}onNavigate={onNavigate}+ onTextSelection={setTextSelection}+ onCommentActivate={activateComment}+ commentHighlights={commentHighlights}+ clearTextSelectionKey={clearTextSelectionKey}/></Box>) : headCode ? (@@ -656,6 +767,10 @@ export function FreeformCanvasView({onError={onError}onRendered={onRendered}onNavigate={onNavigate}+ onTextSelection={setTextSelection}+ onCommentActivate={activateComment}+ commentHighlights={commentHighlights}+ clearTextSelectionKey={clearTextSelectionKey}/></Box>) : (@@ -701,7 +816,7 @@ export function FreeformCanvasView({</Box></Flex>- {showPanel && (+ {(showPanel || showCommentsPanel) && (<ResizableSidebaropen={(!collapsed || generatingPanelOpen) && !waitingForHeroExit}width={panelWidth}@@ -715,6 +830,7 @@ export function FreeformCanvasView({heartbeat — stays alive and chat scroll survives a minimize. */}<CanvasSidePaneleffectiveTaskId={effectiveTaskId}+ commentTaskId={commentTaskId}onMinimize={() => {setCollapsed(true);setGeneratingPanelDismissed(true);@@ -723,6 +839,14 @@ export function FreeformCanvasView({channelId={channelId}channelName={channelName}name={dashboard?.name ?? "Canvas"}+ displayedVersionId={displayedVersionId}+ commentVersionLabel={commentVersionLabel}+ onCommentOpen={(versionId) => {+ setBrowseVersion(+ threadId,+ versionId && versionId !== headVersionId ? versionId : null,+ );+ }}templateId={dashboard?.templateId}isEdit={hasSource}editorRef={editorRef}@@ -731,6 +855,15 @@ export function FreeformCanvasView({</ResizableSidebar>)}+ <CanvasSelectionCommentAction+ selection={textSelection}+ taskId={commentTaskId}+ dashboardId={dashboardId}+ canvasName={dashboard?.name ?? "Canvas"}+ versionId={displayedVersionId}+ onDismiss={dismissTextSelection}+ />+{/* The empty-canvas landing: a centered composer with suggestions,overlaying the canvas area. On submit it slides down; once it's gone(onExitComplete) the side panel slides in from the right. */}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasCommentTask.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasCommentTask.tsnew file mode 100644index 000000000000..e70c545ed997--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasCommentTask.ts@@ -0,0 +1,10 @@+export function canvasCommentTaskId(+ generationTaskId: string | null | undefined,+ versions: { taskId?: string | null }[],+): string | null {+ return (+ generationTaskId ??+ versions.find((version) => version.taskId)?.taskId ??+ null+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasFrameStore.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasFrameStore.tsindex 4133fd785c2b..00c3b9a93c54 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasFrameStore.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasFrameStore.ts@@ -1,6 +1,8 @@import type {CanvasAnalyticsConfig,+ CanvasCommentHighlight,CanvasNavIntent,+ CanvasTextSelection,} from "@posthog/core/canvas/freeformSchemas";import { create } from "zustand";@@ -34,6 +36,10 @@ export interface CanvasFrameInputs {onError?: (message: string, stack?: string) => void;onRendered?: () => void;onNavigate?: (intent: CanvasNavIntent) => void;+ onTextSelection?: (selection: CanvasTextSelection | null) => void;+ onCommentActivate?: (id: string) => void;+ commentHighlights?: CanvasCommentHighlight[];+ clearTextSelectionKey?: number;}interface CanvasFrameSlot {diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.tsindex 7455746fa6df..44f896e38490 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts@@ -1,5 +1,6 @@import type {CanvasNavIntent,+ CanvasTextSelection,CanvasToHostMessage,HostToCanvasMessage,} from "@posthog/core/canvas/freeformSchemas";@@ -28,6 +29,8 @@ export interface CanvasHostCallbacks {onReady?: () => void;onRendered?: () => void;onNavigate?: (intent: CanvasNavIntent) => void;+ onTextSelection?: (selection: CanvasTextSelection | null) => void;+ onCommentActivate?: (id: string) => void;}export type ExternalOpenBlockReason =@@ -120,6 +123,15 @@ export function createCanvasHostMessageRouter(// message.nav is already allowlist-validated by the schema parse.options.callbacks().onNavigate?.(message.nav);break;+ case "text-selection":+ options.callbacks().onTextSelection?.(message.selection);+ break;+ case "text-selection-cleared":+ options.callbacks().onTextSelection?.(null);+ break;+ case "comment-activate":+ options.callbacks().onCommentActivate?.(message.id);+ break;case "open-external":// Re-checks the schema's allowlist refine in case it ever drifts.if (!isSafePostHogUrl(message.url)) {diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.tsnew file mode 100644index 000000000000..2935c90d2cb7--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasSelection.ts@@ -0,0 +1,16 @@+import type { CanvasTextSelection } from "@posthog/core/canvas/freeformSchemas";++export function translateCanvasTextSelection(+ selection: CanvasTextSelection,+ frame: Pick<DOMRect, "left" | "top"> | undefined,+): CanvasTextSelection {+ return {+ ...selection,+ rect: {+ top: selection.rect.top + (frame?.top ?? 0),+ right: selection.rect.right + (frame?.left ?? 0),+ bottom: selection.rect.bottom + (frame?.top ?? 0),+ left: selection.rect.left + (frame?.left ?? 0),+ },+ };+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.tsindex 6786ad40979a..f5c69a8054da 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.test.ts@@ -2,9 +2,18 @@ import { describe, expect, it } from "vitest";import {buildSandboxDocument,decodeJsxUnicodeEscapes,+ isInteractiveCanvasCommentTarget,resolveExternalAnchorUrl,} from "./sandboxRuntime";+function clickTarget(html: string, selector: string): Element {+ const container = document.createElement("div");+ container.innerHTML = html;+ const element = container.querySelector(selector);+ if (!element) throw new Error(`selector ${selector} not found`);+ return element;+}+describe("decodeJsxUnicodeEscapes", () => {it.each([{@@ -75,17 +84,29 @@ describe("buildSandboxDocument", () => {expect(html).not.toContain("var(--background, #fff)");expect(html).toContain("html.dark { color-scheme: dark; }");});++ it("installs the persisted comment protocol", () => {+ const html = buildSandboxDocument("edit");+ expect(html).toContain('d.type === "set-comment-highlights"');+ expect(html).toContain('type: "comment-activate"');+ expect(html).toContain('d.type === "clear-text-selection"');+ });++ it.each([+ ["button labels", "<button><span>Export</span></button>", "span", true],+ ["link labels", '<a href="/docs"><span>Docs</span></a>', "span", true],+ ["plain text", "<p><span>Summary</span></p>", "span", false],+ ])(+ "identifies %s before activating a comment highlight",+ (_name, html, selector, expected) => {+ expect(+ isInteractiveCanvasCommentTarget(clickTarget(html, selector)),+ ).toBe(expected);+ },+ );});describe("resolveExternalAnchorUrl", () => {- const clickTarget = (html: string, selector: string): Element => {- const container = document.createElement("div");- container.innerHTML = html;- const el = container.querySelector(selector);- if (!el) throw new Error(`selector ${selector} not found`);- return el;- };-it("resolves a click inside a target=_blank anchor to its absolute URL", () => {const target = clickTarget('<a href="https://posthog.com/docs" target="_blank"><span>docs</span></a>',diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex 8f4f73d27fd2..628faa1e8c5d 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -5,6 +5,7 @@ import {FREEFORM_POSTHOG_JS_URL,FREEFORM_QUILL_CSS_URLS,} from "@posthog/core/canvas/freeformWhitelist";+import { resolveTextCommentAnchor } from "@posthog/core/comments/anchors";// Builds the HTML document loaded into the freeform-canvas sandbox iframe.//@@ -162,6 +163,15 @@ export function resolveExternalAnchorUrl(target: unknown): string | null {}}+export function isInteractiveCanvasCommentTarget(target: unknown): boolean {+ return (+ target instanceof Element &&+ !!target.closest(+ "a,button,input,select,textarea,[role=button],[contenteditable=true],[onclick]",+ )+ );+}+export function buildSandboxDocument(mode: SandboxMode,// The PostHog host, when in-iframe analytics/replay is enabled. Opens CSP for@@ -276,6 +286,137 @@ export function buildSandboxDocument(true,);+ const clearTextSelection = () => post({ type: "text-selection-cleared" });+ let selectionTimer = 0;+ const reportTextSelection = () => {+ clearTimeout(selectionTimer);+ selectionTimer = setTimeout(() => {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {+ clearTextSelection();+ return;+ }+ const range = selection.getRangeAt(0);+ if (!document.body.contains(range.startContainer) || !document.body.contains(range.endContainer)) {+ clearTextSelection();+ return;+ }+ const before = document.createRange();+ before.selectNodeContents(document.body);+ before.setEnd(range.startContainer, range.startOffset);+ const through = document.createRange();+ through.selectNodeContents(document.body);+ through.setEnd(range.endContainer, range.endOffset);+ const text = commentTextIndex().text;+ const start = before.toString().length;+ const end = through.toString().length;+ const quote = text.slice(start, end);+ if (!quote.trim() || quote.length > 10000) {+ clearTextSelection();+ return;+ }+ const rect = range.getBoundingClientRect();+ post({+ type: "text-selection",+ selection: {+ quote,+ prefix: text.slice(Math.max(0, start - 32), start),+ suffix: text.slice(end, end + 32),+ start,+ end,+ rect: { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left },+ },+ });+ }, 80);+ };+ document.addEventListener("selectionchange", reportTextSelection);+ const clearNativeTextSelection = () => {+ window.getSelection()?.removeAllRanges();+ clearTextSelection();+ };++ const commentHighlightStyle = document.createElement("style");+ commentHighlightStyle.textContent = "::highlight(posthog-canvas-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-canvas-comment-active){background:rgba(250,204,21,.48);color:inherit}";+ document.head.appendChild(commentHighlightStyle);+ let currentCommentHighlights = [];+ let commentRanges = [];+ let cachedCommentTextIndex = null;+ const commentTextIndex = () => {+ if (cachedCommentTextIndex) return cachedCommentTextIndex;+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ const entries = [];+ let text = "";+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const start = text.length;+ text += node.data;+ entries.push({ node, start, end: text.length });+ }+ cachedCommentTextIndex = { text, entries };+ return cachedCommentTextIndex;+ };+ const commentRangeAt = (index, start, end) => {+ const find = (offset) => {+ let low = 0, high = index.entries.length - 1, match = null;+ while (low <= high) {+ const middle = (low + high) >> 1;+ const entry = index.entries[middle];+ if (offset < entry.start) high = middle - 1;+ else if (offset > entry.end) low = middle + 1;+ else { match = entry; high = middle - 1; }+ }+ return match;+ };+ const startEntry = find(start), endEntry = find(end);+ if (!startEntry || !endEntry) return null;+ const range = document.createRange();+ range.setStart(startEntry.node, start - startEntry.start);+ range.setEnd(endEntry.node, end - endEntry.start);+ return range;+ };+ const resolveCommentAnchor = ${resolveTextCommentAnchor.toString()};+ const renderCommentHighlights = (items) => {+ currentCommentHighlights = items || [];+ commentRanges = [];+ if (!window.Highlight || !window.CSS || !CSS.highlights) return;+ const normal = new Highlight();+ const active = new Highlight();+ const index = commentTextIndex();+ for (const item of currentCommentHighlights) {+ const resolved = resolveCommentAnchor(index.text, item.anchor);+ const range = resolved && commentRangeAt(index, resolved.start, resolved.end);+ if (range) {+ commentRanges.push({ id: item.id, range });+ (item.active ? active : normal).add(range);+ }+ }+ CSS.highlights.set("posthog-canvas-comment", normal);+ CSS.highlights.set("posthog-canvas-comment-active", active);+ };+ let commentHighlightTimer = 0;+ new MutationObserver(() => {+ cachedCommentTextIndex = null;+ if (!currentCommentHighlights.length || commentHighlightTimer) return;+ commentHighlightTimer = setTimeout(() => {+ commentHighlightTimer = 0;+ renderCommentHighlights(currentCommentHighlights);+ }, 2000);+ }).observe(document.body, { childList: true, characterData: true, subtree: true });+ const isInteractiveCommentTarget = ${isInteractiveCanvasCommentTarget.toString()};+ document.addEventListener("click", (event) => {+ const selection = window.getSelection();+ if ((selection && !selection.isCollapsed) || isInteractiveCommentTarget(event.target)) return;+ for (const item of commentRanges) {+ for (const rect of item.range.getClientRects()) {+ if (event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom) {+ event.preventDefault();+ event.stopPropagation();+ post({ type: "comment-activate", id: item.id });+ return;+ }+ }+ }+ }, true);+// Boot posthog-js with the PUBLIC key the host passed in (never the read// token). Enables session replay so the author/viewer can be watched.const bootAnalytics = async (cfg) => {@@ -407,6 +548,7 @@ export function buildSandboxDocument(// Let layout settle, then report success.requestAnimationFrame(() => {if (seq !== mountSeq) return;+ renderCommentHighlights(currentCommentHighlights);post({ type: "rendered" });});} catch (err) {@@ -421,11 +563,16 @@ export function buildSandboxDocument(if (!d || d.channel !== CHANNEL) return;if (d.type === "init") {applyTheme(d.theme);+ currentCommentHighlights = d.highlights || [];if (d.analytics) void bootAnalytics(d.analytics);void mount(d.code);} else if (d.type === "set-theme") {// Re-theme in place — no mount(), so the app keeps all its state.applyTheme(d.theme);+ } else if (d.type === "set-comment-highlights") {+ renderCommentHighlights(d.highlights);+ } else if (d.type === "clear-text-selection") {+ clearNativeTextSelection();} else if (d.type === "data-response") {const p = pending.get(d.id);if (!p) return;diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.tsindex f1b0b5606f68..d5bc2ac2e3ed 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasBuilds.ts@@ -21,7 +21,7 @@ const GENERATING_POLL_MS = 4_000;*/export function useCanvasBuilds(dashboardId: string | undefined,- options?: { enabled?: boolean; generating?: boolean },+ options?: { enabled?: boolean; generating?: boolean; versionId?: string },): {lifecycle: CanvasBuildLifecycle | undefined;isLoading: boolean;@@ -33,7 +33,7 @@ export function useCanvasBuilds(const generating = options?.generating ?? false;const { data, isLoading, dataUpdatedAt } = useQuery(trpc.dashboards.builds.queryOptions(- { id: dashboardId ?? "" },+ { id: dashboardId ?? "", versionId: options?.versionId },{enabled: !!dashboardId && (options?.enabled ?? true),staleTime: ACTIVE_POLL_MS,