: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): file canvases in the project file system (#112981)
Mike Warren83a8e514b2ac
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 04f4863b2107..b669906d0084 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10511,9 +10511,9 @@ snapshots:scenes-app-errortracking--group-page-releases-stacked--light:hash: v1.k794b7964.6229ba0294619c7c881929c7375df4700325ee629f842369641e5fe2355c1cd4._sFGlcefvjCQOkjMzoP9-CWeQ054s-pQHQ0vChbYbhEscenes-app-errortracking--group-page-today-rail-nav--dark:- hash: v1.k794b7964.4db963fda7878f500b4e40cf89568376e245dde0afa64735cca1e1b24a734fd3.xu_bFX_-lSckbQ-QgOtAlGgoMmy4jquki2b9lzgbctQ+ hash: v1.k794b7964.7ab84acc163b7e23d7f655a44a090f6f79fbfddbc6e84de1eeaa39041e851840.d__a2juGztMkVn9HsH--AUfMwv3yK1IUidE81k0iLhwscenes-app-errortracking--group-page-today-rail-nav--light:- hash: v1.k794b7964.03b7a71575dc1f12940669a949889497736015fa070a217529e0324ae6041a87.8NxWMWpIreAoN21d5LYIvvGeodw-DXvP4OrRR2RIll8+ hash: v1.k794b7964.ad2fd7d9905a1a02f1ad7f5f96ed78a7066000beb5375a442b66f135b28f2105.-IAWojMrz9ZMe4OnWdfuoq_x4FF8wxpXZrvGcudaiLkscenes-app-errortracking--group-page-with-many-self-driving-reports--dark:hash: v1.k794b7964.0aa0858442d3e422f4825c4665d289c006c87b1c5a22265e447a1c0fa5e5a544.Hy3i1o_nWpWVqH4WqCEDvZTI4LQxeI2c9B6GW9rHDYAscenes-app-errortracking--group-page-with-many-self-driving-reports--light:diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex a3b962edebb0..65a742171bfd 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -45,6 +45,7 @@ import {IconMegaphone,IconMessage,IconNotebook,+ IconPalette,IconNotification,IconPageChart,IconPencil,@@ -111,6 +112,10 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Filicon: <IconDashboard />,iconColor: ['var(--color-product-dashboards-light)'],},+ canvas: {+ icon: <IconPalette />,+ iconColor: ['var(--color-product-tasks-light)', 'var(--color-product-tasks-dark)'],+ },llm_analytics: {icon: <IconLlmAnalytics />,iconColor: ['var(--color-product-llm-analytics-light)'],diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex 50364c73e20f..5b844a5b0527 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -41,6 +41,7 @@ import {convertFileSystemEntryToTreeDataItem,escapePath,formatUrlAsName,+ isFileSystemEntryTypeEnabled,isGroupViewShortcut,isPathUnder,matchesRefType,@@ -601,7 +602,7 @@ export interface projectTreeDataLogicMeta {homeFolder: FileSystemHomeFolderApi | null,viableItems: FileSystemEntry[]) => FileSystemHomeFolderApi | null- savedItems: (folders: Record<string, FileSystemEntry[]>) => FileSystemEntry[]+ savedItems: (folders: Record<string, FileSystemEntry[]>, featureFlags: FeatureFlagsSet) => FileSystemEntry[]shortcutEntryIdMap: (shortcutData: FileSystemEntry[]) => Map<string, string>savedItemsLoading: (folderStates: Record<string, FolderState>) => booleanviableItems: (savedItems: FileSystemEntry[], pendingActions: ProjectTreeAction[]) => FileSystemEntry[]@@ -1332,9 +1333,11 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([},],savedItems: [- (s) => [s.folders],- (folders: Record<string, FileSystemEntry[]>): FileSystemEntry[] =>- Object.entries(folders).reduce((acc, [_, items]) => acc.concat(items), [] as FileSystemEntry[]),+ (s) => [s.folders, s.featureFlags],+ (folders: Record<string, FileSystemEntry[]>, featureFlags: FeatureFlagsSet): FileSystemEntry[] =>+ Object.entries(folders)+ .reduce((acc, [_, items]) => acc.concat(items), [] as FileSystemEntry[])+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags)),],// Maps each top-level Starred row's tree id to the underlying FileSystemEntry id, so the// drag handler can resolve sibling drops without rebuilding the lookup on every render.diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsxindex db2617db4cbf..eb9647b89aff 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeLogic.tsx@@ -21,6 +21,7 @@ import { Spinner } from '@posthog/lemon-ui'import api from 'lib/api'import { LemonTreeSelectMode, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'@@ -28,15 +29,17 @@ import { PAGINATION_LIMIT, projectTreeDataLogic } from '~/layout/panel-layout/Primport { FileSystemEntry } from '~/queries/schema/schema-general'import { ProjectTreeRef } from '~/types'+import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { Breadcrumb, UserBasicType } from '../../../types'import { panelLayoutLogic } from '../panelLayoutLogic'import type { PanelLayoutNavIdentifier } from '../panelLayoutLogic'import type { FolderState, ProjectTreeAction } from './types'import {+ calculateMovePath,convertFileSystemEntryToTreeDataItem,findInProjectTree,formatUrlAsName,- calculateMovePath,+ isFileSystemEntryTypeEnabled,joinPath,matchesRefType,sortFilesAndFolders,@@ -87,6 +90,7 @@ export interface projectTreeLogicValues {appBreadcrumbs: Breadcrumb[] // breadcrumbsLogicprojectTreeRef: ProjectTreeRef | null // breadcrumbsLogicsceneBreadcrumbs: Breadcrumb[] // breadcrumbsLogic+ featureFlags: FeatureFlagsSet // featureFlagLogicactivePanelIdentifier: string // panelLayoutLogicfolderLoadOffset: Record<string, number> // projectTreeDataLogicfolderStates: Record<string, FolderState> // projectTreeDataLogic@@ -471,7 +475,8 @@ export interface projectTreeLogicMeta {recentResultsLoading: boolean,folderStates: Record<string, FolderState>,checkedItems: Record<string, boolean>,- users: Record<string, UserBasicType>+ users: Record<string, UserBasicType>,+ featureFlags: FeatureFlagsSet) => TreeDataItem[]searchTreeItems: (searchResults: SearchResults,@@ -480,7 +485,8 @@ export interface projectTreeLogicMeta {checkedItems: Record<string, boolean>,sortMethod: ProjectTreeSortMethod,onlyFolders: boolean,- users: Record<string, UserBasicType>+ users: Record<string, UserBasicType>,+ featureFlags: FeatureFlagsSet) => TreeDataItem[]projectTreeItems: (searchTerm: string,@@ -555,6 +561,8 @@ export const projectTreeLogic = kea<projectTreeLogicType>([['activePanelIdentifier'],breadcrumbsLogic,['projectTreeRef', 'appBreadcrumbs', 'sceneBreadcrumbs'],+ featureFlagLogic,+ ['featureFlags'],projectTreeDataLogic,['folders',@@ -960,16 +968,19 @@ export const projectTreeLogic = kea<projectTreeLogicType>([},],recentTreeItems: [- (s) => [s.recentResults, s.recentResultsLoading, s.folderStates, s.checkedItems, s.users],+ (s) => [s.recentResults, s.recentResultsLoading, s.folderStates, s.checkedItems, s.users, s.featureFlags],(recentResults: RecentResults,recentResultsLoading: boolean,folderStates: Record<string, import('./types').FolderState>,checkedItems: Record<string, boolean>,- users: Record<string, import('~/types').UserBasicType>+ users: Record<string, import('~/types').UserBasicType>,+ featureFlags: Record<string, unknown>): TreeDataItem[] => {const results = convertFileSystemEntryToTreeDataItem({- imports: recentResults.results.map((i) => ({ ...i, protocol: 'project://' })),+ imports: recentResults.results+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))+ .map((i) => ({ ...i, protocol: 'project://' })),folderStates,checkedItems,root: 'project://',@@ -1009,6 +1020,7 @@ export const projectTreeLogic = kea<projectTreeLogicType>([s.sortMethod,s.onlyFolders,s.users,+ s.featureFlags,],(searchResults: SearchResults,@@ -1017,10 +1029,13 @@ export const projectTreeLogic = kea<projectTreeLogicType>([checkedItems: Record<string, boolean>,sortMethod: ProjectTreeSortMethod,onlyFolders: boolean,- users: Record<string, import('~/types').UserBasicType>+ users: Record<string, import('~/types').UserBasicType>,+ featureFlags: Record<string, unknown>): TreeDataItem[] => {const results = convertFileSystemEntryToTreeDataItem({- imports: searchResults.results.map((i) => ({ ...i, protocol: 'project://' })),+ imports: searchResults.results+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))+ .map((i) => ({ ...i, protocol: 'project://' })),folderStates,checkedItems,root: 'project://',diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts b/frontend/src/layout/panel-layout/ProjectTree/utils.test.tsindex 1b59205e7d10..8db2313d1562 100644--- a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts@@ -12,6 +12,7 @@ import { getDefaultTreeData, getDefaultTreeProducts, iconForType } from './defauimport {convertFileSystemEntryToTreeDataItem,escapePath,+ isFileSystemEntryTypeEnabled,isProjectTreeItemActive,joinPath,matchesRefType,@@ -25,6 +26,27 @@ const catalogProducts = [...getDefaultTreeProducts(), ...getDefaultTreeData()].f)describe('project tree utils', () => {+ describe('isFileSystemEntryTypeEnabled', () => {+ it.each([+ ['a Today type with its flag on', 'canvas', { 'today-rail-nav': true }, true],+ ['a Today type with its flag off', 'canvas', {}, false],+ ['a type behind another flag, with that flag off', 'task', {}, true],+ ['an unflagged type', 'dashboard', {}, true],+ ['a subtype of an unflagged type', 'insight/trends', {}, true],+ ['a folder', 'folder', {}, true],+ ['the Unfiled folder of a Today type with its flag off', 'folder:Unfiled/Canvases', {}, false],+ [+ 'the Unfiled folder of a Today type with its flag on',+ 'folder:Unfiled/Canvases',+ { 'today-rail-nav': true },+ true,+ ],+ ])('keeps %s: %s', (_label, typeAndPath, featureFlags, expected) => {+ const [type, path] = typeAndPath.split(':')+ expect(isFileSystemEntryTypeEnabled({ type, path }, featureFlags)).toBe(expected)+ })+ })+describe('isProjectTreeItemActive', () => {const insight: TreeDataItem = {id: 'project/sql-insight',diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx b/frontend/src/layout/panel-layout/ProjectTree/utils.tsxindex 875d554e88d9..9d6fdba11735 100644--- a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.tsx@@ -1,11 +1,13 @@import { IconPlus, IconShortcut } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'import { urls } from 'scenes/urls'import { SearchHighlightMultiple } from '~/layout/navigation-3000/components/SearchHighlight'import { RecentResults, SearchResults } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'+import { fileSystemTypes } from '~/products'import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'import { ProjectTreeRef, UserBasicType } from '~/types'@@ -475,6 +477,32 @@ export function convertFileSystemEntryToTreeDataItem({* - splitPath("a") => ["a"]* - splitPath("") => []*/+/**+ * Whether a row's type is open to this person. A file system type can carry a feature flag; its rows+ * come from the API regardless, so the tree drops them while the flag is off.+ */+// The backend files Today-only types under these folders; without the flag they would show empty.+const TODAY_UNFILED_FOLDERS: ReadonlySet<string> = new Set(['Unfiled/Canvases'])++/**+ * Whether a row's type belongs in the tree for this person. Only the types the Today navigation brings into+ * the file system hide behind its flag: other flagged types kept their rows before, and their pages gate+ * themselves, so hiding them here would change the tree for everyone.+ */+export function isFileSystemEntryTypeEnabled(+ entry: Pick<FileSystemEntry, 'type'> & { path?: string },+ featureFlags: Record<string, unknown>+): boolean {+ if (entry.type === 'folder') {+ return !TODAY_UNFILED_FOLDERS.has(entry.path ?? '') || !!featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]+ }+ const baseType = entry.type?.split('/')[0] ?? ''+ const flag = Object.hasOwn(fileSystemTypes, baseType)+ ? (fileSystemTypes[baseType as keyof typeof fileSystemTypes] as { flag?: string }).flag+ : undefined+ return flag !== FEATURE_FLAGS.TODAY_RAIL_NAV || !!featureFlags[flag]+}+export function splitPath(path: string | null | undefined): string[] {if (!path) {return []diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsxindex 42ecc9b06e15..25eca40415c8 100644--- a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx@@ -1,7 +1,9 @@import { IconArrowRight } from '@posthog/icons'import { SearchItem } from 'lib/components/Search/searchItems'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { isFileSystemEntryTypeEnabled } from '~/layout/panel-layout/ProjectTree/utils'import { fileSystemTypes } from '~/products'import { FileSystemEntry } from '~/queries/schema/schema-general'import { OrganizationMemberType, UserType } from '~/types'@@ -83,7 +85,12 @@ export function buildFilterOptions(folders: FileSystemEntry[] | null): FilterOptions {return {- is: typeOptions(),+ is: typeOptions().filter((option) =>+ isFileSystemEntryTypeEnabled(+ { type: option.value },+ featureFlagLogic.findMounted()?.values.featureFlags ?? {}+ )+ ),createdBy: userOptions(members, user),in: (folders ?? []).map((folder) => ({ value: folder.path, label: folder.path })),name: [],diff --git a/frontend/src/lib/components/CommandKSearch/commandKSources.ts b/frontend/src/lib/components/CommandKSearch/commandKSources.tsindex b2a430439cb3..049f8dca1698 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSources.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSources.ts@@ -9,9 +9,11 @@ import {unifiedSearchResultToSearchItem,} from 'lib/components/Search/searchItems'import { shouldSearchTickets } from 'lib/components/Search/utils'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import { mapGroupQueryResponse } from 'lib/utils/groups'+import { isFileSystemEntryTypeEnabled } from '~/layout/panel-layout/ProjectTree/utils'import type { Noun } from '~/models/groupsModel'import { GroupType, GroupTypeIndex } from '~/types'@@ -118,10 +120,11 @@ export const REMOTE_REQUESTS: RemoteRequest[] = [sources: ['results'],fetch: async (search, signal) => {const response = await api.fileSystem.list({ search, limit: RESULTS_LIMIT, notType: 'folder', signal })+ const featureFlags = featureFlagLogic.findMounted()?.values.featureFlags ?? {}return {- results: response.results.map((entry) =>- fileSystemEntryToSearchItem(entry, { id: entry.id, category: 'results' })- ),+ results: response.results+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))+ .map((entry) => fileSystemEntryToSearchItem(entry, { id: entry.id, category: 'results' })),}},},diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 984ddd8d2d41..d8c67f75b6e3 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -12,7 +12,7 @@ import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'import { teamLogic } from 'scenes/teamLogic'import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'-import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'+import { isFileSystemEntryTypeEnabled, splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'import { groupsModel } from '~/models/groupsModel'import { recentItemsModel } from '~/models/recentItemsModel'import { FileSystemEntry, GroupsQueryResponse } from '~/queries/schema/schema-general'@@ -428,7 +428,9 @@ export const searchLogic = kea<searchLogicType>([signal: cache.searchAbortController?.signal,})breakpoint()- return response.results.slice(0, RECENTS_LIMIT)+ return response.results+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, values.featureFlags))+ .slice(0, RECENTS_LIMIT)} catch (error) {return rethrowSearchError(error, breakpoint)}diff --git a/frontend/src/lib/hooks/useFileSystemLogView.ts b/frontend/src/lib/hooks/useFileSystemLogView.tsindex 9ba99678e460..22473a569a81 100644--- a/frontend/src/lib/hooks/useFileSystemLogView.ts+++ b/frontend/src/lib/hooks/useFileSystemLogView.ts@@ -17,6 +17,7 @@ type FileSystemLogViewType =| 'early_access_feature'| 'link'| 'notebook'+ | 'canvas'| 'session_recording_playlist'| `hog_function/${string}`diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 38f8d1ed0b69..8f42f368fce4 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1993,6 +1993,15 @@ export const fileSystemTypes = {iconType: 'action' as FileSystemIconType,iconColor: ['var(--color-product-actions-light)', 'var(--color-product-actions-dark)'] as FileSystemIconColor,},+ canvas: {+ name: 'Canvas',+ iconType: 'canvas',+ flag: FEATURE_FLAGS.TODAY_RAIL_NAV,+ href: (ref: string) => urls.canvasDetail(ref),+ listHref: () => urls.canvases(),+ iconColor: ['var(--color-product-tasks-light)', 'var(--color-product-tasks-dark)'],+ filterKey: 'canvas',+ },cohort: {name: 'Cohort',iconType: 'cohort' as FileSystemIconType,diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 6c86040cc3c3..511f961eb4bc 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -27411,6 +27411,7 @@"enum": ["default_icon_type","dashboard",+ "canvas","llm_analytics","product_analytics","revenue_analytics",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 8ebdb84e2353..8ecbb36d2d6c 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5510,6 +5510,7 @@ export interface FileSystemEntry {export type FileSystemIconType =| 'default_icon_type'| 'dashboard'+ | 'canvas'| 'llm_analytics'| 'product_analytics'| 'revenue_analytics'diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.pyindex cc8ef73153e1..63cd00762498 100644--- a/posthog/api/file_system/file_system.py+++ b/posthog/api/file_system/file_system.py@@ -31,6 +31,7 @@ from posthog.api.file_system.deletion import (undo_delete as undo_delete_object,)from posthog.api.file_system.file_system_logging import log_api_file_system_view+from posthog.api.file_system.visibility import apply_file_system_visibility_filtersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action@@ -332,7 +333,17 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if team_access.has_project_access}+ def _filter_by_product_visibility(self, queryset: QuerySet) -> QuerySet:+ """Drop rows whose product hides the object from this person, beyond project RBAC.++ A canvas follows its channel (personal, private or public), which the file system knows nothing+ about, so its product registers a filter. Evaluated on every read, so a channel's type or+ membership changing needs no resync.+ """+ return apply_file_system_visibility_filters(queryset, request=self.request, project_id=self.team.project_id)+def _filter_by_access_control(self, queryset: QuerySet) -> QuerySet:+ queryset = self._filter_by_product_visibility(queryset)if not self.user_access_control:return querysetaccessible_team_ids = self._accessible_team_idsdiff --git a/posthog/api/file_system/file_system_shortcut.py b/posthog/api/file_system/file_system_shortcut.pyindex 2065179ab2bf..a4bfb6d7c017 100644--- a/posthog/api/file_system/file_system_shortcut.py+++ b/posthog/api/file_system/file_system_shortcut.py@@ -11,6 +11,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.file_system.access_levels import FileSystemAccessLevelSerializerMixin+from posthog.api.file_system.visibility import apply_file_system_visibility_filtersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models import Userfrom posthog.models.file_system.constants import DEFAULT_SURFACE, RETIRED_FILE_SYSTEM_TYPES, surface_q@@ -178,6 +179,8 @@ class FileSystemShortcutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:queryset = self._scope_by_project_and_environment(queryset).filter(user=self.request.user)+ # A starred row hidden by its product stays hidden here too.+ queryset = apply_file_system_visibility_filters(queryset, request=self.request, project_id=self.team.project_id)# Destroy keeps retired rows, so that a user can still remove a shortcut that no other action returns.if self.action != "destroy":queryset = queryset.exclude(type__in=RETIRED_FILE_SYSTEM_TYPES)diff --git a/posthog/api/file_system/visibility.py b/posthog/api/file_system/visibility.pynew file mode 100644index 000000000000..d7d9ccd8e44d--- /dev/null+++ b/posthog/api/file_system/visibility.py@@ -0,0 +1,28 @@+"""Per-product visibility filters for file system rows, beyond project RBAC.++A product whose objects have visibility rules of their own (a canvas follows its channel) registers a+filter from its app config. The file system applies every registered filter to each read, so a row lists+only when the product lets this person see the object behind it.+"""++from collections.abc import Callable+from typing import Any++from django.db.models import QuerySet++# (rows, request, project_id): the request carries the user and the credential, since a product's rules may+# depend on both (a sandbox token does not inherit its user's private spaces).+FileSystemVisibilityFilter = Callable[[QuerySet, Any, int], QuerySet]++_VISIBILITY_FILTERS: dict[str, FileSystemVisibilityFilter] = {}+++def register_file_system_visibility_filter(type_string: str, filter_fn: FileSystemVisibilityFilter) -> None:+ """Register how rows of `type_string` narrow by viewer. The filter gets the rows, the request and the project id."""+ _VISIBILITY_FILTERS[type_string] = filter_fn+++def apply_file_system_visibility_filters(queryset: QuerySet, *, request: Any, project_id: int) -> QuerySet:+ for filter_fn in _VISIBILITY_FILTERS.values():+ queryset = filter_fn(queryset, request, project_id)+ return querysetdiff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.pyindex 9023309a4e36..46df02bfde2a 100644--- a/posthog/models/file_system/unfiled_file_saver.py+++ b/posthog/models/file_system/unfiled_file_saver.py@@ -43,6 +43,12 @@ MIXIN_MODELS_BY_SURFACE: dict[str, dict[str, type[FileSystemSyncMixin]]] = {}+def register_mixin_model(file_type: str, model_cls: type[FileSystemSyncMixin], surface: str = DEFAULT_SURFACE) -> None:+ """For a sealed product to add its model from its own `AppConfig.ready()`, so this module+ never has to import the product's internals."""+ MIXIN_MODELS_BY_SURFACE.setdefault(surface, {})[file_type] = model_cls++class UnfiledFileSaver:"""Checks each model's get_file_system_unfiled(...) for items thatdiff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex a8241d57afad..8b37f50fe30c 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1525,6 +1525,7 @@ class Tag(StrEnum):class FileSystemIconType(StrEnum):DEFAULT_ICON_TYPE = "default_icon_type"DASHBOARD = "dashboard"+ CANVAS = "canvas"LLM_ANALYTICS = "llm_analytics"PRODUCT_ANALYTICS = "product_analytics"REVENUE_ANALYTICS = "revenue_analytics"diff --git a/products/canvas/backend/apps.py b/products/canvas/backend/apps.pyindex f572cd8f830d..74dbeb9a0978 100644--- a/products/canvas/backend/apps.py+++ b/products/canvas/backend/apps.py@@ -10,4 +10,67 @@ class CanvasConfig(AppConfig):def ready(self) -> None:# Registers the artifact-delivery configuration system checks and the# search-index signal receivers.+ from typing import Any # noqa: PLC0415++ from django.db.models import QuerySet # noqa: PLC0415++ from rest_framework.exceptions import PermissionDenied, ValidationError # noqa: PLC0415++ from posthog.api.file_system.deletion import ( # noqa: PLC0415+ DeletionContext,+ RestoreContext,+ register_file_system_type,+ register_pre_delete_hook,+ register_pre_restore_hook,+ )+ from posthog.api.file_system.visibility import register_file_system_visibility_filter # noqa: PLC0415+ from posthog.models.file_system.unfiled_file_saver import register_mixin_model # noqa: PLC0415+from products.canvas.backend import checks, search_sync # noqa: F401, PLC0415+ from products.canvas.backend.models import Canvas # noqa: PLC0415++ register_mixin_model("canvas", Canvas)+ register_file_system_type(+ "canvas",+ "canvas",+ "Canvas",+ soft_delete_field="deleted",+ undo_message="Send POST /api/projects/@current/file_system/undo_delete/ with this type and ref.",+ )++ def _filter_rows(rows: QuerySet, request: Any, project_id: int) -> QuerySet:+ # The visibility module reaches the tasks product and the LLM clients, so it loads on first use+ # rather than in every process at startup: keeps the heavy dep off django.setup().+ from products.canvas.backend.logic import visibility # noqa: PLC0415++ return visibility.filter_file_system_rows(rows, request, project_id)++ def _authorize_delete(context: DeletionContext, canvas: Canvas) -> None:+ from posthog.oauth_provenance import is_sandbox_oauth_request # noqa: PLC0415++ from products.canvas.backend.logic import visibility # noqa: PLC0415++ # A file system row carries no channel, so the check reads the canvas's own rules: the creator+ # deletes, as in the canvas API, and a sandbox token never does.+ user_id = getattr(context.user, "id", None)+ if is_sandbox_oauth_request(context.request) or not visibility.canvas_deletable_by(+ team_id=canvas.team_id, canvas_id=canvas.id, user_id=user_id+ ):+ raise PermissionDenied("Only the person who created a canvas can delete it.")++ def _authorize_restore(context: RestoreContext, canvas: Canvas) -> None:+ from posthog.api.file_system.file_system import UNDO_DELETE_REFUSED # noqa: PLC0415+ from posthog.oauth_provenance import is_sandbox_oauth_request # noqa: PLC0415++ from products.canvas.backend.logic import visibility # noqa: PLC0415++ # The same answer as every other refused undo, so the endpoint cannot tell apart refs that exist.+ user_id = getattr(context.user, "id", None)+ if is_sandbox_oauth_request(context.request) or not visibility.canvas_restorable_by(+ team_id=canvas.team_id, canvas_id=canvas.id, user_id=user_id+ ):+ raise ValidationError({"detail": UNDO_DELETE_REFUSED})++ register_file_system_visibility_filter("canvas", _filter_rows)+ register_pre_delete_hook("canvas", _authorize_delete)+ register_pre_restore_hook("canvas", _authorize_restore)diff --git a/products/canvas/backend/logic/visibility.py b/products/canvas/backend/logic/visibility.pyindex 79eaf1b5d5ce..5ada547f680f 100644--- a/products/canvas/backend/logic/visibility.py+++ b/products/canvas/backend/logic/visibility.py@@ -8,7 +8,12 @@ from collections.abc import Iterablefrom uuid import UUIDfrom django.core.exceptions import ValidationError-from django.db.models import Max, Q, QuerySet+from django.db.models import Case, Exists, Max, OuterRef, Q, QuerySet, UUIDField, When+from django.db.models.functions import Cast++from rest_framework.request import Request++from posthog.models.user import Userfrom products.canvas.backend.facade.contracts import CanvasOwnerActivity, CanvasSummaryfrom products.canvas.backend.models import Canvas@@ -109,6 +114,68 @@ def visible_canvas_ids(team_id: int, user_id: int | None) -> set[str]:return {str(canvas_id) for canvas_id in canvases.values_list("id", flat=True)}+# Only a canvas row's `ref` is a UUID, and the planner may evaluate the subquery for any row.+_UUID_PATTERN = r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"+++def filter_file_system_rows(rows: QuerySet, request: Request, project_id: int) -> QuerySet:+ """Keep every non-canvas row, and a canvas row only when its channel lets the caller see the canvas.++ The rows span the project's environments, hence `unscoped()` with the project bound. The cast sits+ on the row side under a CASE, so the lookup hits the canvas primary key and never casts a non-UUID.+ A sandbox token sees public canvases and its user's own, as the canvas API allows it.+ """+ user = request.user+ user_id = user.id if isinstance(user, User) else None+ channel_q = tasks_facade.visible_channels_q(user_id, relation="channel")+ # Imported on first use: the OAuth stack stays off the facade import path.+ from posthog.oauth_provenance import is_sandbox_oauth_request # noqa: PLC0415++ if is_sandbox_oauth_request(request):+ channel_q &= tasks_facade.visible_channels_q(None, relation="channel") | Q(created_by_id=user_id)+ visible = Canvas.objects.unscoped().filter(+ channel_q,+ team__project_id=project_id,+ team_id=OuterRef("team_id"),+ id=OuterRef("_canvas_uuid"),+ **Canvas.FILED_ANALYSIS_FILTER,+ )+ return rows.annotate(+ _canvas_uuid=Case(+ When(type="canvas", ref__regex=_UUID_PATTERN, then=Cast("ref", UUIDField())),+ default=None,+ output_field=UUIDField(),+ )+ ).filter(~Q(type="canvas") | Exists(visible))+++def canvas_deletable_by(*, team_id: int, canvas_id: str | UUID, user_id: int | None) -> bool:+ """Deleting is the creator's call alone, as in the canvas API's `CanvasAccess.DELETE`."""+ if user_id is None:+ return False+ return (+ _visible_canvases(team_id, user_id)+ .filter(id=canvas_id, created_by_id=user_id, source_policy=Canvas.SOURCE_POLICY_STANDARD)+ .exists()+ )+++def canvas_restorable_by(*, team_id: int, canvas_id: str | UUID, user_id: int | None) -> bool:+ """Like deleting, restoring is the creator's call, and it runs while the canvas is still deleted."""+ if user_id is None:+ return False+ return (+ Canvas.objects.for_team(team_id)+ .filter(+ tasks_facade.visible_channels_q(user_id, relation="channel"),+ id=canvas_id,+ created_by_id=user_id,+ source_policy=Canvas.SOURCE_POLICY_STANDARD,+ )+ .exists()+ )++def visible_canvas_user_ids(*, team_id: int, canvas_id: str, user_ids: Iterable[int]) -> set[int]:candidate_ids = set(user_ids) if not isinstance(user_ids, set) else user_idsif not candidate_ids:diff --git a/products/canvas/backend/models.py b/products/canvas/backend/models.pyindex 4ace4059deed..9410a9d7ad4a 100644--- a/products/canvas/backend/models.py+++ b/products/canvas/backend/models.py@@ -1,7 +1,12 @@+from typing import TYPE_CHECKING+from django.db import models-from django.db.models import Q+from django.db.models import Q, QuerySetfrom django.utils import timezone+from posthog.models.file_system.constants import DEFAULT_SURFACE+from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin+from posthog.models.file_system.file_system_representation import FileSystemRepresentationfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel@@ -17,8 +22,11 @@ from products.canvas.backend.facade.enums import (CANVAS_STATE_SCOPES,)+if TYPE_CHECKING:+ from posthog.models.team import Team+-class Canvas(TeamScopedRootMixin, UUIDModel):+class Canvas(FileSystemSyncMixin, TeamScopedRootMixin, UUIDModel):"""A canvas document: an agent-built, sandboxed browser app filed in a channel.The document's source lives in append-only ``CanvasSourceVersion`` rows@@ -101,6 +109,39 @@ class Canvas(TeamScopedRootMixin, UUIDModel):),]+ # What makes a canvas a thing a person opens from the project tree: a live, standalone freeform+ # canvas. Components and grids are widgets, and notebook widgets belong to their notebook. The+ # unfiled sweep filters on this mapping and `is_filed_analysis` compares an instance to it, so the+ # two never drift apart.+ FILED_ANALYSIS_FILTER: dict[str, object] = {+ "deleted": False,+ "kind": KIND_FREEFORM,+ "source_policy": SOURCE_POLICY_STANDARD,+ }++ @property+ def is_filed_analysis(self) -> bool:+ return all(getattr(self, field) == value for field, value in self.FILED_ANALYSIS_FILTER.items())++ @classmethod+ def get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Canvas"]:+ # The unfiled sweep runs outside a request, so the fail-closed manager needs the team spelled out.+ # `for_team` resolves an environment to its project, so the exact team keeps an environment's sweep+ # from filing the project's canvases a second time under its own id.+ base_qs = cls.objects.for_team(team.id).filter(team_id=team.id, **cls.FILED_ANALYSIS_FILTER)+ return cls._filter_unfiled_queryset(base_qs, team, type="canvas", ref_field="id", surface=surface)++ def get_file_system_representation(self) -> FileSystemRepresentation:+ return FileSystemRepresentation(+ base_folder=self._get_assigned_folder("Unfiled/Canvases"),+ type="canvas", # sync with APIScopeObject in scopes.py+ ref=str(self.id),+ name=self.name or "Untitled",+ href=f"/canvases/{self.id}",+ meta={"created_at": str(self.created_at), "created_by": self.created_by_id},+ should_delete=not self.is_filed_analysis,+ )+class CanvasSourceVersion(TeamScopedRootMixin, UUIDModel):"""One immutable published source project of a canvas.diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex c89f01c44148..b3b8eb06b240 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -26,9 +26,9 @@ from posthog.event_usage import report_user_actionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activityfrom posthog.models.user import User+from posthog.oauth_provenance import is_sandbox_oauth_requestfrom posthog.permissions import is_service_authfrom posthog.storage.object_storage import ObjectStorageError-from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDSfrom products.access_control.backend.facade.contracts import ObjectAccessReffrom products.canvas.backend.facade import api as canvas_api@@ -319,23 +319,7 @@ class CanvasAccessMixin(TeamAndOrgViewSetMixin):@staticmethoddef _is_sandbox_authenticated(request: Request) -> bool:- """True when the request bears an OAuth token minted for a task sandbox —- the credential a task sandbox (via the MCP server) calls this API with.-- The sandbox apps also issue the desktop app's interactive grants, so the application- alone does not prove sandbox origin. Server-minted tokens carry either a task binding- or the internal provenance scope. An unbound server token must still fail closed rather- than inherit its user's Canvas visibility.- """- authenticator = request.successful_authenticator- if not isinstance(authenticator, OAuthAccessTokenAuthentication):- return False- access_token = authenticator.access_token- scopes = set((access_token.scope or "").split())- if access_token.sandbox_task_id is None and "internal_run:read" not in scopes:- return False- application = access_token.application- return application is not None and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS+ return is_sandbox_oauth_request(request)def _validate_sandbox_channel(self, channel_id: UUID, task_id: UUID | None) -> None:if not self._is_sandbox_authenticated(self.request):diff --git a/products/canvas/backend/tests/test_file_system.py b/products/canvas/backend/tests/test_file_system.pynew file mode 100644index 000000000000..0388b38c7857--- /dev/null+++ b/products/canvas/backend/tests/test_file_system.py@@ -0,0 +1,205 @@+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import APIBaseTest, BaseTest++from django.utils import timezone++from parameterized import parameterized+from rest_framework.test import APIClient++from posthog.models.file_system.file_system import FileSystem+from posthog.models.file_system.unfiled_file_saver import save_unfiled_files+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.scoping import team_scope+from posthog.models.user import User+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV++from products.canvas.backend.models import Canvas+from products.tasks.backend.models import Channel+++class TestCanvasFileSystem(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(team_scope(self.team.id))+ self.channel = Channel.objects.create(team=self.team, name="general", created_by=self.user)++ def _entry(self, canvas: Canvas) -> FileSystem | None:+ return FileSystem.objects.filter(team=self.team, type="canvas", ref=str(canvas.id)).first()++ def test_freeform_canvas_lifecycle(self) -> None:+ canvas = Canvas.objects.create(team=self.team, channel=self.channel, name="Run rate", created_by=self.user)+ entry = self._entry(canvas)+ assert entry is not None+ self.assertEqual(entry.path, "Unfiled/Canvases/Run rate")+ self.assertEqual(entry.href, f"/canvases/{canvas.id}")+ self.assertEqual(entry.created_by, self.user)++ canvas.deleted = True+ canvas.save()+ self.assertIsNone(self._entry(canvas))++ @parameterized.expand(+ [+ ("component", {"kind": Canvas.KIND_COMPONENT}),+ ("grid", {"kind": Canvas.KIND_GRID}),+ ("notebook_widget", {"source_policy": Canvas.SOURCE_POLICY_NOTEBOOK_WIDGET}),+ ]+ )+ def test_non_analysis_canvases_stay_out(self, _name: str, overrides: dict) -> None:+ canvas = Canvas.objects.create(+ team=self.team, channel=self.channel, name="Widget", created_by=self.user, **overrides+ )+ self.assertIsNone(self._entry(canvas))+ self.assertEqual(Canvas.get_file_system_unfiled(self.team).count(), 0)++ def test_unfiled_saver_files_existing_canvases(self) -> None:+ canvas = Canvas.objects.create(team=self.team, channel=self.channel, name="Older", created_by=self.user)+ FileSystem.objects.all().delete()++ created = save_unfiled_files(self.team, self.user, file_type="canvas")++ self.assertEqual([entry.ref for entry in created], [str(canvas.id)])+ self.assertEqual(self._entry(canvas).path, "Unfiled/Canvases/Older") # type: ignore[union-attr]+++class TestCanvasFileSystemVisibility(APIBaseTest):+ """The file system only applies project RBAC, so canvas rows follow the channel's visibility on read."""++ def setUp(self) -> None:+ super().setUp()+ self.enterContext(team_scope(self.team.id))+ self.other = User.objects.create_and_join(self.organization, "[email protected]", "pwd")+ self.public_channel = Channel.objects.create(team=self.team, name="general", created_by=self.user)+ self.personal_channel = Channel.objects.create(+ team=self.team, name="me", channel_type=Channel.ChannelType.PERSONAL, created_by=self.user+ )+ self.public_canvas = Canvas.objects.create(+ team=self.team, channel=self.public_channel, name="Shared", created_by=self.user+ )+ self.personal_canvas = Canvas.objects.create(+ team=self.team, channel=self.personal_channel, name="Mine", created_by=self.user+ )++ def _refs(self, query: str) -> set[str]:+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/{query}")+ self.assertEqual(response.status_code, 200, response.content)+ return {entry["ref"] for entry in response.json()["results"] if entry["type"] == "canvas"}++ @parameterized.expand(+ [+ ("list", "?type=canvas"),+ ("search", "?search=Mine&type=canvas"),+ ("folder", "?parent=Unfiled/Canvases&depth=3"),+ ]+ )+ def test_personal_canvas_lists_for_its_owner_only(self, _name: str, query: str) -> None:+ self.assertIn(str(self.personal_canvas.id), self._refs(query))++ self.client.force_login(self.other)+ refs = self._refs(query)+ self.assertNotIn(str(self.personal_canvas.id), refs)+ if "search" not in query:+ self.assertIn(str(self.public_canvas.id), refs)++ def test_personal_canvas_stays_out_of_another_members_recents(self) -> None:+ base = f"/api/projects/{self.team.id}/file_system"+ self.client.force_login(self.other)+ self.client.post(+ f"{base}/log_view/",+ {"type": "canvas", "ref": str(self.personal_canvas.id), "viewed_at": "2026-09-01T00:00:00Z"},+ )+ recents = self.client.get(f"{base}/?order_by=-last_viewed_at&limit=5").json()+ self.assertNotIn(str(self.personal_canvas.id), {entry["ref"] for entry in recents["results"]})++ def test_deleting_the_row_soft_deletes_the_canvas_for_someone_who_may_see_it(self) -> None:+ entry = FileSystem.objects.get(team=self.team, type="canvas", ref=str(self.public_canvas.id))+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")+ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response.json()["deleted"][0]["mode"], "soft")+ self.public_canvas.refresh_from_db()+ self.assertTrue(self.public_canvas.deleted)+ self.assertFalse(FileSystem.objects.filter(id=entry.id).exists())++ def test_a_sandbox_token_does_not_inherit_its_users_private_channels(self) -> None:+ private_channel = Channel.objects.create(+ team=self.team, name="team-private", channel_type=Channel.ChannelType.PRIVATE, created_by=self.other+ )+ private_channel.memberships.create(team=self.team, user=self.user)+ private_canvas = Canvas.objects.create(+ team=self.team, channel=private_channel, name="Private plan", created_by=self.other+ )+ self.assertIn(str(private_canvas.id), self._refs("?type=canvas"))++ application = OAuthApplication.objects.create(+ name="Canvas sandbox",+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_canvas_{uuid4().hex}",+ expires=timezone.now() + timedelta(hours=1),+ scope="file_system:read canvas:read",+ scoped_teams=[self.team.id],+ sandbox_task_id=uuid4(),+ )+ sandbox = APIClient()+ sandbox.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ response = sandbox.get(f"/api/projects/{self.team.id}/file_system/?type=canvas")+ self.assertEqual(response.status_code, 200, response.content)+ refs = {entry["ref"] for entry in response.json()["results"]}+ self.assertIn(str(self.public_canvas.id), refs)+ self.assertNotIn(str(private_canvas.id), refs)++ own = FileSystem.objects.get(team=self.team, type="canvas", ref=str(self.public_canvas.id))+ response = sandbox.delete(f"/api/projects/{self.team.id}/file_system/{own.id}/")+ self.assertEqual(response.status_code, 403, response.content)++ def test_another_member_cannot_delete_a_public_canvas_through_the_file_system(self) -> None:+ entry = FileSystem.objects.get(team=self.team, type="canvas", ref=str(self.public_canvas.id))+ self.client.force_login(self.other)+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")+ self.assertEqual(response.status_code, 403, response.content)+ self.public_canvas.refresh_from_db()+ self.assertFalse(self.public_canvas.deleted)++ def test_the_creator_can_undo_a_file_system_delete(self) -> None:+ entry = FileSystem.objects.get(team=self.team, type="canvas", ref=str(self.personal_canvas.id))+ self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")+ response = self.client.post(+ f"/api/projects/{self.team.id}/file_system/undo_delete/",+ {"items": [{"type": "canvas", "ref": str(self.personal_canvas.id), "path": entry.path}]},+ format="json",+ )+ self.assertEqual(response.status_code, 200, response.content)+ self.personal_canvas.refresh_from_db()+ self.assertFalse(self.personal_canvas.deleted)++ def test_restoring_a_hidden_canvas_through_undo_delete_is_refused(self) -> None:+ self.personal_canvas.deleted = True+ self.personal_canvas.save()+ self.client.force_login(self.other)+ response = self.client.post(+ f"/api/projects/{self.team.id}/file_system/undo_delete/",+ {"items": [{"type": "canvas", "ref": str(self.personal_canvas.id), "path": "Unfiled/Canvases/Mine"}]},+ format="json",+ )+ self.assertEqual(response.status_code, 400, response.content)+ self.personal_canvas.refresh_from_db()+ self.assertTrue(self.personal_canvas.deleted)++ def test_deleting_a_hidden_canvas_row_is_refused(self) -> None:+ entry = FileSystem.objects.get(team=self.team, type="canvas", ref=str(self.personal_canvas.id))+ self.client.force_login(self.other)+ response = self.client.delete(f"/api/projects/{self.team.id}/file_system/{entry.id}/")+ self.assertIn(response.status_code, (403, 404), response.content)+ self.personal_canvas.refresh_from_db()+ self.assertFalse(self.personal_canvas.deleted)diff --git a/products/canvas/frontend/scene/CanvasScene.tsx b/products/canvas/frontend/scene/CanvasScene.tsxindex 1f8b95c390ae..a1604e18e096 100644--- a/products/canvas/frontend/scene/CanvasScene.tsx+++ b/products/canvas/frontend/scene/CanvasScene.tsx@@ -14,6 +14,7 @@ import {import { NotFound } from 'lib/components/NotFound'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { useFileSystemLogView } from 'lib/hooks/useFileSystemLogView'import { cn } from 'lib/utils/css-classes'import { SceneExport } from 'scenes/sceneTypes'@@ -169,7 +170,9 @@ function CanvasMain(): JSX.Element {export function CanvasScene({ id }: CanvasSceneLogicProps): JSX.Element {const enabled = useFeatureFlag('TODAY_RAIL_NAV')- const { viewMissing } = useValues(canvasSceneLogic({ id }))+ const { view, viewMissing } = useValues(canvasSceneLogic({ id }))+ // Recently opened lists read the view log, so a canvas records its view like a dashboard does, once it loaded.+ useFileSystemLogView({ type: 'canvas', ref: id, enabled: enabled && !!view && !viewMissing })if (!enabled || viewMissing) {return <NotFound object="canvas" />diff --git a/products/canvas/manifest.tsx b/products/canvas/manifest.tsxindex 63f350c7cf71..2f3164d4ad20 100644--- a/products/canvas/manifest.tsx+++ b/products/canvas/manifest.tsx@@ -1,3 +1,6 @@+import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'+import { ProductManifest } from '../../frontend/src/types'export const manifest: ProductManifest = {@@ -35,7 +38,18 @@ export const manifest: ProductManifest = {spaceId ? `/canvases/new?space=${encodeURIComponent(spaceId)}` : '/canvases/new',canvasDetail: (id: string): string => `/canvases/${id}`,},- fileSystemTypes: {},+ fileSystemTypes: {+ canvas: {+ name: 'Canvas',+ iconType: 'canvas',+ // Canvases open only under the Today navigation, so the old tree's type filters hide them with it.+ flag: FEATURE_FLAGS.TODAY_RAIL_NAV,+ href: (ref: string) => urls.canvasDetail(ref),+ listHref: () => urls.canvases(),+ iconColor: ['var(--color-product-tasks-light)', 'var(--color-product-tasks-dark)'],+ filterKey: 'canvas',+ },+ },treeItemsNew: [],treeItemsProducts: [],}