:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(canvas): make a canvas public or private (#112563)
Shy Alterba526fde50c2
diff --git a/products/canvas/frontend/canvasAnalytics.ts b/products/canvas/frontend/canvasAnalytics.tsindex 562120cf393f..1baa6794498b 100644--- a/products/canvas/frontend/canvasAnalytics.ts+++ b/products/canvas/frontend/canvasAnalytics.ts@@ -41,6 +41,8 @@ export type CanvasDashboardActionType =| 'build_pin'| 'build_unpin'| 'fix_request'+ | 'make_public_opened'+ | 'visibility_change'/** Captures a canvas action from the scene or its side panel. Never pass prompt, comment, or source text. */export function captureCanvasAction(@@ -63,6 +65,10 @@ export function captureCanvasAction(method?: 'click' | 'drag'/** edit_conflict_resolve: whether the author kept their edits over the newer version. */keep_local?: boolean+ /** visibility_change: who can see the canvas after the change. */+ visibility?: 'private' | 'public'+ /** visibility_change: whether the change undid the one before. */+ undo?: boolean}): void {posthog.capture(CANVAS_EVENTS.dashboardAction, {diff --git a/products/canvas/frontend/canvasTasksApi.ts b/products/canvas/frontend/canvasTasksApi.tsindex e4a63a909743..4269a3841ba9 100644--- a/products/canvas/frontend/canvasTasksApi.ts+++ b/products/canvas/frontend/canvasTasksApi.ts@@ -3,13 +3,19 @@ import {taskChannelsProvisionDefaultsCreate,taskChannelsRetrieve,tasksCreate,+ tasksList,+ tasksPartialUpdate,tasksRetrieve,tasksRunCreate,tasksRunsCommandCreate,} from 'products/tasks/frontend/generated/api'import type { ChannelDTOApi, TaskDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'-export type CanvasSpace = Pick<ChannelDTOApi, 'id' | 'name' | 'system_role'>+import { canvasesVersionsRetrieve } from './generated/api'+import type { CanvasApi } from './generated/api.schemas'+import { canvasPromptTarget, isCanvasGenerationPrompt } from './scene/canvasGenerationPrompt'++export type CanvasSpace = Pick<ChannelDTOApi, 'id' | 'name' | 'system_role' | 'channel_type'>export type CanvasTaskRun = Pick<NonNullable<TaskDetailDTOApi['latest_run']>, 'id' | 'status'> &Partial<Pick<NonNullable<TaskDetailDTOApi['latest_run']>, 'error_message'>>export type CanvasGenerationTask = Pick<TaskDetailDTOApi, 'id' | 'title'> & {@@ -42,6 +48,7 @@ function toSpaces(response: unknown): CanvasSpace[] {id: String(row.id),name: String(row.name ?? ''),system_role: row.system_role === 'personal' || row.system_role === 'general' ? row.system_role : null,+ channel_type: String(row.channel_type ?? ''),}))}@@ -91,6 +98,95 @@ export async function loadCanvasGenerationTask(projectId: string, taskId: stringreturn toCanvasTask(await tasksRetrieve(projectId, taskId))}+const VERSION_PAGE_SIZE = 100++/** A task moved to another space, and the space it came from. */+export interface CanvasTaskMove {+ id: string+ from: string | null+}++/** The chat tasks this person started on the canvas: every run whose prompt names it, and the runs behind its versions. */+export async function ownCanvasTaskIds(+ projectId: string,+ canvas: Pick<CanvasApi, 'id' | 'generation_task_id'>,+ user: { id: number; uuid: string }+): Promise<string[]> {+ const userUuid = user.uuid+ const ids = new Set<string>()+ // Each generation prompt names its canvas on one line, so this also finds earlier runs that made no version.+ for (let offset = 0; ; offset += VERSION_PAGE_SIZE) {+ const page = await tasksList(projectId, {+ created_by: user.id,+ search: canvasPromptTarget(canvas.id),+ limit: VERSION_PAGE_SIZE,+ offset,+ })+ // The search matches text anywhere, so only a real generation prompt for this canvas counts.+ for (const task of page.results) {+ if ('description' in task && isCanvasGenerationPrompt(task.description, canvas.id)) {+ ids.add(task.id)+ }+ }+ if (!page.next) {+ break+ }+ }+ for (let offset = 0; ; offset += VERSION_PAGE_SIZE) {+ const page = await canvasesVersionsRetrieve(projectId, canvas.id, { limit: VERSION_PAGE_SIZE, offset })+ for (const version of page.results) {+ if (version.task_id && version.created_by?.uuid === userUuid) {+ ids.add(version.task_id)+ }+ }+ if (!page.next) {+ break+ }+ }+ if (canvas.generation_task_id && !ids.has(canvas.generation_task_id)) {+ const task = await loadCanvasGenerationTask(projectId, canvas.generation_task_id)+ if (task.created_by?.uuid === userUuid) {+ ids.add(task.id)+ }+ }+ return [...ids]+}++/** What happened when a move failed, given how many chats could not move back. */+export function partialMoveMessage(unrestored: number): string {+ return unrestored+ ? `The canvas didn’t move. ${unrestored} of its chats moved to your personal space and stayed there.`+ : 'The canvas and its chats didn’t move, so nothing changed. Try again.'+}++/** Moves tasks back to the spaces they came from. Returns how many stayed where they were. */+export async function restoreCanvasTasks(projectId: string, moves: CanvasTaskMove[]): Promise<number> {+ const results = await Promise.allSettled(+ moves.map((move) => tasksPartialUpdate(projectId, move.id, { channel: move.from }))+ )+ return results.filter((result) => result.status === 'rejected').length+}++/** Files tasks in a space, so their chats are only as visible as that space. Either every task moves or none does. */+export async function moveCanvasTasks(+ projectId: string,+ taskIds: string[],+ spaceId: string+): Promise<CanvasTaskMove[]> {+ const current = await Promise.all(+ taskIds.map(async (id) => ({ id, from: (await tasksRetrieve(projectId, id)).channel ?? null }))+ )+ const pending = current.filter((task) => task.from !== spaceId)+ const results = await Promise.allSettled(+ pending.map((task) => tasksPartialUpdate(projectId, task.id, { channel: spaceId }))+ )+ const moved = pending.filter((_, index) => results[index].status === 'fulfilled')+ if (moved.length < pending.length) {+ throw new Error(partialMoveMessage(await restoreCanvasTasks(projectId, moved)))+ }+ return moved+}+export async function startCanvasGenerationRun(projectId: string, taskId: string): Promise<CanvasGenerationTask> {return toCanvasTask(await tasksRunCreate(projectId, taskId, {diff --git a/products/canvas/frontend/canvasVisibility.ts b/products/canvas/frontend/canvasVisibility.tsnew file mode 100644index 000000000000..ed2057443fc1--- /dev/null+++ b/products/canvas/frontend/canvasVisibility.ts@@ -0,0 +1,20 @@+import type { CanvasSpace } from './canvasTasksApi'++export type CanvasVisibility = 'private' | 'public' | 'shared'++type SpaceShape = Pick<CanvasSpace, 'system_role' | 'channel_type'>++export function canvasVisibility(space: SpaceShape): CanvasVisibility {+ if (space.system_role === 'personal' || space.channel_type === 'personal') {+ return 'private'+ }+ return space.channel_type === 'private' ? 'shared' : 'public'+}++export function visibilitySpace<T extends Pick<CanvasSpace, 'system_role'>>(+ spaces: T[],+ visibility: 'private' | 'public'+): T | null {+ const role = visibility === 'private' ? 'personal' : 'general'+ return spaces.find((space) => space.system_role === role) ?? null+}diff --git a/products/canvas/frontend/scene/CanvasMakePublicDialog.tsx b/products/canvas/frontend/scene/CanvasMakePublicDialog.tsxnew file mode 100644index 000000000000..7ea5cedfffa7--- /dev/null+++ b/products/canvas/frontend/scene/CanvasMakePublicDialog.tsx@@ -0,0 +1,63 @@+import { useActions, useValues } from 'kea'++import { IconGlobe } from '@posthog/icons'+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+} from '@posthog/quill'++import { teamLogic } from 'scenes/teamLogic'++import { canvasSceneLogic } from './canvasSceneLogic'++export function CanvasMakePublicDialog(): JSX.Element {+ const { canvas, visibilityChanging } = useValues(canvasSceneLogic)+ const { closeMakePublic, setCanvasVisibility } = useActions(canvasSceneLogic)+ const { currentTeam } = useValues(teamLogic)+ const project = currentTeam?.name ? `Everyone in ${currentTeam.name}` : 'Everyone in this project'+ const name = canvas?.name ? `“${canvas.name}”` : 'this canvas'++ return (+ <AlertDialog+ open+ onOpenChange={(open: boolean) => {+ if (!open && !visibilityChanging) {+ closeMakePublic()+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Make this canvas public?</AlertDialogTitle>+ <AlertDialogDescription>+ {`${project} will be able to open and edit ${name}. Only you can rename it or make it private again.`}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={() => closeMakePublic()}+ disabled={visibilityChanging}+ data-attr="canvas-make-public-cancel"+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ loading={visibilityChanging}+ onClick={() => setCanvasVisibility('public')}+ data-attr="canvas-make-public-confirm"+ >+ <IconGlobe />+ Make public+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/products/canvas/frontend/scene/CanvasScene.stories.tsx b/products/canvas/frontend/scene/CanvasScene.stories.tsxindex b3dc4ac89952..b08d447cc318 100644--- a/products/canvas/frontend/scene/CanvasScene.stories.tsx+++ b/products/canvas/frontend/scene/CanvasScene.stories.tsx@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'+import { Meta, StoryObj } from '@storybook/react'import { waitFor } from '@testing-library/dom'@@ -28,7 +30,11 @@ const canvas: CanvasApi = {current_version_id: null,published_build_id: null,component_meta: null,- created_by: { id: 1, uuid: 'user-uuid', email: '[email protected]' } as CanvasApi['created_by'],+ created_by: {+ id: MOCK_DEFAULT_USER.id,+ uuid: MOCK_DEFAULT_USER.uuid,+ email: MOCK_DEFAULT_USER.email,+ } as CanvasApi['created_by'],created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',url: `https://app.example.com/canvases/${CANVAS_ID}`,@@ -119,9 +125,12 @@ const comments = [),]+const PERSONAL_SPACE = { id: SPACE_ID, name: 'me', system_role: 'personal', channel_type: 'personal' }+function mocks(view: CanvasViewResponseApi,- threadComments: Record<string, unknown>[] = []+ threadComments: Record<string, unknown>[] = [],+ space: Record<string, unknown> = PERSONAL_SPACE): ReturnType<typeof mswDecorator> {const built = !!view.published_buildreturn mswDecorator({@@ -132,7 +141,7 @@ function mocks(current_version_id: view.current_version_id,builds: built ? [liveBuild] : [],},- '/api/projects/:team_id/task_channels/:id/': { id: SPACE_ID, name: 'me', system_role: 'personal' },+ '/api/projects/:team_id/task_channels/:id/': space,'/api/projects/:team_id/canvases/:id/versions/': {count: built ? versions.length : 0,next: null,@@ -195,6 +204,31 @@ export const Built: Story = {],}+export const BuiltPublicByTeammate: Story = {+ decorators: [+ mocks(+ {+ ...viewResponse({+ name: 'Weekly active users',+ generation_task_id: TASK_ID,+ current_version_id: 'version-2',+ published_build_id: liveBuild.id,+ created_by: {+ id: 1,+ uuid: 'teammate-uuid',+ first_name: 'Sam',+ email: '[email protected]',+ } as CanvasApi['created_by'],+ }),+ published_build: liveBuild,+ current_version_id: 'version-2',+ },+ [],+ { id: SPACE_ID, name: 'general', system_role: 'general', channel_type: 'public' }+ ),+ ],+}+export const BuiltWithTimeline: Story = {...Built,parameters: { pageUrl: `${urls.canvasDetail(CANVAS_ID)}#panel=canvas-timeline` },diff --git a/products/canvas/frontend/scene/CanvasSceneHeader.tsx b/products/canvas/frontend/scene/CanvasSceneHeader.tsxindex f15c7d8c51b0..d0eaa6f8db62 100644--- a/products/canvas/frontend/scene/CanvasSceneHeader.tsx+++ b/products/canvas/frontend/scene/CanvasSceneHeader.tsx@@ -31,6 +31,7 @@ import { CanvasRuntimeErrorNotice } from './CanvasRuntimeErrorNotice'import { canvasSceneLogic } from './canvasSceneLogic'import { CanvasSidePanelToggle } from './CanvasSidePanelToggle'import { CanvasToolbar } from './CanvasToolbar'+import { CanvasVisibilityControl } from './CanvasVisibilityControl'/*** The bar across the top of the canvas, laid out like PostHog Desktop's: the name and version history@@ -60,6 +61,7 @@ export function CanvasSceneHeader(): JSX.Element {<CanvasCommentsMenu /><CanvasFullscreenToggle /><CanvasSidePanelToggle />+ <CanvasVisibilityControl /><DropdownMenu><Tooltip>{/* quill's triggers do not forward refs under React 18, so a span anchors the tooltip. */}diff --git a/products/canvas/frontend/scene/CanvasVisibilityControl.tsx b/products/canvas/frontend/scene/CanvasVisibilityControl.tsxnew file mode 100644index 000000000000..b24b5bb1834e--- /dev/null+++ b/products/canvas/frontend/scene/CanvasVisibilityControl.tsx@@ -0,0 +1,124 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconGlobe, IconLock, IconPeople } from '@posthog/icons'+import {+ Badge,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { teamLogic } from 'scenes/teamLogic'++import { CanvasVisibility } from '../canvasVisibility'+import { CanvasMakePublicDialog } from './CanvasMakePublicDialog'+import { canvasSceneLogic } from './canvasSceneLogic'++const LABELS: Record<CanvasVisibility, string> = { private: 'Private', public: 'Public', shared: 'Shared' }+const ICONS: Record<CanvasVisibility, JSX.Element> = {+ private: <IconLock />,+ public: <IconGlobe />,+ shared: <IconPeople />,+}++function visibilityHint(+ visibility: CanvasVisibility,+ { project, owner, spaceName }: { project: string; owner: string | null; spaceName: string | null }+): string {+ if (visibility === 'private') {+ return 'Only you can see this canvas.'+ }+ if (visibility === 'shared') {+ return `This canvas is in ${spaceName ? `the older space ${spaceName}` : 'an older space'}. Only its members can see it.`+ }+ return owner+ ? `${owner} made this canvas public. Everyone in ${project} can see it.`+ : `Everyone in ${project} can see this canvas.`+}++/** Who can see the canvas, in the header. Its creator can change it here. Everyone else sees a label. */+export function CanvasVisibilityControl(): JSX.Element | null {+ const { canvas, space, visibility, isCreator, visibilityChanging, makePublicOpen } = useValues(canvasSceneLogic)+ const { openMakePublic, setCanvasVisibility } = useActions(canvasSceneLogic)+ const { currentTeam } = useValues(teamLogic)++ if (!canvas || !visibility || (!isCreator && visibility === 'private')) {+ return null+ }+ const hint = visibilityHint(visibility, {+ project: currentTeam?.name || 'this project',+ owner: isCreator ? null : canvas.created_by.first_name || canvas.created_by.email || 'A teammate',+ spaceName: space?.name ?? null,+ })+ const content = (+ <>+ {ICONS[visibility]}+ <span className="hidden @min-[32rem]/canvas-toolbar:inline">{LABELS[visibility]}</span>+ </>+ )+ // quill's Badge and DropdownMenuTrigger do not forward refs under React 18, so a span anchors the tooltip.+ const withHint = (trigger: JSX.Element): JSX.Element => (+ <Tooltip>+ <TooltipTrigger+ delay={300}+ render={<span tabIndex={isCreator ? undefined : 0} className="inline-flex rounded-sm" />}+ >+ {trigger}+ </TooltipTrigger>+ <TooltipContent className="max-w-72">{hint}</TooltipContent>+ </Tooltip>+ )++ if (!isCreator) {+ return withHint(+ <Badge aria-label={LABELS[visibility]} data-attr="canvas-visibility-readonly">+ {content}+ </Badge>+ )+ }+ return (+ <>+ <DropdownMenu>+ {withHint(+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ loading={visibilityChanging}+ aria-label={`${LABELS[visibility]}. Change who can see this canvas`}+ data-attr="canvas-visibility"+ />+ }+ >+ {content}+ <IconChevronDown />+ </DropdownMenuTrigger>+ )}+ <DropdownMenuContent align="end" className="min-w-48">+ {visibility !== 'public' && (+ <DropdownMenuItem onClick={() => openMakePublic()} data-attr="canvas-visibility-make-public">+ <IconGlobe />+ Make public…+ </DropdownMenuItem>+ )}+ {visibility !== 'private' && (+ <DropdownMenuItem+ onClick={() => setCanvasVisibility('private')}+ data-attr="canvas-visibility-make-private"+ >+ <IconLock />+ Make private+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ {makePublicOpen && <CanvasMakePublicDialog />}+ </>+ )+}diff --git a/products/canvas/frontend/scene/canvasGenerationPrompt.ts b/products/canvas/frontend/scene/canvasGenerationPrompt.tsindex 446aab28d86c..7dbd49bd40fc 100644--- a/products/canvas/frontend/scene/canvasGenerationPrompt.ts+++ b/products/canvas/frontend/scene/canvasGenerationPrompt.ts@@ -13,6 +13,18 @@ function escapeXmlAttr(value: string): string {}/** The prompt that routes a cloud task to the building-canvases skill for one canvas. */+/** The line every generation prompt names its canvas with, so a search can find that canvas's runs and no others. */+export function canvasPromptTarget(canvasId: string): string {+ return `canvas id: "${escapeXmlAttr(canvasId)}"`+}++/** Whether a task's prompt is a generation prompt for this canvas: its instructions block names the canvas as the target. */+export function isCanvasGenerationPrompt(description: string | null | undefined, canvasId: string): boolean {+ const start = description?.indexOf(`<${CANVAS_INSTRUCTIONS_TAG}>`) ?? -1+ const end = description?.indexOf(`</${CANVAS_INSTRUCTIONS_TAG}>`, start) ?? -1+ return start >= 0 && end > start && description!.slice(start, end).includes(`- ${canvasPromptTarget(canvasId)}`)+}+export function buildCanvasGenerationPrompt(input: {canvasId: stringname: string@@ -34,7 +46,7 @@ If the canvas source has \`src/blocks/runtime.tsx\`, read the skill's \`referencExpose the values a person may want to change as params with \`editable()\`, as the skill's "Params" section describes.Target:-- canvas id: "${escapeXmlAttr(input.canvasId)}"+- ${canvasPromptTarget(input.canvasId)}- canvas name: "${escapeXmlAttr(input.name)}"- channel: "${escapeXmlAttr(input.spaceName)}"${template}</${CANVAS_INSTRUCTIONS_TAG}>`diff --git a/products/canvas/frontend/scene/canvasSceneLogic.test.ts b/products/canvas/frontend/scene/canvasSceneLogic.test.tsindex ef92e1a5a72d..0b3a6dc24fe8 100644--- a/products/canvas/frontend/scene/canvasSceneLogic.test.ts+++ b/products/canvas/frontend/scene/canvasSceneLogic.test.ts@@ -1,19 +1,34 @@+import { MOCK_USER_UUID } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'+import { toast } from '@posthog/quill'++import { userLogic } from 'scenes/userLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { buildCanvasGenerationPrompt } from './canvasGenerationPrompt'import { canvasSceneLogic } from './canvasSceneLogic'const CANVAS_ID = 'canvas-1'describe('canvasSceneLogic', () => {let releaseTaskRequest: () => void = () => {}+ let patchStatus = 200+ let patchedBody: Record<string, unknown> | null = nullbeforeEach(() => {const taskRequestReleased = new Promise<void>((resolve) => {releaseTaskRequest = resolve})+ patchStatus = 200+ patchedBody = null+ const spaces = {+ 'space-1': { id: 'space-1', name: 'me', system_role: 'personal', channel_type: 'personal' },+ 'space-team': { id: 'space-team', name: 'general', system_role: 'general', channel_type: 'public' },+ }useMocks({get: {'/api/projects/:team_id/canvases/:id/view/': {@@ -34,7 +49,27 @@ describe('canvasSceneLogic', () => {sandbox_document_url: null,},'/api/projects/:team_id/canvases/:id/builds/': { builds: [], published_build_id: null },- '/api/projects/:team_id/task_channels/:id/': { id: 'space-1', name: 'me', system_role: 'personal' },+ '/api/projects/:team_id/task_channels/': Object.values(spaces),+ '/api/projects/:team_id/task_channels/:id/': (req) => [+ 200,+ spaces[req.params.id as keyof typeof spaces],+ ],+ },+ patch: {+ '/api/projects/:team_id/canvases/:id/': async ({ request }) => {+ patchedBody = (await request.json()) as Record<string, unknown>+ return patchStatus === 200+ ? [+ 200,+ {+ id: CANVAS_ID,+ name: 'Untitled canvas',+ kind: 'freeform',+ channel: patchedBody.channel_id,+ },+ ]+ : [patchStatus, { detail: 'Only the canvas creator can rename, move, pin, or describe it.' }]+ },},post: {'/api/projects/:team_id/tasks/:id/run/': [@@ -50,6 +85,177 @@ describe('canvasSceneLogic', () => {initKeaTests()})+ it.each([+ ['moves the canvas to the team space', 200, 'public'],+ ['keeps the canvas where it was when the move fails', 403, 'private'],+ ])('Make public %s', async (_, status, visibility) => {+ patchStatus = status+ const logic = canvasSceneLogic({ id: CANVAS_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadViewSuccess', 'loadSpaceSuccess'])+ expect(logic.values.visibility).toEqual('private')++ logic.actions.openMakePublic()+ logic.actions.setCanvasVisibility('public')+ await expectLogic(logic).toDispatchActions(['canvasVisibilityChanged'])+ await expectLogic(logic).toFinishAllListeners()++ expect(patchedBody).toEqual({ channel_id: 'space-team' })+ expect(logic.values.visibility).toEqual(visibility)+ expect(logic.values.visibilityChanging).toBe(false)+ expect(logic.values.makePublicOpen).toBe(false)+ })++ it.each([+ ['moves the creator’s chats first and leaves a teammate’s chat alone', 200, false],+ ['moves the chats back when the canvas cannot move', 403, false],+ ['says which chats stayed private when one cannot move back', 403, true],+ ])('Make private %s', async (_, canvasStatus, restoreFails) => {+ const errorToast = jest.spyOn(toast, 'error')+ const order: string[] = []+ const tasksPatched: Record<string, unknown[]> = {}+ const me = { id: 1, uuid: MOCK_USER_UUID }+ useMocks({+ get: {+ '/api/projects/:team_id/canvases/:id/view/': {+ canvas: {+ id: CANVAS_ID,+ name: 'Weekly active users',+ kind: 'freeform',+ channel: 'space-team',+ generation_task_id: 'task-authoring',+ created_by: me,+ },+ published_build: null,+ current_version_id: null,+ has_active_build: false,+ source: null,+ layout: null,+ sandbox_document_url: null,+ },+ // An earlier run that failed before it made a version is found by the canvas id in its prompt.+ // A chat that only mentions the canvas id is not one of its runs, so the exact prompt line is searched.+ '/api/projects/:team_id/tasks/': ({ request }) => {+ const search = new URL(request.url).searchParams.get('search') ?? ''+ const tasks = [+ {+ id: 'task-failed-run',+ description: buildCanvasGenerationPrompt({+ canvasId: CANVAS_ID,+ name: 'Weekly active users',+ spaceName: 'general',+ templateId: 'freeform',+ instruction: 'A chart of weekly active users',+ }),+ },+ { id: 'task-mention', description: `Compare with ${CANVAS_ID}` },+ { id: 'task-quote', description: `Why does the prompt say - canvas id: "${CANVAS_ID}"?` },+ ]+ return [200, { next: null, results: tasks.filter((task) => task.description.includes(search)) }]+ },+ '/api/projects/:team_id/tasks/:id/': ({ params }) => [+ 200,+ {+ id: params.id,+ title: 'Weekly active users',+ latest_run: null,+ created_by: me,+ channel: 'space-team',+ },+ ],+ '/api/projects/:team_id/canvases/:id/versions/': {+ next: null,+ results: [+ { id: 'version-2', task_id: 'task-follow-up', created_by: me },+ { id: 'version-3', task_id: 'task-teammate', created_by: { id: 2, uuid: 'teammate-uuid' } },+ ],+ },+ },+ patch: {+ '/api/projects/:team_id/tasks/:id/': async ({ params, request }) => {+ order.push(`task:${params.id}`)+ const body = (await request.json()) as { channel: string }+ tasksPatched[params.id as string] = [...(tasksPatched[params.id as string] ?? []), body]+ return restoreFails && params.id === 'task-authoring' && body.channel === 'space-team'+ ? [500, { detail: 'Server error' }]+ : [200, { id: params.id }]+ },+ '/api/projects/:team_id/canvases/:id/': async ({ request }) => {+ order.push('canvas')+ patchedBody = (await request.json()) as Record<string, unknown>+ return canvasStatus === 200+ ? [+ 200,+ {+ id: CANVAS_ID,+ name: 'Weekly active users',+ kind: 'freeform',+ channel: patchedBody.channel_id,+ created_by: me,+ },+ ]+ : [canvasStatus, { detail: 'Only the canvas creator can rename, move, pin, or describe it.' }]+ },+ },+ })+ userLogic.mount()+ await expectLogic(userLogic).toDispatchActions(['loadUserSuccess'])+ const logic = canvasSceneLogic({ id: CANVAS_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadViewSuccess', 'loadSpaceSuccess'])+ expect(logic.values.visibility).toEqual('public')++ logic.actions.setCanvasVisibility('private')+ await expectLogic(logic).toDispatchActions(['canvasVisibilityChanged'])++ const toPersonal = { channel: 'space-1' }+ const back = { channel: 'space-team' }+ const expected = canvasStatus === 200 ? [toPersonal] : [toPersonal, back]+ expect(tasksPatched).toEqual({+ 'task-failed-run': expected,+ 'task-follow-up': expected,+ 'task-authoring': expected,+ })+ expect(order.indexOf('canvas')).toBeGreaterThan(order.indexOf('task:task-authoring'))+ expect(logic.values.canvas?.channel).toEqual(canvasStatus === 200 ? 'space-1' : 'space-team')+ if (restoreFails) {+ expect(errorToast).toHaveBeenCalledWith(+ expect.objectContaining({+ description: expect.stringContaining('1 of its chats moved to your personal space'),+ })+ )+ }+ errorToast.mockRestore()+ })++ it('Undo after Make private moves the canvas back first, then its chats', async () => {+ const order: string[] = []+ useMocks({+ patch: {+ '/api/projects/:team_id/tasks/:id/': async ({ params, request }) => {+ order.push(`task:${params.id}:${((await request.json()) as { channel: string }).channel}`)+ return [200, { id: params.id }]+ },+ '/api/projects/:team_id/canvases/:id/': async ({ request }) => {+ patchedBody = (await request.json()) as Record<string, unknown>+ order.push(`canvas:${patchedBody.channel_id}`)+ return [+ 200,+ { id: CANVAS_ID, name: 'Untitled canvas', kind: 'freeform', channel: patchedBody.channel_id },+ ]+ },+ },+ })+ const logic = canvasSceneLogic({ id: CANVAS_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadViewSuccess', 'loadSpaceSuccess'])++ logic.actions.moveCanvasToSpace('space-team', null, false, [{ id: 'task-authoring', from: 'space-team' }])+ await expectLogic(logic).toDispatchActions(['canvasVisibilityChanged'])++ expect(order).toEqual(['canvas:space-team', 'task:task-authoring:space-team'])+ })+it('keeps the composer on screen while a run starts and after it fails to start', async () => {const logic = canvasSceneLogic({ id: CANVAS_ID })logic.mount()diff --git a/products/canvas/frontend/scene/canvasSceneLogic.ts b/products/canvas/frontend/scene/canvasSceneLogic.tsindex 2cf4f960eae5..59398b0cb941 100644--- a/products/canvas/frontend/scene/canvasSceneLogic.ts+++ b/products/canvas/frontend/scene/canvasSceneLogic.ts@@ -22,11 +22,12 @@ import { toast } from '@posthog/quill'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { projectLogic } from 'scenes/projectLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { todayViewsLogic } from '~/layout/today/todayViewsLogic'-import { Breadcrumb, SidePanelTab } from '~/types'+import { Breadcrumb, SidePanelTab, UserType } from '~/types'import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'@@ -39,7 +40,14 @@ import {isTerminalRunStatus,loadCanvasGenerationTask,loadCanvasSpace,+ loadCanvasSpaces,+ CanvasTaskMove,+ moveCanvasTasks,+ ownCanvasTaskIds,+ partialMoveMessage,+ restoreCanvasTasks,} from '../canvasTasksApi'+import { CanvasVisibility, canvasVisibility, visibilitySpace } from '../canvasVisibility'import {canvasesBuildActionCreate,canvasesBuildsRetrieve,@@ -148,6 +156,7 @@ export interface canvasSceneLogicValues {currentProjectId: number | null // projectLogicselectedTab: SidePanelTab | null // sidePanelStateLogicsidePanelOpen: boolean // sidePanelStateLogic+ user: UserType | null // userLogicagentTurn: CanvasAgentTurn | nullbodyState: CanvasBodyStatebreadcrumbs: Breadcrumb[]@@ -167,9 +176,11 @@ export interface canvasSceneLogicValues {generationTaskLoading: booleaninstruction: stringinstructionFromSuggestion: boolean+ isCreator: booleanisGenerating: booleanliveBuild: CanvasBuildApi | nullliveRenderSource: CanvasRenderSource+ makePublicOpen: booleanruntimeError: string | nullsandboxDocumentUrl: string | nullshouldPoll: boolean@@ -181,6 +192,8 @@ export interface canvasSceneLogicValues {viewLoading: booleanviewMissing: booleanviewUnavailable: boolean+ visibility: CanvasVisibility | null+ visibilityChanging: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -215,6 +228,12 @@ export interface canvasSceneLogicActions {canvasUpdated: (canvas: CanvasApi) => {canvas: CanvasApi}+ canvasVisibilityChanged: () => {+ value: true+ }+ closeMakePublic: () => {+ value: true+ }copyLink: () => {value: true}@@ -299,6 +318,20 @@ export interface canvasSceneLogicActions {view: CanvasViewResponseApi | nullpayload?: any}+ moveCanvasToSpace: (+ spaceId: string,+ visibility: 'private' | 'public' | null,+ restricted: boolean,+ restoreTasks?: CanvasTaskMove[]+ ) => {+ restoreTasks: CanvasTaskMove[]+ restricted: boolean+ spaceId: string+ visibility: 'private' | 'public' | null+ }+ openMakePublic: () => {+ value: true+ }poll: () => {value: true}@@ -321,6 +354,9 @@ export interface canvasSceneLogicActions {active: boolean | nullrunId: string}+ setCanvasVisibility: (visibility: 'private' | 'public') => {+ visibility: 'private' | 'public'+ }setInstruction: (instruction: string,fromSuggestion: boolean@@ -351,6 +387,8 @@ export interface canvasSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {busy: (isGenerating: boolean, buildStatus: CanvasBuildStatus) => booleancanvas: (view: CanvasViewResponseApi | null) => CanvasApi | null+ visibility: (canvas: CanvasApi | null, space: CanvasSpace | null) => CanvasVisibility | null+ isCreator: (canvas: CanvasApi | null, user: UserType | null) => booleansandboxDocumentUrl: (view: CanvasViewResponseApi | null) => string | nullliveBuild: (view: CanvasViewResponseApi | null) => CanvasBuildApi | nulldraftCode: (view: CanvasViewResponseApi | null) => string | null@@ -410,6 +448,8 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([['selectedTab', 'sidePanelOpen'],canvasSidePanelLogic,['blocksCanvasId'],+ userLogic,+ ['user'],],// Connecting keeps the Views sidebar's logic mounted, so it knows this canvas's state when it opens.actions: [@@ -426,6 +466,25 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([canvasUpdated: (canvas: CanvasApi) => ({ canvas }),copyLink: true,deleteCanvas: true,+ openMakePublic: true,+ closeMakePublic: true,+ setCanvasVisibility: (visibility: 'private' | 'public') => ({ visibility }),+ /**+ * Moves the canvas to a space. `visibility` is null when the move undoes the one before.+ * `restricted` says the space is not the team's, so the creator's chats on the canvas move there first.+ */+ moveCanvasToSpace: (+ spaceId: string,+ visibility: 'private' | 'public' | null,+ restricted: boolean,+ restoreTasks: CanvasTaskMove[] = []+ ) => ({+ spaceId,+ visibility,+ restricted,+ restoreTasks,+ }),+ canvasVisibilityChanged: true,setInstruction: (instruction: string, fromSuggestion: boolean) => ({ instruction, fromSuggestion }),generateCanvas: (instruction: string,@@ -501,6 +560,22 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([view: {canvasUpdated: (state, { canvas }) => (state ? { ...state, canvas } : state),},+ makePublicOpen: [+ false,+ {+ openMakePublic: () => true,+ closeMakePublic: () => false,+ canvasVisibilityChanged: () => false,+ },+ ],+ visibilityChanging: [+ false,+ {+ setCanvasVisibility: () => true,+ moveCanvasToSpace: () => true,+ canvasVisibilityChanged: () => false,+ },+ ],viewMissing: [false,{@@ -589,6 +664,18 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([isGenerating || buildStatus === 'building',],canvas: [(s) => [s.view], (view: CanvasViewResponseApi | null): CanvasApi | null => view?.canvas ?? null],+ /** Null until the canvas's space loads, so the header shows no visibility it might take back. */+ visibility: [+ (s) => [s.canvas, s.space],+ (canvas: CanvasApi | null, space: CanvasSpace | null): CanvasVisibility | null =>+ canvas && space?.id === canvas.channel ? canvasVisibility(space) : null,+ ],+ /** Only the canvas's creator may move it, so only they get the visibility actions. */+ isCreator: [+ (s) => [s.canvas, s.user],+ (canvas: CanvasApi | null, user: UserType | null): boolean =>+ !!canvas && !!user && canvas.created_by.id === user.id,+ ],sandboxDocumentUrl: [(s) => [s.view],(view: CanvasViewResponseApi | null): string | null => view?.sandbox_document_url ?? null,@@ -895,6 +982,100 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([})}},+ openMakePublic: () => {+ if (values.canvas) {+ captureCanvasAction('make_public_opened', {+ dashboard_id: values.canvas.id,+ channel_id: values.canvas.channel,+ })+ }+ },+ setCanvasVisibility: async ({ visibility }) => {+ if (!values.currentProjectId) {+ actions.canvasVisibilityChanged()+ return+ }+ try {+ const spaces = await loadCanvasSpaces(String(values.currentProjectId))+ const space = visibilitySpace(spaces, visibility)+ if (!space) {+ throw new Error('This project has no team space yet.')+ }+ actions.moveCanvasToSpace(space.id, visibility, visibility === 'private')+ } catch (error) {+ toast.error({+ title:+ visibility === 'public'+ ? "Couldn't make the canvas public"+ : "Couldn't make the canvas private",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ actions.canvasVisibilityChanged()+ }+ },+ moveCanvasToSpace: async ({ spaceId, visibility, restricted, restoreTasks }) => {+ const canvas = values.canvas+ if (!values.currentProjectId || !canvas) {+ actions.canvasVisibilityChanged()+ return+ }+ const projectId = String(values.currentProjectId)+ const previousSpaceId = canvas.channel+ const previousRestricted = values.visibility !== 'public'+ const properties = { dashboard_id: canvas.id, ...(visibility ? { visibility } : {}), undo: !visibility }+ let moved: CanvasTaskMove[] = []+ try {+ // Chats first: a task's logs are as visible as its own space, whatever the canvas says.+ if (restricted && values.user) {+ moved = await moveCanvasTasks(+ projectId,+ await ownCanvasTaskIds(projectId, canvas, values.user),+ spaceId+ )+ }+ let updated: CanvasApi+ try {+ updated = await canvasesPartialUpdate(projectId, props.id, { channel_id: spaceId })+ } catch (error) {+ // The canvas stayed, so its chats go back to stay in the same space as it.+ const unrestored = await restoreCanvasTasks(projectId, moved)+ throw unrestored ? new Error(partialMoveMessage(unrestored)) : error+ }+ const unrestored = await restoreCanvasTasks(projectId, restoreTasks)+ actions.canvasUpdated(updated)+ actions.loadSpace()+ todayViewsLogic.findMounted()?.actions.loadRecentViews()+ captureCanvasAction('visibility_change', { ...properties, channel_id: spaceId, success: true })+ toast.success(+ visibility+ ? {+ title:+ visibility === 'public' ? 'This canvas is now public' : 'This canvas is now private',+ action: {+ label: 'Undo',+ onClick: () =>+ actions.moveCanvasToSpace(previousSpaceId, null, previousRestricted, moved),+ },+ }+ : unrestored+ ? { title: 'Change undone. Some of its chats stayed private.' }+ : { title: 'Change undone' }+ )+ } catch (error) {+ captureCanvasAction('visibility_change', { ...properties, channel_id: previousSpaceId, success: false })+ toast.error({+ title:+ visibility === 'public'+ ? "Couldn't make the canvas public"+ : visibility === 'private'+ ? "Couldn't make the canvas private"+ : "Couldn't undo the change",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ } finally {+ actions.canvasVisibilityChanged()+ }+ },copyLink: async () => {// The project in the path makes the link open this canvas for someone whose current project differs.await copyToClipboard(urls.absolute(urls.currentProject(urls.canvasDetail(props.id))), 'canvas link')