: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): add views rail pane and canvas scene to web (#109099)
Peter Kirkham5bb3e7849649
diff --git a/.semgrep/rules/security/csp-header-outside-csp-middleware.py b/.semgrep/rules/security/csp-header-outside-csp-middleware.pyindex 2522c3dc7c6c..11f68d32c173 100644--- a/.semgrep/rules/security/csp-header-outside-csp-middleware.py+++ b/.semgrep/rules/security/csp-header-outside-csp-middleware.py@@ -44,6 +44,11 @@ def ok_canvas_artifact_policy(response, network_origins):response["Content-Security-Policy"] = artifact_csp(network_origins)+def ok_canvas_sandbox_document_policy(response, document):+ # ok: csp-header-outside-csp-middleware+ response["Content-Security-Policy"] = _canvas_sandbox_document_csp(document)++def ok_public_survey_policy(request, response):# ok: csp-header-outside-csp-middlewareresponse["Content-Security-Policy"] = _public_survey_csp(request)@@ -61,6 +66,11 @@ def flag_report_only_canvas_artifact_policy(response, network_origins):response["Content-Security-Policy-Report-Only"] = artifact_csp(network_origins)+def flag_report_only_canvas_sandbox_document_policy(response, document):+ # ruleid: csp-header-outside-csp-middleware+ response["Content-Security-Policy-Report-Only"] = _canvas_sandbox_document_csp(document)++def flag_report_only_public_survey_policy(request, response):# ruleid: csp-header-outside-csp-middlewareresponse["Content-Security-Policy-Report-Only"] = _public_survey_csp(request)diff --git a/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml b/.semgrep/rules/security/csp-header-outside-csp-middleware.yamlindex 07db21d8d662..029677f4180c 100644--- a/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml+++ b/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml@@ -21,13 +21,15 @@ rules:- metavariable-regex:metavariable: $HEADERregex: (?i)^["']?content-security-policy(-report-only)?["']?$- # Three documents sandbox untrusted HTML, so each carries a policy of its own rather than- # the app policy. Each exception names the policy it allows, not the file, so a fourth- # document in the same file trips the rule, and a change to one of these three policies+ # Four documents sandbox untrusted HTML, so each carries a policy of its own rather than+ # the app policy. Each exception names the policy it allows, not the file, so a fifth+ # document in the same file trips the rule, and a change to one of these four policies# trips it too. Each exception also pins the enforced header name, because the `sandbox`- # directive these three documents rely on has no effect when a browser gets the policy as+ # directive these four documents rely on has no effect when a browser gets the policy as# `Content-Security-Policy-Report-Only`. Adding an exception needs a team-security review.- pattern-not: $RESPONSE["Content-Security-Policy"] = artifact_csp(...)+ # The draft canvas policy is server-defined and requires team-security review.+ - pattern-not: $RESPONSE["Content-Security-Policy"] = _canvas_sandbox_document_csp(...)- pattern-not: $RESPONSE["Content-Security-Policy"] = _public_survey_csp(...)- pattern-not: >-$RESPONSE["Content-Security-Policy"] = "sandbox; default-src 'none'; img-src https:diff --git a/docs/internal/canvas-delivery.md b/docs/internal/canvas-delivery.mdindex b294aa86647f..4db2e2f7772a 100644--- a/docs/internal/canvas-delivery.md+++ b/docs/internal/canvas-delivery.md@@ -37,6 +37,12 @@ The handler accepts only the Host configured in `CANVAS_ARTIFACT_ORIGIN`.Forward that Host through the CDN and ingress, with matching TLS and host allowlists.The backend connection can use a separate origin hostname, but the HTTP Host must still match the artifact origin.+Draft previews use the same artifact origin and a server-defined sandbox policy.+Their HTML meta policy cannot expand the header policy, including for retained documents.+The header permits the fixed compiler and module CDNs, but blocks external images and form submissions.+Use a built canvas with declared network origins for external images.+Changes to this server policy and its tests require security review.+## Cache policyShared caching is off by default:diff --git a/frontend/src/layout/today/TodayPaneSearchField.tsx b/frontend/src/layout/today/TodayPaneSearchField.tsxnew file mode 100644index 000000000000..5726402db414--- /dev/null+++ b/frontend/src/layout/today/TodayPaneSearchField.tsx@@ -0,0 +1,82 @@+import { ChangeEvent, KeyboardEvent, MouseEvent } from 'react'++import { IconX } from '@posthog/icons'+import {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+ InputGroupText,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++/** A pane section's search box. Escape or the button clears the query first, then closes the box. */+export function TodayPaneSearchField({+ query,+ resultCount,+ label,+ onQueryChange,+ onClose,+ dataAttr,+}: {+ query: string+ resultCount: number+ /** The accessible name, also the placeholder, for example "Search recent". */+ label: string+ onQueryChange: (query: string) => void+ onClose: () => void+ /** Prefix for the field's `data-attr` and its clear button's `-clear` one. */+ dataAttr: string+}): JSX.Element {+ const hasQuery = query !== ''+ const buttonLabel = hasQuery ? 'Clear search' : 'Close search'+ const clearOrClose = (): void => (hasQuery ? onQueryChange('') : onClose())++ return (+ <InputGroup className="min-w-0 flex-1">+ <InputGroupInput+ autoFocus+ value={query}+ placeholder={`${label}…`}+ aria-label={label}+ data-attr={dataAttr}+ onChange={(event: ChangeEvent<HTMLInputElement>) => onQueryChange(event.target.value)}+ onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {+ if (event.key === 'Escape') {+ event.preventDefault()+ event.stopPropagation()+ clearOrClose()+ }+ }}+ onBlur={() => !hasQuery && onClose()}+ />+ <InputGroupAddon align="inline-end">+ {hasQuery && (+ <InputGroupText className="tabular-nums">+ {resultCount === 0 ? 'No results' : resultCount}+ </InputGroupText>+ )}+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <InputGroupButton+ size="icon-xs"+ aria-label={buttonLabel}+ // Keeps focus in the field, so blur doesn't close it before the click lands.+ onMouseDown={(event: MouseEvent) => event.preventDefault()}+ onClick={clearOrClose}+ data-attr={`${dataAttr}-clear`}+ />+ }+ >+ <IconX />+ </TooltipTrigger>+ <TooltipContent>{buttonLabel}</TooltipContent>+ </Tooltip>+ </InputGroupAddon>+ </InputGroup>+ )+}diff --git a/frontend/src/layout/today/TodayPaneSection.tsx b/frontend/src/layout/today/TodayPaneSection.tsxindex 0bbcb442f79c..68c8287a1a6a 100644--- a/frontend/src/layout/today/TodayPaneSection.tsx+++ b/frontend/src/layout/today/TodayPaneSection.tsx@@ -16,11 +16,11 @@ export interface TodayPaneSectionProps {heading?: JSX.Element | nulldivider?: booleandataAttr: string- height: number- animate: boolean+ height?: number+ animate?: booleanresizer?: TodaySectionResizerresizing?: boolean- contentRef: RefCallback<HTMLElement>+ contentRef?: RefCallback<HTMLElement>children: ReactNode}@@ -34,7 +34,7 @@ export function TodayPaneSection({divider = false,dataAttr,height,- animate,+ animate = false,resizer,resizing = false,contentRef,@@ -68,7 +68,7 @@ export function TodayPaneSection({animate && 'transition-all duration-200 ease-out motion-reduce:transition-none')}// eslint-disable-next-line react/forbid-dom-props- style={{ height: open ? height : 0 }}+ style={{ height: open ? (height ?? 'auto') : 0 }}>{open && (<div className="scroll-mask-8 h-full scroll-py-8 overflow-y-auto">diff --git a/frontend/src/layout/today/TodayRail.tsx b/frontend/src/layout/today/TodayRail.tsxindex 11d6895ba9c6..e95b4ddda6ab 100644--- a/frontend/src/layout/today/TodayRail.tsx+++ b/frontend/src/layout/today/TodayRail.tsx@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'import {IconBook,IconChat,+ IconGridMasonry,IconHome,IconLogomark,IconSearch,@@ -25,6 +26,7 @@ import { TODAY_RAIL_WIDTH, TodayRailPane, todayShellLogic } from './todayShellLoconst RAIL_ITEMS: { pane: TodayRailPane; label: string; icon: JSX.Element }[] = [{ pane: 'home', label: 'Home', icon: <IconHome /> },{ pane: 'spaces', label: 'Spaces', icon: <IconChat /> },+ { pane: 'views', label: 'Views', icon: <IconGridMasonry /> },{ pane: 'library', label: 'Library', icon: <IconBook /> },{ pane: 'tools', label: 'Tools', icon: <IconWrench /> },]diff --git a/frontend/src/layout/today/TodayRecentSearchField.tsx b/frontend/src/layout/today/TodayRecentSearchField.tsxindex 98593d585dfb..26d67ef3d29b 100644--- a/frontend/src/layout/today/TodayRecentSearchField.tsx+++ b/frontend/src/layout/today/TodayRecentSearchField.tsx@@ -1,70 +1,20 @@import { useActions, useValues } from 'kea'-import { ChangeEvent, KeyboardEvent, MouseEvent } from 'react'--import { IconX } from '@posthog/icons'-import {- InputGroup,- InputGroupAddon,- InputGroupButton,- InputGroupInput,- InputGroupText,- Tooltip,- TooltipContent,- TooltipTrigger,-} from '@posthog/quill'+import { TodayPaneSearchField } from './TodayPaneSearchField'import { todaySpacesLogic } from './todaySpacesLogic'export function TodayRecentSearchField(): JSX.Element {const { recentQuery, recentItems } = useValues(todaySpacesLogic)const { setRecentQuery, setRecentSearchOpen } = useActions(todaySpacesLogic)- const hasQuery = recentQuery !== ''- const label = hasQuery ? 'Clear search' : 'Close search'- const clearOrClose = (): void => (hasQuery ? setRecentQuery('') : setRecentSearchOpen(false))return (- <InputGroup className="min-w-0 flex-1">- <InputGroupInput- autoFocus- value={recentQuery}- placeholder="Search recent…"- aria-label="Search recent"- data-attr="today-recent-search"- onChange={(event: ChangeEvent<HTMLInputElement>) => setRecentQuery(event.target.value)}- onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {- if (event.key === 'Escape') {- event.preventDefault()- event.stopPropagation()- clearOrClose()- }- }}- onBlur={() => !hasQuery && setRecentSearchOpen(false)}- />- <InputGroupAddon align="inline-end">- {hasQuery && (- <InputGroupText className="tabular-nums">- {recentItems.length === 0 ? 'No results' : recentItems.length}- </InputGroupText>- )}- <Tooltip>- <TooltipTrigger- delay={0}- render={- <InputGroupButton- size="icon-xs"- aria-label={label}- // Keeps focus in the field, so blur doesn't close it before the click lands.- onMouseDown={(event: MouseEvent) => event.preventDefault()}- onClick={clearOrClose}- data-attr="today-recent-search-clear"- />- }- >- <IconX />- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- </InputGroupAddon>- </InputGroup>+ <TodayPaneSearchField+ query={recentQuery}+ resultCount={recentItems.length}+ label="Search recent"+ onQueryChange={setRecentQuery}+ onClose={() => setRecentSearchOpen(false)}+ dataAttr="today-recent-search"+ />)}diff --git a/frontend/src/layout/today/TodayShell.tsx b/frontend/src/layout/today/TodayShell.tsxindex 75730bf49378..8c16f2599ab7 100644--- a/frontend/src/layout/today/TodayShell.tsx+++ b/frontend/src/layout/today/TodayShell.tsx@@ -20,8 +20,9 @@ import { TODAY_RAIL_WIDTH, TODAY_SIDEBAR_CLOSE_THRESHOLD, clampSidebarWidth, todimport { TodaySidebarFooter } from './TodaySidebarFooter'import { TodaySpacesSidebar } from './TodaySpacesSidebar'import { TodayToolsSidebar } from './TodayToolsSidebar'+import { TodayViewsSidebar } from './TodayViewsSidebar'-const PANE_LABELS = { home: 'Today', spaces: 'Spaces', library: 'Library', tools: 'Tools' }+const PANE_LABELS = { home: 'Today', spaces: 'Spaces', views: 'Views', library: 'Library', tools: 'Tools' }/** The left navigation under the Today layout: the rail, then the sidebar for the pane the rail has open. */export function TodayShell({ className }: { className?: string }): JSX.Element {@@ -71,6 +72,8 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {<TodayPreviewCardProvider><TodaySpacesSidebar /></TodayPreviewCardProvider>+ ) : activePane === 'views' ? (+ <TodayViewsSidebar />) : activePane === 'library' ? (<TodayLibrarySidebar />) : (diff --git a/frontend/src/layout/today/TodayViewsFilterMenu.tsx b/frontend/src/layout/today/TodayViewsFilterMenu.tsxnew file mode 100644index 000000000000..647e10d894aa--- /dev/null+++ b/frontend/src/layout/today/TodayViewsFilterMenu.tsx@@ -0,0 +1,50 @@+import { useActions, useValues } from 'kea'++import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from '@posthog/quill'++import { TodayFilterMenuTrigger } from './TodayFilterMenuTrigger'+import { TodayRecentRadioSubmenu } from './TodayRecentRadioSubmenu'+import { DEFAULT_VIEWS_FILTERS, VIEWS_CREATED_BY_OPTIONS, VIEWS_TYPE_OPTIONS } from './todayViewsFilters'+import { todayViewsLogic } from './todayViewsLogic'++/** The Views pane's filters for its recent list, laid out like the Spaces pane's. */+export function TodayViewsFilterMenu(): JSX.Element {+ const { recentFilters: filters, recentFiltersActive: active } = useValues(todayViewsLogic)+ const { setRecentFilters, clearRecentSearchAndFilters } = useActions(todayViewsLogic)++ return (+ <DropdownMenu>+ <TodayFilterMenuTrigger active={active} dataAttr="today-views-filter" />+ <DropdownMenuContent align="end" className="min-w-56">+ <TodayRecentRadioSubmenu+ label="Type"+ options={VIEWS_TYPE_OPTIONS}+ value={filters.type}+ defaultValue={DEFAULT_VIEWS_FILTERS.type}+ onChange={(type) => setRecentFilters({ ...filters, type })}+ dataAttr="today-views-filter-type"+ />+ <TodayRecentRadioSubmenu+ label="Created by"+ options={VIEWS_CREATED_BY_OPTIONS}+ value={filters.createdBy}+ defaultValue={DEFAULT_VIEWS_FILTERS.createdBy}+ onChange={(createdBy) => setRecentFilters({ ...filters, createdBy })}+ dataAttr="today-views-filter-created-by"+ />+ {active && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={clearRecentSearchAndFilters}+ data-attr="today-views-filter-clear"+ >+ Clear filters+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/frontend/src/layout/today/TodayViewsSidebar.tsx b/frontend/src/layout/today/TodayViewsSidebar.tsxnew file mode 100644index 000000000000..7c16bd685bfb--- /dev/null+++ b/frontend/src/layout/today/TodayViewsSidebar.tsx@@ -0,0 +1,175 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconGridMasonry, IconPlus, IconSearch } from '@posthog/icons'+import { Button, Spinner, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'+import { NewViewMenu } from 'scenes/views/NewViewMenu'+import { VIEW_TYPE_INFO } from 'scenes/views/viewsUtils'+import { ViewTypeIcon } from 'scenes/views/ViewTypeIcon'++import { TodayPaneRow } from './TodayPaneRow'+import { TodayPaneSearchField } from './TodayPaneSearchField'+import { TodayPaneSection } from './TodayPaneSection'+import { TodayViewsFilterMenu } from './TodayViewsFilterMenu'+import { todayViewsLogic } from './todayViewsLogic'+import { shortTimeAgo } from './todayWorkItems'++/** The Views sub-nav: a "New" menu, the full list, and the most recent views of every type, newest first. */+export function TodayViewsSidebar(): JSX.Element {+ const {+ recentViews,+ recentItems,+ recentViewsLoading,+ recentUnavailable,+ recentCollapsed,+ recentQuery,+ recentSearchVisible,+ recentFiltersActive,+ buildingViewIds,+ } = useValues(todayViewsLogic)+ const { loadRecentViews, toggleRecent, setRecentQuery, setRecentSearchOpen, clearRecentSearchAndFilters } =+ useActions(todayViewsLogic)+ const narrowed = recentQuery.trim() !== '' || recentFiltersActive+ const { location } = useValues(router)+ const path = removeProjectIdIfPresent(location.pathname)+ const failedTypes = recentViews?.failedTypes ?? []++ const retryButton = (size: 'sm' | 'xs'): JSX.Element => (+ <Button+ size={size}+ variant="outline"+ loading={recentViewsLoading}+ onClick={() => loadRecentViews()}+ data-attr="today-views-retry"+ >+ Try again+ </Button>+ )++ return (+ <div className="TodayPane" data-quill>+ <NewViewMenu+ trigger={<Button variant="primary" size="lg" className="w-full" data-attr="today-views-new" />}+ >+ <IconPlus />+ New…+ </NewViewMenu>+ <div className="TodayPane__scroll">+ <TodayPaneRow+ label="All views"+ icon={<IconGridMasonry />}+ to={urls.views()}+ active={path === urls.views()}+ dataAttr="today-views-all"+ />+ <TodayPaneSection+ label="Recent"+ open={!recentCollapsed}+ count={recentItems.length}+ onToggle={toggleRecent}+ dataAttr="today-views-section-recent"+ heading={+ recentSearchVisible ? (+ <TodayPaneSearchField+ query={recentQuery}+ resultCount={recentItems.length}+ label="Search views"+ onQueryChange={setRecentQuery}+ onClose={() => setRecentSearchOpen(false)}+ dataAttr="today-views-search"+ />+ ) : null+ }+ actions={+ <>+ {!recentSearchVisible && (+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <Button+ size="icon-xs"+ className="text-muted-foreground"+ aria-label="Search views"+ onClick={() => setRecentSearchOpen(true)}+ data-attr="today-views-search-open"+ />+ }+ >+ <IconSearch />+ </TooltipTrigger>+ <TooltipContent>Search views</TooltipContent>+ </Tooltip>+ )}+ <TodayViewsFilterMenu />+ </>+ }+ >+ {!recentViews ? (+ recentUnavailable ? (+ <div className="TodayPane__state">+ <span>Your views didn’t load.</span>+ {retryButton('sm')}+ </div>+ ) : (+ <div className="TodayPane__state" aria-busy>+ <Spinner />+ </div>+ )+ ) : !recentItems.length && narrowed ? (+ <div className="TodayPane__state">+ <span>Nothing here matches.</span>+ <Button+ size="xs"+ variant="outline"+ onClick={() => clearRecentSearchAndFilters()}+ data-attr="today-views-clear-filters"+ >+ Clear filters+ </Button>+ </div>+ ) : !recentItems.length && !failedTypes.length && !recentUnavailable ? (+ <div className="TodayPane__state">+ Canvases, notebooks and dashboards you create show up here.+ </div>+ ) : (+ <>+ {(recentUnavailable || failedTypes.length > 0) && (+ <div className="TodayPane__state">+ <span>+ {recentUnavailable+ ? 'Your views didn’t refresh.'+ : `${failedTypes.map((type) => VIEW_TYPE_INFO[type].pluralLabel).join(' and ')} didn’t load.`}+ </span>+ {retryButton('xs')}+ </div>+ )}+ {recentViews.truncated && (+ <div className="TodayPane__state">+ Some views are not shown. Open All views and use search to find them.+ </div>+ )}+ {recentItems.map((item) => {+ const building = buildingViewIds.includes(item.id)+ return (+ <TodayPaneRow+ key={`${item.type}-${item.id}`}+ label={item.name}+ icon={building ? <Spinner /> : <ViewTypeIcon type={item.type} />}+ meta={building ? 'Building' : shortTimeAgo(item.timestamp)}+ to={item.href}+ active={path === removeProjectIdIfPresent(item.href)}+ dataAttr={`today-views-recent-${item.type}`}+ />+ )+ })}+ </>+ )}+ </TodayPaneSection>+ </div>+ </div>+ )+}diff --git a/frontend/src/layout/today/todayShellLogic.test.ts b/frontend/src/layout/today/todayShellLogic.test.tsindex 0d9d45f1447f..a3de8c99e785 100644--- a/frontend/src/layout/today/todayShellLogic.test.ts+++ b/frontend/src/layout/today/todayShellLogic.test.ts@@ -26,6 +26,11 @@ describe('todayShellLogic', () => {['/project/1/feature_flags', 'library'],['/project/1/data-management/destinations', 'tools'],['/project/1/sql', 'tools'],+ ['/project/1/views', 'views'],+ ['/project/1/canvases/abc', 'views'],+ ['/project/1/canvases/new', 'views'],+ ['/project/1/notebooks/abc', 'views'],+ ['/project/1/dashboard/12', 'views'],['/project/1/airplane', null],['/project/1/homework', null],])('puts %s under %s', (pathname, pane) => {diff --git a/frontend/src/layout/today/todayShellLogic.ts b/frontend/src/layout/today/todayShellLogic.tsindex 9d6f46728694..7af5ebf1a460 100644--- a/frontend/src/layout/today/todayShellLogic.ts+++ b/frontend/src/layout/today/todayShellLogic.ts@@ -14,7 +14,7 @@ import { navigationLogic } from '~/layout/navigation/navigationLogic'import { toolHrefForPath } from './todayToolsLogic'-export type TodayRailPane = 'home' | 'spaces' | 'library' | 'tools'+export type TodayRailPane = 'home' | 'spaces' | 'views' | 'library' | 'tools'export const TODAY_RAIL_WIDTH = 56export const TODAY_SIDEBAR_DEFAULT_WIDTH: number = 312@@ -43,6 +43,14 @@ export function railPaneForPath(pathname: string): TodayRailPane | null {if (isUnder(path, '/ai') || isUnder(path, '/spaces')) {return 'spaces'}+ if (+ isUnder(path, urls.views()) ||+ isUnder(path, '/canvases') ||+ isUnder(path, urls.notebooks()) ||+ isUnder(path, urls.dashboards())+ ) {+ return 'views'+ }if (isUnder(path, urls.library()) || libraryTypeForPath(path)) {return 'library'}@@ -221,6 +229,9 @@ export const todayShellLogic = kea<todayShellLogicType>([if (pane === 'home' && values.routePane !== 'home') {router.actions.push(urls.projectHomepage())}+ if (pane === 'views' && values.routePane !== 'views') {+ router.actions.push(urls.views())+ }if (pane === 'library' && values.routePane !== 'library') {router.actions.push(urls.library())}diff --git a/frontend/src/layout/today/todayToolsLogic.ts b/frontend/src/layout/today/todayToolsLogic.tsindex fcb30b06bf39..0975a6195dbf 100644--- a/frontend/src/layout/today/todayToolsLogic.ts+++ b/frontend/src/layout/today/todayToolsLogic.ts@@ -12,8 +12,8 @@ export interface ToolGroup {tools: FileSystemImport[]}-// Workspaces for building queries and writing things up come first, apart from the product pages.-const PINNED_TOOL_ICONS = ['sql_editor', 'notebook']+// Workspaces for building queries come first, apart from the product pages.+const PINNED_TOOL_ICONS = ['sql_editor']export const PINNED_TOOLS_CATEGORY = 'Workspace'export function toolLabel(tool: FileSystemImport): string {diff --git a/frontend/src/layout/today/todayViewsFilters.ts b/frontend/src/layout/today/todayViewsFilters.tsnew file mode 100644index 000000000000..28d090f6c509--- /dev/null+++ b/frontend/src/layout/today/todayViewsFilters.ts@@ -0,0 +1,39 @@+import { VIEW_TYPES, ViewItem, ViewTypeFilter } from 'scenes/views/viewsUtils'++import { RECENT_CREATED_BY_OPTIONS, TodayRecentCreatedByFilter } from './todayRecentFilters'++export interface TodayViewsFilters {+ type: ViewTypeFilter+ createdBy: TodayRecentCreatedByFilter+}++export const DEFAULT_VIEWS_FILTERS: TodayViewsFilters = { type: 'all', createdBy: 'anyone' }++export const VIEWS_TYPE_OPTIONS: { value: ViewTypeFilter; label: string }[] = [+ { value: 'all', label: 'All' },+ ...VIEW_TYPES.map((info) => ({ value: info.type, label: info.pluralLabel })),+]++export const VIEWS_CREATED_BY_OPTIONS = RECENT_CREATED_BY_OPTIONS++export function viewsFiltersActive(filters: TodayViewsFilters): boolean {+ return filters.type !== DEFAULT_VIEWS_FILTERS.type || filters.createdBy !== DEFAULT_VIEWS_FILTERS.createdBy+}++/** The views that match the search and the filters, in their original order. */+export function filterRecentViews(+ items: ViewItem[],+ query: string,+ filters: TodayViewsFilters,+ currentUserUuid: string | null+): ViewItem[] {+ const needle = query.trim().toLowerCase()+ return items.filter(+ (item) =>+ (!needle || item.name.toLowerCase().includes(needle)) &&+ (filters.type === 'all' || item.type === filters.type) &&+ (filters.createdBy === 'anyone' ||+ // A view with no known creator is neither yours nor someone else's.+ (!!item.createdByUuid && (filters.createdBy === 'me') === (item.createdByUuid === currentUserUuid)))+ )+}diff --git a/frontend/src/layout/today/todayViewsLogic.ts b/frontend/src/layout/today/todayViewsLogic.tsnew file mode 100644index 000000000000..bfd22bcdf801--- /dev/null+++ b/frontend/src/layout/today/todayViewsLogic.ts@@ -0,0 +1,333 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import type { LocationChangedPayload } from 'kea-router/lib/types'++import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'+import { ViewItemsPage, fetchViewItems } from 'scenes/views/fetchViewItems'+import { ViewItem } from 'scenes/views/viewsUtils'++import type { UserType } from '~/types'++import { canvasesRetrieve } from 'products/canvas/frontend/generated/api'+import { tasksRetrieve } from 'products/tasks/frontend/generated/api'++import { railPaneForPath } from './todayShellLogic'+import { DEFAULT_VIEWS_FILTERS, TodayViewsFilters, filterRecentViews, viewsFiltersActive } from './todayViewsFilters'++// The sidebar shows the most recent views of every type in one list. The Views page lists the rest.+const RECENT_LIMIT = 12+const FIRST_BUILD_POLL_MS = 5000+// pinned: task run statuses from the tasks API+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed', 'cancelled'])++/** Whether a canvas on its first build has its first version yet, and where its run is. */+export interface FirstBuildState {+ hasVersion: boolean+ runStatus: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayViewsLogicValues {+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogic+ buildingViewIds: string[]+ firstBuilds: Record<string, FirstBuildState>+ firstBuildsLoading: boolean+ openCanvasBuilding: Record<string, boolean>+ recentCollapsed: boolean+ recentFilters: TodayViewsFilters+ recentFiltersActive: boolean+ recentItems: ViewItem[]+ recentQuery: string+ recentSearchOpen: boolean+ recentSearchVisible: boolean+ recentUnavailable: boolean+ recentViews: ViewItemsPage | null+ recentViewsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayViewsLogicActions {+ clearRecentSearchAndFilters: () => {+ value: true+ }+ loadFirstBuilds: (_: void) => void+ loadFirstBuildsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFirstBuildsSuccess: (+ firstBuilds: {+ [k: string]: FirstBuildState+ },+ payload?: void+ ) => {+ firstBuilds: {+ [k: string]: FirstBuildState+ }+ payload?: void+ }+ loadRecentViews: (_: void) => void+ loadRecentViewsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRecentViewsSuccess: (+ recentViews: ViewItemsPage | null,+ payload?: void+ ) => {+ recentViews: ViewItemsPage | null+ payload?: void+ }+ setOpenCanvasBuilding: (+ canvasId: string,+ building: boolean | null+ ) => {+ building: boolean | null+ canvasId: string+ }+ setRecentFilters: (filters: TodayViewsFilters) => {+ filters: TodayViewsFilters+ }+ setRecentQuery: (query: string) => {+ query: string+ }+ setRecentSearchOpen: (open: boolean) => {+ open: boolean+ }+ toggleRecent: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayViewsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ recentFiltersActive: (recentFilters: TodayViewsFilters) => boolean+ recentSearchVisible: (recentSearchOpen: boolean, recentQuery: string) => boolean+ recentItems: (+ recentViews: ViewItemsPage | null,+ recentQuery: string,+ recentFilters: TodayViewsFilters,+ user: UserType | null+ ) => ViewItem[]+ buildingViewIds: (+ recentViews: ViewItemsPage | null,+ firstBuilds: Record<string, FirstBuildState>,+ openCanvasBuilding: Record<string, boolean>+ ) => string[]+ }+ __keaTypeGenInternalReducerActions: {+ 'location changed (kea.router)': ({+ method,+ pathname,+ search,+ searchParams,+ hash,+ hashParams,+ initial,+ url,+ routerState,+ }: LocationChangedPayload) => {+ payload: {+ hash: string+ hashParams: Record<string, any>+ initial: boolean+ method: 'POP' | 'PUSH' | 'REPLACE'+ pathname: string+ routerState: Record<string, any>+ search: string+ searchParams: Record<string, any>+ url: string+ }+ type: 'location changed (kea.router)'+ }+ }+}++export type todayViewsLogicType = MakeLogicType<+ todayViewsLogicValues,+ todayViewsLogicActions,+ Record<string, any>,+ todayViewsLogicMeta+>++export const todayViewsLogic = kea<todayViewsLogicType>([+ path(['layout', 'today', 'todayViewsLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId'], userLogic, ['user']] })),+ actions({+ toggleRecent: true,+ setRecentQuery: (query: string) => ({ query }),+ setRecentSearchOpen: (open: boolean) => ({ open }),+ setRecentFilters: (filters: TodayViewsFilters) => ({ filters }),+ clearRecentSearchAndFilters: true,+ /** The open canvas reports whether its agent or a build is at work, which it knows exactly. Null when it closes. */+ setOpenCanvasBuilding: (canvasId: string, building: boolean | null) => ({ canvasId, building }),+ }),+ loaders(({ values }) => ({+ recentViews: [+ null as ViewItemsPage | null,+ {+ loadRecentViews: async (_: void, breakpoint) => {+ // Navigation reloads the list, so a burst of route changes costs one request.+ await breakpoint(100)+ if (!values.currentTeamId) {+ return values.recentViews+ }+ const page = await fetchViewItems(String(values.currentTeamId), '')+ breakpoint()+ return page+ },+ },+ ],+ // A canvas on its first build has nothing to show until its first version, so until then its run+ // says whether the agent is building it. Later runs stay open after the agent's turn, so they cannot.+ firstBuilds: [+ {} as Record<string, FirstBuildState>,+ {+ loadFirstBuilds: async (_: void, breakpoint) => {+ const projectId = values.currentTeamId ? String(values.currentTeamId) : null+ const pending = (values.recentViews?.items ?? []).filter((item) => item.firstBuildTaskId)+ if (!projectId || !pending.length) {+ return {}+ }+ const results = await Promise.allSettled(+ pending.map(async (item): Promise<[string, FirstBuildState]> => {+ const [canvas, task] = await Promise.all([+ canvasesRetrieve(projectId, item.id),+ tasksRetrieve(projectId, item.firstBuildTaskId as string),+ ])+ return [+ item.id,+ { hasVersion: !!canvas.current_version_id, runStatus: task.latest_run?.status ?? null },+ ]+ })+ )+ breakpoint()+ // A canvas whose lookup failed shows no spinner rather than holding up the rest.+ return Object.fromEntries(+ results.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))+ )+ },+ },+ ],+ })),+ reducers({+ recentCollapsed: [false, { persist: true }, { toggleRecent: (state) => !state }],+ recentUnavailable: [false, { loadRecentViews: () => false, loadRecentViewsFailure: () => true }],+ recentQuery: ['', { setRecentQuery: (_, { query }) => query, clearRecentSearchAndFilters: () => '' }],+ recentSearchOpen: [+ false,+ { setRecentSearchOpen: (_, { open }) => open, clearRecentSearchAndFilters: () => false },+ ],+ recentFilters: [+ DEFAULT_VIEWS_FILTERS,+ { persist: true },+ {+ setRecentFilters: (_, { filters }) => filters,+ clearRecentSearchAndFilters: () => DEFAULT_VIEWS_FILTERS,+ },+ ],+ openCanvasBuilding: [+ {} as Record<string, boolean>,+ {+ setOpenCanvasBuilding: (state, { canvasId, building }) => {+ const { [canvasId]: _, ...rest } = state+ return building === null ? rest : { ...rest, [canvasId]: building }+ },+ },+ ],+ }),+ selectors({+ recentFiltersActive: [+ (s) => [s.recentFilters],+ (recentFilters: TodayViewsFilters): boolean => viewsFiltersActive(recentFilters),+ ],+ recentSearchVisible: [+ (s) => [s.recentSearchOpen, s.recentQuery],+ (recentSearchOpen: boolean, recentQuery: string): boolean => recentSearchOpen || recentQuery !== '',+ ],+ recentItems: [+ (s) => [s.recentViews, s.recentQuery, s.recentFilters, s.user],+ // The items arrive newest first across every type. A search or filter looks past the first few.+ (+ recentViews: ViewItemsPage | null,+ recentQuery: string,+ recentFilters: TodayViewsFilters,+ user: UserType | null+ ): ViewItem[] => {+ const items = recentViews?.items ?? []+ if (!recentQuery.trim() && !viewsFiltersActive(recentFilters)) {+ return items.slice(0, RECENT_LIMIT)+ }+ return filterRecentViews(items, recentQuery, recentFilters, user?.uuid ?? null)+ },+ ],+ buildingViewIds: [+ (s) => [s.recentViews, s.firstBuilds, s.openCanvasBuilding],+ (+ recentViews: ViewItemsPage | null,+ firstBuilds: Record<string, FirstBuildState>,+ openCanvasBuilding: Record<string, boolean>+ ): string[] =>+ (recentViews?.items ?? [])+ .filter((item) => {+ if (item.id in openCanvasBuilding) {+ return openCanvasBuilding[item.id]+ }+ const firstBuild = firstBuilds[item.id]+ return (+ !!item.firstBuildTaskId &&+ !!firstBuild &&+ !firstBuild.hasVersion &&+ !!firstBuild.runStatus &&+ !TERMINAL_RUN_STATUSES.has(firstBuild.runStatus)+ )+ })+ .map((item) => item.id),+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ loadRecentViewsSuccess: () => {+ actions.loadFirstBuilds()+ },+ loadFirstBuildsSuccess: ({ firstBuilds }) => {+ const building = Object.values(firstBuilds).filter(+ (build) => !build.hasVersion && !!build.runStatus && !TERMINAL_RUN_STATUSES.has(build.runStatus)+ )+ // A first version changes the row, so the list reloads once the build is done.+ if (Object.values(firstBuilds).some((build) => build.hasVersion)) {+ actions.loadRecentViews()+ return+ }+ if (building.length && !values.recentViewsLoading) {+ cache.disposables.add(() => {+ const id = setTimeout(() => actions.loadFirstBuilds(), FIRST_BUILD_POLL_MS)+ return () => clearTimeout(id)+ }, 'firstBuildPoll')+ } else {+ cache.disposables.dispose('firstBuildPoll')+ }+ },+ [router.actionTypes.locationChanged]: ({ pathname }: LocationChangedPayload) => {+ // Creating, restoring or opening a view lands on a new Views path, so the recents stay current.+ // Search and hash changes, such as dashboard filters, keep the path and do not reload.+ if (pathname !== cache.lastPathname && railPaneForPath(pathname) === 'views') {+ actions.loadRecentViews()+ }+ cache.lastPathname = pathname+ },+ })),+ afterMount(({ actions, cache }) => {+ cache.lastPathname = router.values.location.pathname+ actions.loadRecentViews()+ }),+])diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 2eb15d83fd0c..cf5b5b28814e 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -56,6 +56,8 @@ export const productScenes: Record<string, () => Promise<any>> = {import('../../products/business_knowledge/frontend/scenes/settings/BusinessKnowledgeSettingsScene'),BusinessKnowledgeSource: () =>import('../../products/business_knowledge/frontend/scenes/source/KnowledgeSourceScene'),+ CanvasNew: () => import('../../products/canvas/frontend/newCanvas/CanvasNewScene'),+ CanvasDetail: () => import('../../products/canvas/frontend/scene/CanvasScene'),Transformations: () => import('../../frontend/src/scenes/data-pipelines/TransformationsScene'),EventFiltering: () => import('../../frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene'),CohortsStaffTools: () => import('../../products/cohorts/frontend/staff/CohortsStaffToolsScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex cfbe83b77c36..307c62f9e6d9 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -116,6 +116,8 @@ export const productRoutes: Record<string, [string, string]> = {'/business-knowledge/playground': ['BusinessKnowledgePlayground', 'businessKnowledgePlayground'],'/business-knowledge/playground/:chatId': ['BusinessKnowledgePlayground', 'businessKnowledgePlayground'],'/business-knowledge/:id': ['BusinessKnowledgeSource', 'businessKnowledgeSource'],+ '/canvases/new': ['CanvasNew', 'canvasNew'],+ '/canvases/:id': ['CanvasDetail', 'canvasDetail'],'/transformations': ['Transformations', 'transformations'],'/event-filtering': ['EventFiltering', 'eventFiltering'],'/feature_flags/staff/cohorts': ['CohortsStaffTools', 'cohortsStaffTools'],@@ -687,6 +689,8 @@ export const productConfiguration: Record<string, any> = {activityScope: 'KnowledgeSource',iconType: 'business_knowledge',},+ CanvasNew: { name: 'New canvas', projectBased: true, layout: 'app-raw' },+ CanvasDetail: { name: 'Canvas', projectBased: true, layout: 'app-full-scene-height' },Transformations: {projectBased: true,name: 'Transformations',@@ -1311,6 +1315,9 @@ export const productUrls = {businessKnowledgePlayground: (chatId?: string): string =>chatId ? `/business-knowledge/playground/${chatId}` : '/business-knowledge/playground',businessKnowledgeSource: (id: string): string => `/business-knowledge/${id}`,+ canvasNew: (spaceId?: string | null): string =>+ spaceId ? `/canvases/new?space=${encodeURIComponent(spaceId)}` : '/canvases/new',+ canvasDetail: (id: string): string => `/canvases/${id}`,transformations: (): string => '/transformations',eventFiltering: (): string => '/event-filtering',cohort: (id: string | number): string => `/cohorts/${id}`,diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.tsindex edf1f79541fe..02539c342e7d 100644--- a/frontend/src/scenes/appScenes.ts+++ b/frontend/src/scenes/appScenes.ts@@ -78,6 +78,7 @@ export const appScenes: Record<Scene | string, () => any> = {[Scene.ProjectCreateFirst]: () => import('./project/Create'),[Scene.ProjectHomepage]: () => import('./project-homepage/ProjectHomepage'),[Scene.Library]: () => import('./library/Library'),+ [Scene.Views]: () => import('./views/Views'),[Scene.PropertyDefinitionEdit]: () => import('./data-management/definition/DefinitionEdit'),[Scene.PropertyDefinition]: () => import('./data-management/definition/DefinitionView'),[Scene.SqlVariableEdit]: () => import('./data-management/variables/SqlVariableEditScene'),diff --git a/frontend/src/scenes/library/libraryLogic.ts b/frontend/src/scenes/library/libraryLogic.tsindex e7425d5b1369..d8097586f7c7 100644--- a/frontend/src/scenes/library/libraryLogic.ts+++ b/frontend/src/scenes/library/libraryLogic.ts@@ -1,6 +1,6 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { urlToAction } from 'kea-router'+import { router, urlToAction } from 'kea-router'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'@@ -10,17 +10,11 @@ import { urls } from 'scenes/urls'import { fileSystemTypes, getTreeItemsNew } from '~/products'import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'-import {- LibraryObjectType,- TOOL_FILE_SYSTEM_TYPES,- baseObjectType,- isToolEntry,- sortLibraryTypes,-} from './libraryUtils'+import { LibraryObjectType, baseObjectType, isLibraryEntry, isLibraryType, sortLibraryTypes } from './libraryUtils'export const LIBRARY_PAGE_SIZE = 50-// "All objects" drops tool entries after each page loads, so it reads ahead until a page has something-// to show. This caps how far it reads ahead in one go.+// "All objects" drops tool and view entries after each page loads, so it reads ahead until a page has+// something to show. This caps how far it reads ahead in one go.const MAX_PAGES_PER_LOAD = 5const PLURAL_LABELS: Record<string, string> = {@@ -147,7 +141,7 @@ export const libraryLogic = kea<libraryLogicType>([results.push(...next.results)count = next.countconst exhausted = next.results.length === 0 || offset + results.length >= count- if (exhausted || values.objectType || results.some((entry) => !isToolEntry(entry))) {+ if (exhausted || values.objectType || results.some(isLibraryEntry)) {break}}@@ -190,7 +184,7 @@ export const libraryLogic = kea<libraryLogicType>([Object.entries(fileSystemTypes).filter(([type, entry]) =>- !TOOL_FILE_SYSTEM_TYPES.has(type) &&+ isLibraryType(type) &&(!('flag' in entry) || !!featureFlags[entry.flag as keyof FeatureFlagsSet])).map(([value, entry]) => ({@@ -219,10 +213,10 @@ export const libraryLogic = kea<libraryLogicType>([return byType},],- // "All objects" asks for every type, so drop the ones that live in Tools.+ // "All objects" asks for every type, so drop the ones that live in Tools and Views.visibleObjects: [(s) => [s.objects],- (objects: LibraryObjects): FileSystemEntry[] => objects.results.filter((entry) => !isToolEntry(entry)),+ (objects: LibraryObjects): FileSystemEntry[] => objects.results.filter(isLibraryEntry),],hasMore: [(s) => [s.objects], (objects: LibraryObjects): boolean => objects.results.length < objects.count],}),@@ -236,6 +230,10 @@ export const libraryLogic = kea<libraryLogicType>([if (!values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {return}+ if (objectType && !isLibraryType(objectType)) {+ router.actions.replace(urls.views())+ return+ }if (objectType !== values.objectType || !cache.loaded) {cache.loaded = trueactions.setObjectType(objectType)diff --git a/frontend/src/scenes/library/libraryUtils.test.ts b/frontend/src/scenes/library/libraryUtils.test.tsindex 81e3583e7965..313c37865d45 100644--- a/frontend/src/scenes/library/libraryUtils.test.ts+++ b/frontend/src/scenes/library/libraryUtils.test.ts@@ -1,6 +1,15 @@-import { libraryObjectHref, libraryObjectName, libraryTypeForPath } from './libraryUtils'+import { isLibraryType, libraryObjectHref, libraryObjectName, libraryTypeForPath } from './libraryUtils'describe('libraryUtils', () => {+ test.each([+ ['insight', true],+ ['feature_flag', true],+ ['dashboard', false],+ ['notebook', false],+ ['task', false],+ ])('lists %s in Library: %s', (type, listed) => {+ expect(isLibraryType(type as string)).toBe(listed)+ })test.each([['Unfiled/Insights/Checkout funnel', 'Checkout funnel'],['Unfiled/Insights/Signups a\\/b test', 'Signups a/b test'],@@ -23,7 +32,7 @@ describe('libraryUtils', () => {['/workflows/abc/workflow', 'workflows'],['/replay/playlists/abc', 'session_recording_playlist'],['/feature_flags', 'feature_flag'],- ['/dashboard', 'dashboard'],+ ['/dashboard', null],['/data-management/actions', 'action'],['/feature_flags/templates', null],['/workflows/library/templates/new', null],diff --git a/frontend/src/scenes/library/libraryUtils.ts b/frontend/src/scenes/library/libraryUtils.tsindex cd4214b0da99..498bbfe5726b 100644--- a/frontend/src/scenes/library/libraryUtils.ts+++ b/frontend/src/scenes/library/libraryUtils.ts@@ -4,10 +4,12 @@ import { fileSystemTypes, getTreeItemsMetadata, getTreeItemsProducts } from '~/pimport { FileSystemEntry } from '~/queries/schema/schema-general'// These file system types are working pages rather than saved objects, so they belong to Tools.-export const TOOL_FILE_SYSTEM_TYPES = new Set(['endpoints', 'live_debugger', 'notebook', 'task'])+export const TOOL_FILE_SYSTEM_TYPES = new Set(['endpoints', 'live_debugger', 'task'])+// These file system types are views people open and read, so they belong to Views, next to canvases.+export const VIEW_FILE_SYSTEM_TYPES = new Set(['dashboard', 'notebook'])// The objects people reach for most come first. Any other type follows in name order.-const LIBRARY_TYPE_ORDER = ['insight', 'dashboard', 'feature_flag', 'experiment', 'survey', 'cohort', 'action']+const LIBRARY_TYPE_ORDER = ['insight', 'feature_flag', 'experiment', 'survey', 'cohort', 'action']export interface LibraryObjectType {value: string@@ -21,8 +23,13 @@ export function baseObjectType(type: string | undefined): string {return type?.split('/')[0] ?? ''}-export function isToolEntry(entry: Pick<FileSystemEntry, 'type'>): boolean {- return TOOL_FILE_SYSTEM_TYPES.has(baseObjectType(entry.type))+/** Whether a file system type shows in Library, rather than in Tools or Views. */+export function isLibraryType(type: string): boolean {+ return !TOOL_FILE_SYSTEM_TYPES.has(type) && !VIEW_FILE_SYSTEM_TYPES.has(type)+}++export function isLibraryEntry(entry: Pick<FileSystemEntry, 'type'>): boolean {+ return isLibraryType(baseObjectType(entry.type))}/** The page a saved object opens, from the entry itself or from its type's registered URL. */@@ -72,7 +79,7 @@ export function libraryTypeForPath(path: string): string | null {if (!objectTypeByScene) {const scenes = new Map<string, string>()const addPage = (type: string, href: string | undefined): void => {- const scene = href && !TOOL_FILE_SYSTEM_TYPES.has(type) ? sceneForPath(href) : null+ const scene = href && isLibraryType(type) ? sceneForPath(href) : nullif (scene && !scenes.has(scene)) {scenes.set(scene, type)}diff --git a/frontend/src/scenes/max/testUtils.ts b/frontend/src/scenes/max/testUtils.tsindex fbf7a0a23a3f..ed5dc94efcc7 100644--- a/frontend/src/scenes/max/testUtils.ts+++ b/frontend/src/scenes/max/testUtils.ts@@ -9,6 +9,7 @@ import { Conversation, ConversationStatus, ConversationType } from '~/types'export const maxMocks: Mocks = {get: {+ '/api/billing/usage/team_options/': { team_id_options: [] },'/api/environments/:team_id/conversations/': { results: [] },},post: {diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsxindex e395a0365bc2..fa6d620a5c39 100644--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx@@ -18,6 +18,7 @@ import { TodaySpaceHoverCard } from '~/layout/today/TodaySpaceHoverCard'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { sessionItem } from '~/layout/today/todayWorkItems'import { mswDecorator } from '~/mocks/browser'+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'import { makeReport, mockSignals } from 'products/signals/frontend/inbox/__mocks__/inboxMocks'import { reportMetricQueryHandler } from 'products/signals/frontend/inbox/__mocks__/reportMetricMocks'@@ -226,6 +227,55 @@ const LIBRARY = [{ id: 'fs-3', path: 'Unfiled/Feature flags/one-page-checkout', type: 'feature_flag', ref: '7' },]+const USER = { id: 1, uuid: 'user-1', first_name: 'Ada', email: '[email protected]' }++const VIEW_CANVASES = [+ {+ id: 'canvas-1',+ name: 'Checkout health board',+ kind: 'freeform',+ channel: 'space-checkout',+ updated_at: '2026-09-28T17:50:00Z',+ current_version_id: 'version-1',+ generation_task_id: null,+ },+ {+ id: 'canvas-building',+ name: 'Signup funnel by country',+ kind: 'freeform',+ channel: 'space-checkout',+ updated_at: '2026-09-28T18:05:00Z',+ current_version_id: null,+ generation_task_id: 'task-canvas-building',+ },+ {+ id: 'canvas-2',+ name: 'Weekly growth widgets',+ kind: 'grid',+ channel: 'space-general',+ updated_at: '2026-09-26T08:15:00Z',+ current_version_id: 'version-1',+ generation_task_id: null,+ },+].map((canvas) => ({ description: '', pinned: false, created_by: USER, created_at: canvas.updated_at, ...canvas }))++const NOTEBOOKS = [+ { short_id: 'nb-1', title: 'Trial drop-off investigation', last_modified_at: '2026-09-28T12:30:00Z' },+ { short_id: 'nb-2', title: 'Q3 pricing research notes', last_modified_at: '2026-09-20T10:00:00Z' },+].map((notebook) => ({+ id: notebook.short_id,+ deleted: false,+ created_at: notebook.last_modified_at,+ created_by: USER,+ last_modified_by: USER,+ ...notebook,+}))++const DASHBOARDS = [+ { id: 12, name: 'Growth overview', last_viewed_at: '2026-09-28T09:00:00Z', created_at: '2026-08-01T09:00:00Z' },+ { id: 13, name: 'Billing and revenue', last_viewed_at: null, created_at: '2026-09-24T09:00:00Z' },+].map((dashboard) => ({ description: '', pinned: false, deleted: false, tags: [], created_by: USER, ...dashboard }))+const REPORTS = [makeReport({id: 'report-1',@@ -461,8 +511,13 @@ const meta: Meta = {return [200, { results, count: results.length, next: null, previous: null }]},'/api/projects/:team_id/canvases/': ({ request }) => {- const results =- new URL(request.url).searchParams.get('channel') === 'space-checkout' ? CANVASES : []+ const params = new URL(request.url).searchParams+ const channel = params.get('channel')+ const results = channel+ ? channel === 'space-checkout'+ ? CANVASES+ : []+ : VIEW_CANVASES.filter((canvas) => canvas.kind === params.get('kind'))return [200, { results, count: results.length, next: null, previous: null }]},'/api/projects/:team_id/task_activity/': {@@ -490,6 +545,14 @@ const meta: Meta = {return [200, { results, count: results.length }]},'/api/environments/:team_id/file_system/unfiled/': { results: [], count: 0 },+ '/api/projects/:team_id/canvases/canvas-building/': VIEW_CANVASES[1],+ '/api/projects/:team_id/tasks/task-canvas-building/': {+ id: 'task-canvas-building',+ title: 'Signup funnel by country',+ latest_run: { id: 'run-canvas-building', status: 'in_progress' },+ },+ '/api/projects/:team_id/notebooks/': { results: NOTEBOOKS, count: NOTEBOOKS.length },+ '/api/projects/:team_id/dashboards/': { results: DASHBOARDS, count: DASHBOARDS.length },},post: {'/api/projects/:team_id/tasks/summaries/': {@@ -846,3 +909,27 @@ export const ListItemAppearanceDialog: Story = {await within(document.body).findByText('Edit list item appearance')},}++export const ViewsAll: Story = {+ parameters: { pageUrl: urls.views() },+}++export const ViewsEmpty: Story = {+ parameters: { pageUrl: urls.views() },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/canvases/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/notebooks/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/dashboards/': EMPTY_PAGINATED_RESPONSE,+ },+ }),+ ],+}++export const ViewsNewMenu: Story = {+ parameters: { pageUrl: urls.views() },+ play: async ({ canvasElement }) => {+ await userEvent.click(await within(canvasElement).findByText('New…'))+ },+}diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 88a139768f67..c7cbf6b60048 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -104,6 +104,7 @@ export enum Scene {LegalDocuments = 'LegalDocuments',LegalDocumentNew = 'LegalDocumentNew',Library = 'Library',+ Views = 'Views',Link = 'Link',Links = 'Links',LiveDebugger = 'LiveDebugger',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex 908627018d4c..8d35a17cc156 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -336,6 +336,10 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {projectBased: true,name: 'Library',},+ [Scene.Views]: {+ projectBased: true,+ name: 'Views',+ },[Scene.PropertyDefinitionEdit]: {projectBased: true,name: 'Data management',@@ -832,6 +836,7 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.todayReport(':reportId')]: [Scene.ProjectHomepage, 'todayReport'],[urls.library()]: [Scene.Library, 'library'],[urls.library(':objectType')]: [Scene.Library, 'libraryObjectType'],+ [urls.views()]: [Scene.Views, 'views'],[urls.aiHistory()]: [Scene.Max, 'maxHistory'],[urls.ai()]: [Scene.Max, 'max'],[urls.projectCreateFirst()]: [Scene.ProjectCreateFirst, 'projectCreateFirst'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 3c6f4b81a234..637874720bb0 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -169,6 +169,7 @@ export const urls = {projectHomepage: (): string => '/home',todayReport: (reportId: string): string => `/home/reports/${reportId}`,library: (objectType?: string): string => (objectType ? `/library/${objectType}` : '/library'),+ views: (): string => '/views',ai: (chat?: string, ask?: string): string => combineUrl('/ai', { ask, chat }).url,aiTask: (taskId: string): string => combineUrl('/ai', { task: taskId }).url,aiHistory: (): string => '/ai/history',diff --git a/frontend/src/scenes/views/NewViewMenu.tsx b/frontend/src/scenes/views/NewViewMenu.tsxnew file mode 100644index 000000000000..0ca93653740a--- /dev/null+++ b/frontend/src/scenes/views/NewViewMenu.tsx@@ -0,0 +1,48 @@+import { useActions } from 'kea'++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ ItemContent,+ ItemDescription,+ ItemTitle,+} from '@posthog/quill'++import { newViewLogic } from './newViewLogic'+import { VIEW_TYPES } from './viewsUtils'+import { ViewTypeIcon } from './ViewTypeIcon'++interface NewViewMenuProps {+ /** The element that opens the menu, such as a quill `Button`. The menu merges its own props onto it. */+ trigger: JSX.Element+ children?: React.ReactNode+}++/** Asks which type of view to create, then hands off to that type's own create flow. */+export function NewViewMenu({ trigger, children }: NewViewMenuProps): JSX.Element {+ const { pickNewViewType } = useActions(newViewLogic)++ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={trigger}>{children}</DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-72">+ {VIEW_TYPES.map((info) => (+ <DropdownMenuItem+ key={info.type}+ className="h-auto items-start py-1.5 whitespace-normal [&>svg]:mt-0.5"+ onClick={() => pickNewViewType(info.type)}+ data-attr={`views-new-${info.type}`}+ >+ <ViewTypeIcon type={info.type} />+ <ItemContent variant="menuItem">+ <ItemTitle>{info.label}</ItemTitle>+ <ItemDescription>{info.description}</ItemDescription>+ </ItemContent>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/frontend/src/scenes/views/ViewRow.tsx b/frontend/src/scenes/views/ViewRow.tsxnew file mode 100644index 000000000000..fa2049359a17--- /dev/null+++ b/frontend/src/scenes/views/ViewRow.tsx@@ -0,0 +1,36 @@+import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'+import { LinkPrimitive } from 'lib/lemon-ui/Link'++import { VIEW_TYPE_INFO, ViewItem } from './viewsUtils'+import { ViewTypeIcon } from './ViewTypeIcon'++/** One view in the Views list: its type, name, space and when it last changed. The whole row opens the view. */+export function ViewRow({ view }: { view: ViewItem }): JSX.Element {+ const meta = [+ VIEW_TYPE_INFO[view.type].label,+ view.spaceName && `#${view.spaceName}`,+ view.timestamp && `${view.timestampLabel} ${dayjs(view.timestamp).fromNow()}`,+ ]+ .filter(Boolean)+ .join(' · ')++ return (+ <Item+ variant="outline"+ size="sm"+ // The app styles every link in its accent color. A whole-row link reads as a row, so it keeps the text color.+ className="text-foreground hover:bg-fill-button-tertiary-hover hover:text-foreground"+ render={<LinkPrimitive to={view.href} data-attr={`views-row-${view.type}`} />}+ >+ <ItemMedia variant="icon" aria-hidden>+ <ViewTypeIcon type={view.type} />+ </ItemMedia>+ <ItemContent className="min-w-0">+ <ItemTitle className="truncate">{view.name}</ItemTitle>+ <ItemDescription className="truncate">{meta}</ItemDescription>+ </ItemContent>+ </Item>+ )+}diff --git a/frontend/src/scenes/views/ViewTypeIcon.tsx b/frontend/src/scenes/views/ViewTypeIcon.tsxnew file mode 100644index 000000000000..49b0da5f0ff3--- /dev/null+++ b/frontend/src/scenes/views/ViewTypeIcon.tsx@@ -0,0 +1,8 @@+import { IconDashboard, IconNotebook, IconPalette } from '@posthog/icons'++import { ViewType } from './viewsUtils'++/** The icon that marks a view's type in lists, menus and the sidebar. */+export function ViewTypeIcon({ type }: { type: ViewType }): JSX.Element {+ return type === 'canvas' ? <IconPalette /> : type === 'notebook' ? <IconNotebook /> : <IconDashboard />+}diff --git a/frontend/src/scenes/views/Views.tsx b/frontend/src/scenes/views/Views.tsxnew file mode 100644index 000000000000..1e14c735b782--- /dev/null+++ b/frontend/src/scenes/views/Views.tsx@@ -0,0 +1,197 @@+import { useActions, useValues } from 'kea'++import { IconGridMasonry, IconPlus, IconSearch } from '@posthog/icons'+import {+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,+ Item,+ ItemContent,+ ItemGroup,+ ItemMedia,+ Skeleton,+ Text,+ ToggleGroup,+ ToggleGroupItem,+} from '@posthog/quill'++import { NotFound } from 'lib/components/NotFound'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { NewViewMenu } from './NewViewMenu'+import { ViewRow } from './ViewRow'+import { viewsLogic } from './viewsLogic'+import { VIEW_TYPES, VIEW_TYPE_INFO, ViewTypeFilter } from './viewsUtils'++export const scene: SceneExport = {+ component: Views,+ logic: viewsLogic,+}++const TYPE_FILTERS: { value: ViewTypeFilter; label: string }[] = [+ { value: 'all', label: 'All' },+ ...VIEW_TYPES.map((info) => ({ value: info.type, label: info.pluralLabel })),+]++/** Canvases, notebooks and dashboards in one list. */+export function Views(): JSX.Element {+ const viewsEnabled = useFeatureFlag('TODAY_RAIL_NAV')+ // The page ships behind the Today navigation, so without the flag `/views` stays a missing page.+ return viewsEnabled ? <ViewsContent /> : <NotFound object="page" />+}++function ViewsContent(): JSX.Element {+ const { views, visibleViews, viewsLoading, loadFailed, search, typeFilter } = useValues(viewsLogic)+ const { setSearch, setTypeFilter, loadViews } = useActions(viewsLogic)+ const failedTypes = views?.failedTypes ?? []++ const newViewButton = (+ <NewViewMenu trigger={<Button variant="primary" size="sm" data-attr="views-new" />}>+ <IconPlus />+ New view+ </NewViewMenu>+ )++ const renderList = (): JSX.Element => {+ if (!views) {+ return loadFailed ? (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>Couldn’t load your views</EmptyTitle>+ <EmptyDescription>Try again, and if it keeps happening contact support.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button+ variant="outline"+ loading={viewsLoading}+ onClick={() => loadViews()}+ data-attr="views-retry"+ >+ Try again+ </Button>+ </EmptyContent>+ </Empty>+ ) : (+ <ItemGroup combined aria-busy aria-label="Loading your views">+ {Array.from({ length: 6 }, (_, index) => (+ <Item key={index} variant="outline" size="sm">+ <ItemMedia variant="icon">+ <Skeleton className="size-4" />+ </ItemMedia>+ <ItemContent className="gap-1.5">+ <Skeleton className="h-3.5 w-48 max-w-full" />+ <Skeleton className="h-3 w-32 max-w-full" />+ </ItemContent>+ </Item>+ ))}+ </ItemGroup>+ )+ }+ if (!visibleViews.length) {+ const filterLabel = typeFilter === 'all' ? 'views' : VIEW_TYPE_INFO[typeFilter].pluralLabel.toLowerCase()+ return (+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <IconGridMasonry />+ </EmptyMedia>+ <EmptyTitle>{search ? 'Nothing matches that search' : `No ${filterLabel} yet`}</EmptyTitle>+ <EmptyDescription>+ {search+ ? 'Try a different name, or clear the search.'+ : 'Canvases, notebooks and dashboards you create show up here.'}+ </EmptyDescription>+ </EmptyHeader>+ {!search && <EmptyContent>{newViewButton}</EmptyContent>}+ </Empty>+ )+ }+ return (+ <ItemGroup combined>+ {visibleViews.map((view) => (+ <ViewRow key={`${view.type}-${view.id}`} view={view} />+ ))}+ </ItemGroup>+ )+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name="Views"+ description="Canvases, notebooks and dashboards in this project."+ resourceType={{ type: 'views', forceIcon: <IconGridMasonry /> }}+ actions={<div data-quill>{newViewButton}</div>}+ />+ <div data-quill className="@container/views flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <InputGroup className="min-w-48 flex-1">+ <InputGroupAddon align="inline-start">+ <InputGroupText>+ <IconSearch />+ </InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ type="search"+ aria-label="Search views"+ placeholder="Search views"+ value={search}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}+ data-attr="views-search"+ />+ </InputGroup>+ <ToggleGroup+ size="sm"+ aria-label="Filter by type"+ value={[typeFilter]}+ onValueChange={(value: string[]) => value[0] && setTypeFilter(value[0] as ViewTypeFilter)}+ >+ {TYPE_FILTERS.map((filter) => (+ <ToggleGroupItem key={filter.value} value={filter.value} data-attr="views-type-filter">+ {filter.label}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ </div>+ {views && (loadFailed || failedTypes.length > 0) && (+ <div className="flex flex-wrap items-center gap-2" role="alert">+ <Text size="sm" variant="destructive">+ {loadFailed+ ? 'Couldn’t refresh your views, so this list may be out of date.'+ : `${failedTypes+ .map((type) => VIEW_TYPE_INFO[type].pluralLabel)+ .join(' and ')} didn’t load, so this list may be incomplete.`}+ </Text>+ <Button+ variant="outline"+ size="xs"+ loading={viewsLoading}+ onClick={() => loadViews()}+ data-attr="views-retry"+ >+ Try again+ </Button>+ </div>+ )}+ {views?.truncated && (+ <Text size="sm" variant="muted">+ Some views are not shown. Use search to find more views.+ </Text>+ )}+ {renderList()}+ </div>+ </SceneContent>+ )+}diff --git a/frontend/src/scenes/views/fetchViewItems.test.ts b/frontend/src/scenes/views/fetchViewItems.test.tsnew file mode 100644index 000000000000..3d40298dcf8b--- /dev/null+++ b/frontend/src/scenes/views/fetchViewItems.test.ts@@ -0,0 +1,51 @@+import { useMocks } from '~/mocks/jest'++import { fetchViewItems } from './fetchViewItems'++describe('fetchViewItems', () => {+ it('bounds pagination and marks an incomplete list', async () => {+ let requests = 0+ useMocks({+ get: {+ '/api/projects/:team_id/canvases/': { results: [], next: null },+ '/api/projects/:team_id/notebooks/': { results: [], next: null },+ '/api/projects/:team_id/task_channels/': [],+ '/api/projects/:team_id/dashboards/': () => {+ requests += 1+ return {+ results: [{ id: requests, name: 'Dashboard', created_at: '2026-01-01' }],+ next: requests < 8 ? `?offset=${requests}` : null,+ }+ },+ },+ })+ const page = await fetchViewItems('1', '')+ expect(requests).toBe(5)+ expect(page.truncated).toBe(true)+ })++ it('includes recent dashboards from later pages', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/canvases/': { results: [], next: null },+ '/api/projects/:team_id/notebooks/': { results: [], next: null },+ '/api/projects/:team_id/task_channels/': [],+ '/api/projects/:team_id/dashboards/': ({ request }) => {+ const offset = new URL(request.url).searchParams.get('offset')+ return offset === '0'+ ? {+ results: [{ id: 1, name: 'A', created_at: '2026-01-01', last_viewed_at: '2026-01-01' }],+ next: '?offset=1',+ }+ : {+ results: [{ id: 2, name: 'Z', created_at: '2026-01-01', last_viewed_at: '2026-01-02' }],+ next: null,+ }+ },+ },+ })+ const page = await fetchViewItems('1', '')+ expect(page.failedTypes).toEqual([])+ expect(page.items.map((item) => item.id)).toEqual(['2', '1'])+ })+})diff --git a/frontend/src/scenes/views/fetchViewItems.ts b/frontend/src/scenes/views/fetchViewItems.tsnew file mode 100644index 000000000000..df8466145078--- /dev/null+++ b/frontend/src/scenes/views/fetchViewItems.ts@@ -0,0 +1,91 @@+import { spaceLabel } from '~/layout/today/todaySpacesLogic'++import { canvasesList } from 'products/canvas/frontend/generated/api'+import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'+import { dashboardsList } from 'products/dashboards/frontend/generated/api'+import { notebooksList } from 'products/notebooks/frontend/generated/api'+import type { NotebooksListParams } from 'products/notebooks/frontend/generated/api.schemas'+import { taskChannelsList } from 'products/tasks/frontend/generated/api'+import type { ChannelDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import { LISTED_CANVAS_KINDS, ViewItem, ViewType, mergeViews } from './viewsUtils'++const VIEWS_PAGE_SIZE = 100+const MAX_VIEW_PAGES = 5++export interface ViewItemsPage {+ items: ViewItem[]+ /** Types whose request failed. The list holds the other types only. */+ failedTypes: ViewType[]+ truncated?: boolean+}++async function fetchViewPages<T>(+ fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>+): Promise<{ items: T[]; truncated: boolean }> {+ const results: T[] = []+ let page+ for (let pageIndex = 0; pageIndex < MAX_VIEW_PAGES; pageIndex++) {+ page = await fetchPage(results.length)+ results.push(...page.results)+ if (!page.next || page.results.length === 0) {+ return { items: results, truncated: false }+ }+ }+ return { items: results, truncated: true }+}++async function fetchCanvases(+ projectId: string,+ search: string | undefined,+ limit: number+): Promise<{ items: CanvasApi[]; truncated: boolean }> {+ const pages = await Promise.all(+ LISTED_CANVAS_KINDS.map((kind) =>+ fetchViewPages((offset) => canvasesList(projectId, { kind, search, limit, offset }))+ )+ )+ return { items: pages.flatMap((page) => page.items), truncated: pages.some((page) => page.truncated) }+}++async function fetchSpaceNames(projectId: string): Promise<Record<string, string>> {+ const response = await taskChannelsList(projectId)+ // Without `limit` the endpoint answers with a bare array rather than a page.+ const spaces = Array.isArray(response) ? (response as ChannelDTOApi[]) : response.results+ return Object.fromEntries(spaces.map((space) => [space.id, spaceLabel(space)]))+}++/** Canvases, notebooks and dashboards in one list. A type that fails to load leaves the others in place. */+export async function fetchViewItems(projectId: string, search: string): Promise<ViewItemsPage> {+ const limit = VIEWS_PAGE_SIZE+ const query = search.trim() || undefined+ // The notebooks endpoint filters on `search`, but its schema does not declare the parameter.+ const notebookParams: NotebooksListParams & { search?: string } = { limit, search: query }+ const [canvases, notebooks, dashboards, spaceNames] = await Promise.allSettled([+ fetchCanvases(projectId, query, limit),+ fetchViewPages((offset) => notebooksList(projectId, { ...notebookParams, offset })),+ fetchViewPages((offset) => dashboardsList(projectId, { search: query, limit, offset })),+ fetchSpaceNames(projectId),+ ])+ const failedTypes: ViewType[] = [+ ...(canvases.status === 'rejected' ? (['canvas'] as const) : []),+ ...(notebooks.status === 'rejected' ? (['notebook'] as const) : []),+ ...(dashboards.status === 'rejected' ? (['dashboard'] as const) : []),+ ]+ if (failedTypes.length === 3) {+ throw canvases.status === 'rejected' ? canvases.reason : new Error('Views did not load')+ }+ return {+ items: mergeViews({+ canvases: canvases.status === 'fulfilled' ? canvases.value.items : [],+ notebooks: notebooks.status === 'fulfilled' ? notebooks.value.items : [],+ dashboards: dashboards.status === 'fulfilled' ? dashboards.value.items : [],+ // Without space names, canvas rows still show. They only lose the space label.+ spaceNames: spaceNames.status === 'fulfilled' ? spaceNames.value : {},+ }),+ failedTypes,+ truncated: [canvases, notebooks, dashboards].some(+ (result) => result.status === 'fulfilled' && result.value.truncated+ ),+ }+}diff --git a/frontend/src/scenes/views/newViewLogic.ts b/frontend/src/scenes/views/newViewLogic.tsnew file mode 100644index 000000000000..fc2dab06c0a3--- /dev/null+++ b/frontend/src/scenes/views/newViewLogic.ts@@ -0,0 +1,52 @@+import { MakeLogicType, actions, kea, listeners, path } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { toast } from '@posthog/quill'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'++import { canvasSceneLogic } from 'products/canvas/frontend/scene/canvasSceneLogic'++import { ViewType, newCanvasSpaceIdForPath } from './viewsUtils'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newViewLogicActions {+ pickNewViewType: (type: ViewType) => {+ type: ViewType+ }+}++export type newViewLogicType = MakeLogicType<{}, newViewLogicActions>++/** Hands a "New view" pick to the flow that creates that type. */+export const newViewLogic = kea<newViewLogicType>([+ path(['scenes', 'views', 'newViewLogic']),+ actions({+ pickNewViewType: (type: ViewType) => ({ type }),+ }),+ listeners(() => ({+ pickNewViewType: ({ type }) => {+ // pinned: analytics event name and property. Renaming them breaks dashboards.+ posthog.capture('views new picked', { type })+ if (type === 'canvas') {+ const pathname = removeProjectIdIfPresent(router.values.location.pathname)+ const canvasId = /^\/canvases\/([^/]+)$/.exec(pathname)?.[1]+ const canvas = canvasId ? canvasSceneLogic.findMounted({ id: canvasId })?.values.canvas : null+ if (canvasId && canvasId !== 'new' && !canvas) {+ toast.error({ title: 'Wait for the canvas to load, then try again.' })+ return+ }+ const spaceId = newCanvasSpaceIdForPath(pathname, canvas ?? null)+ router.actions.push(urls.canvasNew(spaceId))+ } else if (type === 'notebook') {+ router.actions.push(urls.notebook('new'))+ } else {+ // The dashboards page opens its new-dashboard dialog from this hash. Some scenes already host+ // that dialog, so a second host in the shell would open it twice on those pages.+ router.actions.push(`${urls.dashboards()}#newDashboard=modal`)+ }+ },+ })),+])diff --git a/frontend/src/scenes/views/viewsLogic.ts b/frontend/src/scenes/views/viewsLogic.tsnew file mode 100644index 000000000000..9cd2e45a538f--- /dev/null+++ b/frontend/src/scenes/views/viewsLogic.ts@@ -0,0 +1,124 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { ViewItemsPage, fetchViewItems } from './fetchViewItems'+import { ViewItem, ViewTypeFilter, filterViews } from './viewsUtils'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface viewsLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentTeamId: number | null // teamLogic+ loadFailed: boolean+ search: string+ typeFilter: ViewTypeFilter+ views: ViewItemsPage | null+ viewsLoading: boolean+ visibleViews: ViewItem[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface viewsLogicActions {+ loadViews: (_: void) => void+ loadViewsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadViewsSuccess: (+ views: ViewItemsPage | null,+ payload?: void+ ) => {+ views: ViewItemsPage | null+ payload?: void+ }+ setSearch: (search: string) => {+ search: string+ }+ setTypeFilter: (typeFilter: ViewTypeFilter) => {+ typeFilter: ViewTypeFilter+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface viewsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ visibleViews: (views: ViewItemsPage | null, typeFilter: ViewTypeFilter) => ViewItem[]+ }+}++export type viewsLogicType = MakeLogicType<viewsLogicValues, viewsLogicActions, Record<string, any>, viewsLogicMeta>++export const viewsLogic = kea<viewsLogicType>([+ path(['scenes', 'views', 'viewsLogic']),+ connect(() => ({ values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentTeamId']] })),+ actions({+ setSearch: (search: string) => ({ search }),+ setTypeFilter: (typeFilter: ViewTypeFilter) => ({ typeFilter }),+ }),+ reducers({+ search: ['', { setSearch: (_, { search }) => search }],+ typeFilter: ['all' as ViewTypeFilter, { setTypeFilter: (_, { typeFilter }) => typeFilter }],+ }),+ loaders(({ values }) => ({+ views: [+ null as ViewItemsPage | null,+ {+ loadViews: async (_: void, breakpoint) => {+ await breakpoint(250)+ if (!values.currentTeamId) {+ return values.views+ }+ const page = await fetchViewItems(String(values.currentTeamId), values.search)+ breakpoint()+ return page+ },+ },+ ],+ })),+ reducers({+ loadFailed: [false, { loadViews: () => false, loadViewsFailure: () => true }],+ }),+ selectors({+ visibleViews: [+ (s) => [s.views, s.typeFilter],+ (views: ViewItemsPage | null, typeFilter: ViewTypeFilter): ViewItem[] =>+ filterViews(views?.items ?? [], typeFilter),+ ],+ }),+ listeners(({ actions, values }) => ({+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ // Flags can arrive after urlToAction ran, so a visit that skipped the load must load now.+ if (+ values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] &&+ !values.views &&+ !values.viewsLoading &&+ removeProjectIdIfPresent(router.values.location.pathname) === urls.views()+ ) {+ actions.loadViews()+ }+ },+ setSearch: () => actions.loadViews(),+ setTypeFilter: ({ typeFilter }) => {+ // pinned: analytics event name and property. Renaming them breaks dashboards.+ posthog.capture('views list filtered', { type: typeFilter })+ },+ })),+ urlToAction(({ actions, values }) => ({+ [urls.views()]: () => {+ // The Views scene renders nothing without the flag, so it must not load anything either.+ if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {+ actions.loadViews()+ }+ },+ })),+])diff --git a/frontend/src/scenes/views/viewsUtils.test.ts b/frontend/src/scenes/views/viewsUtils.test.tsnew file mode 100644index 000000000000..d6206bde57df--- /dev/null+++ b/frontend/src/scenes/views/viewsUtils.test.ts@@ -0,0 +1,84 @@+import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'+import type { DashboardBasicApi } from 'products/dashboards/frontend/generated/api.schemas'+import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'++import { ViewItem, filterViews, mergeViews, newCanvasSpaceIdForPath } from './viewsUtils'++const canvas = (overrides: Partial<CanvasApi>): CanvasApi =>+ ({+ id: 'c',+ name: 'Canvas',+ kind: 'freeform',+ channel: 'space-1',+ updated_at: '2026-09-01T00:00:00Z',+ ...overrides,+ }) as CanvasApi++const notebook = (overrides: Partial<NotebookMinimalApi>): NotebookMinimalApi =>+ ({+ short_id: 'n',+ title: 'Notebook',+ deleted: false,+ last_modified_at: '2026-09-01T00:00:00Z',+ ...overrides,+ }) as NotebookMinimalApi++const dashboard = (overrides: Partial<DashboardBasicApi>): DashboardBasicApi =>+ ({+ id: 1,+ name: 'Dashboard',+ deleted: false,+ last_viewed_at: null,+ created_at: '2026-09-01T00:00:00Z',+ ...overrides,+ }) as DashboardBasicApi++const summary = (items: ViewItem[]): string[] => items.map((item) => `${item.type}:${item.id}`)++describe('viewsUtils', () => {+ it('merges every type into one list, most recent first, and leaves out unsupported canvases and deleted views', () => {+ const items = mergeViews({+ canvases: [+ canvas({ id: 'grid', kind: 'grid', updated_at: '2026-09-20T00:00:00Z' }),+ canvas({ id: 'widget', kind: 'component', updated_at: '2026-09-29T00:00:00Z' }),+ canvas({ id: 'board', kind: 'freeform', updated_at: '2026-09-05T00:00:00Z' }),+ ],+ notebooks: [+ notebook({ short_id: 'notes', last_modified_at: '2026-09-25T00:00:00Z' }),+ notebook({ short_id: 'gone', deleted: true, last_modified_at: '2026-09-28T00:00:00Z' }),+ ],+ dashboards: [+ dashboard({ id: 7, last_viewed_at: '2026-09-10T00:00:00Z', created_at: '2026-08-01T00:00:00Z' }),+ dashboard({ id: 8, last_viewed_at: null, created_at: '2026-09-15T00:00:00Z' }),+ ],+ spaceNames: {},+ })++ expect(summary(items)).toEqual(['notebook:notes', 'dashboard:8', 'dashboard:7', 'canvas:board'])+ expect(filterViews(items, 'dashboard').map((item) => item.timestampLabel)).toEqual(['Created', 'Viewed'])+ })++ it('names the space a canvas belongs to, and leaves it out when the space is unknown', () => {+ const items = mergeViews({+ canvases: [+ canvas({ id: 'known', channel: 'space-1', updated_at: '2026-09-02T00:00:00Z' }),+ canvas({ id: 'unknown', channel: 'space-2' }),+ ],+ notebooks: [],+ dashboards: [],+ spaceNames: { 'space-1': 'growth' },+ })++ expect(items.map((item) => item.spaceName)).toEqual(['growth', null])+ })++ test.each([+ ['a space page', '/spaces/space-3', 'space-3'],+ ['a canvas page', '/canvases/board', 'space-1'],+ ['a different open canvas', '/canvases/other', null],+ ['the start page', '/canvases/new', null],+ ['a page with no space', '/views', null],+ ])('defaults a new canvas from %s to the right space', (_, path, spaceId) => {+ expect(newCanvasSpaceIdForPath(path, canvas({ id: 'board', channel: 'space-1' }))).toBe(spaceId)+ })+})diff --git a/frontend/src/scenes/views/viewsUtils.ts b/frontend/src/scenes/views/viewsUtils.tsnew file mode 100644index 000000000000..b65eb59869f8--- /dev/null+++ b/frontend/src/scenes/views/viewsUtils.ts@@ -0,0 +1,149 @@+import { urls } from 'scenes/urls'++import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'+import type { DashboardBasicApi } from 'products/dashboards/frontend/generated/api.schemas'+import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'++// pinned: these values are the `type` property of the `views new picked` and `views list filtered` events.+export type ViewType = 'canvas' | 'notebook' | 'dashboard'+export type ViewTypeFilter = ViewType | 'all'++export interface ViewTypeInfo {+ type: ViewType+ label: string+ pluralLabel: string+ /** One line for the "New" menu. */+ description: string+}++export const VIEW_TYPES: ViewTypeInfo[] = [+ {+ type: 'canvas',+ label: 'Canvas',+ pluralLabel: 'Canvases',+ description: 'A board or a grid of widgets, kept in a space',+ },+ {+ type: 'notebook',+ label: 'Notebook',+ pluralLabel: 'Notebooks',+ description: 'A document that mixes text, queries and charts',+ },+ {+ type: 'dashboard',+ label: 'Dashboard',+ pluralLabel: 'Dashboards',+ description: 'A grid of insights to track your metrics',+ },+]++export const VIEW_TYPE_INFO = Object.fromEntries(VIEW_TYPES.map((info) => [info.type, info])) as Record<+ ViewType,+ ViewTypeInfo+>++// Component canvases are widgets that grids place, not views a person opens.+export const LISTED_CANVAS_KINDS = ['freeform'] as const++export interface ViewItem {+ type: ViewType+ id: string+ name: string+ href: string+ /** When the view last changed, or was last viewed or created when that is all the API knows. */+ timestamp: string | null+ timestampLabel: 'Edited' | 'Viewed' | 'Created'+ /** The space a canvas belongs to. Null for other types. */+ spaceId: string | null+ /** The space's name. Null for other types, or when the space is unknown. */+ spaceName: string | null+ createdByUuid: string | null+ /** The run building a canvas that has no version yet. Null once it has one, and for other types. */+ firstBuildTaskId: string | null+}++export function canvasToView(canvas: CanvasApi, spaceNames: Record<string, string>): ViewItem {+ return {+ type: 'canvas',+ id: canvas.id,+ name: canvas.name || 'Untitled canvas',+ href: urls.canvasDetail(canvas.id),+ timestamp: canvas.updated_at,+ timestampLabel: 'Edited',+ spaceId: canvas.channel,+ spaceName: spaceNames[canvas.channel] ?? null,+ createdByUuid: canvas.created_by?.uuid ?? null,+ firstBuildTaskId: canvas.current_version_id ? null : (canvas.generation_task_id ?? null),+ }+}++export function notebookToView(notebook: NotebookMinimalApi): ViewItem {+ return {+ type: 'notebook',+ id: notebook.short_id,+ name: notebook.title || 'Untitled notebook',+ href: urls.notebook(notebook.short_id),+ timestamp: notebook.last_modified_at,+ timestampLabel: 'Edited',+ spaceId: null,+ spaceName: null,+ createdByUuid: notebook.created_by?.uuid ?? null,+ firstBuildTaskId: null,+ }+}++export function dashboardToView(dashboard: DashboardBasicApi): ViewItem {+ return {+ type: 'dashboard',+ id: String(dashboard.id),+ name: dashboard.name || 'Untitled dashboard',+ href: urls.dashboard(dashboard.id),+ // Dashboards have no edit time in the list API, so the last view stands in for it.+ timestamp: dashboard.last_viewed_at ?? dashboard.created_at,+ timestampLabel: dashboard.last_viewed_at ? 'Viewed' : 'Created',+ spaceId: null,+ spaceName: null,+ createdByUuid: dashboard.created_by?.uuid ?? null,+ firstBuildTaskId: null,+ }+}++export interface ViewSources {+ canvases: CanvasApi[]+ notebooks: NotebookMinimalApi[]+ dashboards: DashboardBasicApi[]+ spaceNames: Record<string, string>+}++/** Every view in one list, most recent first. */+export function mergeViews({ canvases, notebooks, dashboards, spaceNames }: ViewSources): ViewItem[] {+ const items = [+ ...canvases+ .filter((canvas) => (LISTED_CANVAS_KINDS as readonly string[]).includes(canvas.kind))+ .map((canvas) => canvasToView(canvas, spaceNames)),+ ...notebooks.filter((notebook) => !notebook.deleted).map(notebookToView),+ ...dashboards.filter((dashboard) => !dashboard.deleted).map(dashboardToView),+ ]+ const time = (item: ViewItem): number => (item.timestamp ? new Date(item.timestamp).getTime() : 0)+ return items.sort((first, second) => time(second) - time(first) || first.name.localeCompare(second.name))+}++export function filterViews(items: ViewItem[], filter: ViewTypeFilter): ViewItem[] {+ return filter === 'all' ? items : items.filter((item) => item.type === filter)+}++/**+ * The space a new canvas defaults to from the page the person is on: the open space, or the open+ * canvas's space. Null when the page names no space, so the start page falls back to the personal space.+ */+export function newCanvasSpaceIdForPath(+ path: string,+ openCanvas: Pick<CanvasApi, 'id' | 'channel'> | null+): string | null {+ const space = /^\/spaces\/([^/]+)/.exec(path)+ if (space) {+ return space[1]+ }+ const canvas = /^\/canvases\/([^/]+)$/.exec(path)+ return canvas && openCanvas?.id === canvas[1] ? openCanvas.channel : null+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 827b2839198a..2c26d5a1a718 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2755,15 +2755,42 @@ importers:products/canvas:dependencies:+ '@posthog/icons':+ specifier: 'catalog:'+ '@posthog/lemon-ui':+ specifier: '*'+ version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])+ '@posthog/quill':+ specifier: workspace:*+ version: link:../../packages/quill/packages/quill+ '@storybook/react':+ specifier: 'catalog:'+ version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@types/react':specifier: 18.3.27version: 18.3.27+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-router:+ specifier: 'catalog:'+ version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.435.5(@types/[email protected])([email protected])react:specifier: 18.3.1version: 18.3.1react-dom:specifier: 18.3.1version: 18.3.1([email protected])+ zod:+ specifier: '*'+ version: 4.3.6devDependencies:'@testing-library/react':specifier: ^14.3.1@@ -2771,6 +2798,9 @@ importers:jest:specifier: ^29.7.0version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))products/cdp:dependencies:diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex 85fb259dc699..ff5953c690a1 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -92,6 +92,19 @@ def is_embeddable_document(path: str) -> bool:return path in EMBEDDABLE_PATHS or path.startswith(EMBEDDABLE_PATH_PREFIXES)+def app_frame_ancestor_sources() -> list[str]:+ """The origins that may frame the app, as `frame-ancestors` sources.++ A frame the app embeds has these origins in its ancestor chain too, so its own policy must+ admit them.+ """+ sources = ["https://posthog.com", "https://preview.posthog.com"]+ if not (settings.DEBUG or settings.TEST) and settings.SITE_URL.endswith(".dev.posthog.dev"):+ # The posthog.com dev server frames the dev app.+ sources.append("http://localhost:8001")+ return sources++CSP_ENFORCE_OTHER_SIGNED_OUT_PAGES_FLAG = "csp-enforce-other-signed-out-pages"# The pages that take a password or a one-time code. Other signed-out pages follow the flag above.@@ -282,18 +295,19 @@ class CSPMiddleware:response.headers["Reporting-Endpoints"] = f'default="{reporting_endpoint}"'response.headers["Content-Security-Policy"] = "; ".join(csp_parts)elif "Content-Security-Policy" in response.headers:- # The view picked this policy for this document: a canvas artifact runs untrusted code,- # and the workflow asset endpoint sandboxes captured email HTML. The app policy would- # drop that sandbox and impose a frame-ancestors list the app's own origin does not- # match. Adding it report-only is no better, because these documents never aim to- # satisfy it, so each load would report a violation of a policy we chose not to apply.+ # The view picked this policy for this document: a canvas artifact and the draft canvas+ # sandbox document run untrusted code, and the workflow asset endpoint sandboxes+ # captured email HTML. The app policy would drop that sandbox and impose a+ # frame-ancestors list the app's own origin does not match. Adding it report-only is no+ # better, because these documents never aim to satisfy it, so each load would report a+ # violation of a policy we chose not to apply.return responseelse:resource_url = "https://*.posthog.com"# Enforced for every viewer, flag or not, because this directive is what admits these# origins: a frame-ancestors directive makes browsers ignore X-Frame-Options, which# names only our own origin.- frame_ancestors = "frame-ancestors https://posthog.com https://preview.posthog.com"+ frame_ancestors = f"frame-ancestors {' '.join(app_frame_ancestor_sources())}"js_url = urlsplit(settings.JS_URL)bundle_origin = f"{js_url.scheme}://{js_url.netloc}" if js_url.scheme and js_url.netloc else ""if settings.DEBUG or settings.TEST:@@ -301,8 +315,6 @@ class CSPMiddleware:resource_url = " ".join(dict.fromkeys(filter(None, ["http://localhost:8234", bundle_origin])))elif settings.SITE_URL.endswith(".dev.posthog.dev"):resource_url = "https://*.dev.posthog.dev"- # The posthog.com dev server frames the dev app.- frame_ancestors += " http://localhost:8001"connect_debug_url = "ws://localhost:8234" if settings.DEBUG or settings.TEST else ""object_storage_source = object_storage_upload_source()diff --git a/posthog/urls.py b/posthog/urls.pyindex 651b3416fc16..d3114a03a4bf 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -39,7 +39,7 @@ from posthog.temporal.codec_server import decode_payloadsfrom posthog.web_bot_auth import http_message_signatures_directoryfrom products.ai_observability.backend.api.personal_spend import PersonalSpendEUProxyViewSet-from products.canvas.backend.artifacts import canvas_artifact+from products.canvas.backend.artifacts import canvas_artifact, canvas_sandbox_documentfrom products.cdp.backend.api import hog_function_templatefrom products.conversations.backend.api.internal import InternalTicketView as ConversationsInternalTicketViewfrom products.customer_analytics.backend.presentation.views.internal import (@@ -364,6 +364,12 @@ urlpatterns = [*([path("delete_events/", playwright_setup.delete_events)] if settings.TEST else []),# Temporal UI decryption is needed in tests even when DEBUG is off.*([path("decode", decode_payloads, name="temporal_decode")] if settings.TEST and not settings.DEBUG else []),+ # Precedes the artifact route, which would otherwise read "sandbox" as a token.+ re_path(+ r"^canvas-artifacts/sandbox/(?P<content_hash>[0-9a-f]{64})/index\.html$",+ canvas_sandbox_document,+ name="canvas-sandbox-document",+ ),re_path(r"^canvas-artifacts/(?P<token>[^/]+)/(?P<artifact_path>.+)$", canvas_artifact, name="canvas-artifact"),# Preserve the host and query when redirecting the legacy signup URL.opt_slash_path("sign-up", RedirectView.as_view(url="/signup", permanent=True, query_string=True)),diff --git a/products/canvas/backend/artifacts.py b/products/canvas/backend/artifacts.pyindex 2c2c45cb5c2e..4929c3c0cb55 100644--- a/products/canvas/backend/artifacts.py+++ b/products/canvas/backend/artifacts.py@@ -11,11 +11,14 @@ Integrity is verified when artifacts are written and again when they are readfrom object storage. The manifest hash is also used as the response ETag."""+import reimport mathimport timeimport hashlib+import functools+from pathlib import Pathfrom typing import Any-from urllib.parse import urlparse+from urllib.parse import urlparse, urlsplitfrom uuid import UUIDfrom django.conf import settings@@ -23,7 +26,10 @@ from django.core import signingfrom django.http import Http404, HttpRequest, HttpResponse, HttpResponseNotModifiedfrom django.views.decorators.clickjacking import xframe_options_exempt+from posthog.csp_middleware import app_frame_ancestor_sources+from posthog.dataclasses import frozenfrom posthog.storage import object_storage+from posthog.storage.object_storage import ObjectStorageErrorfrom products.canvas.backend.contract import artifact_cspfrom products.canvas.backend.models import CanvasBuild@@ -35,6 +41,11 @@ ARTIFACT_TOKEN_SALT = "posthog.canvas.artifact.v1"# its own bucket and the next one, i.e. between one and two hours.ARTIFACT_TOKEN_BUCKET_SECONDS = 3600+# Generated from the desktop's sandboxRuntime.ts by `pnpm --filter @posthog/ui+# generate-web-sandbox`. Do not edit it by hand.+SANDBOX_DOCUMENT_PATH = Path(__file__).parent / "sandbox" / "sandbox_document.html"+ARTIFACT_PERMISSIONS_POLICY = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"+def _configured_artifact_host() -> str | None:origin = urlparse(settings.CANVAS_ARTIFACT_ORIGIN)@@ -56,11 +67,15 @@ def _artifact_signing_keys() -> list[str]:return configured or [settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS]+def _artifact_delivery_enabled(keys: list[str]) -> bool:+ if not keys or (not settings.CANVAS_ARTIFACT_ORIGIN and not (settings.DEBUG or settings.TEST)):+ return False+ return bool(settings.DEBUG or settings.TEST) or (len(keys[0]) >= 32 and _configured_artifact_host() is not None)++def create_canvas_artifact_token(build: CanvasBuild) -> str | None:keys = _artifact_signing_keys()- if not keys or (not settings.CANVAS_ARTIFACT_ORIGIN and not (settings.DEBUG or settings.TEST)):- return None- if not (settings.DEBUG or settings.TEST) and (len(keys[0]) < 32 or _configured_artifact_host() is None):+ if not _artifact_delivery_enabled(keys):return Nonebucket = int(time.time() // ARTIFACT_TOKEN_BUCKET_SECONDS)return signing.Signer(key=keys[0], salt=ARTIFACT_TOKEN_SALT).sign_object(@@ -102,11 +117,105 @@ def _read_token(token: str) -> dict[str, Any]:raise Http404-@xframe_options_exempt-def canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> HttpResponse:+def _require_artifact_host(request: HttpRequest) -> None:configured_host = _configured_artifact_host()if settings.CANVAS_ARTIFACT_ORIGIN and (configured_host is None or request.get_host().lower() != configured_host):raise Http404+++@frozen+class _SandboxDocument:+ content: bytes+ content_hash: str+++def _parse_sandbox_document(content: bytes) -> _SandboxDocument:+ return _SandboxDocument(+ content=content,+ content_hash=hashlib.sha256(content).hexdigest(),+ )+++def _sandbox_document() -> _SandboxDocument:+ return _parse_sandbox_document(SANDBOX_DOCUMENT_PATH.read_bytes())+++def _publish_sandbox_document(document: _SandboxDocument) -> None:+ object_storage.write(f"canvas_sandbox/{document.content_hash}/index.html", document.content)+++def _canvas_sandbox_document_csp() -> str:+ site = urlsplit(settings.SITE_URL)+ ancestors = dict.fromkeys([f"{site.scheme}://{site.netloc}", *app_frame_ancestor_sources()])+ return "; ".join(+ [+ # A stored document's meta policy must not widen the web preview's network access.+ "default-src 'none'",+ "script-src 'unsafe-inline' blob: https://cdn.jsdelivr.net/npm/@tailwindcss/ https://esm.sh",+ "style-src 'unsafe-inline' https://esm.sh",+ "font-src data: https://esm.sh",+ "img-src data: blob:",+ "worker-src blob:",+ "connect-src https://esm.sh https://cdn.jsdelivr.net/npm/@tailwindcss/",+ "form-action 'none'",+ "base-uri 'none'",+ "object-src 'none'",+ # The document runs in an opaque origin even when it opens top-level or in a frame+ # without the sandbox attribute.+ "sandbox allow-scripts",+ f"frame-ancestors {' '.join(ancestors)}",+ ]+ )+++def create_canvas_sandbox_document_url() -> str | None:+ """The URL of the draft canvas sandbox document, or None when artifact delivery is off.++ The content hash in the path makes each URL immutable, so a deploy that changes the+ document changes the URL too.+ """+ if not _artifact_delivery_enabled(_artifact_signing_keys()):+ return None+ document = _sandbox_document()+ try:+ _publish_sandbox_document(document)+ except ObjectStorageError:+ return None+ return f"{_artifact_origin()}/canvas-artifacts/sandbox/{document.content_hash}/index.html"+++@xframe_options_exempt+def canvas_sandbox_document(request: HttpRequest, content_hash: str) -> HttpResponse:+ """The bootstrap document that renders a draft canvas in a sandboxed iframe.++ The web app cannot use this document as srcdoc, because a srcdoc frame inherits the app's CSP,+ which refuses the CDNs the document transpiles and resolves imports from. It holds no+ credentials: the canvas code arrives later by postMessage.+ """+ _require_artifact_host(request)+ document = _sandbox_document()+ if not re.fullmatch(r"[0-9a-f]{64}", content_hash):+ raise Http404+ if content_hash != document.content_hash:+ content = object_storage.read_bytes(f"canvas_sandbox/{content_hash}/index.html", missing_ok=True)+ if content is None or hashlib.sha256(content).hexdigest() != content_hash:+ raise Http404+ document = _parse_sandbox_document(content)+ response = HttpResponse(document.content, content_type="text/html; charset=utf-8")+ response["ETag"] = f'"{document.content_hash}"'+ response["Cache-Control"] = "public, max-age=31536000, immutable"+ response["Referrer-Policy"] = "no-referrer"+ response["X-Content-Type-Options"] = "nosniff"+ response["Content-Security-Policy"] = _canvas_sandbox_document_csp()+ response["Permissions-Policy"] = ARTIFACT_PERMISSIONS_POLICY+ return response+++@xframe_options_exempt+def canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> HttpResponse:+ _require_artifact_host(request)claims = _read_token(token)token_expires_at = (claims["bucket"] + 2) * ARTIFACT_TOKEN_BUCKET_SECONDSteam_id = claims.get("team_id")@@ -185,5 +294,5 @@ def _with_artifact_headers(response: HttpResponse, etag: str, manifest: dict, toresponse["X-Content-Type-Options"] = "nosniff"network_origins = ((manifest.get("capabilities") or {}).get("network") or {}).get("origins") or []response["Content-Security-Policy"] = artifact_csp(network_origins)- response["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"+ response["Permissions-Policy"] = ARTIFACT_PERMISSIONS_POLICYreturn responsediff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.pyindex b58e402b0eb8..de8dfb357125 100644--- a/products/canvas/backend/facade/api.py+++ b/products/canvas/backend/facade/api.py@@ -1,3 +1,4 @@+from products.canvas.backend.artifacts import create_canvas_sandbox_document_url as create_canvas_sandbox_document_urlfrom products.canvas.backend.connectors import (ConnectorCallStatus as ConnectorCallStatus,ConnectorKind as ConnectorKind,diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex 7bdcfd3104b3..31ec1b14fe94 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -1063,6 +1063,14 @@ class CanvasViewResponseSerializer(serializers.Serializer):"reference, so the grid renders from this one call. Absent for other kinds."),)+ sandbox_document_url = serializers.CharField(+ allow_null=True,+ read_only=True,+ help_text=(+ "URL of the sandbox document that renders the head source project in an iframe, served from "+ "the artifact origin. Load it by URL, not as srcdoc. Null when artifact delivery is unavailable."+ ),+ )class CanvasLayoutWithComponentsResponseSerializer(CanvasLayoutResponseSerializer):diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 870208167659..3a0fd13d9eab 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -43,6 +43,7 @@ from products.canvas.backend.facade.api import (call_connector_tool,canvas_connectors_enabled,connector_listings,+ create_canvas_sandbox_document_url,default_layout,native_connector_listings,seed_home_canvas,@@ -811,6 +812,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):"has_active_build": newest_active is not None,"source": source,"layout": layout,+ "sandbox_document_url": create_canvas_sandbox_document_url(),}if layout is not None:instance["component_lifecycles"] = _component_lifecycles(self.team_id, self.get_queryset(), layout)diff --git a/products/canvas/backend/sandbox/sandbox_document.html b/products/canvas/backend/sandbox/sandbox_document.htmlnew file mode 100644index 000000000000..a90b88e4e274--- /dev/null+++ b/products/canvas/backend/sandbox/sandbox_document.html@@ -0,0 +1,1557 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob: https://cdn.jsdelivr.net/npm/@tailwindcss/ https://esm.sh ; style-src 'unsafe-inline' https://esm.sh; font-src data: https://esm.sh; img-src data: blob: https:; worker-src blob:; connect-src https://esm.sh https://cdn.jsdelivr.net/npm/@tailwindcss/ " />+<script>+ // The map is assembled here rather than baked into the HTML because+ // "@posthog/canvas-sdk" is platform-provided rather than CDN-pinned, and the+ // blob holding it only exists inside this document. Keep this ahead of the+ // bootstrap module: a map added after module loading starts is ignored.+ var canvasImportMap = {"imports":{"react":"https://esm.sh/[email protected]","react-dom":"https://esm.sh/[email protected]?external=react","react-dom/client":"https://esm.sh/[email protected]/client?external=react","@posthog/quill":"https://esm.sh/@posthog/[email protected]?external=react,react-dom&deps=@base-ui/[email protected]","recharts":"https://esm.sh/[email protected]?external=react,react-dom","lucide-react":"https://esm.sh/[email protected]?external=react","dayjs":"https://esm.sh/[email protected]","d3":"https://esm.sh/[email protected]","three":"https://esm.sh/[email protected]","framer-motion":"https://esm.sh/[email protected]?external=react,react-dom&[email protected],[email protected]","zod":"https://esm.sh/[email protected]","@tanstack/react-table":"https://esm.sh/@tanstack/[email protected]?external=react,react-dom","@tanstack/react-virtual":"https://esm.sh/@tanstack/[email protected]?external=react,react-dom","react-hook-form":"https://esm.sh/[email protected]?external=react","lodash-es":"https://esm.sh/[email protected]","react-markdown":"https://esm.sh/[email protected]?external=react","papaparse":"https://esm.sh/[email protected]","react/jsx-runtime":"https://esm.sh/[email protected]/jsx-runtime","react/jsx-dev-runtime":"https://esm.sh/[email protected]/jsx-dev-runtime"}};+ canvasImportMap.imports["@posthog/canvas-sdk"] =+ URL.createObjectURL(new Blob(["export const ph = globalThis.ph\nexport default globalThis.ph\n\nexport function editable(name, props, params) {\n const schema = params || {}\n const values = {}\n for (const key of Object.keys(schema)) {\n const value = props ? props[key] : undefined\n if (value === undefined || typeof value === 'function') {\n continue\n }\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n continue\n }\n values[key] = value\n }\n const attributes = {\n 'data-ph-block': name,\n 'data-ph-params': JSON.stringify(schema),\n 'data-ph-props': JSON.stringify(values),\n }\n if (props && props['data-ph-src']) {\n attributes['data-ph-src'] = props['data-ph-src']\n }\n if (props && props.blockId) {\n attributes['data-ph-block-id'] = props.blockId\n }\n return attributes\n}\n"], { type: "text/javascript" }));+ var canvasImportMapTag = document.createElement("script");+ canvasImportMapTag.type = "importmap";+ canvasImportMapTag.textContent = JSON.stringify(canvasImportMap);+ document.head.appendChild(canvasImportMapTag);+</script>+<script type="module" src="https://cdn.jsdelivr.net/npm/@tailwindcss/[email protected]"></script>+<style type="text/tailwindcss">+@import "tailwindcss";+/* Drive `dark:` off the `.dark` class the host toggles (not prefers-color-scheme),+ so the canvas follows the user's PostHog theme even when it differs from the OS. */+@custom-variant dark (&:where(.dark, .dark *));+@theme inline {+ --color-border: var(--border);+ --color-input: var(--input);+ --color-ring: var(--ring);+ --color-chrome: var(--chrome);+ --color-background: var(--background);+ --color-foreground: var(--foreground);+ --color-primary: var(--primary);+ --color-primary-foreground: var(--primary-foreground);+ --color-destructive: var(--destructive);+ --color-destructive-foreground: var(--destructive-foreground);+ --color-muted: var(--muted);+ --color-muted-foreground: var(--muted-foreground);+ --color-card: var(--card);+ --color-card-foreground: var(--card-foreground);+ --color-success: var(--success);+ --color-success-foreground: var(--success-foreground);+ --color-warning: var(--warning);+ --color-warning-foreground: var(--warning-foreground);+ --color-info: var(--info);+ --color-info-foreground: var(--info-foreground);+ --color-fill-hover: var(--fill-hover);+ --color-fill-selected: var(--fill-selected);+ --color-fill-expanded: var(--fill-expanded);+ --radius-lg: var(--radius);+ --radius-md: calc(var(--radius) - 2px);+ --radius-sm: calc(var(--radius) - 4px);+}+</style>++<link rel="stylesheet" href="https://esm.sh/@posthog/[email protected]/tokens.css" />+<link rel="stylesheet" href="https://esm.sh/@posthog/[email protected]/color-system.css" />+<link rel="stylesheet" href="https://esm.sh/@posthog/[email protected]/base.css" />+<link rel="stylesheet" href="https://esm.sh/@posthog/[email protected]/primitives.css" />+<style>+ *, *::before, *::after { box-sizing: border-box; }+ /* Fill the iframe viewport exactly so overflow scrolls on the iframe's own root+ scroller — the iframe is pinned to its parent's height and never grows it. */+ html, body { margin: 0; padding: 0; height: 100%; }+ /* No light default: leaving `color-scheme` alone lets the base canvas inherit+ the embedder's scheme (the host sets it on the iframe), so the first paint+ is already dark in a dark app. Once the host's theme message toggles+ `.dark`, this pins it so form controls and scrollbars match too. */+ html.dark { color-scheme: dark; }+ /* Track the theme via Quill's tokens (set on :root / .dark) so the page chrome+ flips with the host theme. Until those tokens land — the stylesheets are+ still loading, and `.dark` is only applied once the host's init/set-theme+ message arrives — stay transparent and inherit, so the host iframe's own+ themed background shows through. A hard light fallback here flashed white+ over a dark app every time a preview scrolled into view. */+ body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; color: var(--foreground, inherit); background: var(--background, transparent); }+ #root { min-height: 100vh; }+</style>+</head>+<body>+<div id="root"></div>+<script type="module">+ import * as Babel from "https://esm.sh/@babel/[email protected]";+ const CHANNEL = "posthog-canvas";+ const portOnly = new URLSearchParams(location.hash.slice(1)).get("bridge") === "port";+ let bridgePort = null;+ let sendToHost = null;+ const post = (msg) => {+ const message = { channel: CHANNEL, ...msg };+ if (sendToHost) sendToHost(message);+ else if (!portOnly) parent.postMessage(message, "*");+ };++ // --- data shim: the ONLY way canvas code reaches PostHog. No token here. ---+ const pending = new Map();+ let reqSeq = 0;+ // The host caps how many requests run at once and queues the rest. Past+ // that queue it refuses the request and marks it retryable.+ const MAX_CALL_RETRIES = 2;+ const RETRY_BASE_DELAY_MS = 1000;+ const call = (method, payload, attempt = 0) =>+ new Promise((resolve, reject) => {+ const id = String(++reqSeq);+ pending.set(id, {+ resolve,+ reject: (error, retryable) => {+ if (!retryable || attempt >= MAX_CALL_RETRIES) {+ reject(error);+ return;+ }+ const delay =+ RETRY_BASE_DELAY_MS * Math.pow(2, attempt) * (0.5 + Math.random());+ setTimeout(+ () => call(method, payload, attempt + 1).then(resolve, reject),+ delay,+ );+ },+ });+ post({ type: "data-request", id, method, payload });+ });+ // posthog-js runs IN here (the only way replay records the app's DOM). It is+ // booted by init when analytics config is present; until then capture falls+ // back to the host-mediated path.+ let phClient = null;+ window.ph = {+ // Run a named, server-stored query — the published tier's model. The host+ // still rejects it (Phase 3).+ run: (name, params) => call("run", { name, params: params ?? {} }),+ // PREFERRED data path: load a SAVED, validated insight by its short id and+ // render its STORED result from the insights endpoint (not a fresh /query/+ // run). Pass the date picker's window to re-scope it:+ // `ph.loadInsight("AbC123", { dateRange: { date_from, date_to } })`.+ // A SQL insight's `{variables.x}` placeholders are set per call, keyed by+ // code name: `ph.loadInsight("AbC123", { variables: { product: "surveys" } })`+ // — so one saved insight serves a whole board. The host REJECTS a variable the+ // insight doesn't use, rather than quietly falling back to its saved value.+ // Returns `{ columns, results }` — SAME shape as ph.query: a trends-style+ // insight returns SERIES OBJECTS, a SQL insight returns ROWS.+ loadInsight: (shortId, opts) =>+ call("loadInsight", {+ shortId,+ dateRange: opts && opts.dateRange,+ variables: opts && opts.variables,+ refresh: opts && opts.refresh,+ }),+ // Run a query. Pass a TYPED query node (`{ kind: "TrendsQuery", … }`) for+ // UI-matching numbers (preferred), or an inline HogQL string (escape hatch).+ // A built canvas needs `capabilities.posthog.inlineQueries` for this.+ query: (queryOrHogql, params, opts) =>+ call(+ "query",+ typeof queryOrHogql === "string"+ ? { hogql: queryOrHogql, params: params ?? {}, refresh: opts && opts.refresh }+ : { query: queryOrHogql, params: params ?? {}, refresh: opts && opts.refresh },+ ),+ // Send an analytics event. Prefer in-iframe posthog-js (so it shares the+ // session/replay); otherwise host-mediated (no replay, still captured).+ capture: (event, properties, distinctId) => {+ if (phClient) {+ phClient.capture(event, properties ?? {});+ return Promise.resolve({ ok: true });+ }+ return call("capture", { event, properties: properties ?? {}, distinctId });+ },+ // Durable key-value memory, declared in capabilities.posthog.state.+ // Scope "user" (default) is private to this viewer; "shared" is one+ // value per canvas, visible to the whole team. Values are JSON, capped+ // at 64 KB serialized and 256 keys per scope; setting null deletes:+ // `ph.state.set("board", { columns: 3 }, { scope: "shared" })`.+ state: {+ get: (key, opts) => call("stateGet", { key, scope: (opts && opts.scope) || "user" }),+ set: (key, value, opts) =>+ call("stateSet", { key, value: value === undefined ? null : value, scope: (opts && opts.scope) || "user" }),+ list: (opts) => call("stateList", { scope: opts && opts.scope }),+ },+ // Write into PostHog as the viewer. Every verb must be declared in+ // capabilities.posthog.actions; wire invocations to explicit user+ // gestures (a button), never to load or render:+ // `ph.actions.invoke("tasks.create", { title, description })`.+ actions: {+ invoke: (verb, payload) => call("actionInvoke", { verb, payload: payload ?? {} }),+ },+ // Read live third-party data with the viewer's own connection. Every+ // provider and tool must be declared in capabilities.connectors; the+ // result is cached per canvas for `refresh` seconds (default 60):+ // `ph.connectors.call("github", "list_pull_requests", { repository: "app" })`.+ // A "not_connected" status carries a connect_path; `connect(provider)`+ // opens that settings page from a click.+ connectors: {+ call: (provider, tool, args, options) =>+ call("connectorCall", { provider, tool, arguments: args ?? {}, refresh: options?.refresh }),+ connect: (provider) => {+ if (!navigator.userActivation?.isActive) throw new Error("Connecting a provider requires a user action");+ post({ type: "navigate", nav: { target: "connect", provider } });+ },+ },+ // Ask the authoring agent for a change; the host shows the exact prompt+ // and asks the viewer to approve before anything is dispatched:+ // `ph.agent.request("Make the square blue")`.+ agent: {+ request: (prompt) => call("agentRequest", { prompt }),+ },+ // Brokered by the host: PostHog and GitHub PR HTTPS URLs, rate-limited, and+ // ignored while the canvas is unfocused (no auto-opens on load).+ openExternal: (url) => post({ type: "open-external", url }),+ // Navigate the host app. Fire-and-forget: the host validates the intent+ // against its allowlist and routes within the current channel. The canvas+ // cannot pick the channel or an arbitrary path — only these four targets.+ navigate: {+ toTask: (taskId) => post({ type: "navigate", nav: { target: "task", taskId } }),+ toNewTask: (options) => {+ if (!navigator.userActivation?.isActive) throw new Error("Opening a task requires a user action");+ post({ type: "navigate", nav: { target: options ? "compose-task" : "new-task", prompt: options?.prompt, repository: options?.repository } });+ },+ toCanvas: (dashboardId) => post({ type: "navigate", nav: { target: "canvas", dashboardId } }),+ toNewCanvas: () => post({ type: "navigate", nav: { target: "new-canvas" } }),+ },+ };++ // Keep target="_blank" anchors working without popup permission. Capture+ // phase so stopPropagation() can't swallow the click; the open is deferred+ // a tick so preventDefault() is honored (the native popup attempt is+ // sandbox-blocked regardless, so we never call preventDefault ourselves).+ const resolveExternalAnchorUrl = function resolveExternalAnchorUrl(target) {+ const anchor = target instanceof Element ? target.closest("a[href]") : null;+ if (!anchor) return null;+ // HTML matches the _blank keyword ASCII-case-insensitively.+ if ((anchor.getAttribute("target") ?? "").toLowerCase() !== "_blank") {+ return null;+ };+ // getAttribute, not the .href property: SVG anchors expose SVGAnimatedString+ // there, and relative hrefs would resolve against the host's base URL.+ const href = anchor.getAttribute("href") ?? "";+ try {+ return new URL(href).href;+ } catch {+ return null;+ }+};+ document.addEventListener(+ "click",+ (event) => {+ const url = resolveExternalAnchorUrl(event.target);+ if (!url) return;+ setTimeout(() => {+ if (!event.defaultPrevented) window.ph.openExternal(url);+ }, 0);+ },+ true,+ );++ const selectionAnchorRect = function commentActionAnchorRect(rects, fallback) {+ const boxes = [];+ for (let index = 0; index < rects.length; index++) {+ const rect = rects[index];+ if (rect.width > 0 || rect.height > 0) {+ boxes.push(rect);+ }+ };+ if (boxes.length === 0) {+ return fallback;+ };+ const EPSILON = .5;+ const area = (box) => box.width * box.height;+ const encloses = (outer, inner) => area(outer) > area(inner) + 1 && outer.left <= inner.left + EPSILON && outer.right >= inner.right - EPSILON && outer.top <= inner.top + EPSILON && outer.bottom >= inner.bottom - EPSILON;+ const candidates = boxes.slice().sort((left, right) => {+ const verticalDistance = right.bottom - left.bottom;+ return Math.abs(verticalDistance) > EPSILON ? verticalDistance : right.right - left.right;+ });+ for (const box of candidates) {+ if (!boxes.some((other) => other !== box && encloses(box, other))) {+ return box;+ }+ };+ return candidates[0];+};+ let textSelectionPublished = false;+ const clearTextSelection = () => {+ if (!textSelectionPublished) return;+ textSelectionPublished = false;+ 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;+ }+ // The END line's rect, so the host anchors the comment action where the+ // pointer was released rather than at the whole-range bounding box.+ const rect = selectionAnchorRect(range.getClientRects(), range.getBoundingClientRect());+ textSelectionPublished = true;+ 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);+ };+ // Report the selection only once it settles, so the host's comment action+ // doesn't chase the cursor mid-drag. The settle callback re-reads the live+ // selection, which self-corrects clicks that didn't change the selection.+ const selectionSettleGate = function installSelectionSettleGate(doc, callbacks) {+ const view = doc.defaultView;+ let selecting = false;+ let keyGesture = false;+ let frame = 0;+ // Keys that move or extend a selection. "a" only counts with a modifier, so+ // typing the letter doesn't read as select-all.+ const isSelectionKey = (event) => {+ if (event.key === "a" || event.key === "A") {+ return event.metaKey || event.ctrlKey;+ };+ return event.key === "Shift" || event.key === "Home" || event.key === "End" || event.key === "PageUp" || event.key === "PageDown" || event.key.startsWith("Arrow");+ };+ const cancelFrame = () => {+ if (frame && view?.cancelAnimationFrame) {+ view.cancelAnimationFrame(frame);+ };+ frame = 0;+ };+ const settle = () => {+ cancelFrame();+ const request = view?.requestAnimationFrame;+ if (!request) {+ callbacks.onSelectionSettled?.();+ return;+ };+ frame = request.call(view, () => {+ frame = request.call(view, () => {+ frame = 0;+ callbacks.onSelectionSettled?.();+ });+ });+ };+ const inActionUi = (target) => target instanceof Element && !!target.closest("[data-selection-comment-overlay]");+ const startGesture = () => {+ if (selecting) {+ return;+ };+ selecting = true;+ cancelFrame();+ callbacks.onGestureStart?.();+ };+ const cancelGesture = () => {+ if (!selecting) {+ return;+ };+ selecting = false;+ keyGesture = false;+ cancelFrame();+ callbacks.onGestureCancel?.();+ };+ const onPointerDown = (event) => {+ // Secondary buttons open menus; they don't select.+ if (event instanceof MouseEvent && event.button > 0) {+ return;+ };+ if (inActionUi(event.target)) {+ return;+ };+ startGesture();+ };+ // Catches drags whose pointerdown we never saw, and keyboard selections.+ const onSelectStart = (event) => {+ if (inActionUi(event.target)) {+ return;+ };+ startGesture();+ };+ const onPointerUp = (event) => {+ if (event instanceof MouseEvent && event.button > 0) {+ return;+ };+ if (!selecting) {+ return;+ };+ selecting = false;+ keyGesture = false;+ settle();+ };+ const onKeyDown = (event) => {+ if (inActionUi(event.target) || !isSelectionKey(event)) {+ return;+ };+ keyGesture = true;+ startGesture();+ };+ const onKeyUp = () => {+ if (!selecting || !keyGesture) {+ return;+ };+ selecting = false;+ keyGesture = false;+ settle();+ };+ const onSelectionChange = () => {+ if (selecting) {+ return;+ };+ callbacks.onIdleSelectionChange?.();+ };+ doc.addEventListener("pointerdown", onPointerDown, true);+ doc.addEventListener("selectstart", onSelectStart, true);+ doc.addEventListener("pointerup", onPointerUp, true);+ doc.addEventListener("pointercancel", cancelGesture, true);+ doc.addEventListener("keydown", onKeyDown, true);+ doc.addEventListener("keyup", onKeyUp, true);+ doc.addEventListener("selectionchange", onSelectionChange);+ view?.addEventListener("blur", cancelGesture);+ return () => {+ cancelFrame();+ doc.removeEventListener("pointerdown", onPointerDown, true);+ doc.removeEventListener("selectstart", onSelectStart, true);+ doc.removeEventListener("pointerup", onPointerUp, true);+ doc.removeEventListener("pointercancel", cancelGesture, true);+ doc.removeEventListener("keydown", onKeyDown, true);+ doc.removeEventListener("keyup", onKeyUp, true);+ doc.removeEventListener("selectionchange", onSelectionChange);+ view?.removeEventListener("blur", cancelGesture);+ };+};+ // Dropping the pending report matters: a new drag started within the+ // debounce window would otherwise publish the previous selection mid-drag.+ const abortTextSelection = () => {+ clearTimeout(selectionTimer);+ clearTextSelection();+ };+ selectionSettleGate(document, {+ onGestureStart: abortTextSelection,+ onSelectionSettled: reportTextSelection,+ onIdleSelectionChange: reportTextSelection,+ onGestureCancel: abortTextSelection,+ });+ document.addEventListener("scroll", abortTextSelection, true);+ 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 = function resolveTextCommentAnchor(text, anchor) {+ if (text.slice(anchor.start, anchor.end) === anchor.quote) {+ return {+ start: anchor.start,+ end: anchor.end,+ status: "exact"+ };+ };+ const candidates = [];+ let from = 0;+ while (from <= text.length - anchor.quote.length) {+ const match = text.indexOf(anchor.quote, from);+ if (match < 0) break;+ candidates.push(match);+ from = match + Math.max(anchor.quote.length, 1);+ };+ if (candidates.length === 0) return null;+ if (candidates.length === 1) {+ const start = candidates[0];+ return {+ start,+ end: start + anchor.quote.length,+ status: "reanchored"+ };+ };+ const ranked = candidates.map((start) => {+ const end = start + anchor.quote.length;+ const prefix = text.slice(Math.max(0, start - anchor.prefix.length), start);+ const suffix = text.slice(end, end + anchor.suffix.length);+ let score = 0;+ if (anchor.prefix && prefix === anchor.prefix) score += 2;+ if (anchor.suffix && suffix === anchor.suffix) score += 2;+ return {+ start,+ score+ };+ }).sort((a, b) => b.score - a.score);+ if (ranked[0].score === 0 || ranked[0].score === ranked[1].score) return null;+ return {+ start: ranked[0].start,+ end: ranked[0].start + anchor.quote.length,+ status: "reanchored"+ };+};+ 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 = function isInteractiveCanvasCommentTarget(target) {+ return target instanceof Element && !!target.closest("a,button,input,select,textarea,[role=button],[contenteditable=true],[onclick]");+};+ 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) => {+ if (phClient || !cfg) return;+ try {+ const mod = await import("https://esm.sh/[email protected]");+ const posthog = mod.default || mod.posthog || mod;+ posthog.init(cfg.publicKey, {+ api_host: cfg.apiHost,+ // No storage on a null-origin sandbox → memory session; the+ // usercontent origin (shared tier) persists per-viewer.+ persistence: cfg.persist ? "localStorage+cookie" : "memory",+ capture_pageview: false,+ disable_session_recording: false,+ loaded: (ph) => {+ if (cfg.distinctId) ph.identify(cfg.distinctId);+ },+ });+ phClient = posthog;+ window.posthog = posthog;+ } catch (err) {+ reportError(+ "analytics init failed: " + (err && err.message),+ err && err.stack,+ );+ }+ };++ // --- theme: mirror the host's light/dark by toggling `.dark` on the root,+ // exactly as the main app does. Quill's CSS tokens (:root / .dark) and the+ // `dark:` Tailwind utilities both key off this class, so the whole canvas+ // flips. Applied on init and on every live `set-theme` frame.+ const applyTheme = (theme) =>+ document.documentElement.classList.toggle("dark", theme === "dark");++ window.addEventListener("keydown", (e) => {+ if (!e.isTrusted || (!e.metaKey && !e.ctrlKey)) return;+ post({+ type: "keydown",+ key: e.key,+ code: e.code,+ metaKey: e.metaKey,+ ctrlKey: e.ctrlKey,+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ });+ });++ // --- error reporting (feeds the host's self-repair loop) ---+ const reportError = (message, stack) =>+ post({ type: "error", message: String(message ?? "Unknown error"), stack });+ window.addEventListener("error", (e) =>+ reportError(e.message, e.error && e.error.stack),+ );+ window.addEventListener("unhandledrejection", (e) =>+ reportError(+ (e.reason && e.reason.message) || e.reason,+ e.reason && e.reason.stack,+ ),+ );++ // JSX text and attribute strings never process \uXXXX escapes (they render+ // verbatim, e.g. "\u00b7" instead of "·"), but generated canvases still+ // contain them despite the prompt rules — decode at transpile time so both+ // new and already-saved canvases render the real characters. Escapes inside+ // JS string/template literals are untouched (Babel already decoded those).+ const decodeUnicodeEscapes = function decodeJsxUnicodeEscapes(value) {+ return value.replace(/\\u\{([0-9a-fA-F]{1,6})\}|\\u([0-9a-fA-F]{4})/g, (match, braced, plain) => {+ try {+ return String.fromCodePoint(Number.parseInt(braced || plain, 16));+ } catch {+ return match;+ }+ });+};+ const jsxUnicodeEscapesPlugin = () => ({+ visitor: {+ JSXText(path) {+ const decoded = decodeUnicodeEscapes(path.node.value);+ if (decoded !== path.node.value) {+ path.node.value = decoded;+ }+ },+ JSXAttribute(path) {+ const v = path.node.value;+ if (v && v.type === "StringLiteral") {+ const decoded = decodeUnicodeEscapes(v.value);+ if (decoded !== v.value) {+ v.value = decoded;+ v.extra = undefined; // drop stale raw so the decoded value is emitted+ }+ }+ },+ },+ });++ const compileCanvasProject = function compileCanvasProject(Babel, files, entry, options) {+ const urls = new Map();+ const extensions = [+ "",+ ".tsx",+ ".ts",+ ".jsx",+ ".js",+ "/index.tsx",+ "/index.ts"+ ];+ const normalize = (parts) => {+ const out = [];+ for (const part of parts) {+ if (part === "" || part === ".") continue;+ if (part === "..") out.pop();+ else out.push(part);+ };+ return out.join("/");+ };+ const resolve = (from, specifier) => {+ const base = from.split("/").slice(0, -1);+ const joined = normalize([...base, ...specifier.split("/")]);+ for (const extension of extensions) {+ const candidate = joined + extension;+ if (candidate in files) return candidate;+ };+ return null;+ };+ const blobUrl = (code) => {+ const cached = options.cache.get(code);+ if (cached) return cached;+ const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));+ options.cache.set(code, url);+ return url;+ };+ const styleModule = (css) => {+ const style = document.createElement("style");+ style.setAttribute("data-canvas-style", "");+ style.textContent = css;+ document.head.appendChild(style);+ return blobUrl("export default null;");+ };+ const sourceRangePlugin = (file) => ({ types: t }) => ({ visitor: { JSXElement(path) {+ const node = path.node;+ if (typeof node.start !== "number" || typeof node.end !== "number") return;+ const name = node.openingElement.name;+ const tag = name.type === "JSXIdentifier" ? name.name : name.property?.name;+ if (tag === "Fragment") return;+ const repeated = !!path.findParent((parent) => parent.isCallExpression() && parent.node.callee.type === "MemberExpression" && parent.node.callee.property?.name === "map");+ const value = `${file}|${node.start}|${node.end}${repeated ? "|r" : ""}`;+ node.openingElement.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-ph-src"), t.stringLiteral(value)));+ } } });+ const build = (path, stack) => {+ const known = urls.get(path);+ if (known) return known;+ if (stack.includes(path)) throw new Error(`Circular import: ${[...stack, path].join(" -> ")}`);+ const source = files[path] ?? "";+ if (path.endsWith(".css")) {+ const url = styleModule(source);+ urls.set(path, url);+ return url;+ };+ if (path.endsWith(".json")) {+ const url = blobUrl(`export default ${source.trim() || "null"};`);+ urls.set(path, url);+ return url;+ };+ const rewriteImports = () => ({ visitor: { "ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration"(nodePath) {+ const sourceNode = nodePath.node.source;+ if (!sourceNode || typeof sourceNode.value !== "string") return;+ if (!sourceNode.value.startsWith(".")) return;+ const resolved = resolve(path, sourceNode.value);+ if (!resolved) throw new Error(`Cannot find "${sourceNode.value}" imported from ${path}`);+ sourceNode.value = build(resolved, [...stack, path]);+ } } });+ const plugins = [+ ...options.basePlugins,+ rewriteImports,+ ...options.editing && !path.startsWith("src/blocks/") ? [sourceRangePlugin(path)] : []+ ];+ const out = Babel.transform(source, {+ filename: path.split("/").pop(),+ plugins,+ presets: [["react", { runtime: "automatic" }], ["typescript", {+ isTSX: true,+ allExtensions: true,+ onlyRemoveTypeImports: true+ }]]+ }).code;+ const url = blobUrl(out ?? "");+ urls.set(path, url);+ return url;+ };+ for (const style of Array.from(document.querySelectorAll("style[data-canvas-style]"))) {+ style.remove();+ };+ return build(entry, []);+};+ const installCanvasEditing = function installCanvasEditing(post, labels) {+ const PRIMARY = "#f54e00";+ let enabled = false;+ let rev = 0;+ let hovered = null;+ let selected = null;+ let selectedBlockId = null;+ let selectedSource = null;+ let dragOrigin = null;+ let frame = 0;+ const EASE_OUT = "cubic-bezier(0.23, 1, 0.32, 1)";+ const EASE_IN_OUT = "cubic-bezier(0.77, 0, 0.175, 1)";+ const reduceMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const layer = document.createElement("div");+ layer.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483646;";+ const hoverBox = document.createElement("div");+ const selectBox = document.createElement("div");+ const label = document.createElement("div");+ const line = document.createElement("div");+ hoverBox.style.cssText = `position:fixed;left:0;top:0;border:1px solid rgba(245,78,0,.45);border-radius:8px;opacity:0;transition:opacity 100ms ease;`;+ selectBox.style.cssText = `position:fixed;left:0;top:0;border:1.5px solid ${PRIMARY};border-radius:10px;opacity:0;box-shadow:0 0 0 3px rgba(245,78,0,.08);transition:opacity 120ms ease;`;+ label.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};color:#fff;font:600 10.5px/18px system-ui,sans-serif;padding:0 7px;border-radius:5px 5px 0 0;opacity:0;white-space:nowrap;transition:opacity 120ms ease;`;+ line.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};border-radius:99px;opacity:0;transition:opacity 120ms ease,transform 110ms ${EASE_OUT};`;+ const emptyHint = document.createElement("div");+ emptyHint.textContent = "Drop blocks here, or click one in the panel";+ emptyHint.style.cssText = "position:fixed;display:flex;align-items:center;justify-content:center;border:1.5px dashed rgba(128,128,128,.35);border-radius:12px;color:rgba(128,128,128,.95);font:500 13px/1.4 system-ui,sans-serif;opacity:0;transition:opacity 160ms;";+ layer.append(emptyHint, hoverBox, selectBox, label, line);+ const parseSource = (element) => {+ const raw = element.getAttribute("data-ph-src");+ if (!raw) return null;+ const [file, start, end, flag] = raw.split("|");+ if (!file) return null;+ return {+ file,+ start: Number(start),+ end: Number(end),+ repeated: flag === "r"+ };+ };+ let openBlock = null;+ const candidateOf = (start) => {+ let element = start;+ while (element && element !== document.body) {+ const blockRoot = element.closest("[data-ph-block]");+ if (blockRoot instanceof HTMLElement && blockRoot !== openBlock && blockRoot.hasAttribute("data-ph-src")) return blockRoot;+ const source = parseSource(element);+ const rect = element.getBoundingClientRect();+ if (source && !source.repeated && rect.width >= 24 && rect.height >= 12) {+ return element;+ };+ element = element.parentElement;+ };+ return null;+ };+ const gridSourceOf = (element) => {+ const parent = element.parentElement;+ if (!parent || !getComputedStyle(parent).display.includes("grid")) return null;+ const source = parseSource(parent);+ if (!source || source.repeated) return null;+ return {+ file: source.file,+ start: source.start,+ end: source.end+ };+ };+ const fullGridRow = (element) => {+ const grid = gridSourceOf(element);+ const parent = element.parentElement;+ if (!grid || !parent) return null;+ const columns = getComputedStyle(parent).gridTemplateColumns.split(" ").filter(Boolean).length;+ if (columns < 2 || columns >= 4 || parent.children.length !== columns) return null;+ return {+ ...grid,+ columns+ };+ };+ const describe = (element) => {+ const source = parseSource(element);+ const blockType = element.getAttribute("data-ph-block");+ let props = {};+ try {+ props = JSON.parse(element.getAttribute("data-ph-props") ?? "{}");+ } catch {+ props = {};+ };+ const onlyText = element.children.length === 0 ? element.textContent ?? "" : null;+ const rawSource = element.getAttribute("data-ph-src");+ const twins = rawSource ? Array.from(document.querySelectorAll(`[data-ph-src="${CSS.escape(rawSource)}"]`)) : [];+ const instance = twins.length > 1 ? {+ index: twins.indexOf(element) + 1,+ count: twins.length+ } : null;+ const shownText = (element.innerText ?? "").replace(/\s+/g, " ").trim().slice(0, 120);+ return {+ rev,+ source: source ? {+ file: source.file,+ start: source.start,+ end: source.end+ } : null,+ blockType,+ blockId: element.getAttribute("data-ph-block-id"),+ props,+ tag: element.tagName.toLowerCase(),+ text: onlyText,+ visibleText: shownText || null,+ instance,+ params: element.getAttribute("data-ph-params"),+ layout: {+ inGrid: !!element.parentElement && getComputedStyle(element.parentElement).display.includes("grid"),+ grow: fullGridRow(element),+ grid: gridSourceOf(element)+ }+ };+ };+ const place = (box, element, inset = 0) => {+ if (!element || !element.isConnected) {+ box.style.opacity = "0";+ return;+ };+ const rect = element.getBoundingClientRect();+ box.style.transform = `translate3d(${rect.left - inset}px, ${rect.top - inset}px, 0)`;+ box.style.width = `${rect.width + inset * 2}px`;+ box.style.height = `${rect.height + inset * 2}px`;+ box.style.opacity = "1";+ };+ const labelFor = (element) => {+ const block = element.getAttribute("data-ph-block");+ if (!block) return labels[element.tagName.toLowerCase()] ?? "Element";+ const spaced = block.replace(/([a-z0-9])([A-Z])/g, "$1 $2");+ return labels[block] ?? spaced.charAt(0) + spaced.slice(1).toLowerCase();+ };+ const paintEmptyHint = () => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ const last = rootElement?.lastElementChild;+ const empty = enabled && !!rootElement && rootElement.children.length <= 1;+ if (!empty || !rootElement) {+ emptyHint.style.opacity = "0";+ return;+ };+ const style = getComputedStyle(rootElement);+ const box = rootElement.getBoundingClientRect();+ const left = box.left + Number.parseFloat(style.paddingLeft);+ const width = box.width - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight);+ const top = (last ? last.getBoundingClientRect().bottom : box.top) + 24;+ emptyHint.style.left = `${left}px`;+ emptyHint.style.top = `${top}px`;+ emptyHint.style.width = `${width}px`;+ emptyHint.style.height = "180px";+ emptyHint.style.opacity = "1";+ };+ const paint = () => {+ place(hoverBox, hovered && hovered !== selected ? hovered : null, 3);+ place(selectBox, selected, 4);+ if (selected?.isConnected) {+ const rect = selected.getBoundingClientRect();+ label.textContent = labelFor(selected);+ label.style.transform = `translate3d(${rect.left - 4}px, ${rect.top - 22}px, 0)`;+ label.style.opacity = "1";+ } else {+ label.style.opacity = "0";+ };+ paintEmptyHint();+ frame = requestAnimationFrame(paint);+ };+ const remember = (element) => {+ selected = element;+ selectedBlockId = element?.getAttribute("data-ph-block-id") ?? null;+ const source = element ? parseSource(element) : null;+ selectedSource = source ? {+ key: `${source.file}|${source.start}`,+ block: element?.getAttribute("data-ph-block") ?? null+ } : null;+ };+ const select = (element) => {+ remember(element);+ post({+ type: "canvas-edit-select",+ element: element ? describe(element) : null,+ byPointer: true+ });+ };+ const axisOf = (element) => {+ const parent = element.parentElement;+ if (!parent) return "column";+ const style = getComputedStyle(parent);+ if (style.display.includes("flex")) return style.flexDirection.startsWith("row") ? "row" : "column";+ if (style.display.includes("grid")) {+ const top = element.getBoundingClientRect().top;+ const siblings = Array.from(parent.children).filter((child) => child !== element);+ const sameRow = siblings.some((sibling) => Math.abs(sibling.getBoundingClientRect().top - top) < 6);+ return sameRow ? "row" : "column";+ };+ return "column";+ };+ const nearestChild = (container, x, y) => {+ let best = null;+ let bestDistance = Number.POSITIVE_INFINITY;+ for (const child of Array.from(container.children)) {+ const candidate = candidateOf(child);+ if (!candidate || candidate === container || !container.contains(candidate)) continue;+ const rect = candidate.getBoundingClientRect();+ const dx = Math.max(rect.left - x, 0, x - rect.right);+ const dy = Math.max(rect.top - y, 0, y - rect.bottom);+ const distance = Math.hypot(dx, dy);+ if (distance < bestDistance) {+ best = candidate;+ bestDistance = distance;+ }+ };+ return best;+ };+ const isBox = (element) => {+ const style = getComputedStyle(element);+ const bordered = Number.parseFloat(style.borderTopWidth) > 0 && Number.parseFloat(style.borderBottomWidth) > 0;+ const filled = style.backgroundColor !== "rgba(0, 0, 0, 0)" && style.backgroundColor !== "transparent";+ return (bordered || filled) && Number.parseFloat(style.borderTopLeftRadius) > 0;+ };+ const coarseTarget = (element, root) => {+ let current = element;+ while (current && current !== root) {+ const tall = current.getBoundingClientRect().height >= 100;+ if (current.hasAttribute("data-ph-block") || tall && isBox(current)) return current;+ const parent = candidateOf(current.parentElement);+ if (!parent || parent === current) break;+ current = parent;+ };+ let fallback = element;+ while (fallback !== root && fallback.getBoundingClientRect().height < 100) {+ const parent = candidateOf(fallback.parentElement);+ if (!parent || parent === fallback) break;+ fallback = parent;+ };+ return fallback;+ };+ const findDropTarget = (x, y, exclude, coarse) => {+ let target = candidateOf(document.elementFromPoint(x, y));+ const root = candidateOf(document.getElementById("root")?.firstElementChild ?? null);+ if (!target) target = root;+ if (!target) return null;+ if (coarse) target = coarseTarget(target, root);+ const rect = target.getBoundingClientRect();+ const layout = getComputedStyle(target).display;+ const arrangesChildren = layout.includes("grid") || layout.includes("flex") || rect.height > 160;+ const atomic = coarse && target !== root && isBox(target);+ const isContainer = target === root || !atomic && target.children.length > 1 && !target.hasAttribute("data-ph-block") && arrangesChildren;+ if (isContainer) {+ const child = nearestChild(target, x, y);+ if (child) target = child;+ };+ const source = parseSource(target);+ if (!source) return null;+ if (exclude) {+ const [file, start, end] = exclude.split("|");+ if (source.file === file && source.start >= Number(start) && source.end <= Number(end)) return null;+ };+ const box = target.getBoundingClientRect();+ const axis = axisOf(target);+ let position;+ let indicator;+ const edge = Math.min(64, box.width * .2);+ if (axis === "column" && box.width > 240 && x < box.left + edge) position = "left";+ else if (axis === "column" && box.width > 240 && x > box.right - edge) position = "right";+ else if (axis === "row") position = x < box.left + box.width / 2 ? "before" : "after";+ else position = y < box.top + box.height / 2 ? "before" : "after";+ const vertical = axis === "row" || position === "left" || position === "right";+ if (vertical) {+ const atStart = position === "before" || position === "left";+ indicator = {+ left: atStart ? box.left - 9 : box.right + 7,+ top: box.top,+ width: 2,+ height: box.height+ };+ } else {+ indicator = {+ left: box.left,+ top: position === "before" ? box.top - 9 : box.bottom + 7,+ width: box.width,+ height: 2+ };+ };+ const grow = position === "before" || position === "after" ? fullGridRow(target) : null;+ return {+ rev,+ target: {+ file: source.file,+ start: source.start,+ end: source.end,+ place: position,+ ...grow ? { grow } : {}+ },+ indicator+ };+ };+ const dropTarget = (x, y, exclude, coarse) => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ openBlock = rootElement?.hasAttribute("data-ph-block") ? rootElement : null;+ try {+ return findDropTarget(x, y, exclude, coarse);+ } finally {+ openBlock = null;+ }+ };+ const showLine = (indicator) => {+ if (!indicator) {+ line.style.opacity = "0";+ return;+ };+ const wasHidden = line.style.opacity !== "1";+ if (wasHidden) line.style.transition = "none";+ line.style.transform = `translate3d(${indicator.left}px, ${indicator.top}px, 0)`;+ line.style.width = `${indicator.width}px`;+ line.style.height = `${indicator.height}px`;+ if (wasHidden) {+ void line.offsetWidth;+ line.style.transition = `opacity 120ms ease, transform 110ms ${EASE_OUT}`;+ };+ line.style.opacity = "1";+ };+ let forwarding = false;+ let lifted = null;+ const drop = () => {+ if (!lifted) return;+ lifted.style.removeProperty("opacity");+ lifted.style.removeProperty("transition");+ lifted = null;+ };+ const onMove = (event) => {+ if (!enabled) return;+ const pressed = (event.buttons & 1) === 1;+ if (forwarding) {+ if (!pressed) {+ forwarding = false;+ drop();+ post({ type: "canvas-edit-pointer-cancel" });+ return;+ };+ post({+ type: "canvas-edit-pointer",+ x: event.clientX,+ y: event.clientY+ });+ return;+ };+ if (dragOrigin && !pressed) dragOrigin = null;+ hovered = candidateOf(event.target);+ if (dragOrigin && Math.hypot(event.clientX - dragOrigin.x, event.clientY - dragOrigin.y) > 5) {+ const described = describe(dragOrigin.element);+ lifted = dragOrigin.element;+ lifted.style.transition = "opacity 120ms";+ lifted.style.opacity = "0.35";+ dragOrigin = null;+ forwarding = true;+ hovered = null;+ post({+ type: "canvas-edit-drag-start",+ element: described,+ x: event.clientX,+ y: event.clientY+ });+ }+ };+ const TEXT_TAGS = [+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "p",+ "span",+ "li",+ "small",+ "strong",+ "em",+ "label",+ "td",+ "th",+ "blockquote",+ "figcaption"+ ];+ let editingText = null;+ const finishText = (commit) => {+ const current = editingText;+ if (!current) return;+ editingText = null;+ const { element, original } = current;+ const text = (element.textContent ?? "").replace(/\s+/g, " ").trim();+ element.removeAttribute("contenteditable");+ element.style.removeProperty("outline");+ element.style.removeProperty("cursor");+ if (!commit || !text || text === original.trim()) {+ element.textContent = original;+ return;+ };+ post({+ type: "canvas-edit-text",+ element: describe(element),+ text+ });+ };+ const startText = (element) => {+ const plain = !element.hasAttribute("data-ph-block") && element.children.length === 0 && TEXT_TAGS.includes(element.tagName.toLowerCase());+ if (!plain) return false;+ editingText = {+ element,+ original: element.textContent ?? ""+ };+ element.setAttribute("contenteditable", "plaintext-only");+ element.style.outline = "none";+ element.style.cursor = "text";+ element.focus();+ const range = document.createRange();+ range.selectNodeContents(element);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ element.addEventListener("blur", () => finishText(true), { once: true });+ element.addEventListener("keydown", (event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ element.blur();+ };+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ finishText(false);+ element.blur();+ }+ });+ return true;+ };+ const onDouble = (event) => {+ if (!enabled) return;+ event.preventDefault();+ event.stopPropagation();+ const element = candidateOf(event.target);+ if (element && element !== editingText?.element) startText(element);+ };+ const onDown = (event) => {+ forwarding = false;+ if (!enabled || event.button !== 0) return;+ if (editingText?.element.contains(event.target)) return;+ const element = candidateOf(event.target);+ event.preventDefault();+ event.stopPropagation();+ if (!element) {+ select(null);+ return;+ };+ select(element);+ const isRoot = element === candidateOf(document.getElementById("root")?.firstElementChild ?? null);+ if (!isRoot) dragOrigin = {+ x: event.clientX,+ y: event.clientY,+ element+ };+ };+ const swallow = (event) => {+ if (!enabled) return;+ event.preventDefault();+ event.stopPropagation();+ };+ const onUp = (_event) => {+ dragOrigin = null;+ if (!forwarding) return;+ forwarding = false;+ post({ type: "canvas-edit-pointer-up" });+ };+ const onKey = (event) => {+ if (!enabled) return;+ const target = event.target;+ if (target && (target.isContentEditable || [+ "INPUT",+ "TEXTAREA",+ "SELECT"+ ].includes(target.tagName))) return;+ if ([+ "Backspace",+ "Delete",+ "Escape"+ ].includes(event.key) || (event.metaKey || event.ctrlKey) && ["d", "z"].includes(event.key.toLowerCase())) {+ event.preventDefault();+ post({+ type: "canvas-edit-key",+ key: event.key,+ metaKey: event.metaKey,+ ctrlKey: event.ctrlKey,+ shiftKey: event.shiftKey+ });+ }+ };+ const land = (element) => {+ const keyframes = reduceMotion() ? [{ opacity: 0 }, { opacity: 1 }] : [{+ opacity: 0,+ transform: "scale(0.985)"+ }, {+ opacity: 1,+ transform: "none"+ }];+ element.animate(keyframes, {+ duration: 240,+ easing: EASE_OUT+ });+ };+ let captured = new Map();+ const capture = () => {+ captured = new Map();+ for (const element of Array.from(document.querySelectorAll("[data-ph-block-id]"))) {+ const id = element.getAttribute("data-ph-block-id");+ if (id) captured.set(id, element.getBoundingClientRect());+ }+ };+ const slideIntoPlace = () => {+ const before = captured;+ captured = new Map();+ if (reduceMotion() || before.size === 0) return before;+ for (const element of Array.from(document.querySelectorAll("[data-ph-block-id]"))) {+ const id = element.getAttribute("data-ph-block-id");+ const previous = id ? before.get(id) : undefined;+ if (!previous) continue;+ const now = element.getBoundingClientRect();+ const dx = previous.left - now.left;+ const dy = previous.top - now.top;+ const resized = Math.abs(previous.width - now.width) > 2 || Math.abs(previous.height - now.height) > 2;+ if (resized || Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;+ element.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }], {+ duration: 300,+ easing: EASE_IN_OUT+ });+ };+ return before;+ };+ const afterMount = (nextRev, focusBlockId, focusSource, attempt = 0) => {+ rev = nextRev;+ hovered = null;+ const rootElement = candidateOf(document.getElementById("root")?.firstElementChild ?? null);+ if (!rootElement && attempt < 120) {+ requestAnimationFrame(() => {+ if (rev === nextRev) afterMount(nextRev, focusBlockId, focusSource, attempt + 1);+ });+ return;+ };+ const previousRects = slideIntoPlace();+ const rootSource = rootElement ? parseSource(rootElement) : null;+ post({+ type: "canvas-edit-root",+ rev,+ root: rootSource ? {+ file: rootSource.file,+ start: rootSource.start,+ end: rootSource.end+ } : null+ });+ const id = focusBlockId ?? selectedBlockId;+ const sourceAt = (key) => document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);+ const previous = selectedSource ? sourceAt(selectedSource.key) : null;+ const sameBlock = previous?.getAttribute("data-ph-block") === selectedSource?.block;+ const bySource = focusSource ? sourceAt(focusSource) : sameBlock ? previous : null;+ const element = id ? document.querySelector(`[data-ph-block-id="${CSS.escape(id)}"]`) : bySource;+ if (element instanceof HTMLElement) {+ remember(element);+ post({+ type: "canvas-edit-select",+ element: describe(element)+ });+ const arrived = !!focusBlockId && !focusSource && !previousRects.has(focusBlockId);+ if (arrived) land(element);+ } else {+ remember(null);+ post({+ type: "canvas-edit-select",+ element: null+ });+ }+ };+ const setEnabled = (next) => {+ if (next === enabled) return;+ enabled = next;+ if (enabled) {+ document.body.appendChild(layer);+ document.documentElement.style.cursor = "default";+ frame = requestAnimationFrame(paint);+ } else {+ layer.remove();+ cancelAnimationFrame(frame);+ selected = null;+ hovered = null;+ }+ };+ window.addEventListener("mousemove", onMove, true);+ window.addEventListener("mousedown", onDown, true);+ window.addEventListener("mouseup", onUp, true);+ window.addEventListener("click", swallow, true);+ window.addEventListener("dblclick", onDouble, true);+ window.addEventListener("keydown", onKey, true);+ document.addEventListener("mouseleave", () => {+ hovered = null;+ });+ return {+ capture,+ setEnabled,+ afterMount,+ handle(message) {+ if (message.type === "canvas-edit-drag-move") {+ const hit = enabled ? dropTarget(Number(message.x), Number(message.y), message.exclude ?? null, message.coarse === true) : null;+ showLine(hit?.indicator ?? null);+ post({+ type: "canvas-edit-drop-target",+ hit: hit ? {+ rev: hit.rev,+ target: hit.target+ } : null+ });+ return true;+ };+ if (message.type === "canvas-edit-drag-end") {+ if (message.final === true) {+ forwarding = false;+ dragOrigin = null;+ drop();+ };+ showLine(null);+ return true;+ };+ if (message.type === "canvas-edit-deselect") {+ remember(null);+ return true;+ };+ return false;+ }+ };+};+ const editing = installCanvasEditing(post, {"h1":"Heading","h2":"Heading","h3":"Heading","p":"Text","hr":"Divider","header":"Header","main":"Page","section":"Section","Metric":"Number","Trend":"Trend","TopList":"Top list","Funnel":"Funnel","SqlTable":"SQL","Goal":"Goal","Insight":"Saved insight","Retention":"Retention","RecentEvents":"Recent events","DateRange":"Date range","Interval":"Interval","Filters":"Filters","PropertyFilter":"Quick filter","Compare":"Compare","Refresh":"Refresh","Heading":"Heading","Paragraph":"Text","Divider":"Divider","Callout":"Callout"});+ const moduleCache = new Map();++ let root = null;+ // mount() is async and is called once per streamed code snapshot, so several+ // runs overlap on their awaits. Without ordering, a slower EARLIER (partial,+ // often invalid) snapshot could run root.render last and clobber the latest+ // good render — the bug where live edits don't appear until you revisit.+ // A monotonic sequence makes only the newest mount commit its render/error;+ // superseded runs bail out after each await.+ let mountSeq = 0;+ const mount = async (input) => {+ const seq = ++mountSeq;+ try {+ const revoke = !input.files;+ const url = compileCanvasProject(+ Babel,+ input.files || { "canvas.tsx": input.code },+ input.files ? input.entry || "src/canvas.tsx" : "canvas.tsx",+ {+ editing: !!input.editing,+ basePlugins: [jsxUnicodeEscapesPlugin],+ cache: revoke ? new Map() : moduleCache,+ },+ );+ let mod;+ try {+ mod = await import(url);+ } finally {+ if (revoke) URL.revokeObjectURL(url);+ }+ if (seq !== mountSeq) return; // a newer snapshot superseded this one+ const Comp = mod.default;+ if (typeof Comp !== "function") {+ throw new Error("Canvas must `export default` a React component.");+ }+ const React = await import("react");+ const { createRoot } = await import("react-dom/client");+ if (seq !== mountSeq) return;+ const el = document.getElementById("root");+ if (!root) root = createRoot(el);++ // Catch render-time throws so one bad render doesn't white-screen the+ // host; the error is reported and the host keeps showing last-good.+ class Boundary extends React.Component {+ constructor(p) { super(p); this.state = { error: null }; }+ static getDerivedStateFromError(error) { return { error }; }+ componentDidCatch(error) { reportError(error.message, error.stack); }+ render() {+ if (this.state.error) return React.createElement(Committed, { key: "failed", failed: true });+ return this.props.children;+ }+ }+ if (input.editing) editing.capture();+ const afterCommit = (failed) => {+ requestAnimationFrame(() => {+ if (seq !== mountSeq) return;+ renderCommentHighlights(currentCommentHighlights);+ editing.setEnabled(!!input.editing);+ if (input.editing) editing.afterMount(input.rev || 0, input.focusBlockId || null, input.focusSource || null);+ if (!failed) post({ type: "rendered" });+ });+ };+ function Committed(props) {+ React.useLayoutEffect(() => {+ afterCommit(!!props.failed);+ }, []);+ return null;+ }+ root.render(+ React.createElement(+ Boundary,+ null,+ React.createElement(Comp),+ React.createElement(Committed, { key: seq }),+ ),+ );+ } catch (err) {+ // Only the latest snapshot reports — a superseded partial's parse error+ // must not surface as the canvas's error or flicker the host banner.+ if (seq !== mountSeq) return;+ let message = err && err.message;+ // Chrome reports a failed CDN fetch of the code's imports as an opaque+ // error naming the blob module; name the real dependency instead.+ if (message && message.indexOf("Failed to fetch dynamically imported module") !== -1) {+ message = "Couldn't load the canvas libraries from esm.sh. " ++ "Previewing an unbuilt canvas needs network access to https://esm.sh; " ++ "published canvases are unaffected.";+ }+ reportError(message, err && err.stack);+ }+ };++ const receive = (d) => {+ if (!d || d.channel !== CHANNEL) return;+ if (editing.handle(d)) return;+ if (d.type === "init") {+ applyTheme(d.theme);+ currentCommentHighlights = d.highlights || [];+ if (d.analytics) void bootAnalytics(d.analytics);+ void mount(d);+ } 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;+ pending.delete(d.id);+ d.ok+ ? p.resolve(d.result)+ : p.reject(new Error(d.error || "data error"), d.retryable === true);+ }+ };+ window.addEventListener("message", (e) => {+ if (e.source !== parent) return;+ if (e.data?.channel === CHANNEL && e.data.type === "connect" && e.ports[0] && !bridgePort) {+ bridgePort = e.ports[0];+ sendToHost = bridgePort.postMessage.bind(bridgePort);+ bridgePort.onmessage = (event) => receive(event.data);+ post({ type: "ready" });+ } else if (!portOnly && !bridgePort) {+ receive(e.data);+ }+ });+ window.addEventListener("pagehide", () => bridgePort?.close());++ post({ type: "ready" });+ </script>+</body>+</html>\ No newline at end of filediff --git a/products/canvas/backend/tests/test_artifact_tokens.py b/products/canvas/backend/tests/test_artifact_tokens.pyindex f3a2fe692099..646ca73cabc0 100644--- a/products/canvas/backend/tests/test_artifact_tokens.py+++ b/products/canvas/backend/tests/test_artifact_tokens.py@@ -7,12 +7,19 @@ from django.core import signingfrom django.http import Http404from django.test import RequestFactory, SimpleTestCase, override_settings+from parameterized import parameterized+from products.canvas.backend.artifacts import (ARTIFACT_TOKEN_SALT,+ SANDBOX_DOCUMENT_PATH,+ _parse_sandbox_document,+ _publish_sandbox_document,_read_token,+ _sandbox_document,canvas_artifact,create_canvas_artifact_token,create_canvas_artifact_url,+ create_canvas_sandbox_document_url,)from products.canvas.backend.checks import check_artifact_delivery_settings@@ -29,6 +36,12 @@ def _claims(**overrides):class TestCanvasArtifactTokens(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.write = patch("products.canvas.backend.artifacts.object_storage.write").start()+ self.addCleanup(patch.stopall)+ _publish_sandbox_document.cache_clear()+@override_settings(CANVAS_ARTIFACT_SIGNING_KEYS=["new-key-at-least-32-bytes-long", "old-key-at-least-32-bytes-long"])@@ -194,11 +207,19 @@ class TestCanvasArtifactTokens(SimpleTestCase):# A too-short primary key is refused in production (fail closed).with override_settings(CANVAS_ARTIFACT_SIGNING_KEYS=["too-short"]):self.assertIsNone(create_canvas_artifact_token(MagicMock()))+ self.assertIsNone(create_canvas_sandbox_document_url())# A misconfigured origin (non-https, or carrying a path/credentials) is refused.with override_settings(CANVAS_ARTIFACT_ORIGIN="http://usercontent.example"):self.assertIsNone(create_canvas_artifact_token(MagicMock()))+ self.assertIsNone(create_canvas_sandbox_document_url())with override_settings(CANVAS_ARTIFACT_ORIGIN="https://usercontent.example/path"):self.assertIsNone(create_canvas_artifact_token(MagicMock()))+ self.assertIsNone(create_canvas_sandbox_document_url())+ self.assertEqual(+ create_canvas_sandbox_document_url(),+ f"https://usercontent.example/canvas-artifacts/sandbox/"+ f"{hashlib.sha256(SANDBOX_DOCUMENT_PATH.read_bytes()).hexdigest()}/index.html",+ )@override_settings(CANVAS_ARTIFACT_SIGNING_KEYS=["a-signing-key-at-least-32-bytes-long"])def test_url_round_trips_through_read_token(self) -> None:@@ -211,3 +232,86 @@ class TestCanvasArtifactTokens(SimpleTestCase):claims = _read_token(token)self.assertEqual(claims["team_id"], 1)self.assertEqual(claims["canvas_id"], "00000000-0000-0000-0000-000000000001")+++@override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example",+ SITE_URL="https://app.example",+)+class TestCanvasSandboxDocument(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.objects: dict[str, bytes] = {}+ writer = patch("products.canvas.backend.artifacts.object_storage.write", side_effect=self.objects.__setitem__)+ reader = patch(+ "products.canvas.backend.artifacts.object_storage.read_bytes",+ side_effect=lambda key, **kwargs: self.objects.get(key),+ )+ writer.start()+ reader.start()+ self.addCleanup(writer.stop)+ self.addCleanup(reader.stop)+ _publish_sandbox_document.cache_clear()+ self.addCleanup(_publish_sandbox_document.cache_clear)++ def test_serves_an_advertised_document_after_the_process_changes_version(self) -> None:+ path = self._path()+ original = _sandbox_document().content+ replacement = _parse_sandbox_document(original + b"\n")+ with patch("products.canvas.backend.artifacts._sandbox_document", return_value=replacement):+ response = self.client.get(path, HTTP_HOST="usercontent.example")+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.content, original)++ def _path(self) -> str:+ url = create_canvas_sandbox_document_url()+ assert url is not None+ return url.removeprefix("https://usercontent.example")++ @parameterized.expand([("artifact_host", "usercontent.example", 200), ("app_host", "app.example", 404)])+ def test_serves_only_on_the_artifact_host(self, _name: str, host: str, expected_status: int) -> None:+ response = self.client.get(self._path(), HTTP_HOST=host)++ self.assertEqual(response.status_code, expected_status)++ @parameterized.expand([("generated", False), ("widened_meta_policy", True)])+ def test_serves_the_document_under_its_own_sandboxing_policy(self, _name: str, widen_meta: bool) -> None:+ content = SANDBOX_DOCUMENT_PATH.read_bytes()+ if widen_meta:+ content = content.replace(+ b"default-src 'none';",+ b"sandbox allow-scripts allow-same-origin allow-popups; frame-ancestors *; "+ b"img-src https:; form-action *; base-uri *; default-src 'none';",+ )+ with patch(+ "products.canvas.backend.artifacts._sandbox_document", return_value=_parse_sandbox_document(content)+ ):+ response = self.client.get(self._path(), HTTP_HOST="usercontent.example")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.content, content)+ self.assertEqual(response["Content-Type"], "text/html; charset=utf-8")+ self.assertEqual(response["Cache-Control"], "public, max-age=31536000, immutable")+ self.assertEqual(response["X-Content-Type-Options"], "nosniff")+ self.assertEqual(response["Referrer-Policy"], "no-referrer")+ self.assertNotIn("X-Frame-Options", response)+ self.assertNotIn("Content-Security-Policy-Report-Only", response)+ csp = [part.strip() for part in response["Content-Security-Policy"].split(";")]+ self.assertIn("sandbox allow-scripts", csp)+ self.assertIn("frame-ancestors https://app.example https://posthog.com https://preview.posthog.com", csp)+ self.assertIn("default-src 'none'", csp)+ self.assertTrue(any(part.startswith("script-src ") and "https://esm.sh" in part for part in csp))+ for name, directive in {+ "sandbox": "sandbox allow-scripts",+ "frame-ancestors": "frame-ancestors https://app.example https://posthog.com https://preview.posthog.com",+ "img-src": "img-src data: blob:",+ "form-action": "form-action 'none'",+ "base-uri": "base-uri 'none'",+ "object-src": "object-src 'none'",+ }.items():+ self.assertEqual([part for part in csp if part.split()[0] == name], [directive])++ def test_unknown_content_hash_404s(self) -> None:+ response = self.client.get(f"/canvas-artifacts/sandbox/{'0' * 64}/index.html", HTTP_HOST="usercontent.example")++ self.assertEqual(response.status_code, 404)diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex 50e2e715d44c..8216dba92c33 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -1,3 +1,4 @@+import reimport jsonfrom datetime import timedeltafrom types import SimpleNamespace@@ -1041,6 +1042,9 @@ class TestCanvasViewEndpoint(CanvasAPIBaseTest):assert body["has_active_build"] is Trueassert "src/canvas.tsx" in body["source"]["files"]assert body["layout"] is None+ assert re.fullmatch(+ r"http://localhost:8010/canvas-artifacts/sandbox/[0-9a-f]{64}/index\.html", body["sandbox_document_url"]+ )def test_view_after_build_returns_artifact_url_and_omits_source(self):canvas_id = self._create_canvas()diff --git a/products/canvas/frontend/canvasAnalytics.ts b/products/canvas/frontend/canvasAnalytics.tsnew file mode 100644index 000000000000..80bce5514b2b--- /dev/null+++ b/products/canvas/frontend/canvasAnalytics.ts@@ -0,0 +1,17 @@+// pinned: analytics event names and property names, shared with PostHog Desktop. Renaming breaks dashboards.+export const CANVAS_EVENTS = {+ dashboardAction: 'Dashboard action',+ promptSent: 'Canvas prompt sent',+ viewed: 'Canvas viewed',+ rendered: 'Canvas rendered',+ runtimeError: 'Canvas runtime error',+} as const++// pinned: `surface` values, shared with PostHog Desktop+export type CanvasSurface = 'web_new_canvas_page' | 'web_canvas_scene'++/** The error's class name, never its message: canvas errors can carry source, data, or secrets. */+export function canvasErrorType(message: string): string {+ const match = /^([A-Z][A-Za-z]*Error)\b/.exec(message.trim())+ return match ? match[1] : 'unknown'+}diff --git a/products/canvas/frontend/canvasTasksApi.ts b/products/canvas/frontend/canvasTasksApi.tsnew file mode 100644index 000000000000..358db1b1a471--- /dev/null+++ b/products/canvas/frontend/canvasTasksApi.ts@@ -0,0 +1,91 @@+import {+ taskChannelsList,+ taskChannelsProvisionDefaultsCreate,+ taskChannelsRetrieve,+ tasksCreate,+ tasksRetrieve,+ tasksRunCreate,+} 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'>++export type CanvasGenerationTask = Pick<TaskDetailDTOApi, 'id' | 'title'> & {+ latest_run: Pick<NonNullable<TaskDetailDTOApi['latest_run']>, 'status'> | null+}++function toCanvasTask(task: Pick<TaskDetailDTOApi, 'id' | 'title' | 'latest_run'>): CanvasGenerationTask {+ return { id: task.id, title: task.title, latest_run: task.latest_run ?? null }+}++// pinned: task run statuses from the tasks API+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed', 'cancelled'])++export function isTerminalRunStatus(status: string | null | undefined): boolean {+ return !!status && TERMINAL_RUN_STATUSES.has(status)+}++function toSpaces(response: unknown): CanvasSpace[] {+ const rows = Array.isArray(response) ? response : ((response as { results?: unknown[] })?.results ?? [])+ return (rows as Record<string, unknown>[]).map((row) => ({+ id: String(row.id),+ name: String(row.name ?? ''),+ system_role: row.system_role === 'personal' || row.system_role === 'general' ? row.system_role : null,+ }))+}++/** The spaces the user can see. Provisions the personal space when it does not exist yet. */+export async function loadCanvasSpaces(projectId: string): Promise<CanvasSpace[]> {+ const spaces = toSpaces(await taskChannelsList(projectId))+ if (spaces.some((space) => space.system_role === 'personal')) {+ return spaces+ }+ const provisioned = await taskChannelsProvisionDefaultsCreate(projectId)+ return toSpaces(provisioned.channels)+}++export async function loadCanvasSpace(projectId: string, spaceId: string): Promise<CanvasSpace> {+ const [space] = toSpaces([await taskChannelsRetrieve(projectId, spaceId)])+ return space+}++/** The label a person sees for a space. It matches the Spaces sidebar, which shows the personal space as "Me". */+export function canvasSpaceLabel(space: Pick<CanvasSpace, 'name' | 'system_role'>): string {+ return space.system_role === 'personal' ? 'Me' : space.name+}++/**+ * Starts the cloud task that builds a canvas. The run is unattended, so it bypasses+ * permission prompts the same way PostHog Desktop's canvas generation does. The model+ * is left to the server default. The server titles the task synchronously.+ */+export async function createCanvasGenerationTask(+ projectId: string,+ input: { description: string; namingSource: string; spaceId: string; startRun?: boolean }+): Promise<CanvasGenerationTask> {+ return toCanvasTask(+ await tasksCreate(projectId, {+ description: input.description,+ // The server titles the task from this, so the title reflects the request, not the injected instructions.+ naming_source: input.namingSource,+ origin_product: 'user_created',+ channel: input.spaceId,+ start_run: input.startRun ?? true,+ initial_permission_mode: 'bypassPermissions',+ })+ )+}++export async function loadCanvasGenerationTask(projectId: string, taskId: string): Promise<CanvasGenerationTask> {+ return toCanvasTask(await tasksRetrieve(projectId, taskId))+}++export async function startCanvasGenerationRun(projectId: string, taskId: string): Promise<CanvasGenerationTask> {+ return toCanvasTask(+ await tasksRunCreate(projectId, taskId, {+ mode: 'background',+ run_source: 'manual',+ initial_permission_mode: 'bypassPermissions',+ })+ )+}diff --git a/products/canvas/frontend/canvasTemplates.ts b/products/canvas/frontend/canvasTemplates.tsnew file mode 100644index 000000000000..193466d4bbf5--- /dev/null+++ b/products/canvas/frontend/canvasTemplates.ts@@ -0,0 +1,27 @@+// Mirrors PostHog Desktop's built-in canvas templates. The backend exposes no template+// endpoint, so the picker reads this list.++// pinned: template id stored on the canvas record and read by the generation prompt+export const FREEFORM_TEMPLATE_ID = 'freeform'++// Default name for a new canvas, and the marker that it is still safe to auto-name.+export const UNTITLED_CANVAS_NAME = 'Untitled canvas'++export interface CanvasTemplate {+ id: string+ name: string+ description: string+}++export const CANVAS_TEMPLATES: CanvasTemplate[] = [+ {+ id: FREEFORM_TEMPLATE_ID,+ name: 'Freeform (React)',+ description: 'Describe anything. The agent writes a React app that runs in a sandbox and can be shared.',+ },+]++export function isPlaceholderCanvasName(name: string): boolean {+ const trimmed = name.trim()+ return trimmed === UNTITLED_CANVAS_NAME || trimmed === 'Untitled dashboard'+}diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex 329e3cdcf8e3..453f4538d9d2 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -1748,6 +1748,11 @@ export interface CanvasViewResponseApi {layout?: CanvasLayoutApi | null/** For grid canvases: the renderable build of every component the layout's live placements reference, so the grid renders from this one call. Absent for other kinds. */component_lifecycles?: CanvasComponentLifecycleApi[]+ /**+ * URL of the sandbox document that renders the head source project in an iframe, served from the artifact origin. Load it by URL, not as srcdoc. Null when artifact delivery is unavailable.+ * @nullable+ */+ readonly sandbox_document_url: string | null}/**diff --git a/products/canvas/frontend/host/BuiltCanvas.tsx b/products/canvas/frontend/host/BuiltCanvas.tsxnew file mode 100644index 000000000000..60973aeaec95--- /dev/null+++ b/products/canvas/frontend/host/BuiltCanvas.tsx@@ -0,0 +1,116 @@+import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'++import type { CanvasCapabilitiesApi } from '../generated/api.schemas'+import { assertCanvasCapability } from './canvasCapabilities'+import { CanvasHostCallbacks, createCanvasHostMessageRouter } from './canvasHostMessageRouter'+import { CANVAS_CHANNEL, CanvasTheme, HostToCanvasMessage, canvasToHostMessageSchema } from './canvasProtocol'++export interface BuiltCanvasProps extends CanvasHostCallbacks {+ /** The signed URL of the build's entry HTML, on the artifact origin. */+ artifactUrl: string+ /** The capabilities frozen into the build. A missing manifest denies every data request. */+ capabilities: CanvasCapabilitiesApi | null | undefined+ theme: CanvasTheme+ hasUserActivation: () => boolean+ onOpenExternal: (url: string) => void+}++/** The artifact URL with the theme in its fragment, which never reaches the server. */+export function themedArtifactUrl(artifactUrl: string, theme: CanvasTheme): string {+ const url = new URL(artifactUrl)+ url.hash = new URLSearchParams({ theme }).toString()+ return url.href+}++/**+ * Renders a published build. The iframe loads the signed artifact URL directly: a+ * srcdoc host document would inherit the web app's CSP, which blocks its inline script.+ * On load the host hands the artifact a MessagePort, and every message after that goes+ * over the port.+ */+export function BuiltCanvas({+ artifactUrl,+ capabilities,+ theme,+ hasUserActivation,+ onOpenExternal,+ ...callbacks+}: BuiltCanvasProps): JSX.Element {+ const iframeRef = useRef<HTMLIFrameElement>(null)+ const portRef = useRef<MessagePort | null>(null)+ // The theme reaches the first paint through the fragment. Later changes go over the+ // port, so a theme toggle does not reload the artifact.+ const initialTheme = useRef(theme).current+ const src = useMemo(() => themedArtifactUrl(artifactUrl, initialTheme), [artifactUrl, initialTheme])+ const latest = useRef({ capabilities, callbacks, theme, onOpenExternal, hasUserActivation })+ latest.current = { capabilities, callbacks, theme, onOpenExternal, hasUserActivation }++ useLayoutEffect(() => {+ const iframe = iframeRef.current+ let loads = 0+ const post = (message: HostToCanvasMessage): void => portRef.current?.postMessage(message)+ const route = createCanvasHostMessageRouter({+ post,+ callbacks: () => ({+ ...latest.current.callbacks,+ onDataRequest: (method, payload) => {+ // Gating here means every consumer of a build gets it.+ assertCanvasCapability(latest.current.capabilities, method, payload)+ return latest.current.callbacks.onDataRequest(method, payload)+ },+ }),+ hasUserActivation: () => latest.current.hasUserActivation(),+ openExternal: (url) => latest.current.onOpenExternal(url),+ })+ const onPortMessage = (event: MessageEvent): void => {+ const parsed = canvasToHostMessageSchema.safeParse(event.data)+ if (parsed.success) {+ void route(parsed.data)+ }+ }+ const dropPort = (): void => {+ portRef.current?.close()+ portRef.current = null+ }+ const onLoad = (): void => {+ loads += 1+ // A second load means the artifact navigated away from itself. Whatever loaded+ // now is not the build, so it gets no bridge.+ if (loads > 1) {+ dropPort()+ return+ }+ const bridge = new MessageChannel()+ portRef.current = bridge.port1+ bridge.port1.addEventListener('message', onPortMessage)+ bridge.port1.start()+ // nosemgrep: wildcard-postmessage-configuration -- Opaque sandbox origin; only the first load gets a port, which closes on navigation.+ iframe?.contentWindow?.postMessage({ channel: CANVAS_CHANNEL, type: 'connect' }, '*', [bridge.port2])+ post({ channel: CANVAS_CHANNEL, type: 'set-theme', theme: latest.current.theme })+ }+ iframe?.addEventListener('load', onLoad)+ return () => {+ iframe?.removeEventListener('load', onLoad)+ dropPort()+ }+ }, [src])++ useEffect(() => {+ portRef.current?.postMessage({ channel: CANVAS_CHANNEL, type: 'set-theme', theme })+ }, [theme])++ return (+ <iframe+ ref={iframeRef}+ title="Canvas"+ // allow-scripts without allow-same-origin keeps the artifact in an opaque origin.+ // Do not add allow-popups or allow-same-origin.+ sandbox="allow-scripts"+ src={src}+ referrerPolicy="no-referrer"+ // Without a matching color-scheme the browser paints the frame white before the artifact's styles land.+ style={{ colorScheme: theme }}+ className="h-full w-full border-0 bg-background"+ />+ )+}diff --git a/products/canvas/frontend/host/CanvasHostPromptDialog.stories.tsx b/products/canvas/frontend/host/CanvasHostPromptDialog.stories.tsxnew file mode 100644index 000000000000..dc0db70194a3--- /dev/null+++ b/products/canvas/frontend/host/CanvasHostPromptDialog.stories.tsx@@ -0,0 +1,53 @@+import { Meta, StoryObj } from '@storybook/react'+import { screen, waitFor } from '@testing-library/react'+import { BindLogic } from 'kea'++import { canvasHostLogic } from './canvasHostLogic'+import { CanvasHostPromptDialog } from './CanvasHostPromptDialog'++const props = { canvasId: 'example-canvas', spaceId: 'example-space', sourceVersionId: 'example-version' }++const meta: Meta<typeof CanvasHostPromptDialog> = {+ component: CanvasHostPromptDialog,+ title: 'Scenes-App/Canvas/Action confirmation',+ tags: ['test-skip'],+ decorators: [+ (Story) => (+ <BindLogic logic={canvasHostLogic} props={props}>+ <Story />+ </BindLogic>+ ),+ ],+ parameters: { layout: 'fullscreen', testOptions: { viewport: { width: 900, height: 700 } } },+}+export default meta++type Story = StoryObj<typeof CanvasHostPromptDialog>++export const StartTask: Story = {+ play: async () => {+ await waitFor(() => {+ if (!canvasHostLogic.findMounted(props)) {+ throw new Error('Canvas host is not mounted yet')+ }+ })+ canvasHostLogic(props).actions.enqueuePrompt({+ kind: 'action',+ id: 'example-prompt',+ request: {+ action: {+ verb: 'tasks.create_and_run',+ summary: 'Start a cloud task in this space.',+ destructive: false,+ usage: '',+ },+ payload: {+ title: 'Check the example chart',+ description: 'Check how the example chart counts daily signups.',+ idempotency_key: 'example-request',+ },+ },+ })+ await screen.findByRole('dialog', { name: 'Let this canvas make this change?' })+ },+}diff --git a/products/canvas/frontend/host/CanvasHostPromptDialog.tsx b/products/canvas/frontend/host/CanvasHostPromptDialog.tsxnew file mode 100644index 000000000000..c0bc66526688--- /dev/null+++ b/products/canvas/frontend/host/CanvasHostPromptDialog.tsx@@ -0,0 +1,174 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Text,+} from '@posthog/quill'++import { CanvasHostPrompt, canvasHostLogic } from './canvasHostLogic'++interface PromptCopy {+ title: string+ description: string+ confirm: string+ destructive?: boolean+}++function promptCopy(prompt: CanvasHostPrompt): PromptCopy {+ switch (prompt.kind) {+ case 'connector':+ return prompt.request.reason === 'tool'+ ? {+ title: 'Allow this tool call?',+ description:+ 'This tool is set to ask for permission. Allow only this call. Your saved tool permissions will not change.',+ confirm: 'Allow once',+ }+ : {+ title: 'Allow this canvas to use your connection?',+ description:+ 'This canvas wants to read data with your connection. Only allow canvases you trust.',+ confirm: 'Allow access',+ }+ case 'agent-request':+ return {+ title: 'Ask the canvas agent to make this change?',+ description:+ 'Review the exact request. Accepting starts an agent run that uses compute. The result arrives as a draft for review.',+ confirm: 'Accept and run',+ }+ case 'action':+ return {+ title: 'Let this canvas make this change?',+ description:+ prompt.request.action.verb === 'tasks.create_and_run'+ ? 'Review this request. Accepting starts a cloud task that uses paid compute.'+ : 'Review this request before the canvas makes a change on your behalf.',+ confirm: 'Continue',+ destructive: prompt.request.action.destructive,+ }+ case 'external-link':+ return {+ title: 'Open this link?',+ description: 'The canvas wants to open a page in a new tab.',+ confirm: 'Open link',+ }+ }+}++function PromptDetails({ prompt }: { prompt: CanvasHostPrompt }): JSX.Element {+ switch (prompt.kind) {+ case 'connector':+ return (+ <div className="flex flex-col gap-2">+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 rounded border border-border p-3">+ <dt>+ <Text size="sm">Connection</Text>+ </dt>+ <dd className="break-all">+ <Text size="sm">{prompt.request.provider}</Text>+ </dd>+ <dt>+ <Text size="sm">Tool</Text>+ </dt>+ <dd className="break-all font-mono">+ <Text size="sm">{prompt.request.tool}</Text>+ </dd>+ </dl>+ {prompt.request.reason === 'tool' && (+ <pre className="max-h-48 overflow-auto whitespace-pre-wrap break-all rounded border border-border p-3 text-xs">+ {JSON.stringify(prompt.request.arguments ?? {}, null, 2)}+ </pre>+ )}+ <Text size="sm" variant="muted">+ The canvas can receive private data and share it through its declared capabilities.+ </Text>+ </div>+ )+ case 'agent-request':+ return (+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded border border-border p-3 text-sm">+ {prompt.prompt}+ </pre>+ )+ case 'action':+ return (+ <div className="flex flex-col gap-2">+ <Text size="sm">{prompt.request.action.summary}</Text>+ <Text size="sm" className="break-all font-mono">+ {prompt.request.action.verb}+ </Text>+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-all rounded border border-border p-3 text-sm">+ {JSON.stringify(prompt.request.payload, null, 2)}+ </pre>+ </div>+ )+ case 'external-link':+ return (+ <Text className="break-all font-mono" size="sm">+ {prompt.url}+ </Text>+ )+ }+}++/**+ * Asks the viewer before a canvas uses a connection, starts an agent run, runs a+ * action, or opens a link. Render it under a `BindLogic` for `canvasHostLogic`.+ */+export function CanvasHostPromptDialog(): JSX.Element {+ const { activePrompt } = useValues(canvasHostLogic)+ const { respondToPrompt } = useActions(canvasHostLogic)+ const denyRef = useRef<HTMLButtonElement>(null)+ const copy = activePrompt ? promptCopy(activePrompt) : null++ return (+ <Dialog+ open={!!activePrompt}+ onOpenChange={(open) => {+ if (!open && activePrompt) {+ respondToPrompt(activePrompt.id, false)+ }+ }}+ >+ <DialogContent showCloseButton={false} initialFocus={denyRef}>+ {activePrompt && copy && (+ <>+ <DialogHeader>+ <DialogTitle>{copy.title}</DialogTitle>+ <DialogDescription>{copy.description}</DialogDescription>+ </DialogHeader>+ <DialogBody>+ <PromptDetails prompt={activePrompt} />+ </DialogBody>+ <DialogFooter>+ <Button+ ref={denyRef}+ variant="outline"+ onClick={() => respondToPrompt(activePrompt.id, false)}+ data-attr="canvas-host-prompt-deny"+ >+ Cancel+ </Button>+ <Button+ variant={copy.destructive ? 'destructive-outline' : 'primary'}+ onClick={() => respondToPrompt(activePrompt.id, true)}+ data-attr={`canvas-host-prompt-allow-${activePrompt.kind}`}+ >+ {copy.confirm}+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/products/canvas/frontend/host/DraftCanvas.test.tsx b/products/canvas/frontend/host/DraftCanvas.test.tsxnew file mode 100644index 000000000000..324b1b248984--- /dev/null+++ b/products/canvas/frontend/host/DraftCanvas.test.tsx@@ -0,0 +1,45 @@+import { render, waitFor } from '@testing-library/react'++import type { CanvasCapabilitiesApi } from '../generated/api.schemas'+import { CanvasDocumentBridge } from './canvasDocumentBridge'+import { DraftCanvas } from './DraftCanvas'++jest.mock('./canvasDocumentBridge', () => ({+ CanvasDocumentBridge: jest.fn().mockImplementation(() => ({ post: jest.fn(), close: jest.fn() })),+}))++const capabilities: CanvasCapabilitiesApi = {+ posthog: { insights: [], inlineQueries: false, captureEvents: [] },+ network: { origins: [] },+}++describe('DraftCanvas capabilities', () => {+ test.each([null, capabilities, { ...capabilities, posthog: { ...capabilities.posthog, inlineQueries: true } }])(+ 'only forwards declared query requests with manifest %j',+ async (manifest) => {+ jest.mocked(CanvasDocumentBridge).mockClear()+ const onDataRequest = jest.fn(async () => ({ results: [] }))+ render(+ <DraftCanvas+ documentUrl="https://example.com/sandbox"+ capabilities={manifest}+ files={{ 'src/canvas.tsx': 'export default function Canvas() { return null }' }}+ entry="src/canvas.tsx"+ theme="light"+ hasUserActivation={() => false}+ onOpenExternal={jest.fn()}+ onDataRequest={onDataRequest}+ />+ )+ const onMessage = jest.mocked(CanvasDocumentBridge).mock.calls[0][1]+ const bridge = jest.mocked(CanvasDocumentBridge).mock.results[0].value+ onMessage({ channel: 'posthog-canvas', type: 'data-request', id: 'q1', method: 'query', payload: {} })++ const allowed = manifest?.posthog.inlineQueries === true+ await waitFor(() =>+ expect(bridge.post).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1', ok: allowed }))+ )+ expect(onDataRequest).toHaveBeenCalledTimes(allowed ? 1 : 0)+ }+ )+})diff --git a/products/canvas/frontend/host/DraftCanvas.tsx b/products/canvas/frontend/host/DraftCanvas.tsxnew file mode 100644index 000000000000..366fcbd72dd6--- /dev/null+++ b/products/canvas/frontend/host/DraftCanvas.tsx@@ -0,0 +1,127 @@+import { useEffect, useLayoutEffect, useRef } from 'react'++import type { CanvasCapabilitiesApi } from '../generated/api.schemas'+import { assertCanvasCapability } from './canvasCapabilities'+import { CanvasDocumentBridge } from './canvasDocumentBridge'+import { CanvasHostCallbacks, createCanvasHostMessageRouter } from './canvasHostMessageRouter'+import { CANVAS_CHANNEL, CanvasTheme, HostToCanvasMessage, canvasToHostMessageSchema } from './canvasProtocol'++export interface DraftCanvasProps extends CanvasHostCallbacks {+ /** The sandbox bootstrap document on the artifact origin. */+ documentUrl: string+ capabilities: CanvasCapabilitiesApi | null | undefined+ files: Record<string, string>+ entry: string+ theme: CanvasTheme+ hasUserActivation: () => boolean+ onOpenExternal: (url: string) => void+}++/**+ * Renders unbuilt source in the sandbox document, which transpiles it in the browser.+ * The document loads by URL, not as srcdoc, because a srcdoc frame inherits the web+ * app's CSP. The source arrives over a document-bound port after the first load.+ * Every data request must be declared by the source project.+ */+export function DraftCanvas({+ documentUrl,+ capabilities,+ files,+ entry,+ theme,+ hasUserActivation,+ onOpenExternal,+ ...callbacks+}: DraftCanvasProps): JSX.Element {+ const iframeRef = useRef<HTMLIFrameElement>(null)+ const bridgeRef = useRef<CanvasDocumentBridge | null>(null)+ const readyRef = useRef(false)+ const latest = useRef({ capabilities, files, entry, theme, callbacks, hasUserActivation, onOpenExternal })+ latest.current = { capabilities, files, entry, theme, callbacks, hasUserActivation, onOpenExternal }++ const post = (message: HostToCanvasMessage): void => {+ bridgeRef.current?.post(message)+ }+ const postInit = (): void => {+ post({+ channel: CANVAS_CHANNEL,+ type: 'init',+ files: latest.current.files,+ entry: latest.current.entry,+ theme: latest.current.theme,+ })+ }++ // Attach before load so the port connects before any canvas source runs.+ useLayoutEffect(() => {+ readyRef.current = false+ const route = createCanvasHostMessageRouter({+ post,+ callbacks: () => ({+ ...latest.current.callbacks,+ onDataRequest: (method, payload) => {+ assertCanvasCapability(latest.current.capabilities, method, payload)+ return latest.current.callbacks.onDataRequest(method, payload)+ },+ onReady: () => {+ if (readyRef.current) {+ return+ }+ readyRef.current = true+ postInit()+ latest.current.callbacks.onReady?.()+ },+ }),+ hasUserActivation: () => latest.current.hasUserActivation(),+ openExternal: (url) => latest.current.onOpenExternal(url),+ })+ const bridge = new CanvasDocumentBridge(+ iframeRef.current!,+ (data) => {+ const parsed = canvasToHostMessageSchema.safeParse(data)+ if (parsed.success) {+ void route(parsed.data)+ }+ },+ () => {}+ )+ bridgeRef.current = bridge+ return () => {+ readyRef.current = false+ bridge.close()+ bridgeRef.current = null+ }+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- a new document needs a fresh listener and ready flag+ }, [documentUrl])++ // A new init remounts the canvas app, so only a code change sends one.+ useEffect(() => {+ if (readyRef.current) {+ postInit()+ }+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- postInit reads the latest code through a ref+ }, [files, entry])++ useEffect(() => {+ if (readyRef.current) {+ post({ channel: CANVAS_CHANNEL, type: 'set-theme', theme })+ }+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- post is stable in behavior+ }, [theme])++ return (+ <iframe+ key={documentUrl}+ ref={iframeRef}+ title="Canvas draft"+ // allow-scripts without allow-same-origin keeps the sandbox in an opaque origin.+ // Do not add allow-popups or allow-same-origin.+ sandbox="allow-scripts"+ src={`${documentUrl}#bridge=port`}+ referrerPolicy="no-referrer"+ // Without a matching color-scheme the browser paints the frame white before init lands.+ style={{ colorScheme: theme }}+ className="h-full w-full border-0 bg-background"+ />+ )+}diff --git a/products/canvas/frontend/host/canvasCapabilities.test.ts b/products/canvas/frontend/host/canvasCapabilities.test.tsnew file mode 100644index 000000000000..7c7fb35d6315--- /dev/null+++ b/products/canvas/frontend/host/canvasCapabilities.test.ts@@ -0,0 +1,61 @@+import type { CanvasCapabilitiesApi } from '../generated/api.schemas'+import { assertCanvasCapability } from './canvasCapabilities'++const capabilities: CanvasCapabilitiesApi = {+ posthog: {+ insights: ['abc123'],+ inlineQueries: false,+ captureEvents: ['canvas clicked'],+ state: ['user'],+ actions: ['annotations.create'],+ agentRequests: false,+ },+ network: { origins: [] },+ connectors: [{ provider: 'github', tools: ['list_pull_requests'] }],+}++describe('assertCanvasCapability', () => {+ test.each([+ ['query', {}, 'Inline queries are not allowed by this canvas'],+ ['loadInsight', { shortId: 'abc123' }, null],+ ['loadInsight', { shortId: 'other' }, 'Insight is not allowed by this canvas'],+ ['capture', { event: 'canvas clicked' }, null],+ ['capture', { event: '$pageview' }, 'Event capture is not allowed by this canvas'],+ ['stateGet', { key: 'k', scope: 'user' }, null],+ ['stateSet', { key: 'k', scope: 'shared' }, 'State scope "shared" is not allowed by this canvas'],+ ['stateList', {}, 'State scope "any" is not allowed by this canvas'],+ ['actionInvoke', { verb: 'annotations.create' }, null],+ ['actionInvoke', { verb: 'flags.delete' }, 'Action "flags.delete" is not allowed by this canvas'],+ ['agentRequest', { prompt: 'x' }, 'Agent requests are not allowed by this canvas'],+ ['connectorCall', { provider: 'github', tool: 'list_pull_requests' }, null],+ [+ 'connectorCall',+ { provider: 'github', tool: 'merge_pull_request' },+ 'Connector tool "github/merge_pull_request" is not allowed by this canvas',+ ],+ ['run', {}, 'Method "run" is not allowed by this canvas'],+ ])('%s with %j', (method, payload, error) => {+ const check = (): void => assertCanvasCapability(capabilities, method, payload)+ if (error) {+ expect(check).toThrow(error)+ } else {+ expect(check).not.toThrow()+ }+ })++ test.each(['stateGet', 'stateSet'])('defaults %s to user scope', (method) => {+ expect(() =>+ assertCanvasCapability(+ { ...capabilities, posthog: { ...capabilities.posthog, state: ['shared'] } },+ method,+ {}+ )+ ).toThrow('State scope "user" is not allowed')+ })++ test('a build without a manifest denies everything', () => {+ expect(() => assertCanvasCapability(undefined, 'loadInsight', { shortId: 'abc123' })).toThrow(+ 'Canvas capability manifest is unavailable'+ )+ })+})diff --git a/products/canvas/frontend/host/canvasCapabilities.ts b/products/canvas/frontend/host/canvasCapabilities.tsnew file mode 100644index 000000000000..a18b2c2d2858--- /dev/null+++ b/products/canvas/frontend/host/canvasCapabilities.ts@@ -0,0 +1,74 @@+import type { CanvasCapabilitiesApi } from '../generated/api.schemas'++/**+ * Throws unless the rendered build or source project's manifest admits this request.+ */+export function assertCanvasCapability(+ capabilities: CanvasCapabilitiesApi | null | undefined,+ method: string,+ payload: unknown+): void {+ if (!capabilities) {+ throw new Error('Canvas capability manifest is unavailable')+ }+ const input = (payload ?? {}) as Record<string, unknown>++ switch (method) {+ case 'query':+ if (!capabilities.posthog.inlineQueries) {+ throw new Error('Inline queries are not allowed by this canvas')+ }+ return+ case 'loadInsight':+ if (typeof input.shortId !== 'string' || !capabilities.posthog.insights.includes(input.shortId)) {+ throw new Error('Insight is not allowed by this canvas')+ }+ return+ case 'capture':+ if (typeof input.event !== 'string' || !capabilities.posthog.captureEvents.includes(input.event)) {+ throw new Error('Event capture is not allowed by this canvas')+ }+ return+ case 'stateGet':+ case 'stateSet':+ case 'stateList': {+ const scope = (input.scope ?? (method === 'stateList' ? undefined : 'user')) as+ | 'user'+ | 'shared'+ | undefined+ const declared = capabilities.posthog.state ?? []+ // The backend uses the current head's scopes, which can exceed this build's scopes.+ if (+ scope+ ? !declared.includes(scope)+ : !['user', 'shared'].every((value) => declared.includes(value as 'user' | 'shared'))+ ) {+ throw new Error(`State scope "${scope ?? 'any'}" is not allowed by this canvas`)+ }+ return+ }+ case 'actionInvoke': {+ const verb = input.verb+ if (typeof verb !== 'string' || !(capabilities.posthog.actions ?? []).includes(verb)) {+ throw new Error(`Action "${typeof verb === 'string' ? verb : ''}" is not allowed by this canvas`)+ }+ return+ }+ case 'agentRequest':+ if (!capabilities.posthog.agentRequests) {+ throw new Error('Agent requests are not allowed by this canvas')+ }+ return+ case 'connectorCall': {+ const provider = typeof input.provider === 'string' ? input.provider : ''+ const tool = typeof input.tool === 'string' ? input.tool : ''+ const declared = (capabilities.connectors ?? []).find((entry) => entry.provider === provider)+ if (!provider || !tool || !declared?.tools.includes(tool)) {+ throw new Error(`Connector tool "${provider}/${tool}" is not allowed by this canvas`)+ }+ return+ }+ default:+ throw new Error(`Method "${method}" is not allowed by this canvas`)+ }+}diff --git a/products/canvas/frontend/host/canvasDataBridge.test.ts b/products/canvas/frontend/host/canvasDataBridge.test.tsnew file mode 100644index 000000000000..6817a1dda30a--- /dev/null+++ b/products/canvas/frontend/host/canvasDataBridge.test.ts@@ -0,0 +1,100 @@+import api from 'lib/api'++import { canvasesActionsInvoke, canvasesActionsRetrieve } from '../generated/api'+import { CanvasDataBridge } from './canvasDataBridge'++jest.mock('../generated/api')+jest.mock('lib/api')++describe('CanvasDataBridge query routing', () => {+ const bridge = (): CanvasDataBridge =>+ new CanvasDataBridge(+ () => ({+ projectId: '1',+ canvasId: 'canvas-1',+ sourceVersionId: 'v1',+ captureToken: null,+ distinctId: null,+ }),+ {+ confirmAction: jest.fn(),+ confirmAgentRequest: jest.fn(),+ requestConnectorPermission: jest.fn(),+ hasUserActivation: () => true,+ }+ )++ beforeEach(() => {+ jest.mocked(api.query).mockReset().mockResolvedValue({ results: [], columns: [] })+ })++ test.each([+ '../tasks/example-task/run',+ '..\\tasks\\example-task\\run',+ '%2e%2e/tasks/example-task/run',+ 'UnknownQuery',+ ])('rejects an unrecognized query kind before any request: %s', async (kind) => {+ await expect(bridge().handle('query', { query: { kind } })).rejects.toThrow()+ expect(api.query).not.toHaveBeenCalled()+ })++ test.each([+ { query: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode', event: '$pageview' }] } },+ { query: { kind: 'HogQLQuery', query: 'SELECT 1' } },+ { hogql: 'SELECT 1' },+ ])('runs a supported query: %j', async (input) => {+ await expect(bridge().handle('query', input)).resolves.toEqual({ results: [], columns: [] })+ expect(api.query).toHaveBeenCalledWith(input.query ?? { kind: 'HogQLQuery', query: input.hogql }, {+ refresh: 'blocking',+ })+ })+})++describe('CanvasDataBridge action confirmation', () => {+ test.each([false, true])('only starts a paid task after approval: %s', async (allowed) => {+ const action = {+ verb: 'tasks.create_and_run',+ summary: 'Start a cloud task.',+ destructive: false,+ usage: '',+ }+ const payload = {+ title: 'Check example chart',+ description: 'Check the example chart.',+ idempotency_key: 'one',+ }+ jest.mocked(canvasesActionsRetrieve).mockResolvedValue({ actions: [action] })+ jest.mocked(canvasesActionsInvoke)+ .mockReset()+ .mockResolvedValue({ verb: action.verb, result: { task_id: 'task-1' } })+ const confirmAction = jest.fn(async () => {+ expect(canvasesActionsInvoke).not.toHaveBeenCalled()+ return allowed+ })+ const bridge = new CanvasDataBridge(+ () => ({+ projectId: '1',+ canvasId: 'canvas-1',+ sourceVersionId: 'v1',+ captureToken: null,+ distinctId: null,+ }),+ {+ confirmAction,+ confirmAgentRequest: jest.fn(),+ requestConnectorPermission: jest.fn(),+ hasUserActivation: () => true,+ }+ )++ const result = bridge.handle('actionInvoke', { verb: action.verb, payload })+ if (allowed) {+ await expect(result).resolves.toEqual({ verb: action.verb, result: { task_id: 'task-1' } })+ expect(canvasesActionsInvoke).toHaveBeenCalledWith('1', 'canvas-1', { verb: action.verb, payload })+ } else {+ await expect(result).rejects.toThrow('Canvas action canceled')+ expect(canvasesActionsInvoke).not.toHaveBeenCalled()+ }+ expect(confirmAction).toHaveBeenCalledWith({ action, payload })+ })+})diff --git a/products/canvas/frontend/host/canvasDataBridge.ts b/products/canvas/frontend/host/canvasDataBridge.tsnew file mode 100644index 000000000000..87dbb21ddc64--- /dev/null+++ b/products/canvas/frontend/host/canvasDataBridge.ts@@ -0,0 +1,419 @@+import { z } from 'zod'++import api from 'lib/api'+import { apiHostOrigin } from 'lib/utils/apiHost'++import { DashboardFilter, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'+import { InsightShortId } from '~/types'++import {+ canvasesActionsInvoke,+ canvasesActionsRetrieve,+ canvasesConnectorsCall,+ canvasesRequestAgentCreate,+ canvasesStateRetrieve,+ canvasesStateSet,+} from '../generated/api'+import type {+ CanvasActionDefinitionApi,+ CanvasConnectorCallResultApi,+ CanvasStateEntryApi,+} from '../generated/api.schemas'+import {+ CanvasConnectorCallInput,+ canvasAgentRequestInputSchema,+ canvasConnectorCallInputSchema,+} from './canvasProtocol'+import { CanvasReadCache } from './canvasReadCache'++const MAX_RESULT_ROWS = 1_000+const MAX_RESULT_BYTES = 2 * 1024 * 1024+const DEFAULT_READ_TTL_SECONDS = 5 * 60+// Connector results describe live external state, so they go stale faster than an insight.+const CONNECTOR_READ_TTL_SECONDS = 60+const MAX_STATE_PAGES = 20+const canvasQuerySchema = z.object({ kind: z.nativeEnum(NodeKind) }).passthrough()+// pinned: `$lib` value on events a canvas captures, shared with PostHog Desktop+const CANVAS_CAPTURE_LIB = 'posthog-canvas'++export interface CanvasConnectorPermissionRequest {+ provider: string+ tool: string+ arguments?: Record<string, unknown>+ /** `canvas` asks once per canvas version, `tool` approves a single call. */+ reason: 'canvas' | 'tool'+}++export interface CanvasDataBridgeContext {+ projectId: string+ canvasId: string+ /** The source version the running code came from. Connector consent is scoped to it. */+ sourceVersionId: string | null+ /** The current project's public capture token. */+ captureToken: string | null+ distinctId: string | null+}++export interface CanvasActionConfirmation {+ action: CanvasActionDefinitionApi+ payload: Record<string, unknown>+}++export interface CanvasDataBridgePrompts {+ confirmAction: (request: CanvasActionConfirmation) => Promise<boolean>+ confirmAgentRequest: (prompt: string) => Promise<boolean>+ requestConnectorPermission: (request: CanvasConnectorPermissionRequest) => Promise<boolean>+ hasUserActivation: () => boolean+}++interface CanvasDataResult {+ columns: string[]+ results: unknown[]+ hogql?: string+ insight?: { name: string | null; kind: string | null; display: string | null }+}++type QueryNode = { kind?: string; source?: QueryNode | null; variables?: Record<string, unknown> | null }++function refreshSeconds(value: unknown): number | undefined {+ if (value === undefined) {+ return undefined+ }+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 30 || value > 86_400) {+ throw new Error('refresh must be an integer between 30 and 86400 seconds')+ }+ return value+}++function normalizeHogQLRows(results: unknown[]): unknown[] {+ return results.map((row) => (Array.isArray(row) ? row : [row]))+}++function boundedResult(result: CanvasDataResult): CanvasDataResult {+ if (result.results.length > MAX_RESULT_ROWS || JSON.stringify(result).length > MAX_RESULT_BYTES) {+ throw new Error('Canvas data result exceeds the result limit')+ }+ return result+}++// SQL variables sit on the HogQLQuery node, under one or more wrapper nodes.+function resolvedVariables(query: QueryNode | null | undefined): Record<string, unknown> {+ let node = query+ for (let depth = 0; node && depth < 5; depth++) {+ if (node.variables) {+ return Object.fromEntries(+ Object.values(node.variables)+ .map((variable) => variable as { code_name?: unknown; value?: unknown })+ .filter((variable) => typeof variable?.code_name === 'string')+ .map((variable) => [variable.code_name as string, variable.value])+ )+ }+ node = node.source+ }+ return {}+}++// The API drops an unknown variable without an error, and the insight then returns its+// saved defaults, which look plausible. So check what the server actually applied.+function assertVariablesApplied(+ requested: Record<string, unknown> | undefined,+ resolved: Record<string, unknown>,+ shortId: string+): void {+ for (const [codeName, value] of Object.entries(requested ?? {})) {+ if (!(codeName in resolved)) {+ throw new Error(`Insight "${shortId}" has no SQL variable "${codeName}"`)+ }+ if (JSON.stringify(resolved[codeName] ?? null) !== JSON.stringify(value ?? null)) {+ throw new Error(`SQL variable "${codeName}" was not applied to insight "${shortId}"`)+ }+ }+}++/**+ * Resolves the `ph.*` data requests a canvas sends. The web app's session runs every+ * call, and the iframe only ever sees the result. Each canvas passes each request+ * through `assertCanvasCapability` before it reaches here.+ */+export class CanvasDataBridge {+ private readonly cache = new CanvasReadCache()+ private readonly connectorConsent = new Map<string, boolean>()++ constructor(+ private readonly context: () => CanvasDataBridgeContext,+ private readonly prompts: CanvasDataBridgePrompts+ ) {}++ async handle(method: string, payload: unknown): Promise<unknown> {+ const input = (payload ?? {}) as Record<string, unknown>+ switch (method) {+ case 'query':+ return this.query(input)+ case 'loadInsight':+ return this.loadInsight(input)+ case 'capture':+ return this.capture(input)+ case 'stateGet':+ return this.stateGet(input)+ case 'stateSet':+ return this.stateSet(input)+ case 'stateList':+ return this.stateList(input)+ case 'actionInvoke':+ return this.actionInvoke(input)+ case 'agentRequest':+ return this.agentRequest(payload)+ case 'connectorCall':+ return this.connectorCall(payload)+ case 'run':+ throw new Error('ph.run is not available yet')+ default:+ throw new Error(`Unknown data method "${method}"`)+ }+ }++ private async query(input: Record<string, unknown>): Promise<CanvasDataResult> {+ const typed = input.query != null && typeof input.query === 'object'+ const hogql = typeof input.hogql === 'string' && input.hogql.length > 0 ? input.hogql : null+ if (!typed && !hogql) {+ throw new Error('ph.query requires a typed query node or a HogQL string')+ }+ if (input.params != null && (typeof input.params !== 'object' || Object.keys(input.params).length > 0)) {+ throw new Error('ph.query parameters are not supported. Use a typed query with variables instead.')+ }+ const refresh = refreshSeconds(input.refresh)+ const node = canvasQuerySchema.parse(typed ? input.query : { kind: NodeKind.HogQLQuery, query: hogql })+ return this.cache.read(+ 'query',+ { node, params: input.params },+ refresh ?? DEFAULT_READ_TTL_SECONDS,+ async () => {+ const response = (await api.query(node, { refresh: 'blocking' })) as Record<string, unknown>+ if (typeof response.error === 'string' && response.error) {+ throw new Error(response.error)+ }+ const results = Array.isArray(response.results) ? response.results : []+ return boundedResult({+ columns: Array.isArray(response.columns) ? response.columns.map(String) : [],+ // Typed nodes return series objects, which a row wrapper would read as zero.+ results: typed ? results : normalizeHogQLRows(results),+ ...(typeof response.hogql === 'string' ? { hogql: response.hogql } : {}),+ })+ }+ )+ }++ private async loadInsight(input: Record<string, unknown>): Promise<CanvasDataResult> {+ const shortId = input.shortId+ if (typeof shortId !== 'string' || !shortId) {+ throw new Error('ph.loadInsight(shortId) requires an insight short id')+ }+ const dateRange = input.dateRange as DashboardFilter | undefined+ const variables = input.variables as Record<string, unknown> | undefined+ return this.cache.read(+ 'loadInsight',+ { shortId, dateRange, variables },+ refreshSeconds(input.refresh) ?? DEFAULT_READ_TTL_SECONDS,+ async () => {+ const variablesOverride =+ variables && Object.keys(variables).length > 0+ ? (Object.fromEntries(+ Object.entries(variables).map(([codeName, value]) => [+ codeName,+ { code_name: codeName, value },+ ])+ ) as unknown as Record<string, HogQLVariable>)+ : undefined+ const response = await api.insights.loadInsight(+ shortId as InsightShortId,+ false,+ 'blocking',+ dateRange ?? undefined,+ variablesOverride+ )+ const insight = response.results[0] as Record<string, unknown> | undefined+ if (!insight) {+ throw new Error(`Insight "${shortId}" not found`)+ }+ const query = insight.query as QueryNode | null | undefined+ assertVariablesApplied(variables, resolvedVariables(query), shortId)+ const source = query?.source as (QueryNode & { trendsFilter?: { display?: string } }) | undefined+ const results = Array.isArray(insight.result) ? insight.result : []+ return boundedResult({+ columns: Array.isArray(insight.columns) ? insight.columns.map(String) : [],+ results: query?.kind === 'HogQLQuery' ? normalizeHogQLRows(results) : results,+ insight: {+ name: (insight.name as string) || (insight.derived_name as string) || null,+ kind: source?.kind ?? query?.kind ?? null,+ display: source?.trendsFilter?.display ?? null,+ },+ })+ }+ )+ }++ // Sends to the current project with its public token, never through the web app's+ // own analytics client, which reports into PostHog's project rather than the user's.+ private async capture(input: Record<string, unknown>): Promise<{ ok: boolean }> {+ const event = input.event+ if (typeof event !== 'string' || !event) {+ throw new Error('ph.capture(event) requires an event name')+ }+ const { captureToken, distinctId } = this.context()+ if (!captureToken) {+ throw new Error('This project has no capture key')+ }+ const response = await fetch(`${apiHostOrigin()}/i/v0/e/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'omit',+ body: JSON.stringify({+ api_key: captureToken,+ event,+ distinct_id:+ (typeof input.distinctId === 'string' && input.distinctId) || distinctId || 'freeform-canvas',+ properties: {+ ...(input.properties as Record<string, unknown> | undefined),+ $lib: CANVAS_CAPTURE_LIB,+ },+ }),+ })+ if (!response.ok) {+ throw new Error(`Capture failed (${response.status})`)+ }+ return { ok: true }+ }++ private async stateGet(input: Record<string, unknown>): Promise<unknown> {+ if (typeof input.key !== 'string' || !input.key) {+ throw new Error('ph.state.get(key) requires a key')+ }+ const { projectId, canvasId } = this.context()+ // Never cached: state is the canvas's live memory, and a stale read undoes its own write.+ const response = await canvasesStateRetrieve(projectId, canvasId, {+ key: input.key,+ scope: input.scope === 'shared' ? 'shared' : 'user',+ })+ return response.entries.find((entry) => entry.key === input.key)?.value ?? null+ }++ private async stateSet(input: Record<string, unknown>): Promise<{ ok: true }> {+ if (typeof input.key !== 'string' || !input.key) {+ throw new Error('ph.state.set(key, value) requires a key')+ }+ const { projectId, canvasId } = this.context()+ await canvasesStateSet(projectId, canvasId, {+ key: input.key,+ scope: input.scope === 'shared' ? 'shared' : 'user',+ value: input.value ?? null,+ })+ return { ok: true }+ }++ private async stateList(input: Record<string, unknown>): Promise<CanvasStateEntryApi[]> {+ const { projectId, canvasId } = this.context()+ const scope = input.scope === 'shared' || input.scope === 'user' ? input.scope : undefined+ const entries: CanvasStateEntryApi[] = []+ let offset: number | null = 0+ for (let page = 0; offset !== null && page < MAX_STATE_PAGES; page++) {+ const response = await canvasesStateRetrieve(projectId, canvasId, { scope, offset })+ entries.push(...response.entries)+ offset = response.complete ? null : response.next_offset+ }+ return entries+ }++ private async actionInvoke(input: Record<string, unknown>): Promise<unknown> {+ const verb = input.verb+ if (typeof verb !== 'string' || !verb) {+ throw new Error('ph.actions.invoke(verb, payload) requires a verb')+ }+ const { projectId, canvasId } = this.context()+ const { actions } = await canvasesActionsRetrieve(projectId)+ const action = actions.find((entry) => entry.verb === verb)+ if (!action) {+ throw new Error('Unknown canvas action')+ }+ const payload = (input.payload as Record<string, unknown> | undefined) ?? {}+ if (!(await this.prompts.confirmAction({ action, payload }))) {+ throw new Error('Canvas action canceled')+ }+ return canvasesActionsInvoke(projectId, canvasId, {+ verb,+ payload,+ })+ }++ private async agentRequest(payload: unknown): Promise<{ requestOutcome: string; taskId: string }> {+ const { prompt } = canvasAgentRequestInputSchema.parse(payload)+ if (!(await this.prompts.confirmAgentRequest(prompt))) {+ throw new Error('Agent request canceled')+ }+ const { projectId, canvasId } = this.context()+ const result = await canvasesRequestAgentCreate(projectId, canvasId, { prompt })+ return { requestOutcome: result.request_outcome, taskId: result.task_id }+ }++ private async connectorCall(payload: unknown): Promise<Omit<CanvasConnectorCallResultApi, 'approval_token'>> {+ const input = canvasConnectorCallInputSchema.parse(payload)+ const { projectId, canvasId, sourceVersionId } = this.context()+ if (!sourceVersionId) {+ throw new Error('Connector calls require a saved canvas version')+ }+ await this.requireConnectorConsent(sourceVersionId, input)+ const args = { provider: input.provider, tool: input.tool, arguments: input.arguments }+ return this.cache.read(+ 'connectorCall',+ { ...args, sourceVersionId },+ input.refresh ?? CONNECTOR_READ_TTL_SECONDS,+ async () => {+ const first = await canvasesConnectorsCall(projectId, canvasId, args)+ if (first.status !== 'needs_approval') {+ return this.withoutApprovalToken(first)+ }+ if (!first.approval_token) {+ throw new Error('This connection cannot accept one-time approval.')+ }+ const approved = await this.prompts.requestConnectorPermission({ ...args, reason: 'tool' })+ if (!approved) {+ throw new Error('Tool access was not granted.')+ }+ const second = await canvasesConnectorsCall(projectId, canvasId, {+ ...args,+ approval_token: first.approval_token,+ })+ return this.withoutApprovalToken(second)+ }+ )+ }++ // The approval token is bound to this viewer and must never reach the iframe.+ private withoutApprovalToken(+ result: CanvasConnectorCallResultApi+ ): Omit<CanvasConnectorCallResultApi, 'approval_token'> {+ const { approval_token: _approvalToken, ...rest } = result+ return rest+ }++ private async requireConnectorConsent(sourceVersionId: string, input: CanvasConnectorCallInput): Promise<void> {+ const key = `${sourceVersionId}:${input.provider}:${input.tool}`+ const known = this.connectorConsent.get(key)+ // A denial sticks until the viewer interacts with the canvas again, so a render+ // loop cannot reopen the dialog.+ if (known === true || (known === false && !this.prompts.hasUserActivation())) {+ if (known) {+ return+ }+ throw new Error('Connector access was not granted. Click in the canvas to try again.')+ }+ const allowed = await this.prompts.requestConnectorPermission({+ provider: input.provider,+ tool: input.tool,+ reason: 'canvas',+ })+ this.connectorConsent.set(key, allowed)+ if (!allowed) {+ throw new Error('Connector access was not granted. Click in the canvas to try again.')+ }+ }+}diff --git a/products/canvas/frontend/host/canvasDocumentBridge.ts b/products/canvas/frontend/host/canvasDocumentBridge.tsnew file mode 100644index 000000000000..ad60ed2a7d4f--- /dev/null+++ b/products/canvas/frontend/host/canvasDocumentBridge.ts@@ -0,0 +1,40 @@+import { CANVAS_CHANNEL } from './canvasProtocol'++/** A port belongs to one document, unlike an iframe's WindowProxy. */+export class CanvasDocumentBridge {+ private port: MessagePort | null = null+ private loads = 0++ constructor(+ private readonly iframe: HTMLIFrameElement,+ private readonly onMessage: (data: unknown) => void,+ private readonly onConnect: () => void+ ) {+ iframe.addEventListener('load', this.onLoad)+ }++ post = (message: unknown): void => {+ this.port?.postMessage(message)+ }++ private onLoad = (): void => {+ this.loads += 1+ this.port?.close()+ this.port = null+ if (this.loads !== 1) {+ return+ }+ const { port1, port2 } = new MessageChannel()+ this.port = port1+ port1.onmessage = (event) => this.onMessage(event.data)+ // nosemgrep: wildcard-postmessage-configuration -- Opaque sandbox origin; this transfers only the first document's private port.+ this.iframe.contentWindow?.postMessage({ channel: CANVAS_CHANNEL, type: 'connect' }, '*', [port2])+ this.onConnect()+ }++ close = (): void => {+ this.iframe.removeEventListener('load', this.onLoad)+ this.port?.close()+ this.port = null+ }+}diff --git a/products/canvas/frontend/host/canvasHostLogic.ts b/products/canvas/frontend/host/canvasHostLogic.tsnew file mode 100644index 000000000000..183a15a24392--- /dev/null+++ b/products/canvas/frontend/host/canvasHostLogic.ts@@ -0,0 +1,270 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import type { TeamPublicType, TeamType, UserType } from '../../../../frontend/src/types'+import { CANVAS_EVENTS, canvasErrorType } from '../canvasAnalytics'+import { CanvasActionConfirmation, CanvasConnectorPermissionRequest, CanvasDataBridge } from './canvasDataBridge'+import { CanvasNavIntent, isSafeGitHubPullRequestUrl } from './canvasProtocol'++export interface CanvasHostLogicProps {+ canvasId: string+ /** The canvas's space. Supplied by the host, never by the iframe. */+ spaceId: string | null+ /** The source version the running code came from. */+ sourceVersionId: string | null+}++export type CanvasHostPrompt =+ | { kind: 'connector'; id: string; request: CanvasConnectorPermissionRequest }+ | { kind: 'agent-request'; id: string; prompt: string }+ | { kind: 'action'; id: string; request: CanvasActionConfirmation }+ | { kind: 'external-link'; id: string; url: string }++type CanvasHostPromptInput = CanvasHostPrompt extends infer P+ ? P extends CanvasHostPrompt+ ? Omit<P, 'id'>+ : never+ : never++let promptSequence = 0++export function canvasHasUserActivation(): boolean {+ return navigator.userActivation?.isActive === true+}++function openInNewTab(url: string): void {+ window.open(url, '_blank', 'noopener,noreferrer')+}++/** Where a viewer connects a connector provider in the web app. */+export function connectorSettingsUrl(provider: string): string {+ return provider === 'github' ? urls.settings('user-personal-integrations') : urls.settings('mcp-servers')+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasHostLogicValues {+ currentProjectId: number | null // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ user: UserType | null // userLogic+ activePrompt: CanvasHostPrompt | null+ prompts: CanvasHostPrompt[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasHostLogicActions {+ canvasErrored: (+ message: string,+ buildId: string | null+ ) => {+ buildId: string | null+ message: string+ }+ canvasRendered: (buildId: string | null) => {+ buildId: string | null+ }+ enqueuePrompt: (prompt: CanvasHostPrompt) => {+ prompt: CanvasHostPrompt+ }+ navigate: (intent: CanvasNavIntent) => {+ intent:+ | {+ target: 'new-canvas'+ }+ | {+ target: 'new-task'+ }+ | {+ dashboardId: string+ target: 'canvas'+ }+ | {+ provider: string+ target: 'connect'+ }+ | {+ target: 'task'+ taskId: string+ }+ | {+ prompt?: string | undefined+ repository?: string | undefined+ target: 'compose-task'+ }+ }+ openExternal: (url: string) => {+ url: string+ }+ respondToPrompt: (+ id: string,+ allowed: boolean+ ) => {+ allowed: boolean+ id: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasHostLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ activePrompt: (prompts: CanvasHostPrompt[]) => CanvasHostPrompt | null+ }+}++export type canvasHostLogicType = MakeLogicType<+ canvasHostLogicValues,+ canvasHostLogicActions,+ CanvasHostLogicProps,+ canvasHostLogicMeta+>++/**+ * The trusted host around one rendered canvas: it answers the canvas's data requests,+ * asks the viewer before anything that writes, starts work, or leaves the app, and maps+ * the canvas's allowlisted navigation intents to web routes.+ */+export const canvasHostLogic = kea<canvasHostLogicType>([+ props({} as CanvasHostLogicProps),+ key((props) => props.canvasId),+ path((key) => ['products', 'canvas', 'frontend', 'host', 'canvasHostLogic', key]),+ connect(() => ({+ values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam'], userLogic, ['user']],+ })),+ actions({+ enqueuePrompt: (prompt: CanvasHostPrompt) => ({ prompt }),+ respondToPrompt: (id: string, allowed: boolean) => ({ id, allowed }),+ navigate: (intent: CanvasNavIntent) => ({ intent }),+ openExternal: (url: string) => ({ url }),+ canvasRendered: (buildId: string | null) => ({ buildId }),+ canvasErrored: (message: string, buildId: string | null) => ({ message, buildId }),+ }),+ reducers({+ prompts: [+ [] as CanvasHostPrompt[],+ {+ enqueuePrompt: (state, { prompt }) => [...state, prompt],+ respondToPrompt: (state, { id }) => state.filter((prompt) => prompt.id !== id),+ },+ ],+ }),+ selectors({+ activePrompt: [+ (s) => [s.prompts],+ (prompts: CanvasHostPrompt[]): CanvasHostPrompt | null => prompts[0] ?? null,+ ],+ }),+ listeners(({ props, cache }) => ({+ respondToPrompt: ({ id, allowed }) => {+ const resolve = (cache.resolvers as Map<string, (allowed: boolean) => void>).get(id)+ cache.resolvers.delete(id)+ resolve?.(allowed)+ },+ openExternal: ({ url }) => {+ // Only a validated GitHub pull request link skips the confirmation.+ if (isSafeGitHubPullRequestUrl(url)) {+ openInNewTab(url)+ return+ }+ void (cache.requestPrompt({ kind: 'external-link', url }) as Promise<boolean>).then((allowed) => {+ if (allowed) {+ openInNewTab(url)+ }+ })+ },+ navigate: ({ intent }) => {+ switch (intent.target) {+ case 'task':+ router.actions.push(urls.taskDetail(intent.taskId))+ break+ case 'canvas':+ router.actions.push(urls.canvasDetail(intent.dashboardId))+ break+ case 'new-canvas':+ router.actions.push(urls.canvasNew(props.spaceId))+ break+ case 'connect':+ router.actions.push(connectorSettingsUrl(intent.provider))+ break+ default:+ // The web app has no task composer route to prefill, so these are dropped.+ break+ }+ },+ canvasRendered: ({ buildId }) => {+ posthog.capture(CANVAS_EVENTS.rendered, {+ channel_id: props.spaceId ?? undefined,+ dashboard_id: props.canvasId,+ build_id: buildId ?? undefined,+ })+ },+ canvasErrored: ({ message, buildId }) => {+ posthog.capture(CANVAS_EVENTS.runtimeError, {+ channel_id: props.spaceId ?? undefined,+ dashboard_id: props.canvasId,+ build_id: buildId ?? undefined,+ error_type: canvasErrorType(message),+ })+ },+ })),+ afterMount((logic) => {+ const { actions, values, cache } = logic+ cache.resolvers = new Map<string, (allowed: boolean) => void>()+ cache.requestPrompt = (input: CanvasHostPromptInput): Promise<boolean> =>+ new Promise((resolve) => {+ const id = `canvas-prompt-${++promptSequence}`+ cache.resolvers.set(id, resolve)+ actions.enqueuePrompt({ ...input, id } as CanvasHostPrompt)+ })+ cache.bridge = new CanvasDataBridge(+ () => ({+ projectId: String(values.currentProjectId ?? ''),+ // Read through the logic so a new source version is picked up without a remount.+ canvasId: logic.props.canvasId,+ sourceVersionId: logic.props.sourceVersionId,+ captureToken: values.currentTeam?.api_token ?? null,+ distinctId: values.user?.distinct_id ?? null,+ }),+ {+ confirmAction: (request) => cache.requestPrompt({ kind: 'action', request }),+ confirmAgentRequest: (prompt) => cache.requestPrompt({ kind: 'agent-request', prompt }),+ requestConnectorPermission: (request) => cache.requestPrompt({ kind: 'connector', request }),+ hasUserActivation: canvasHasUserActivation,+ }+ )+ }),+ beforeUnmount(({ cache }) => {+ // A canvas waiting on the viewer gets a denial rather than a promise that never settles.+ for (const resolve of (cache.resolvers as Map<string, (allowed: boolean) => void>).values()) {+ resolve(false)+ }+ cache.resolvers.clear()+ }),+])++/** Resolves a data request through the host's bridge. The logic must be mounted. */+export function handleCanvasDataRequest(+ logic: ReturnType<typeof canvasHostLogic>,+ method: string,+ payload: unknown+): Promise<unknown> {+ return (logic.cache.bridge as CanvasDataBridge).handle(method, payload)+}diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.test.ts b/products/canvas/frontend/host/canvasHostMessageRouter.test.tsnew file mode 100644index 000000000000..9546f87c8cd6--- /dev/null+++ b/products/canvas/frontend/host/canvasHostMessageRouter.test.ts@@ -0,0 +1,161 @@+import {+ DATA_REQUEST_TIMEOUT_MS,+ EXTERNAL_OPEN_MIN_INTERVAL_MS,+ MAX_DATA_REQUEST_BYTES,+ createCanvasHostMessageRouter,+} from './canvasHostMessageRouter'+import { CanvasToHostMessage, HostToCanvasMessage, canvasToHostMessageSchema } from './canvasProtocol'++function setup(options: { activated?: boolean; onDataRequest?: () => Promise<unknown> } = {}): {+ route: (message: CanvasToHostMessage) => Promise<void>+ posted: HostToCanvasMessage[]+ onDataRequest: jest.Mock+ onNavigate: jest.Mock+ openExternal: jest.Mock+ onExternalOpenBlocked: jest.Mock+ clock: { now: number }+} {+ const posted: HostToCanvasMessage[] = []+ const onDataRequest = jest.fn(options.onDataRequest ?? (async () => ({ ok: true })))+ const onNavigate = jest.fn()+ const openExternal = jest.fn()+ const onExternalOpenBlocked = jest.fn()+ const clock = { now: 10_000 }+ const route = createCanvasHostMessageRouter({+ post: (message) => posted.push(message),+ callbacks: () => ({ onDataRequest, onNavigate }),+ hasUserActivation: () => options.activated ?? false,+ openExternal,+ onExternalOpenBlocked,+ now: () => clock.now,+ })+ return { route, posted, onDataRequest, onNavigate, openExternal, onExternalOpenBlocked, clock }+}++const dataRequest = (method: string, payload: unknown = {}): CanvasToHostMessage =>+ ({ channel: 'posthog-canvas', type: 'data-request', id: 'r1', method, payload }) as CanvasToHostMessage++describe('createCanvasHostMessageRouter', () => {+ afterEach(() => {+ jest.useRealTimers()+ })++ test.each([+ ['actionInvoke', false, 'Canvas actions require a user action'],+ ['agentRequest', false, 'Agent requests require a user action'],+ ['actionInvoke', true, null],+ ['agentRequest', true, null],+ ['query', false, null],+ ])('%s with user activation %s is rejected with %s', async (method, activated, error) => {+ const { route, posted, onDataRequest } = setup({ activated })++ await route(dataRequest(method))++ expect(onDataRequest).toHaveBeenCalledTimes(error ? 0 : 1)+ expect(posted).toEqual([+ error+ ? { channel: 'posthog-canvas', type: 'data-response', id: 'r1', ok: false, error }+ : { channel: 'posthog-canvas', type: 'data-response', id: 'r1', ok: true, result: { ok: true } },+ ])+ })++ test('rejects a payload over the size cap without calling the host', async () => {+ const { route, posted, onDataRequest } = setup()++ await route(dataRequest('query', { hogql: 'x'.repeat(MAX_DATA_REQUEST_BYTES) }))++ expect(onDataRequest).not.toHaveBeenCalled()+ expect(posted[0]).toMatchObject({ ok: false, error: 'Canvas data request exceeds runtime limits' })+ })++ test('caps concurrent reads and frees the slot when one settles', async () => {+ const releases: (() => void)[] = []+ const { route, posted } = setup({+ onDataRequest: () => new Promise((resolve) => releases.push(() => resolve('done'))),+ })++ const inFlight = Array.from({ length: 8 }, () => route(dataRequest('query')))+ await route(dataRequest('query'))+ expect(posted).toEqual([+ expect.objectContaining({ ok: false, error: 'Canvas data request exceeds runtime limits' }),+ ])++ releases.forEach((release) => release())+ await Promise.all(inFlight)+ const afterRelease = route(dataRequest('query'))+ expect(releases).toHaveLength(9)+ releases[8]()+ await afterRelease+ expect(posted.filter((message) => 'ok' in message && message.ok)).toHaveLength(9)+ })++ test.each([+ ['query', true],+ ['connectorCall', false],+ ['agentRequest', false],+ ])('a hung %s times out: %s', async (method, timesOut) => {+ jest.useFakeTimers()+ const { route, posted } = setup({ activated: true, onDataRequest: () => new Promise(() => {}) })++ void route(dataRequest(method))+ await jest.advanceTimersByTimeAsync(DATA_REQUEST_TIMEOUT_MS)++ expect(posted).toEqual(+ timesOut ? [expect.objectContaining({ ok: false, error: 'Canvas data request timed out' })] : []+ )+ })++ test('reports a host failure as an error response', async () => {+ const { route, posted } = setup({+ onDataRequest: async () => {+ throw new Error('Unknown data method "nope"')+ },+ })++ await route(dataRequest('query'))++ expect(posted[0]).toMatchObject({ ok: false, error: 'Unknown data method "nope"' })+ })++ test.each([+ ['an unknown method', { type: 'data-request', id: 'r1', method: 'deleteProject', payload: {} }],+ ['a non-allowlisted navigation', { type: 'navigate', nav: { target: 'settings' } }],+ ['a non-PostHog external URL', { type: 'open-external', url: 'https://evil.example.com' }],+ ['another channel', { type: 'ready', channel: 'other' }],+ ])('the schema drops %s', (_, message) => {+ expect(canvasToHostMessageSchema.safeParse({ channel: 'posthog-canvas', ...message }).success).toBe(false)+ })++ test.each([+ ['connect', { target: 'connect', provider: 'github' }, false, false],+ ['connect', { target: 'connect', provider: 'github' }, true, true],+ ['canvas', { target: 'canvas', dashboardId: 'c1' }, false, true],+ ])('navigate to %s with user activation %s reaches the host: %s', async (_, nav, activated, forwarded) => {+ const { route, onNavigate } = setup({ activated })++ await route({ channel: 'posthog-canvas', type: 'navigate', nav } as CanvasToHostMessage)++ expect(onNavigate).toHaveBeenCalledTimes(forwarded ? 1 : 0)+ })++ test('open-external needs a gesture and is throttled', async () => {+ const blocked = setup({ activated: false })+ await blocked.route({ channel: 'posthog-canvas', type: 'open-external', url: 'https://posthog.com/docs' })+ expect(blocked.openExternal).not.toHaveBeenCalled()+ expect(blocked.onExternalOpenBlocked).toHaveBeenCalledWith('https://posthog.com/docs', 'no-interaction')++ const { route, openExternal, onExternalOpenBlocked, clock } = setup({ activated: true })+ const open: CanvasToHostMessage = {+ channel: 'posthog-canvas',+ type: 'open-external',+ url: 'https://posthog.com/docs',+ }+ await route(open)+ await route(open)+ clock.now += EXTERNAL_OPEN_MIN_INTERVAL_MS+ await route(open)++ expect(openExternal).toHaveBeenCalledTimes(2)+ expect(onExternalOpenBlocked).toHaveBeenCalledWith('https://posthog.com/docs', 'throttled')+ })+})diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.ts b/products/canvas/frontend/host/canvasHostMessageRouter.tsnew file mode 100644index 000000000000..618e988576ae--- /dev/null+++ b/products/canvas/frontend/host/canvasHostMessageRouter.ts@@ -0,0 +1,212 @@+import {+ CANVAS_CHANNEL,+ CanvasNavIntent,+ CanvasToHostMessage,+ HostToCanvasMessage,+ isSafeGitHubPullRequestUrl,+ isSafePostHogUrl,+} from './canvasProtocol'++// Canvas code can post open-external without a gesture, so opens are limited.+export const EXTERNAL_OPEN_MIN_INTERVAL_MS = 1_000+// Canvas code is untrusted, so a runaway loop must not pile up concurrent requests,+// ship oversized payloads, or hold a request slot forever.+export const MAX_CONCURRENT_DATA_REQUESTS = 8+export const MAX_CONCURRENT_CONNECTOR_REQUESTS = 8+export const MAX_DATA_REQUEST_BYTES = 64 * 1024+export const DATA_REQUEST_TIMEOUT_MS = 30_000++const REPLAYABLE_SHORTCUT_KEYS = new Set([+ ',',+ '/',+ '[',+ ']',+ '{',+ '}',+ '1',+ '2',+ '3',+ '4',+ '5',+ '6',+ '7',+ '8',+ '9',+ 'arrowdown',+ 'arrowleft',+ 'arrowright',+ 'arrowup',+ 'b',+ 'i',+ 'j',+ 'k',+ 'n',+ 't',+ 'tab',+])++// These write or start work, so the canvas must not fire them just by loading.+const GESTURE_GATED_METHODS = new Set(['actionInvoke', 'agentRequest'])+const GESTURE_GATED_NAV_TARGETS = new Set<CanvasNavIntent['target']>(['connect', 'compose-task', 'new-task'])+// Approval dialogs can stay open longer than the I/O timeout, so these wait unbounded.+const UNTIMED_METHODS = new Set(['agentRequest', 'actionInvoke', 'connectorCall'])++function isBoundedPayload(payload: unknown): boolean {+ try {+ return (JSON.stringify(payload) ?? '').length <= MAX_DATA_REQUEST_BYTES+ } catch {+ return false+ }+}++export interface CanvasHostCallbacks {+ onDataRequest: (method: string, payload: unknown) => Promise<unknown>+ onError?: (message: string, stack?: string) => void+ onReady?: () => void+ onRendered?: () => void+ onNavigate?: (intent: CanvasNavIntent) => void+}++export type ExternalOpenBlockReason = 'unsafe-url' | 'no-interaction' | 'throttled'++export interface CanvasHostMessageRouterOptions {+ /** Transport back into the canvas through its document port. */+ post: (message: HostToCanvasMessage) => void+ /** Read fresh per message, so the router can live for the whole mount without going stale. */+ callbacks: () => CanvasHostCallbacks+ /** Whether the browser is processing a trusted user gesture right now. */+ hasUserActivation: () => boolean+ /** Runs once the safety, gesture and throttle gates pass. */+ openExternal: (url: string) => void+ onExternalOpenBlocked?: (url: string, reason: ExternalOpenBlockReason) => void+ now?: () => number+}++/** The host side of the canvas protocol, shared by the built and the draft iframe. */+export function createCanvasHostMessageRouter(+ options: CanvasHostMessageRouterOptions+): (message: CanvasToHostMessage) => Promise<void> {+ const now = options.now ?? Date.now+ let lastExternalOpen = Number.NEGATIVE_INFINITY+ let activeDataRequests = 0+ let activeConnectorRequests = 0++ const respondError = (id: string, error: string): void =>+ options.post({ channel: CANVAS_CHANNEL, type: 'data-response', id, ok: false, error })++ return async (message) => {+ switch (message.type) {+ case 'data-request': {+ if (GESTURE_GATED_METHODS.has(message.method) && !options.hasUserActivation()) {+ respondError(+ message.id,+ message.method === 'agentRequest'+ ? 'Agent requests require a user action'+ : 'Canvas actions require a user action'+ )+ break+ }+ // Approval waits must not consume ordinary read and write slots.+ const isConnectorRequest = message.method === 'connectorCall'+ const holdsSlot = message.method !== 'agentRequest' && !isConnectorRequest+ if (+ (holdsSlot && activeDataRequests >= MAX_CONCURRENT_DATA_REQUESTS) ||+ (isConnectorRequest && activeConnectorRequests >= MAX_CONCURRENT_CONNECTOR_REQUESTS) ||+ !isBoundedPayload(message.payload)+ ) {+ respondError(message.id, 'Canvas data request exceeds runtime limits')+ break+ }+ if (holdsSlot) {+ activeDataRequests += 1+ }+ if (isConnectorRequest) {+ activeConnectorRequests += 1+ }+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const call = options.callbacks().onDataRequest(message.method, message.payload)+ const result = UNTIMED_METHODS.has(message.method)+ ? await call+ : await Promise.race([+ call,+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('Canvas data request timed out')),+ DATA_REQUEST_TIMEOUT_MS+ )+ }),+ ])+ options.post({ channel: CANVAS_CHANNEL, type: 'data-response', id: message.id, ok: true, result })+ } catch (error) {+ respondError(message.id, error instanceof Error ? error.message : String(error))+ } finally {+ clearTimeout(timer)+ if (holdsSlot) {+ activeDataRequests -= 1+ }+ if (isConnectorRequest) {+ activeConnectorRequests -= 1+ }+ }+ break+ }+ case 'error':+ options.callbacks().onError?.(message.message, message.stack)+ break+ case 'rendered':+ options.callbacks().onRendered?.()+ break+ case 'ready':+ options.callbacks().onReady?.()+ break+ case 'navigate':+ if (GESTURE_GATED_NAV_TARGETS.has(message.nav.target) && !options.hasUserActivation()) {+ break+ }+ options.callbacks().onNavigate?.(message.nav)+ break+ case 'open-external':+ // Re-checks the schema's allowlist in case the two ever drift.+ if (!isSafePostHogUrl(message.url) && !isSafeGitHubPullRequestUrl(message.url)) {+ options.onExternalOpenBlocked?.(message.url, 'unsafe-url')+ } else if (!options.hasUserActivation()) {+ options.onExternalOpenBlocked?.(message.url, 'no-interaction')+ } else if (now() - lastExternalOpen < EXTERNAL_OPEN_MIN_INTERVAL_MS) {+ options.onExternalOpenBlocked?.(message.url, 'throttled')+ } else {+ lastExternalOpen = now()+ options.openExternal(message.url)+ }+ break+ case 'keydown': {+ // Replays app shortcuts pressed while the iframe has focus.+ if (!message.metaKey && !message.ctrlKey) {+ break+ }+ if (!REPLAYABLE_SHORTCUT_KEYS.has(message.key.toLowerCase())) {+ break+ }+ if (!(document.activeElement instanceof HTMLIFrameElement)) {+ break+ }+ const init = {+ key: message.key,+ code: message.code,+ metaKey: message.metaKey,+ ctrlKey: message.ctrlKey,+ shiftKey: message.shiftKey,+ altKey: message.altKey,+ }+ document.dispatchEvent(new KeyboardEvent('keydown', init))+ document.dispatchEvent(new KeyboardEvent('keyup', init))+ break+ }+ case 'text-selection':+ case 'text-selection-cleared':+ case 'comment-activate':+ // The web app has no comment surface for canvases yet, so these are dropped.+ break+ }+ }+}diff --git a/products/canvas/frontend/host/canvasProtocol.ts b/products/canvas/frontend/host/canvasProtocol.tsnew file mode 100644index 000000000000..2de9231a5f6b--- /dev/null+++ b/products/canvas/frontend/host/canvasProtocol.ts@@ -0,0 +1,172 @@+import { z } from 'zod'++// The host side of the canvas postMessage protocol. It mirrors PostHog Desktop's+// freeformSchemas.ts, because the sandbox document and the built artifact runtime+// speak one protocol to both hosts. A canvas runs untrusted code in an opaque-origin+// iframe, so the schemas below are the allowlist of what it may ask the host to do.++// pinned: protocol channel tag, shared with the sandbox document and the artifact runtime+export const CANVAS_CHANNEL = 'posthog-canvas'++export function isSafePostHogUrl(url: string): boolean {+ let parsed: URL+ try {+ parsed = new URL(url)+ } catch {+ return false+ }+ return (+ parsed.protocol === 'https:' && (parsed.hostname === 'posthog.com' || parsed.hostname.endsWith('.posthog.com'))+ )+}++export function isSafeGitHubPullRequestUrl(url: string): boolean {+ let parsed: URL+ try {+ parsed = new URL(url)+ } catch {+ return false+ }+ return (+ parsed.protocol === 'https:' &&+ parsed.hostname === 'github.com' &&+ !parsed.username &&+ !parsed.password &&+ !parsed.port &&+ !parsed.search &&+ /^\/[a-z0-9-]+\/[a-z0-9_.-]+\/pull\/[1-9]\d*(?:\/(?:files|commits|checks))?\/?$/i.test(parsed.pathname)+ )+}++export const canvasConnectorProviderSchema = z.union([+ z.literal('github'),+ z+ .string()+ .max(300)+ .regex(/^mcp:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i),+])++export const canvasConnectorCallInputSchema = z.object({+ provider: canvasConnectorProviderSchema,+ tool: z.string().min(1).max(200),+ arguments: z.record(z.string().max(128), z.unknown()).default({}),+ refresh: z.number().int().min(30).max(86_400).optional(),+})+export type CanvasConnectorCallInput = z.infer<typeof canvasConnectorCallInputSchema>++export const canvasAgentRequestInputSchema = z.object({+ prompt: z.string().min(1).max(10_000),+})++export type CanvasTheme = 'light' | 'dark'++// The only navigations a canvas may request. There is no free-form route field, and the+// space is never part of the intent: the host supplies it from the loaded record.+export const canvasNavIntentSchema = z.discriminatedUnion('target', [+ z.object({ target: z.literal('task'), taskId: z.string().min(1) }),+ z.object({ target: z.literal('new-task') }),+ z.object({+ target: z.literal('compose-task'),+ prompt: z.string().max(16_000).optional(),+ repository: z+ .string()+ .max(200)+ .regex(/^[a-z0-9-]+\/[a-z0-9_.-]+$/i)+ .optional(),+ }),+ z.object({ target: z.literal('canvas'), dashboardId: z.string().min(1) }),+ z.object({ target: z.literal('new-canvas') }),+ z.object({ target: z.literal('connect'), provider: canvasConnectorProviderSchema }),+])+export type CanvasNavIntent = z.infer<typeof canvasNavIntentSchema>++export const CANVAS_DATA_METHODS = [+ 'query',+ 'loadInsight',+ 'capture',+ 'run',+ 'stateGet',+ 'stateSet',+ 'stateList',+ 'actionInvoke',+ 'agentRequest',+ 'connectorCall',+] as const+export type CanvasDataMethod = (typeof CANVAS_DATA_METHODS)[number]++const canvasTextSelectionSchema = z+ .object({+ quote: z.string(),+ prefix: z.string(),+ suffix: z.string(),+ start: z.number().int().min(0),+ end: z.number().int().min(0),+ rect: z.object({+ top: z.number().finite(),+ right: z.number().finite(),+ bottom: z.number().finite(),+ left: z.number().finite(),+ }),+ })+ .refine(({ start, end }) => end > start)++const channel = z.literal(CANVAS_CHANNEL)++export const canvasToHostMessageSchema = z.discriminatedUnion('type', [+ z.object({ channel, type: z.literal('ready') }),+ z.object({+ channel,+ type: z.literal('data-request'),+ id: z.string().min(1).max(128),+ method: z.enum(CANVAS_DATA_METHODS),+ payload: z.unknown(),+ }),+ z.object({+ channel,+ type: z.literal('error'),+ message: z.string().max(10_000),+ stack: z.string().max(50_000).optional(),+ }),+ z.object({ channel, type: z.literal('rendered') }),+ z.object({ channel, type: z.literal('navigate'), nav: canvasNavIntentSchema }),+ z.object({+ channel,+ type: z.literal('open-external'),+ url: z.string().refine((url) => isSafePostHogUrl(url) || isSafeGitHubPullRequestUrl(url)),+ }),+ z.object({ channel, type: z.literal('text-selection'), selection: canvasTextSelectionSchema }),+ z.object({ channel, type: z.literal('text-selection-cleared') }),+ z.object({ channel, type: z.literal('comment-activate'), id: z.string().min(1).max(128) }),+ z.object({+ channel,+ type: z.literal('keydown'),+ key: z.string().min(1).max(32),+ code: z.string().max(32),+ metaKey: z.boolean(),+ ctrlKey: z.boolean(),+ shiftKey: z.boolean(),+ altKey: z.boolean(),+ }),+])+export type CanvasToHostMessage = z.infer<typeof canvasToHostMessageSchema>++export type HostToCanvasMessage =+ | {+ channel: typeof CANVAS_CHANNEL+ type: 'init'+ files: Record<string, string>+ entry: string+ theme?: CanvasTheme+ highlights?: unknown[]+ }+ | { channel: typeof CANVAS_CHANNEL; type: 'set-theme'; theme: CanvasTheme }+ | { channel: typeof CANVAS_CHANNEL; type: 'set-comment-highlights'; highlights: unknown[] }+ | { channel: typeof CANVAS_CHANNEL; type: 'clear-text-selection' }+ | {+ channel: typeof CANVAS_CHANNEL+ type: 'data-response'+ id: string+ ok: boolean+ result?: unknown+ error?: string+ }diff --git a/products/canvas/frontend/host/canvasReadCache.ts b/products/canvas/frontend/host/canvasReadCache.tsnew file mode 100644index 000000000000..d79590fc2f70--- /dev/null+++ b/products/canvas/frontend/host/canvasReadCache.ts@@ -0,0 +1,71 @@+// Deterministic stringify for cache keys: object keys sort at every depth, so two reads+// that differ only by key order share an entry. `undefined` and non-finite numbers get+// their own tokens, because JSON.stringify collapses them all to `null`.+export function stableStringify(value: unknown): string {+ if (value === undefined) {+ return 'undef'+ }+ if (value === null) {+ return 'null'+ }+ if (typeof value === 'number') {+ return Number.isFinite(value) ? String(value) : `num:${String(value)}`+ }+ if (typeof value !== 'object') {+ return JSON.stringify(value)+ }+ if (Array.isArray(value)) {+ return `[${value.map(stableStringify).join(',')}]`+ }+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, entry]) => entry !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)+ return `{${entries.join(',')}}`+}++interface CacheEntry {+ value: unknown+ expiresAt: number+}++const MAX_ENTRIES = 256++/**+ * A small TTL cache for canvas reads. An iframe reboot or a render loop resolves a+ * repeated read from here instead of hitting ClickHouse again, and identical reads in+ * flight share one request.+ */+export class CanvasReadCache {+ private readonly entries = new Map<string, CacheEntry>()+ private readonly inFlight = new Map<string, Promise<unknown>>()++ constructor(private readonly now: () => number = Date.now) {}++ async read<T>(method: string, input: unknown, ttlSeconds: number, run: () => Promise<T>): Promise<T> {+ const key = `${method}:${stableStringify(input)}`+ const cached = this.entries.get(key)+ if (cached && cached.expiresAt > this.now()) {+ return cached.value as T+ }+ const pending = this.inFlight.get(key)+ if (pending) {+ return pending as Promise<T>+ }+ const request = run()+ .then((value) => {+ this.entries.delete(key)+ this.entries.set(key, { value, expiresAt: this.now() + ttlSeconds * 1_000 })+ if (this.entries.size > MAX_ENTRIES) {+ const oldest = this.entries.keys().next().value+ if (oldest !== undefined) {+ this.entries.delete(oldest)+ }+ }+ return value+ })+ .finally(() => this.inFlight.delete(key))+ this.inFlight.set(key, request)+ return request+ }+}diff --git a/products/canvas/frontend/newCanvas/CanvasNewScene.tsx b/products/canvas/frontend/newCanvas/CanvasNewScene.tsxnew file mode 100644index 000000000000..b33d283b5453--- /dev/null+++ b/products/canvas/frontend/newCanvas/CanvasNewScene.tsx@@ -0,0 +1,50 @@+import { useActions, useValues } from 'kea'++import { Text } from '@posthog/quill'++import { NotFound } from 'lib/components/NotFound'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { SceneExport } from 'scenes/sceneTypes'++import { CanvasComposer } from '../scene/CanvasComposer'+import { CanvasStartHero } from '../scene/CanvasStartHero'+import { CanvasToolbar } from '../scene/CanvasToolbar'+import { canvasNewLogic } from './canvasNewLogic'+import { CanvasSpaceSelect } from './CanvasSpaceSelect'++export const scene: SceneExport = {+ component: CanvasNewScene,+ logic: canvasNewLogic,+}++/** The start page for a new canvas. Nothing is saved until the first prompt is sent. */+export function CanvasNewScene(): JSX.Element {+ const enabled = useFeatureFlag('TODAY_RAIL_NAV')+ const { instruction, sending, sendDisabledReason } = useValues(canvasNewLogic)+ const { setInstruction, send } = useActions(canvasNewLogic)++ if (!enabled) {+ return <NotFound object="page" />+ }+ return (+ <div data-quill className="flex h-full min-h-0 flex-col bg-background">+ <CanvasToolbar dataAttr="canvas-new-toolbar">+ <Text size="sm" weight="medium" className="truncate pl-2">+ New canvas+ </Text>+ </CanvasToolbar>+ <main className="min-h-0 flex-1">+ <CanvasStartHero description="Describe it and an agent builds it. The canvas is saved when you send.">+ <CanvasComposer+ instruction={instruction}+ onInstructionChange={setInstruction}+ onSubmit={send}+ submitting={sending}+ disabledReason={sendDisabledReason}+ footerStart={<CanvasSpaceSelect />}+ />+ </CanvasStartHero>+ </main>+ </div>+ )+}diff --git a/products/canvas/frontend/newCanvas/CanvasSpaceSelect.tsx b/products/canvas/frontend/newCanvas/CanvasSpaceSelect.tsxnew file mode 100644index 000000000000..cb738d9495a0--- /dev/null+++ b/products/canvas/frontend/newCanvas/CanvasSpaceSelect.tsx@@ -0,0 +1,58 @@+import { useActions, useValues } from 'kea'++import { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Skeleton, Text } from '@posthog/quill'++import { canvasSpaceLabel } from '../canvasTasksApi'+import { canvasNewLogic } from './canvasNewLogic'++/** The space a new canvas goes in, shown in the composer's footer. */+export function CanvasSpaceSelect(): JSX.Element {+ const { spaces, spacesLoading, spacesUnavailable, selectedSpaceId, sending } = useValues(canvasNewLogic)+ const { setSelectedSpaceId, loadSpaces } = useActions(canvasNewLogic)++ if (spacesUnavailable) {+ return (+ <div className="flex flex-wrap items-center gap-2" role="alert">+ <Text size="xs" variant="destructive">+ Your spaces didn’t load.+ </Text>+ <Button+ type="button"+ variant="outline"+ size="xs"+ loading={spacesLoading}+ onClick={() => loadSpaces()}+ data-attr="canvas-new-spaces-retry"+ >+ Try again+ </Button>+ </div>+ )+ }+ if (spaces === null) {+ return <Skeleton className="h-6 w-24" aria-label="Loading your spaces" />+ }+ return (+ <Select+ value={selectedSpaceId ?? ''}+ disabled={sending || !spaces.length}+ onValueChange={(value) => value && setSelectedSpaceId(String(value))}+ >+ <SelectTrigger size="sm" aria-label="Space" data-attr="canvas-new-space">+ <SelectValue>+ {(value: string) => {+ const space = spaces.find((entry) => entry.id === value)+ return space ? `#${canvasSpaceLabel(space)}` : 'Pick a space'+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {spaces.map((space) => (+ <SelectItem key={space.id} value={space.id}>+ {`#${canvasSpaceLabel(space)}`}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}diff --git a/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts b/products/canvas/frontend/newCanvas/canvasNewLogic.test.tsnew file mode 100644index 000000000000..6066b447aa42--- /dev/null+++ b/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts@@ -0,0 +1,125 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { urls } from 'scenes/urls'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { canvasSceneLogic } from '../scene/canvasSceneLogic'+import { canvasNewLogic } from './canvasNewLogic'++const CANVAS_ID = 'canvas-new-1'+const PROMPT = 'A chart of daily signups'++describe('canvasNewLogic', () => {+ let createdCanvas: Record<string, unknown> | null = null+ let createCount = 0+ let taskStatus = 201+ let linkStatus = 200+ let runCount = 0++ beforeEach(() => {+ createdCanvas = null+ createCount = 0+ linkStatus = 200+ runCount = 0+ useMocks({+ get: {+ '/api/projects/:team_id/task_channels/': [+ { id: 'space-me', name: 'me', system_role: 'personal' },+ { id: 'space-growth', name: 'growth', system_role: null },+ ],+ '/api/projects/:team_id/canvases/:id/view/': () => [+ 200,+ {+ canvas: createdCanvas,+ published_build: null,+ current_version_id: null,+ has_active_build: false,+ source: null,+ layout: null,+ sandbox_document_url: null,+ },+ ],+ '/api/projects/:team_id/tasks/:id/': { id: 'task-1', title: 'Daily signups', latest_run: null },+ '/api/projects/:team_id/canvases/:id/builds/': { builds: [], published_build_id: null },+ '/api/projects/:team_id/task_channels/:id/': { id: 'space-growth', name: 'growth', system_role: null },+ },+ post: {+ '/api/projects/:team_id/tasks/:id/run/': async ({ request }) => {+ expect(await request.json()).toMatchObject({ run_source: 'manual' })+ runCount+++ return [201, { id: 'task-1', title: 'Daily signups', latest_run: { status: 'queued' } }]+ },+ '/api/projects/:team_id/canvases/': async ({ request }) => {+ const body = (await request.json()) as Record<string, string>+ createCount += 1+ createdCanvas = {+ id: CANVAS_ID,+ name: body.name,+ kind: 'freeform',+ channel: body.channel_id,+ template_id: body.template_id,+ generation_task_id: null,+ published_build_id: null,+ }+ return [201, createdCanvas]+ },+ '/api/projects/:team_id/tasks/': async ({ request }) => {+ expect(await request.json()).toMatchObject({ start_run: false })+ return taskStatus === 201+ ? [201, { id: 'task-1', title: 'Daily signups', latest_run: null }]+ : [403, { error: 'Agent-started task runs are not available for this project' }]+ },+ },+ patch: {+ '/api/projects/:team_id/canvases/:id/': async ({ request }) => {+ if (linkStatus !== 200) {+ return [linkStatus, { detail: 'Link failed' }]+ }++ createdCanvas = { ...createdCanvas, ...((await request.json()) as Record<string, unknown>) }+ return [200, createdCanvas]+ },+ },+ })+ initKeaTests()+ })++ test.each([+ ['the build starts', 201, 200, ''],+ ['the build fails to start', 403, 200, PROMPT],+ ['the task link fails', 201, 503, PROMPT],+ ])(+ 'creates the canvas only on send and replaces the start page with it when %s',+ async (_, status, patchStatus, composerText) => {+ taskStatus = status+ linkStatus = patchStatus+ const logic = canvasNewLogic()+ logic.mount()+ router.actions.push(urls.canvasNew('space-growth'))+ await expectLogic(logic).toDispatchActions(['loadSpacesSuccess'])+ expect(logic.values.selectedSpaceId).toEqual('space-growth')+ expect(createdCanvas).toBeNull()++ logic.actions.setInstruction(PROMPT, false)+ logic.actions.send()+ logic.actions.send()+ await expectLogic(logic).toDispatchActions(['sendFinished'])++ expect(runCount).toBe(composerText ? 0 : 1)+ expect(createCount).toEqual(1)+ expect(createdCanvas).toMatchObject({ id: CANVAS_ID, channel: 'space-growth' })+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.canvasDetail(CANVAS_ID))+ expect(router.values.lastMethod).toEqual('REPLACE')++ const sceneLogic = canvasSceneLogic({ id: CANVAS_ID })+ sceneLogic.mount()+ await expectLogic(sceneLogic).toDispatchActions(['loadViewSuccess', 'loadSpaceSuccess'])+ expect(sceneLogic.values.instruction).toEqual(composerText)+ expect(logic.values.startHandoff).toBeNull()+ }+ )+})diff --git a/products/canvas/frontend/newCanvas/canvasNewLogic.ts b/products/canvas/frontend/newCanvas/canvasNewLogic.tsnew file mode 100644index 000000000000..3c56d4c2df3e--- /dev/null+++ b/products/canvas/frontend/newCanvas/canvasNewLogic.ts@@ -0,0 +1,331 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'+import posthog from 'posthog-js'++import { toast } from '@posthog/quill'++import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { CANVAS_EVENTS } from '../canvasAnalytics'+import { CanvasSpace, loadCanvasSpaces } from '../canvasTasksApi'+import { FREEFORM_TEMPLATE_ID, UNTITLED_CANVAS_NAME } from '../canvasTemplates'+import { canvasesCreate } from '../generated/api'+import type { CanvasApi } from '../generated/api.schemas'+import { startCanvasGeneration } from '../startCanvasGeneration'++/** A prompt whose canvas exists but whose build did not start. The canvas page picks it up. */+export interface CanvasStartHandoff {+ canvasId: string+ instruction: string+ fromSuggestion: boolean+}++function pickCanvasSpaceId(+ spaces: CanvasSpace[] | null,+ chosen: string | null,+ requested: string | null+): string | null {+ if (!spaces) {+ return null+ }+ const has = (id: string | null): id is string => !!id && spaces.some((space) => space.id === id)+ if (has(chosen)) {+ return chosen+ }+ if (has(requested)) {+ return requested+ }+ return (spaces.find((space) => space.system_role === 'personal') ?? spaces[0])?.id ?? null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasNewLogicValues {+ currentProjectId: number | null // projectLogic+ breadcrumbs: Breadcrumb[]+ chosenSpaceId: string | null+ fromSuggestion: boolean+ instruction: string+ requestedSpaceId: string | null+ selectedSpace: CanvasSpace | null+ selectedSpaceId: string | null+ sendDisabledReason: string | null+ sending: boolean+ spaces: CanvasSpace[] | null+ spacesLoading: boolean+ spacesUnavailable: boolean+ startHandoff: CanvasStartHandoff | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasNewLogicActions {+ clearStartHandoff: () => {+ value: true+ }+ handOffStart: (handoff: CanvasStartHandoff) => {+ handoff: CanvasStartHandoff+ }+ loadSpaces: () => any+ loadSpacesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSpacesSuccess: (+ spaces: CanvasSpace[],+ payload?: any+ ) => {+ spaces: CanvasSpace[]+ payload?: any+ }+ send: () => {+ value: true+ }+ sendFinished: () => {+ value: true+ }+ sendStarted: () => {+ value: true+ }+ sent: () => {+ value: true+ }+ setInstruction: (+ instruction: string,+ fromSuggestion: boolean+ ) => {+ fromSuggestion: boolean+ instruction: string+ }+ setRequestedSpaceId: (spaceId: string | null) => {+ spaceId: string | null+ }+ setSelectedSpaceId: (spaceId: string) => {+ spaceId: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasNewLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ selectedSpaceId: (+ spaces: CanvasSpace[] | null,+ chosenSpaceId: string | null,+ requestedSpaceId: string | null+ ) => string | null+ selectedSpace: (spaces: CanvasSpace[] | null, selectedSpaceId: string | null) => CanvasSpace | null+ sendDisabledReason: (+ instruction: string,+ spaces: CanvasSpace[] | null,+ spacesUnavailable: boolean,+ selectedSpaceId: string | null+ ) => string | null+ }+}++export type canvasNewLogicType = MakeLogicType<+ canvasNewLogicValues,+ canvasNewLogicActions,+ Record<string, any>,+ canvasNewLogicMeta+>++/**+ * The new canvas start page: a prompt and a space. Sending creates the canvas, starts the+ * agent that builds it, and replaces the page with the canvas, so Back skips the empty start page.+ */+export const canvasNewLogic = kea<canvasNewLogicType>([+ path(['products', 'canvas', 'frontend', 'newCanvas', 'canvasNewLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ setInstruction: (instruction: string, fromSuggestion: boolean) => ({ instruction, fromSuggestion }),+ setRequestedSpaceId: (spaceId: string | null) => ({ spaceId }),+ setSelectedSpaceId: (spaceId: string) => ({ spaceId }),+ send: true,+ sendStarted: true,+ sendFinished: true,+ sent: true,+ handOffStart: (handoff: CanvasStartHandoff) => ({ handoff }),+ clearStartHandoff: true,+ }),+ loaders(({ values }) => ({+ spaces: [+ null as CanvasSpace[] | null,+ {+ loadSpaces: async () =>+ values.currentProjectId ? await loadCanvasSpaces(String(values.currentProjectId)) : [],+ },+ ],+ })),+ reducers({+ instruction: [+ '',+ {+ setInstruction: (_, { instruction }) => instruction,+ sent: () => '',+ handOffStart: () => '',+ },+ ],+ fromSuggestion: [+ false,+ {+ setInstruction: (_, { fromSuggestion }) => fromSuggestion,+ sent: () => false,+ handOffStart: () => false,+ },+ ],+ requestedSpaceId: [+ null as string | null,+ {+ setRequestedSpaceId: (_, { spaceId }) => spaceId,+ },+ ],+ chosenSpaceId: [+ null as string | null,+ {+ setRequestedSpaceId: () => null,+ setSelectedSpaceId: (_, { spaceId }) => spaceId,+ },+ ],+ sending: [+ false,+ {+ sendStarted: () => true,+ sendFinished: () => false,+ },+ ],+ spacesUnavailable: [+ false,+ {+ loadSpaces: () => false,+ loadSpacesFailure: () => true,+ },+ ],+ startHandoff: [+ null as CanvasStartHandoff | null,+ {+ handOffStart: (_, { handoff }) => handoff,+ clearStartHandoff: () => null,+ },+ ],+ }),+ selectors({+ selectedSpaceId: [+ (s) => [s.spaces, s.chosenSpaceId, s.requestedSpaceId],+ (spaces: CanvasSpace[] | null, chosen: string | null, requested: string | null): string | null =>+ pickCanvasSpaceId(spaces, chosen, requested),+ ],+ selectedSpace: [+ (s) => [s.spaces, s.selectedSpaceId],+ (spaces: CanvasSpace[] | null, selectedSpaceId: string | null): CanvasSpace | null =>+ spaces?.find((space) => space.id === selectedSpaceId) ?? null,+ ],+ sendDisabledReason: [+ (s) => [s.instruction, s.spaces, s.spacesUnavailable, s.selectedSpaceId],+ (+ instruction: string,+ spaces: CanvasSpace[] | null,+ spacesUnavailable: boolean,+ selectedSpaceId: string | null+ ): string | null => {+ if (spacesUnavailable) {+ return 'Your spaces didn’t load. Try again to pick one.'+ }+ if (!spaces) {+ return 'Loading your spaces'+ }+ if (!selectedSpaceId) {+ return 'You don’t have a space to put a canvas in yet'+ }+ if (!instruction.trim()) {+ return 'Describe the canvas first'+ }+ return null+ },+ ],+ breadcrumbs: [+ () => [],+ (): Breadcrumb[] => [+ { key: 'views', name: 'Views', path: urls.views() },+ { key: 'CanvasNew', name: 'New canvas' },+ ],+ ],+ }),+ listeners(({ actions, values }) => ({+ send: async () => {+ const projectId = values.currentProjectId ? String(values.currentProjectId) : null+ const space = values.selectedSpace+ const instruction = values.instruction.trim()+ const fromSuggestion = values.fromSuggestion+ if (values.sending || values.sendDisabledReason || !projectId || !space) {+ return+ }+ actions.sendStarted()+ const stillOnStartPage = (): boolean =>+ removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()+ try {+ let canvas: CanvasApi+ try {+ canvas = await canvasesCreate(projectId, {+ channel_id: space.id,+ name: UNTITLED_CANVAS_NAME,+ template_id: FREEFORM_TEMPLATE_ID,+ })+ } catch (error) {+ toast.error({+ title: "Couldn't create the canvas",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ return+ }+ posthog.capture(CANVAS_EVENTS.dashboardAction, {+ action_type: 'create',+ surface: 'web_new_canvas_page',+ channel_id: space.id,+ dashboard_id: canvas.id,+ template_id: FREEFORM_TEMPLATE_ID,+ })+ try {+ await startCanvasGeneration({+ projectId,+ canvas,+ spaceName: space.name,+ instruction,+ fromSuggestion,+ surface: 'web_new_canvas_page',+ })+ actions.sent()+ } catch (error) {+ // The canvas exists, so the person lands on it with the prompt kept, ready to send again.+ actions.handOffStart({ canvasId: canvas.id, instruction, fromSuggestion })+ toast.error({+ title: "Couldn't start building the canvas",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ }+ if (stillOnStartPage()) {+ router.actions.replace(urls.canvasDetail(canvas.id))+ }+ } finally {+ actions.sendFinished()+ }+ },+ })),+ urlToAction(({ actions, values }) => ({+ [urls.canvasNew()]: (_, searchParams) => {+ if (values.sending) {+ return+ }+ actions.setRequestedSpaceId(typeof searchParams.space === 'string' ? searchParams.space : null)+ actions.loadSpaces()+ },+ })),+])diff --git a/products/canvas/frontend/scene/CanvasBuildStatusBadge.tsx b/products/canvas/frontend/scene/CanvasBuildStatusBadge.tsxnew file mode 100644index 000000000000..b40ae9402860--- /dev/null+++ b/products/canvas/frontend/scene/CanvasBuildStatusBadge.tsx@@ -0,0 +1,56 @@+import { useValues } from 'kea'++import { Badge, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { canvasSceneLogic } from './canvasSceneLogic'++/** A compact read of the canvas's build lifecycle, beside its name. */+export function CanvasBuildStatusBadge(): JSX.Element | null {+ const { buildStatus, view } = useValues(canvasSceneLogic)++ if (buildStatus === 'building') {+ return <StatusBadge variant="info" label="Building" hint="A new version is building." />+ }+ if (buildStatus === 'failed') {+ return (+ <StatusBadge+ variant="destructive"+ label="Build failed"+ hint={+ view?.published_build+ ? "The latest version didn't build. The last working version stays live."+ : "This version didn't build, so the canvas shows its source as a draft."+ }+ />+ )+ }+ if (buildStatus === 'live') {+ return <StatusBadge variant="success" label="Live" hint="Everyone with access sees this version." />+ }+ if (view?.current_version_id) {+ return <StatusBadge variant="default" label="Draft" hint="This canvas has not been built yet." />+ }+ return null+}++function StatusBadge({+ variant,+ label,+ hint,+}: {+ variant: 'info' | 'destructive' | 'success' | 'default'+ label: string+ hint: string+}): JSX.Element {+ return (+ <Tooltip>+ {/* quill's Badge does not forward refs under React 18, so a span anchors the tooltip. */}+ <TooltipTrigger render={<span className="inline-flex" />}>+ <Badge variant={variant} data-attr="canvas-build-status">+ {label}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>{hint}</TooltipContent>+ </Tooltip>+ )+}diff --git a/products/canvas/frontend/scene/CanvasComposer.tsx b/products/canvas/frontend/scene/CanvasComposer.tsxnew file mode 100644index 000000000000..9020774aa928--- /dev/null+++ b/products/canvas/frontend/scene/CanvasComposer.tsx@@ -0,0 +1,140 @@+import { ChangeEvent, KeyboardEvent, useRef } from 'react'++import { IconSend } from '@posthog/icons'+import {+ Button,+ InputGroup,+ InputGroupAddon,+ InputGroupTextarea,+ Item,+ ItemContent,+ ItemGroup,+ ItemMedia,+ ItemTitle,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { CANVAS_GENERATE_SUGGESTIONS } from './canvasGenerateSuggestions'++export interface CanvasComposerProps {+ instruction: string+ onInstructionChange: (instruction: string, fromSuggestion: boolean) => void+ onSubmit: () => void+ /** True while the send is in flight. It blocks a second send. */+ submitting: boolean+ /** Why the prompt cannot be sent yet, or null when it can. */+ disabledReason: string | null+ /** Controls at the start of the composer's footer, such as the space picker. */+ footerStart?: JSX.Element+}++/** Describe a canvas and send it to the agent that builds it, with starter prompts below. */+export function CanvasComposer({+ instruction,+ onInstructionChange,+ onSubmit,+ submitting,+ disabledReason,+ footerStart,+}: CanvasComposerProps): JSX.Element {+ // quill's textarea does not forward refs, so focus goes through its form.+ const formRef = useRef<HTMLFormElement>(null)+ const focusComposer = (): void => formRef.current?.querySelector('textarea')?.focus()+ const submit = (): void => {+ if (!disabledReason && !submitting) {+ onSubmit()+ }+ }++ return (+ <div className="flex flex-col gap-4">+ <form+ ref={formRef}+ onSubmit={(event) => {+ event.preventDefault()+ submit()+ }}+ >+ <InputGroup>+ <InputGroupTextarea+ autoFocus+ aria-label="Describe the canvas"+ placeholder="A chart of daily signups for the last 30 days, with the total at the top"+ rows={4}+ value={instruction}+ disabled={submitting}+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>+ onInstructionChange(event.target.value, false)+ }+ onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault()+ submit()+ }+ }}+ data-attr="canvas-generate-input"+ />+ <InputGroupAddon align="block-end" className="flex-wrap">+ {footerStart}+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <Button+ type="submit"+ variant="primary"+ size="icon-sm"+ className="ml-auto"+ aria-label="Build canvas"+ loading={submitting}+ disabled={!!disabledReason}+ data-attr="canvas-generate-submit"+ />+ }+ >+ <IconSend />+ </TooltipTrigger>+ <TooltipContent>{disabledReason ?? 'Build canvas'}</TooltipContent>+ </Tooltip>+ </InputGroupAddon>+ </InputGroup>+ </form>+ <section aria-labelledby="canvas-suggestions-label" className="flex flex-col gap-2">+ <Text id="canvas-suggestions-label" size="xs" variant="muted" weight="medium" render={<h2 />}>+ Start from an example+ </Text>+ <ItemGroup combined>+ {CANVAS_GENERATE_SUGGESTIONS.map((suggestion) => (+ <Item+ key={suggestion.label}+ variant="outline"+ size="xs"+ className="text-left hover:bg-fill-button-tertiary-hover"+ render={+ <button+ type="button"+ disabled={submitting}+ onClick={() => {+ onInstructionChange(suggestion.prompt, true)+ focusComposer()+ }}+ data-attr="canvas-generate-suggestion"+ />+ }+ >+ <ItemMedia aria-hidden>+ <suggestion.icon />+ </ItemMedia>+ <ItemContent className="min-w-0">+ <ItemTitle className="truncate">{suggestion.label}</ItemTitle>+ </ItemContent>+ </Item>+ ))}+ </ItemGroup>+ </section>+ </div>+ )+}diff --git a/products/canvas/frontend/scene/CanvasEmptyBody.tsx b/products/canvas/frontend/scene/CanvasEmptyBody.tsxnew file mode 100644index 000000000000..bed8c8539200--- /dev/null+++ b/products/canvas/frontend/scene/CanvasEmptyBody.tsx@@ -0,0 +1,23 @@+import { useActions, useValues } from 'kea'++import { CanvasComposer } from './CanvasComposer'+import { canvasSceneLogic } from './canvasSceneLogic'+import { CanvasStartHero } from './CanvasStartHero'++/** The body of a canvas with nothing to render yet: the composer that starts its first build. */+export function CanvasEmptyBody({ notice }: { notice?: string }): JSX.Element {+ const { instruction, instructionFromSuggestion, generationStarting } = useValues(canvasSceneLogic)+ const { setInstruction, generateCanvas } = useActions(canvasSceneLogic)++ return (+ <CanvasStartHero description={notice ?? 'Describe it and an agent builds it.'}>+ <CanvasComposer+ instruction={instruction}+ onInstructionChange={setInstruction}+ onSubmit={() => generateCanvas(instruction, instructionFromSuggestion)}+ submitting={generationStarting}+ disabledReason={instruction.trim() ? null : 'Describe the canvas first'}+ />+ </CanvasStartHero>+ )+}diff --git a/products/canvas/frontend/scene/CanvasGeneratingState.tsx b/products/canvas/frontend/scene/CanvasGeneratingState.tsxnew file mode 100644index 000000000000..2ecb430db1fc--- /dev/null+++ b/products/canvas/frontend/scene/CanvasGeneratingState.tsx@@ -0,0 +1,37 @@+import { useValues } from 'kea'++import { Button, Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle, Spinner } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import { canvasSceneLogic } from './canvasSceneLogic'++/** Shown while the agent writes a canvas that has nothing to render yet. */+export function CanvasGeneratingState(): JSX.Element {+ const { canvas } = useValues(canvasSceneLogic)+ const taskId = canvas?.generation_task_id++ return (+ <Empty className="h-full">+ <EmptyHeader>+ <Spinner />+ <EmptyTitle className="quill-shimmer">Building your canvas</EmptyTitle>+ <EmptyDescription>+ The agent is writing the canvas. It shows here as soon as the first version is ready.+ </EmptyDescription>+ </EmptyHeader>+ {taskId && (+ <EmptyContent>+ <Button+ variant="outline"+ render={<LinkPrimitive to={urls.taskDetail(taskId)} />}+ data-attr="canvas-generating-view-task"+ >+ View the agent's task+ </Button>+ </EmptyContent>+ )}+ </Empty>+ )+}diff --git a/products/canvas/frontend/scene/CanvasRenderer.tsx b/products/canvas/frontend/scene/CanvasRenderer.tsxnew file mode 100644index 000000000000..15365cc0cb6a--- /dev/null+++ b/products/canvas/frontend/scene/CanvasRenderer.tsx@@ -0,0 +1,100 @@+import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'+import { useCallback } from 'react'++import { themeLogic } from 'lib/logic/themeLogic'++import type { CanvasCapabilitiesApi, CanvasSourceProjectApi } from '../generated/api.schemas'+import { BuiltCanvas } from '../host/BuiltCanvas'+import {+ CanvasHostLogicProps,+ canvasHasUserActivation,+ canvasHostLogic,+ handleCanvasDataRequest,+} from '../host/canvasHostLogic'+import { CanvasHostPromptDialog } from '../host/CanvasHostPromptDialog'+import { DraftCanvas } from '../host/DraftCanvas'+import { canvasSceneLogic } from './canvasSceneLogic'++/** Renders the live build when there is one, else the head source in the draft sandbox. */+export function CanvasRenderer(): JSX.Element | null {+ const { canvas, liveBuild, sandboxDocumentUrl, view } = useValues(canvasSceneLogic)+ if (!canvas) {+ return null+ }+ const hostProps: CanvasHostLogicProps = {+ canvasId: canvas.id,+ spaceId: canvas.channel,+ sourceVersionId: liveBuild ? liveBuild.source_version_id : (view?.current_version_id ?? null),+ }+ return (+ <BindLogic logic={canvasHostLogic} props={hostProps}>+ <CanvasHostFrame+ hostProps={hostProps}+ artifactUrl={liveBuild?.artifact_url ?? null}+ capabilities={(liveBuild?.manifest?.capabilities as CanvasCapabilitiesApi | undefined) ?? null}+ buildId={liveBuild?.id ?? null}+ draftSource={view?.source ?? null}+ sandboxDocumentUrl={sandboxDocumentUrl}+ />+ <CanvasHostPromptDialog />+ </BindLogic>+ )+}++function CanvasHostFrame({+ hostProps,+ artifactUrl,+ capabilities,+ buildId,+ draftSource,+ sandboxDocumentUrl,+}: {+ hostProps: CanvasHostLogicProps+ artifactUrl: string | null+ capabilities: CanvasCapabilitiesApi | null+ buildId: string | null+ draftSource: CanvasSourceProjectApi | null+ sandboxDocumentUrl: string | null+}): JSX.Element | null {+ const hostLogic = useMountedLogic(canvasHostLogic(hostProps))+ const { navigate, openExternal, canvasRendered, canvasErrored } = useActions(hostLogic)+ const { isDarkModeOn } = useValues(themeLogic)+ const theme = isDarkModeOn ? 'dark' : 'light'+ const onDataRequest = useCallback(+ (method: string, payload: unknown) => handleCanvasDataRequest(hostLogic, method, payload),+ [hostLogic]+ )+ const shared = {+ theme,+ onDataRequest,+ onNavigate: navigate,+ onOpenExternal: openExternal,+ onRendered: () => canvasRendered(buildId),+ onError: (message: string) => canvasErrored(message, buildId),+ hasUserActivation: canvasHasUserActivation,+ } as const++ if (artifactUrl) {+ // Keyed by build, so a new live build gets a fresh frame and bridge.+ return (+ <BuiltCanvas+ key={buildId ?? artifactUrl}+ artifactUrl={artifactUrl}+ capabilities={capabilities}+ {...shared}+ />+ )+ }+ if (draftSource?.files['src/canvas.tsx'] && sandboxDocumentUrl) {+ return (+ <DraftCanvas+ documentUrl={sandboxDocumentUrl}+ capabilities={draftSource.capabilities}+ files={draftSource.files}+ entry="src/canvas.tsx"+ {...shared}+ />+ )+ }+ return null+}diff --git a/products/canvas/frontend/scene/CanvasScene.stories.tsx b/products/canvas/frontend/scene/CanvasScene.stories.tsxnew file mode 100644index 000000000000..79361ab51750--- /dev/null+++ b/products/canvas/frontend/scene/CanvasScene.stories.tsx@@ -0,0 +1,107 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type { CanvasApi, CanvasViewResponseApi } from '../generated/api.schemas'++const CANVAS_ID = '0190aaaa-0000-7000-8000-000000000001'+const SPACE_ID = '0190aaaa-0000-7000-8000-0000000000aa'+const TASK_ID = '0190aaaa-0000-7000-8000-0000000000bb'++const canvas: CanvasApi = {+ id: CANVAS_ID,+ name: 'Untitled canvas',+ kind: 'freeform',+ description: '',+ channel: SPACE_ID,+ template_id: 'freeform',+ generation_task_id: null,+ pinned: false,+ pinned_at: null,+ 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_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ url: `https://app.example.com/canvases/${CANVAS_ID}`,+}++function viewResponse(overrides: Partial<CanvasApi> = {}): CanvasViewResponseApi {+ return {+ canvas: { ...canvas, ...overrides },+ published_build: null,+ current_version_id: null,+ has_active_build: false,+ source: null,+ layout: null,+ sandbox_document_url: null,+ }+}++function mocks(view: CanvasViewResponseApi): ReturnType<typeof mswDecorator> {+ return mswDecorator({+ get: {+ '/api/projects/:team_id/canvases/:id/view/': view,+ '/api/projects/:team_id/canvases/:id/builds/': {+ published_build_id: null,+ current_version_id: null,+ builds: [],+ },+ '/api/projects/:team_id/task_channels/:id/': { id: SPACE_ID, name: 'me', system_role: 'personal' },+ '/api/projects/:team_id/tasks/:id/': {+ id: TASK_ID,+ title: 'Weekly active users',+ latest_run: { status: 'in_progress' },+ },+ },+ })+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Canvas',+ tags: ['test-skip'],+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ pageUrl: urls.canvasDetail(CANVAS_ID),+ featureFlags: [FEATURE_FLAGS.TODAY_RAIL_NAV],+ testOptions: { viewport: { width: 1300, height: 900 } },+ },+}+export default meta++type Story = StoryObj<{}>++export const Empty: Story = {+ decorators: [mocks(viewResponse())],+}++export const Generating: Story = {+ parameters: {+ testOptions: {+ waitForLoadersToDisappear: false,+ waitForSelector: '[data-attr="canvas-generating-view-task"]',+ },+ },+ decorators: [mocks(viewResponse({ name: 'Weekly active users', generation_task_id: TASK_ID }))],+}++export const NewCanvas: Story = {+ parameters: { pageUrl: urls.canvasNew(SPACE_ID) },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/task_channels/': [+ { id: 'space-personal', name: 'me', system_role: 'personal' },+ { id: SPACE_ID, name: 'growth', system_role: null },+ ],+ },+ }),+ ],+}diff --git a/products/canvas/frontend/scene/CanvasScene.tsx b/products/canvas/frontend/scene/CanvasScene.tsxnew file mode 100644index 000000000000..c0dcf7d4f104--- /dev/null+++ b/products/canvas/frontend/scene/CanvasScene.tsx@@ -0,0 +1,121 @@+import { BindLogic, useActions, useValues } from 'kea'++import { IconWarning } from '@posthog/icons'+import {+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Skeleton,+} from '@posthog/quill'++import { NotFound } from 'lib/components/NotFound'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'++import { CanvasEmptyBody } from './CanvasEmptyBody'+import { CanvasGeneratingState } from './CanvasGeneratingState'+import { CanvasRenderer } from './CanvasRenderer'+import { CanvasSceneHeader } from './CanvasSceneHeader'+import { CanvasSceneLogicProps, canvasSceneLogic } from './canvasSceneLogic'++export const scene: SceneExport<CanvasSceneLogicProps> = {+ component: CanvasScene,+ logic: canvasSceneLogic,+ paramsToProps: ({ params: { id } }) => ({ id }),+}++function CanvasBody(): JSX.Element {+ const { bodyState, viewLoading } = useValues(canvasSceneLogic)+ const { loadView } = useActions(canvasSceneLogic)++ switch (bodyState) {+ case 'loading':+ return (+ <div className="flex h-full flex-col gap-3 py-2">+ <Skeleton className="h-4 w-1/3" />+ <Skeleton className="h-full w-full" />+ </div>+ )+ case 'error':+ return (+ <Empty className="h-full">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <IconWarning />+ </EmptyMedia>+ <EmptyTitle>This canvas didn't load</EmptyTitle>+ <EmptyDescription>Check your connection and try again.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button+ variant="outline"+ loading={viewLoading}+ onClick={() => loadView()}+ data-attr="canvas-load-retry"+ >+ Try again+ </Button>+ </EmptyContent>+ </Empty>+ )+ case 'empty':+ return <CanvasEmptyBody />+ case 'generation-ended':+ return (+ <CanvasEmptyBody notice="The last run finished without a canvas to show. Describe it again to start a new run." />+ )+ case 'generating':+ return <CanvasGeneratingState />+ case 'draft-unavailable':+ return (+ <Empty className="h-full">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <IconWarning />+ </EmptyMedia>+ <EmptyTitle>This draft can't be shown here</EmptyTitle>+ <EmptyDescription>+ Drafts render from a separate canvas origin, and this PostHog instance doesn't have one set+ up. The canvas shows here once it's built, or you can open it in PostHog Desktop.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )+ case 'built':+ case 'draft':+ return <CanvasRenderer />+ case 'missing':+ return <NotFound object="canvas" />+ }+}++export function CanvasScene({ id }: CanvasSceneLogicProps): JSX.Element {+ const enabled = useFeatureFlag('TODAY_RAIL_NAV')+ const { viewMissing, sidePanelOpen } = useValues(canvasSceneLogic({ id }))++ if (!enabled || viewMissing) {+ return <NotFound object="canvas" />+ }+ return (+ <BindLogic logic={canvasSceneLogic} props={{ id }}>+ <SceneContent className="h-full min-h-0 gap-y-2">+ <CanvasSceneHeader />+ <div data-quill className="@container/canvas-scene flex min-h-0 flex-1">+ <main className="min-w-0 flex-1">+ <CanvasBody />+ </main>+ {sidePanelOpen && (+ // The side panel (chat, timeline, comments, versions) mounts here.+ <aside className="w-96 shrink-0 border-l border-border" data-attr="canvas-side-panel" />+ )}+ </div>+ </SceneContent>+ </BindLogic>+ )+}diff --git a/products/canvas/frontend/scene/CanvasSceneHeader.tsx b/products/canvas/frontend/scene/CanvasSceneHeader.tsxnew file mode 100644index 000000000000..965ea38a1390--- /dev/null+++ b/products/canvas/frontend/scene/CanvasSceneHeader.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { IconCopy, IconEllipsis, IconPalette, IconTrash } from '@posthog/icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { CanvasBuildStatusBadge } from './CanvasBuildStatusBadge'+import { canvasSceneLogic } from './canvasSceneLogic'++/** The canvas's name, its build status, and the actions on the canvas as a whole. Select the name to rename it. */+export function CanvasSceneHeader(): JSX.Element {+ const { canvas } = useValues(canvasSceneLogic)+ const { renameCanvas, copyLink, deleteCanvas } = useActions(canvasSceneLogic)++ return (+ <SceneTitleSection+ name={canvas?.name ?? null}+ isLoading={!canvas}+ resourceType={{ type: 'canvas', forceIcon: <IconPalette /> }}+ canEdit={!!canvas}+ onNameChange={renameCanvas}+ saveOnBlur+ renameDebounceMs={0}+ nameSuffix={+ canvas ? (+ <span data-quill className="inline-flex items-center">+ <CanvasBuildStatusBadge />+ </span>+ ) : undefined+ }+ actions={+ canvas ? (+ <div data-quill>+ <DropdownMenu>+ <Tooltip>+ {/* quill's triggers do not forward refs under React 18, so a span anchors the tooltip. */}+ <TooltipTrigger delay={0} render={<span className="inline-flex" />}>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="icon-sm"+ aria-label="Canvas actions"+ data-attr="canvas-actions-menu"+ />+ }+ >+ <IconEllipsis />+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>Canvas actions</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => copyLink()} data-attr="canvas-action-copy-link">+ <IconCopy />+ Copy link+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => deleteCanvas()}+ data-attr="canvas-action-delete"+ >+ <IconTrash />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ ) : undefined+ }+ />+ )+}diff --git a/products/canvas/frontend/scene/CanvasStartHero.tsx b/products/canvas/frontend/scene/CanvasStartHero.tsxnew file mode 100644index 000000000000..4cf4c9423335--- /dev/null+++ b/products/canvas/frontend/scene/CanvasStartHero.tsx@@ -0,0 +1,30 @@+import { IconPalette } from '@posthog/icons'+import { EmptyMedia, Heading, Text } from '@posthog/quill'++/** The centered start of a canvas with nothing in it yet, like PostHog Desktop: a heading, a line of help, and the composer. */+export function CanvasStartHero({+ description,+ children,+}: {+ description: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex h-full w-full flex-col items-center overflow-y-auto px-4 py-10">+ <div className="my-auto flex w-full max-w-2xl flex-col gap-5">+ <div className="flex flex-col items-center gap-2 text-center">+ <EmptyMedia variant="icon">+ <IconPalette />+ </EmptyMedia>+ <Heading render={<h1 />} size="xl">+ Build a canvas+ </Heading>+ <Text size="sm" variant="muted">+ {description}+ </Text>+ </div>+ {children}+ </div>+ </div>+ )+}diff --git a/products/canvas/frontend/scene/CanvasToolbar.tsx b/products/canvas/frontend/scene/CanvasToolbar.tsxnew file mode 100644index 000000000000..5b92c612de04--- /dev/null+++ b/products/canvas/frontend/scene/CanvasToolbar.tsx@@ -0,0 +1,23 @@+/**+ * The bar across the top of a canvas page, like PostHog Desktop's ChromeBar. It is as tall as the app+ * side panel's tab bar, so the two borders meet.+ */+export function CanvasToolbar({+ children,+ actions,+ dataAttr,+}: {+ children: React.ReactNode+ actions?: React.ReactNode+ dataAttr: string+}): JSX.Element {+ return (+ <div+ className="@container/canvas-toolbar flex h-12.5 shrink-0 items-center gap-2 border-b border-border bg-chrome pr-2 pl-1"+ data-attr={dataAttr}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden">{children}</div>+ {actions && <div className="flex shrink-0 items-center gap-1">{actions}</div>}+ </div>+ )+}diff --git a/products/canvas/frontend/scene/canvasGenerateSuggestions.ts b/products/canvas/frontend/scene/canvasGenerateSuggestions.tsnew file mode 100644index 000000000000..704886b856fd--- /dev/null+++ b/products/canvas/frontend/scene/canvasGenerateSuggestions.ts@@ -0,0 +1,48 @@+import { IconFunnels, IconGraph, IconPeople, IconPiggyBank, IconRetention, IconTrends } from '@posthog/icons'++export interface CanvasGenerateSuggestion {+ label: string+ description: string+ icon: typeof IconTrends+ prompt: string+}++// Starter prompts under the composer on an empty canvas. Mirrors PostHog Desktop.+export const CANVAS_GENERATE_SUGGESTIONS: CanvasGenerateSuggestion[] = [+ {+ label: 'Weekly active users',+ description: 'Active users over time, with the trend called out',+ icon: IconTrends,+ prompt: 'Build a dashboard showing weekly active users over the last 90 days, with the overall trend and any notable changes called out.',+ },+ {+ label: 'Signup to activation funnel',+ description: 'Conversion at each step from signup to activation',+ icon: IconFunnels,+ prompt: 'Build a funnel from signup to activation, showing the conversion rate at each step and where the biggest drop-off happens.',+ },+ {+ label: 'Revenue by plan',+ description: 'Revenue trends over time, broken down by plan',+ icon: IconPiggyBank,+ prompt: 'Build a canvas showing revenue trends over time broken down by plan, calling out the fastest-growing and shrinking segments.',+ },+ {+ label: 'Top events',+ description: 'The most common events over the last 30 days',+ icon: IconGraph,+ prompt: 'Build a breakdown of the most common events over the last 30 days, ranked by volume, with a short note on what stands out.',+ },+ {+ label: 'Retention cohorts',+ description: 'How well users stick around week over week',+ icon: IconRetention,+ prompt: 'Build a retention cohort view showing how well new users stick around week over week, and highlight which cohorts retain best.',+ },+ {+ label: 'Feature adoption',+ description: 'Adoption and engagement of a specific feature',+ icon: IconPeople,+ prompt: 'Build a canvas analyzing how a specific feature is being adopted: usage over time, share of active users, and engagement.\n\nFeature to analyze: ',+ },+]diff --git a/products/canvas/frontend/scene/canvasGenerationPrompt.ts b/products/canvas/frontend/scene/canvasGenerationPrompt.tsnew file mode 100644index 000000000000..446aab28d86c--- /dev/null+++ b/products/canvas/frontend/scene/canvasGenerationPrompt.ts@@ -0,0 +1,41 @@+import { FREEFORM_TEMPLATE_ID } from '../canvasTemplates'++// pinned: tag the task harness recognizes as injected canvas instructions, shared with PostHog Desktop+const CANVAS_INSTRUCTIONS_TAG = 'canvas_generation_instructions'++function escapeXmlAttr(value: string): string {+ return value+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/'/g, ''')+ .replace(/</g, '<')+ .replace(/>/g, '>')+}++/** The prompt that routes a cloud task to the building-canvases skill for one canvas. */+export function buildCanvasGenerationPrompt(input: {+ canvasId: string+ name: string+ spaceName: string+ templateId?: string+ instruction: string+}): string {+ // Every canvas created today is freeform, which names no layout for the skill to follow.+ const template =+ input.templateId && input.templateId !== FREEFORM_TEMPLATE_ID+ ? `\n- requested pattern: "${escapeXmlAttr(input.templateId)}"`+ : ''++ return `${input.instruction}++<${CANVAS_INSTRUCTIONS_TAG}>+Invoke the \`building-canvases\` skill and follow it completely.+If the canvas source has \`src/blocks/runtime.tsx\`, read the skill's \`references/blocks.md\` before you edit, and keep the canvas's blocks.+Expose 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)}"+- 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.tsnew file mode 100644index 000000000000..acd72a9454d9--- /dev/null+++ b/products/canvas/frontend/scene/canvasSceneLogic.test.ts@@ -0,0 +1,67 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { canvasSceneLogic } from './canvasSceneLogic'++const CANVAS_ID = 'canvas-1'++describe('canvasSceneLogic', () => {+ let releaseTaskRequest: () => void = () => {}++ beforeEach(() => {+ const taskRequestReleased = new Promise<void>((resolve) => {+ releaseTaskRequest = resolve+ })+ useMocks({+ get: {+ '/api/projects/:team_id/canvases/:id/view/': {+ canvas: {+ id: CANVAS_ID,+ name: 'Untitled canvas',+ kind: 'freeform',+ channel: 'space-1',+ template_id: 'freeform',+ generation_task_id: null,+ published_build_id: null,+ },+ published_build: null,+ current_version_id: null,+ has_active_build: false,+ source: null,+ layout: null,+ 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' },+ },+ post: {+ '/api/projects/:team_id/tasks/:id/run/': [+ 201,+ { id: 'task-1', title: 'Daily signups', latest_run: { status: 'queued' } },+ ],+ '/api/projects/:team_id/tasks/': async () => {+ await taskRequestReleased+ return [403, { error: 'Agent-started task runs are not available for this project' }]+ },+ },+ })+ initKeaTests()+ })++ 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()+ await expectLogic(logic).toDispatchActions(['loadViewSuccess'])+ expect(logic.values.bodyState).toEqual('empty')++ logic.actions.generateCanvas('A chart of daily signups', false)+ expect(logic.values.generationStarting).toBe(true)+ expect(logic.values.bodyState).toEqual('empty')++ releaseTaskRequest()+ await expectLogic(logic).toDispatchActions(['generationFinished'])+ expect(logic.values.bodyState).toEqual('empty')+ })+})diff --git a/products/canvas/frontend/scene/canvasSceneLogic.ts b/products/canvas/frontend/scene/canvasSceneLogic.tsnew file mode 100644index 000000000000..01115c50355e--- /dev/null+++ b/products/canvas/frontend/scene/canvasSceneLogic.ts@@ -0,0 +1,654 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { toast } from '@posthog/quill'++import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import { todayViewsLogic } from '~/layout/today/todayViewsLogic'+import { Breadcrumb } from '~/types'++import { CANVAS_EVENTS } from '../canvasAnalytics'+import {+ CanvasGenerationTask,+ CanvasSpace,+ canvasSpaceLabel,+ isTerminalRunStatus,+ loadCanvasGenerationTask,+ loadCanvasSpace,+} from '../canvasTasksApi'+import { canvasesBuildsRetrieve, canvasesPartialUpdate, canvasesViewRetrieve } from '../generated/api'+import type {+ CanvasApi,+ CanvasBuildApi,+ CanvasBuildsResponseApi,+ CanvasViewResponseApi,+} from '../generated/api.schemas'+import { CanvasStartHandoff, canvasNewLogic } from '../newCanvas/canvasNewLogic'+import { startCanvasGeneration } from '../startCanvasGeneration'+import { deleteCanvasWithUndo } from './deleteCanvasWithUndo'++// pinned: the path of the single-file component a draft renders, shared with PostHog Desktop+export const CANVAS_COMPONENT_PATH = 'src/canvas.tsx'+const POLL_INTERVAL_MS = 3000++export interface CanvasSceneLogicProps {+ id: string+}++/** What the canvas body shows. Each value is a distinct screen. */+export type CanvasBodyState =+ | 'loading'+ | 'error'+ | 'missing'+ | 'empty'+ | 'generating'+ | 'generation-ended'+ | 'built'+ | 'draft'+ | 'draft-unavailable'++export type CanvasBuildStatus = 'none' | 'building' | 'failed' | 'live'++export function canvasBuildStatus(+ builds: CanvasBuildsResponseApi | null,+ view: CanvasViewResponseApi | null+): CanvasBuildStatus {+ const list = builds?.builds ?? []+ if (list.some((build) => build.build_status === 'queued' || build.build_status === 'building')) {+ return 'building'+ }+ if (!builds && view?.has_active_build) {+ return 'building'+ }+ const currentVersionId = builds?.current_version_id ?? view?.current_version_id ?? null+ const newestForHead = list.find((build) => build.source_version_id === currentVersionId)+ if (newestForHead?.build_status === 'failed') {+ return 'failed'+ }+ if (builds?.published_build_id ?? view?.canvas.published_build_id) {+ return 'live'+ }+ return 'none'+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasSceneLogicValues {+ startHandoff: CanvasStartHandoff | null // canvasNewLogic+ currentProjectId: number | null // projectLogic+ bodyState: CanvasBodyState+ breadcrumbs: Breadcrumb[]+ buildStatus: CanvasBuildStatus+ builds: CanvasBuildsResponseApi | null+ buildsLoading: boolean+ busy: boolean+ canvas: CanvasApi | null+ draftCode: string | null+ generationStarting: boolean+ generationTask: CanvasGenerationTask | null+ generationTaskLoading: boolean+ instruction: string+ instructionFromSuggestion: boolean+ isGenerating: boolean+ liveBuild: CanvasBuildApi | null+ sandboxDocumentUrl: string | null+ shouldPoll: boolean+ sidePanelOpen: boolean+ space: CanvasSpace | null+ spaceLoading: boolean+ view: CanvasViewResponseApi | null+ viewLoading: boolean+ viewMissing: boolean+ viewUnavailable: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasSceneLogicActions {+ clearStartHandoff: () => {+ value: true+ } // canvasNewLogic+ setOpenCanvasBuilding: (+ canvasId: string,+ building: boolean | null+ ) => {+ building: boolean | null+ canvasId: string+ } // todayViewsLogic+ canvasUpdated: (canvas: CanvasApi) => {+ canvas: CanvasApi+ }+ copyLink: () => {+ value: true+ }+ deleteCanvas: () => {+ value: true+ }+ generateCanvas: (+ instruction: string,+ fromSuggestion: boolean+ ) => {+ fromSuggestion: boolean+ instruction: string+ }+ generationFinished: () => {+ value: true+ }+ generationStarted: () => {+ value: true+ }+ loadBuilds: () => any+ loadBuildsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBuildsSuccess: (+ builds: CanvasBuildsResponseApi | null,+ payload?: any+ ) => {+ builds: CanvasBuildsResponseApi | null+ payload?: any+ }+ loadGenerationTask: () => any+ loadGenerationTaskFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadGenerationTaskSuccess: (+ generationTask: CanvasGenerationTask | null,+ payload?: any+ ) => {+ generationTask: CanvasGenerationTask | null+ payload?: any+ }+ loadSpace: () => any+ loadSpaceFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSpaceSuccess: (+ space: CanvasSpace | null,+ payload?: any+ ) => {+ space: CanvasSpace | null+ payload?: any+ }+ loadView: () => any+ loadViewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadViewSuccess: (+ view: CanvasViewResponseApi | null,+ payload?: any+ ) => {+ view: CanvasViewResponseApi | null+ payload?: any+ }+ poll: () => {+ value: true+ }+ renameCanvas: (name: string) => {+ name: string+ }+ reportBusy: () => {+ value: true+ }+ setInstruction: (+ instruction: string,+ fromSuggestion: boolean+ ) => {+ fromSuggestion: boolean+ instruction: string+ }+ setSidePanelOpen: (open: boolean) => {+ open: boolean+ }+ startPolling: () => {+ value: true+ }+ stopPolling: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface canvasSceneLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ busy: (isGenerating: boolean, buildStatus: CanvasBuildStatus) => boolean+ canvas: (view: CanvasViewResponseApi | null) => CanvasApi | null+ sandboxDocumentUrl: (view: CanvasViewResponseApi | null) => string | null+ liveBuild: (view: CanvasViewResponseApi | null) => CanvasBuildApi | null+ draftCode: (view: CanvasViewResponseApi | null) => string | null+ buildStatus: (builds: CanvasBuildsResponseApi | null, view: CanvasViewResponseApi | null) => CanvasBuildStatus+ isGenerating: (+ view: CanvasViewResponseApi | null,+ generationTask: CanvasGenerationTask | null,+ generationTaskLoading: boolean+ ) => boolean+ bodyState: (+ view: CanvasViewResponseApi | null,+ viewLoading: boolean,+ viewMissing: boolean,+ viewUnavailable: boolean,+ liveBuild: CanvasBuildApi | null,+ draftCode: string | null,+ sandboxDocumentUrl: string | null,+ isGenerating: boolean+ ) => CanvasBodyState+ shouldPoll: (+ view: CanvasViewResponseApi | null,+ isGenerating: boolean,+ buildStatus: CanvasBuildStatus+ ) => boolean+ breadcrumbs: (canvas: CanvasApi | null, space: CanvasSpace | null, arg: string) => Breadcrumb[]+ }+}++export type canvasSceneLogicType = MakeLogicType<+ canvasSceneLogicValues,+ canvasSceneLogicActions,+ CanvasSceneLogicProps,+ canvasSceneLogicMeta+>++export const canvasSceneLogic = kea<canvasSceneLogicType>([+ props({} as CanvasSceneLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'canvas', 'frontend', 'scene', 'canvasSceneLogic', key]),+ connect(() => ({+ // The start page hands over a prompt whose canvas exists but whose build did not start.+ values: [projectLogic, ['currentProjectId'], canvasNewLogic, ['startHandoff']],+ // Connecting keeps the Views sidebar's logic mounted, so it knows this canvas's state when it opens.+ actions: [canvasNewLogic, ['clearStartHandoff'], todayViewsLogic, ['setOpenCanvasBuilding']],+ })),+ actions({+ renameCanvas: (name: string) => ({ name }),+ canvasUpdated: (canvas: CanvasApi) => ({ canvas }),+ copyLink: true,+ deleteCanvas: true,+ setInstruction: (instruction: string, fromSuggestion: boolean) => ({ instruction, fromSuggestion }),+ generateCanvas: (instruction: string, fromSuggestion: boolean) => ({ instruction, fromSuggestion }),+ generationStarted: true,+ /** Tells the Views sidebar whether this canvas is busy, when that changed. */+ reportBusy: true,+ generationFinished: true,+ setSidePanelOpen: (open: boolean) => ({ open }),+ startPolling: true,+ stopPolling: true,+ poll: true,+ }),+ loaders(({ props, values }) => ({+ view: [+ null as CanvasViewResponseApi | null,+ {+ loadView: async () =>+ values.currentProjectId+ ? await canvasesViewRetrieve(String(values.currentProjectId), props.id)+ : null,+ },+ ],+ builds: [+ null as CanvasBuildsResponseApi | null,+ {+ loadBuilds: async () =>+ values.currentProjectId+ ? await canvasesBuildsRetrieve(String(values.currentProjectId), props.id, { scope: 'slim' })+ : null,+ },+ ],+ generationTask: [+ null as CanvasGenerationTask | null,+ {+ loadGenerationTask: async () => {+ const taskId = values.view?.canvas.generation_task_id+ return values.currentProjectId && taskId+ ? await loadCanvasGenerationTask(String(values.currentProjectId), taskId)+ : null+ },+ },+ ],+ space: [+ null as CanvasSpace | null,+ {+ loadSpace: async () => {+ const spaceId = values.view?.canvas.channel+ return values.currentProjectId && spaceId+ ? await loadCanvasSpace(String(values.currentProjectId), spaceId)+ : null+ },+ },+ ],+ })),+ reducers({+ view: {+ canvasUpdated: (state, { canvas }) => (state ? { ...state, canvas } : state),+ },+ viewMissing: [+ false,+ {+ loadView: () => false,+ loadViewFailure: (_, { errorObject }) => errorObject?.status === 404,+ },+ ],+ viewUnavailable: [+ false,+ {+ loadViewSuccess: () => false,+ loadViewFailure: () => true,+ },+ ],+ instruction: [+ '',+ {+ setInstruction: (_, { instruction }) => instruction,+ generationStarted: () => '',+ },+ ],+ instructionFromSuggestion: [+ false,+ {+ setInstruction: (_, { fromSuggestion }) => fromSuggestion,+ generationStarted: () => false,+ },+ ],+ generationStarting: [+ false,+ {+ generateCanvas: () => true,+ generationFinished: () => false,+ },+ ],+ // The right-hand panel (chat, timeline, versions) mounts into this slot.+ sidePanelOpen: [+ false,+ {+ setSidePanelOpen: (_, { open }) => open,+ },+ ],+ }),+ selectors({+ /** Whether an agent or a build is at work on the canvas, which the Views sidebar marks with a spinner. */+ busy: [+ (s) => [s.isGenerating, s.buildStatus],+ (isGenerating: boolean, buildStatus: CanvasBuildStatus): boolean =>+ isGenerating || buildStatus === 'building',+ ],+ canvas: [(s) => [s.view], (view: CanvasViewResponseApi | null): CanvasApi | null => view?.canvas ?? null],+ sandboxDocumentUrl: [+ (s) => [s.view],+ (view: CanvasViewResponseApi | null): string | null => view?.sandbox_document_url ?? null,+ ],+ liveBuild: [+ (s) => [s.view],+ (view: CanvasViewResponseApi | null): CanvasBuildApi | null => {+ const build = view?.published_build+ return build?.build_status === 'ready' && build.artifact_url ? build : null+ },+ ],+ draftCode: [+ (s) => [s.view],+ (view: CanvasViewResponseApi | null): string | null => view?.source?.files[CANVAS_COMPONENT_PATH] ?? null,+ ],+ buildStatus: [+ (s) => [s.builds, s.view],+ (builds: CanvasBuildsResponseApi | null, view: CanvasViewResponseApi | null): CanvasBuildStatus =>+ canvasBuildStatus(builds, view),+ ],+ isGenerating: [+ // A run that is still starting is not generating yet: the composer stays up, so a+ // failed start keeps what the person typed.+ (s) => [s.view, s.generationTask, s.generationTaskLoading],+ (view: CanvasViewResponseApi | null, task: CanvasGenerationTask | null, taskLoading: boolean): boolean => {+ const taskId = view?.canvas.generation_task_id+ if (!taskId) {+ return false+ }+ // Assume the run is live until its record says otherwise.+ if (!task || task.id !== taskId) {+ return taskLoading || !task+ }+ return !!task.latest_run && !isTerminalRunStatus(task.latest_run.status)+ },+ ],+ bodyState: [+ (s) => [+ s.view,+ s.viewLoading,+ s.viewMissing,+ s.viewUnavailable,+ s.liveBuild,+ s.draftCode,+ s.sandboxDocumentUrl,+ s.isGenerating,+ ],+ (+ view: CanvasViewResponseApi | null,+ viewLoading: boolean,+ missing: boolean,+ unavailable: boolean,+ liveBuild: CanvasBuildApi | null,+ draftCode: string | null,+ sandboxDocumentUrl: string | null,+ isGenerating: boolean+ ): CanvasBodyState => {+ if (missing) {+ return 'missing'+ }+ if (!view) {+ return unavailable ? 'error' : 'loading'+ }+ if (liveBuild) {+ return 'built'+ }+ if (draftCode) {+ return sandboxDocumentUrl ? 'draft' : 'draft-unavailable'+ }+ if (isGenerating) {+ return 'generating'+ }+ if (view.canvas.generation_task_id || view.current_version_id) {+ return viewLoading ? 'loading' : 'generation-ended'+ }+ return 'empty'+ },+ ],+ shouldPoll: [+ (s) => [s.view, s.isGenerating, s.buildStatus],+ (view: CanvasViewResponseApi | null, isGenerating: boolean, buildStatus: CanvasBuildStatus): boolean =>+ !!view && (isGenerating || buildStatus === 'building'),+ ],+ breadcrumbs: [+ (s) => [s.canvas, s.space, (_, props: CanvasSceneLogicProps) => props.id],+ (canvas: CanvasApi | null, space: CanvasSpace | null, id: string): Breadcrumb[] => [+ ...(space+ ? [{ key: 'canvas-space', name: canvasSpaceLabel(space), path: urls.taskSpace(space.id) }]+ : []),+ { key: ['CanvasDetail', id], name: canvas?.name ?? 'Canvas' },+ ],+ ],+ }),+ listeners(({ actions, values, props, cache }) => ({+ reportBusy: () => {+ if (cache.reportedBusy !== values.busy) {+ cache.reportedBusy = values.busy+ actions.setOpenCanvasBuilding(props.id, values.busy)+ }+ },+ canvasUpdated: () => actions.reportBusy(),+ loadViewSuccess: ({ view }) => {+ actions.reportBusy()+ if (!view) {+ return+ }+ if (!cache.viewedTracked) {+ cache.viewedTracked = true+ posthog.capture(CANVAS_EVENTS.viewed, {+ channel_id: view.canvas.channel,+ dashboard_id: view.canvas.id,+ canvas_kind: view.canvas.kind,+ template_id: view.canvas.template_id,+ })+ }+ if (!values.space || values.space.id !== view.canvas.channel) {+ actions.loadSpace()+ }+ if (view.canvas.generation_task_id && values.generationTask?.id !== view.canvas.generation_task_id) {+ actions.loadGenerationTask()+ }+ if (values.shouldPoll) {+ actions.startPolling()+ }+ },+ loadGenerationTaskSuccess: () => {+ actions.reportBusy()+ if (values.shouldPoll) {+ actions.startPolling()+ } else {+ actions.stopPolling()+ }+ },+ loadBuildsSuccess: ({ builds }) => {+ actions.reportBusy()+ const view = values.view+ // A new live build or head version changes what renders, so the view is re-read.+ if (+ builds &&+ view &&+ (builds.published_build_id !== view.published_build?.id ||+ builds.current_version_id !== view.current_version_id)+ ) {+ actions.loadView()+ }+ if (!values.shouldPoll) {+ actions.stopPolling()+ }+ },+ startPolling: () => {+ cache.disposables.add(() => {+ const id = setInterval(() => actions.poll(), POLL_INTERVAL_MS)+ return () => clearInterval(id)+ }, 'poll')+ },+ stopPolling: () => {+ cache.disposables.dispose('poll')+ },+ poll: () => {+ if (!values.shouldPoll) {+ actions.stopPolling()+ return+ }+ if (!values.buildsLoading) {+ actions.loadBuilds()+ }+ if (values.view?.canvas.generation_task_id && !values.generationTaskLoading) {+ actions.loadGenerationTask()+ }+ },+ renameCanvas: async ({ name }) => {+ const trimmed = name.trim()+ if (!values.currentProjectId || !values.canvas || !trimmed || trimmed === values.canvas.name) {+ return+ }+ try {+ const canvas = await canvasesPartialUpdate(String(values.currentProjectId), props.id, { name: trimmed })+ actions.canvasUpdated(canvas)+ // The Views sidebar lists canvases by name.+ todayViewsLogic.findMounted()?.actions.loadRecentViews()+ } catch (error) {+ toast.error({+ title: "Couldn't rename the canvas",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ }+ },+ 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')+ },+ deleteCanvas: () => {+ const canvas = values.canvas+ if (!values.currentProjectId || !canvas) {+ return+ }+ deleteCanvasWithUndo({+ projectId: String(values.currentProjectId),+ canvasId: canvas.id,+ spaceId: canvas.channel,+ name: canvas.name,+ surface: 'web_canvas_scene',+ onRestore: () => router.actions.push(urls.canvasDetail(canvas.id)),+ })+ router.actions.push(urls.taskSpace(canvas.channel))+ },+ generateCanvas: async ({ instruction, fromSuggestion }) => {+ const canvas = values.canvas+ if (!values.currentProjectId || !canvas || !instruction.trim()) {+ actions.generationFinished()+ return+ }+ try {+ const started = await startCanvasGeneration({+ projectId: String(values.currentProjectId),+ canvas,+ spaceName: values.space?.name ?? null,+ instruction,+ fromSuggestion,+ surface: 'web_canvas_scene',+ })+ actions.canvasUpdated(started.canvas)+ actions.loadGenerationTaskSuccess(started.task)+ actions.generationStarted()+ actions.startPolling()+ } catch (error) {+ toast.error({+ title: "Couldn't start building the canvas",+ description: error instanceof Error ? error.message : 'Try again in a moment.',+ })+ } finally {+ actions.generationFinished()+ }+ },+ })),+ afterMount(({ actions, values, props }) => {+ const handoff = values.startHandoff+ if (handoff?.canvasId === props.id) {+ actions.setInstruction(handoff.instruction, handoff.fromSuggestion)+ actions.clearStartHandoff()+ }+ actions.loadView()+ actions.loadBuilds()+ }),+ beforeUnmount(({ actions, props }) => {+ actions.setOpenCanvasBuilding(props.id, null)+ }),+])diff --git a/products/canvas/frontend/scene/deleteCanvasWithUndo.ts b/products/canvas/frontend/scene/deleteCanvasWithUndo.tsnew file mode 100644index 000000000000..81238c35331c--- /dev/null+++ b/products/canvas/frontend/scene/deleteCanvasWithUndo.ts@@ -0,0 +1,81 @@+import posthog from 'posthog-js'++import { toast } from '@posthog/quill'++import { CANVAS_EVENTS, CanvasSurface } from '../canvasAnalytics'+import { canvasesDestroy } from '../generated/api'++// Nothing reaches the server until this runs out, so it is also the undo window.+export const CANVAS_DELETE_UNDO_MS = 8000++// Module level on purpose: the window outlives the scene that started it, because+// deleting from the canvas itself navigates away at once.+const pendingTimers = new Map<string, ReturnType<typeof setTimeout>>()++interface DeleteCanvasWithUndoOptions {+ projectId: string+ canvasId: string+ spaceId: string+ name: string+ surface: CanvasSurface+ /** Runs when the viewer undoes the delete, or when the delete fails. */+ onRestore: () => void+}++/** Deletes a canvas after an undo window. Undo cancels the timer, so nothing is ever recreated. */+export function deleteCanvasWithUndo({+ projectId,+ canvasId,+ spaceId,+ name,+ surface,+ onRestore,+}: DeleteCanvasWithUndoOptions): void {+ const properties = { surface, channel_id: spaceId, dashboard_id: canvasId }+ const existing = pendingTimers.get(canvasId)+ if (existing) {+ clearTimeout(existing)+ }++ const commit = async (): Promise<void> => {+ pendingTimers.delete(canvasId)+ try {+ await canvasesDestroy(projectId, canvasId)+ posthog.capture(CANVAS_EVENTS.dashboardAction, { action_type: 'delete', success: true, ...properties })+ } catch (error) {+ posthog.capture(CANVAS_EVENTS.dashboardAction, { action_type: 'delete', success: false, ...properties })+ toast.error({+ title: `Couldn't delete ${name}. ${error instanceof Error ? error.message : 'Try again in a moment.'}`,+ })+ onRestore()+ }+ }++ pendingTimers.set(+ canvasId,+ setTimeout(() => void commit(), CANVAS_DELETE_UNDO_MS)+ )++ toast.success({+ title: `Deleted ${name}`,+ timeout: CANVAS_DELETE_UNDO_MS,+ action: {+ label: 'Undo',+ onClick: () => {+ const timer = pendingTimers.get(canvasId)+ // No timer means the delete is already in flight or done.+ if (!timer) {+ return+ }+ clearTimeout(timer)+ pendingTimers.delete(canvasId)+ posthog.capture(CANVAS_EVENTS.dashboardAction, { action_type: 'delete_undo', ...properties })+ onRestore()+ },+ },+ })+}++export function isCanvasDeletePending(canvasId: string): boolean {+ return pendingTimers.has(canvasId)+}diff --git a/products/canvas/frontend/startCanvasGeneration.ts b/products/canvas/frontend/startCanvasGeneration.tsnew file mode 100644index 000000000000..58f26629f00c--- /dev/null+++ b/products/canvas/frontend/startCanvasGeneration.ts@@ -0,0 +1,62 @@+import posthog from 'posthog-js'++import { CANVAS_EVENTS, CanvasSurface } from './canvasAnalytics'+import { CanvasGenerationTask, createCanvasGenerationTask, startCanvasGenerationRun } from './canvasTasksApi'+import { isPlaceholderCanvasName } from './canvasTemplates'+import { canvasesPartialUpdate } from './generated/api'+import type { CanvasApi } from './generated/api.schemas'+import { buildCanvasGenerationPrompt } from './scene/canvasGenerationPrompt'++export interface StartCanvasGenerationInput {+ projectId: string+ canvas: CanvasApi+ /** The space's name for the agent. Falls back to the space id when the space has not loaded. */+ spaceName: string | null+ instruction: string+ fromSuggestion: boolean+ surface: CanvasSurface+}++export interface StartedCanvasGeneration {+ canvas: CanvasApi+ task: CanvasGenerationTask+}++/**+ * Links the agent task to the canvas before starting its run.+ * A placeholder name takes the task's title. Throws when the task does not start.+ */+export async function startCanvasGeneration({+ projectId,+ canvas,+ spaceName,+ instruction,+ fromSuggestion,+ surface,+}: StartCanvasGenerationInput): Promise<StartedCanvasGeneration> {+ const trimmed = instruction.trim()+ posthog.capture(CANVAS_EVENTS.promptSent, {+ surface,+ dashboard_id: canvas.id,+ from_suggestion: fromSuggestion,+ prompt_length_chars: trimmed.length,+ })+ const task = await createCanvasGenerationTask(projectId, {+ description: buildCanvasGenerationPrompt({+ canvasId: canvas.id,+ name: canvas.name,+ spaceName: spaceName ?? canvas.channel,+ templateId: canvas.template_id,+ instruction: trimmed,+ }),+ namingSource: trimmed,+ spaceId: canvas.channel,+ startRun: false,+ })+ const autoName = isPlaceholderCanvasName(canvas.name) && task.title?.trim()+ const updated = await canvasesPartialUpdate(projectId, canvas.id, {+ generation_task_id: task.id,+ ...(autoName ? { name: task.title.trim() } : {}),+ })+ return { canvas: updated, task: await startCanvasGenerationRun(projectId, task.id) }+}diff --git a/products/canvas/manifest.tsx b/products/canvas/manifest.tsxnew file mode 100644index 000000000000..9fdeccc971d0--- /dev/null+++ b/products/canvas/manifest.tsx@@ -0,0 +1,34 @@+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Canvas',+ scenes: {+ CanvasNew: {+ name: 'New canvas',+ import: () => import('./frontend/newCanvas/CanvasNewScene'),+ projectBased: true,+ layout: 'app-raw',+ },+ // `Canvas` and `urls.canvas` already belong to the notebooks canvas.+ CanvasDetail: {+ name: 'Canvas',+ import: () => import('./frontend/scene/CanvasScene'),+ projectBased: true,+ layout: 'app-full-scene-height',+ },+ },+ routes: {+ // Listed before `/canvases/:id`, so "new" never matches as a canvas id.+ '/canvases/new': ['CanvasNew', 'canvasNew'],+ '/canvases/:id': ['CanvasDetail', 'canvasDetail'],+ },+ redirects: {},+ urls: {+ canvasNew: (spaceId?: string | null): string =>+ spaceId ? `/canvases/new?space=${encodeURIComponent(spaceId)}` : '/canvases/new',+ canvasDetail: (id: string): string => `/canvases/${id}`,+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/canvas/package.json b/products/canvas/package.jsonindex 8bf2572e0575..e6e2764c34b0 100644--- a/products/canvas/package.json+++ b/products/canvas/package.json@@ -4,14 +4,25 @@"prebackend:test": "npm ci --ignore-scripts --omit=dev --prefix packages/canvas_builder","backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"},- "dependencies": {},+ "dependencies": {+ "@posthog/quill": "workspace:*",+ "kea": "catalog:",+ "kea-loaders": "catalog:",+ "kea-router": "catalog:",+ "posthog-js": "catalog:"+ },"devDependencies": {"@testing-library/react": "^14.3.1",- "jest": "^29.7.0"+ "jest": "^29.7.0",+ "kea-test-utils": "catalog:"},"peerDependencies": {+ "@posthog/icons": "catalog:",+ "@posthog/lemon-ui": "*",+ "@storybook/react": "catalog:","@types/react": "*","react": "*",- "react-dom": "*"+ "react-dom": "*",+ "zod": "*"}}diff --git a/products/desktop/package.json b/products/desktop/package.jsonindex 3e4eff31fc61..740150e91b15 100644--- a/products/desktop/package.json+++ b/products/desktop/package.json@@ -40,7 +40,7 @@"clean": "pnpm -r clean","knip": "knip","skills:pull": "node scripts/pull-skills.mjs",- "hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD=1 pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"+ "hosthog:build": "pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/web... && pnpm build:agent && SKIP_PRODUCT_ENGINEER_SKILLS_DOWNLOAD=1 pnpm exec turbo build --filter=@posthog/web && ln -sfn apps/web/dist dist"},"keywords": ["posthog",diff --git a/products/desktop/packages/ui/package.json b/products/desktop/packages/ui/package.jsonindex 209a2713d6a5..69c21739633c 100644--- a/products/desktop/packages/ui/package.json+++ b/products/desktop/packages/ui/package.json@@ -14,6 +14,7 @@"typecheck": "tsc --noEmit","test": "vitest run","generate-routes": "node scripts/generate-routes.mjs",+ "generate-web-sandbox": "vitest run src/features/canvas/freeform/webSandboxDocument.test.ts --update","clean": "node ../../scripts/rimraf.mjs dist .turbo"},"dependencies": {diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex e22bcb588034..45abf8dbf87d 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -225,7 +225,14 @@ export function buildSandboxDocument(const bootstrap = /* js */ `import * as Babel from "${FREEFORM_BABEL_URL}";const CHANNEL = "posthog-canvas";- const post = (msg) => parent.postMessage({ channel: CHANNEL, ...msg }, "*");+ const portOnly = new URLSearchParams(location.hash.slice(1)).get("bridge") === "port";+ let bridgePort = null;+ let sendToHost = null;+ const post = (msg) => {+ const message = { channel: CHANNEL, ...msg };+ if (sendToHost) sendToHost(message);+ else if (!portOnly) parent.postMessage(message, "*");+ };// --- data shim: the ONLY way canvas code reaches PostHog. No token here. ---const pending = new Map();@@ -709,8 +716,7 @@ export function buildSandboxDocument(}};- window.addEventListener("message", (e) => {- const d = e.data;+ const receive = (d) => {if (!d || d.channel !== CHANNEL) return;if (editing.handle(d)) return;if (d.type === "init") {@@ -733,7 +739,19 @@ export function buildSandboxDocument(? p.resolve(d.result): p.reject(new Error(d.error || "data error"), d.retryable === true);}+ };+ window.addEventListener("message", (e) => {+ if (e.source !== parent) return;+ if (e.data?.channel === CHANNEL && e.data.type === "connect" && e.ports[0] && !bridgePort) {+ bridgePort = e.ports[0];+ sendToHost = bridgePort.postMessage.bind(bridgePort);+ bridgePort.onmessage = (event) => receive(event.data);+ post({ type: "ready" });+ } else if (!portOnly && !bridgePort) {+ receive(e.data);+ }});+ window.addEventListener("pagehide", () => bridgePort?.close());post({ type: "ready" });`;@@ -813,9 +831,8 @@ function contentSecurityPolicy(analyticsApiHost?: string): string {return ["default-src 'none'",// Inline bootstrap + esm.sh modules + the transpiled Blob module + the- // posthog-js recorder script + the in-browser Tailwind engine (JIT-compiles,- // so 'unsafe-eval' is required).- `script-src 'unsafe-inline' 'unsafe-eval' blob: ${twCdn} ${esm} ${ph}`,+ // posthog-js recorder script + the in-browser Tailwind engine.+ `script-src 'unsafe-inline' blob: ${twCdn} ${esm} ${ph}`,`style-src 'unsafe-inline' ${esm}`,`font-src data: ${esm}`,"img-src data: blob: https:",diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/webSandboxDocument.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/webSandboxDocument.test.tsnew file mode 100644index 000000000000..8b87ff54c8e9--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/webSandboxDocument.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from "vitest";+import { buildSandboxDocument } from "./sandboxRuntime";++// The web app cannot load the sandbox as srcdoc, because a srcdoc frame+// inherits the app's CSP. Django serves this checked-in copy from the canvas+// artifact origin instead. Run `pnpm --filter @posthog/ui+// generate-web-sandbox` to write it again after a change to sandboxRuntime.ts.+const WEB_SANDBOX_DOCUMENT =+ "../../../../../../../canvas/backend/sandbox/sandbox_document.html";++describe("web sandbox document", () => {+ it("matches the copy Django serves", async () => {+ await expect(buildSandboxDocument()).toMatchFileSnapshot(+ WEB_SANDBOX_DOCUMENT,+ );+ });+});diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5a2509349b8c..6e10c1108be7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20958,6 +20958,11 @@ export namespace Schemas {layout?: CanvasLayout | null;/** For grid canvases: the renderable build of every component the layout's live placements reference, so the grid renders from this one call. Absent for other kinds. */component_lifecycles?: CanvasComponentLifecycle[];+ /**+ * URL of the sandbox document that renders the head source project in an iframe, served from the artifact origin. Load it by URL, not as srcdoc. Null when artifact delivery is unavailable.+ * @nullable+ */+ readonly sandbox_document_url: string | null;}export interface CapabilityReadiness {diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex bfce8848b7c9..4f8a6daaea2d 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -319,6 +319,16 @@"params": [],"scope": "project"},+ "canvasDetail": {+ "template": "/canvases/{id}",+ "params": ["id"],+ "scope": "project"+ },+ "canvasNew": {+ "template": "/canvases/new",+ "params": [],+ "scope": "project"+ },"cliAuthorize": {"template": "/cli/authorize","params": [],@@ -1774,6 +1784,11 @@"params": [],"scope": "project"},+ "views": {+ "template": "/views",+ "params": [],+ "scope": "project"+ },"visualReviewFlakiness": {"template": "/visual_review/repos/{repoId}/flakiness","params": ["repoId"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 49ddd9cd16c0..0a992919b2af 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/{id}\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/{id}\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/views\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},