Skip to content

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

feat(cross-project-dashboards): add the scene, tiles and editing (#109768)

Yasen20ef7a73a725
diff --git a/frontend/src/lib/components/ActivityLog/describers.tsx b/frontend/src/lib/components/ActivityLog/describers.tsx
index 475d6ffe4abc..a711b7f810f2 100644
--- a/frontend/src/lib/components/ActivityLog/describers.tsx
+++ b/frontend/src/lib/components/ActivityLog/describers.tsx
@@ -41,6 +41,7 @@ import { alertConfigurationActivityDescriber } from 'products/alerts/frontend/co
import { annotationActivityDescriber } from 'products/annotations/frontend/activityDescriptions'
import { canvasActivityDescriber } from 'products/canvas/frontend/activityDescriber'
import { ticketActivityDescriber } from 'products/conversations/frontend/activityDescriber'
+import { crossProjectDashboardActivityDescriber } from 'products/cross_project_dashboards/frontend/crossProjectDashboardActivityDescriber'
import { externalDataSourceActivityDescriber } from 'products/data_warehouse/frontend/shared/components/activityDescriptions'
import { endpointActivityDescriber } from 'products/endpoints/frontend/activityDescriber'
import { groupActivityDescriber } from 'products/groups/frontend/activityDescriptions'
@@ -69,6 +70,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =
return exportedAssetActivityDescriber
case ActivityScope.DASHBOARD:
return dashboardActivityDescriber
+ case ActivityScope.CROSS_PROJECT_DASHBOARD:
+ return crossProjectDashboardActivityDescriber
case ActivityScope.FEATURE_FLAG:
return flagActivityDescriber
case ActivityScope.HOG_FUNCTION:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b9b037c57aef..b55d732ed551 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -292,6 +292,7 @@ export const FEATURE_FLAGS = {
CONDENSED_FILTER_BAR: 'condensed_filter_bar', // owner: @jordanm-posthog #team-web-analytics
CREATE_FORM_TOOL: 'phai-create-form-tool', // owner: @kappa90 #team-posthog-ai
CRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analytics
+ CROSS_PROJECT_DASHBOARDS: 'cross-project-dashboards', // owner: #team-platform-features
CUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet rails
CUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_ACCOUNT_SCENE: 'customer-analytics-account-scene', // owner: @arthurdedeus #team-customer-analytics
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 8e88f7299bcd..ca1c023972c0 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -68,6 +68,9 @@ export const productScenes: Record<string, () => Promise<any>> = {
SupportTicketDetail: () => import('../../products/conversations/frontend/scenes/ticket/SupportTicketScene'),
SupportSettings: () => import('../../products/conversations/frontend/scenes/settings/SupportSettingsScene'),
MyTickets: () => import('../../products/conversations/frontend/scenes/myTickets/MyTicketsScene'),
+ CrossProjectDashboards: () =>
+ import('../../products/cross_project_dashboards/frontend/CrossProjectDashboardsScene'),
+ CrossProjectDashboard: () => import('../../products/cross_project_dashboards/frontend/CrossProjectDashboardScene'),
CustomerAnalytics: () => import('../../products/customer_analytics/frontend/CustomerAnalyticsScene'),
CustomerAnalyticsAccount: () =>
import('../../products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene'),
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 972f9bce2dff..2f13a4080110 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -127,6 +127,8 @@ export const productRoutes: Record<string, [string, string]> = {
'/support/tickets/:ticketId': ['SupportTicketDetail', 'supportTicketDetail'],
'/support/settings': ['SupportSettings', 'supportSettings'],
'/my-tickets': ['MyTickets', 'myTickets'],
+ '/cross-project-dashboards': ['CrossProjectDashboards', 'crossProjectDashboards'],
+ '/cross-project-dashboards/:id': ['CrossProjectDashboard', 'crossProjectDashboard'],
'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],
'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
'/customer_analytics/accounts/by-external-id/*': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
@@ -719,6 +721,17 @@ export const productConfiguration: Record<string, any> = {
SupportTicketDetail: { name: 'Ticket detail', projectBased: true, layout: 'app-container' },
SupportSettings: { name: 'Support settings', projectBased: true, layout: 'app-container' },
MyTickets: { name: 'Your tickets', projectBased: true, layout: 'app-container' },
+ CrossProjectDashboards: {
+ name: 'Cross-project dashboards',
+ organizationBased: true,
+ activityScope: 'CrossProjectDashboard',
+ description: 'Put insights from several projects on one page.',
+ },
+ CrossProjectDashboard: {
+ name: 'Cross-project dashboard',
+ organizationBased: true,
+ activityScope: 'CrossProjectDashboard',
+ },
CustomerAnalytics: {
projectBased: true,
name: 'Customer analytics',
@@ -1319,6 +1332,8 @@ export const productUrls = {
supportSettings: (): string => '/support/settings',
myTickets: (ticketId?: string): string =>
ticketId ? `/my-tickets?ticket=${encodeURIComponent(ticketId)}` : '/my-tickets',
+ crossProjectDashboards: (): string => '/cross-project-dashboards',
+ crossProjectDashboard: (id: string): string => `/cross-project-dashboards/${id}`,
customerAnalytics: (): string => '/customer_analytics',
customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
diff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
index 4a5c05c5b14c..c4e971a1b3bf 100644
--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
@@ -7,7 +7,9 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { DashboardTemplateModal } from 'scenes/dashboard/dashboards/templates/DashboardTemplateModal'
import { DashboardTemplatesTable } from 'scenes/dashboard/dashboards/templates/DashboardTemplatesTable'
@@ -26,6 +28,8 @@ import { dashboardsModel } from '~/models/dashboardsModel'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { CrossProjectDashboardsList } from 'products/cross_project_dashboards/frontend/CrossProjectDashboardsList'
+import { NewCrossProjectDashboardButton } from 'products/cross_project_dashboards/frontend/NewCrossProjectDashboardButton'
import { dashboardsEmptyState } from 'products/dashboards/frontend/emptyState/dashboardsEmptyState'
import { DashboardsTableContainer } from './DashboardsTable'
@@ -42,6 +46,9 @@ export function Dashboards(): JSX.Element {
const { dashboardsLoading } = useValues(dashboardsModel)
const { setCurrentTab } = useActions(dashboardsLogic)
const { dashboards, currentTab, isFiltering } = useValues(dashboardsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const crossProjectEnabled = !!featureFlags[FEATURE_FLAGS.CROSS_PROJECT_DASHBOARDS]
+ const crossProjectTabOpen = crossProjectEnabled && currentTab === DashboardsTab.CrossProject
const { showNewDashboardModal } = useActions(newDashboardLogic)
const templatesModalOpen = String(searchParams.templates) === '1'
const enabledTabs: LemonTab<DashboardsTab>[] = [
@@ -50,6 +57,7 @@ export function Dashboards(): JSX.Element {
label: 'All dashboards',
},
{ key: DashboardsTab.Yours, label: 'My dashboards' },
+ ...(crossProjectEnabled ? [{ key: DashboardsTab.CrossProject, label: 'Cross-project dashboards' }] : []),
]
return (
@@ -82,7 +90,9 @@ export function Dashboards(): JSX.Element {
type: sceneConfigurations[Scene.Dashboards].iconType || 'default_icon_type',
}}
actions={
- <>
+ crossProjectTabOpen ? (
+ <NewCrossProjectDashboardButton />
+ ) : (
<AccessControlAction
resourceType={AccessControlResourceType.Dashboard}
minAccessLevel={AccessControlLevel.Editor}
@@ -112,7 +122,7 @@ export function Dashboards(): JSX.Element {
</LemonButton>
</Shortcut>
</AccessControlAction>
- </>
+ )
}
/>
<LemonTabs
@@ -124,7 +134,13 @@ export function Dashboards(): JSX.Element {
sceneInset
/>
- <div>{dashboardsLoading || dashboards.length > 0 || isFiltering ? <DashboardsTableContainer /> : null}</div>
+ {crossProjectTabOpen ? (
+ <CrossProjectDashboardsList />
+ ) : (
+ <div>
+ {dashboardsLoading || dashboards.length > 0 || isFiltering ? <DashboardsTableContainer /> : null}
+ </div>
+ )}
</SceneContent>
)
}
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index bfa2f7190964..bd709bbbeb7d 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -550,6 +550,15 @@ describe('dashboardsLogic', () => {
expect(router.values.searchParams['tab']).toBeUndefined()
})
+ it('keeps the cross-project tab selected from the URL', async () => {
+ logic.unmount()
+ router.actions.push(urls.dashboards(), { tab: DashboardsTab.CrossProject })
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ currentTab: DashboardsTab.CrossProject })
+ })
+
it('restores both search and tags from the URL and fetches with the restored tags', async () => {
let lastRequestUrl: URL | null = null
useMocks({
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index dd556ab5bed6..19afcb09d479 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -27,6 +27,7 @@ export enum DashboardsTab {
All = 'all',
Yours = 'yours',
Pinned = 'pinned',
+ CrossProject = 'cross-project',
}
const DEFAULT_SORTING: Sorting = { columnKey: 'name', order: 1 }
@@ -579,7 +580,10 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
urlToAction(({ actions, values }) => ({
'/dashboard': (_, searchParams) => {
const requestedTab = (searchParams['tab'] as DashboardsTab | undefined) || DashboardsTab.All
- const tab = requestedTab === DashboardsTab.Yours ? DashboardsTab.Yours : DashboardsTab.All
+ // Pinned is deliberately absent: it arrives as a filter, not a tab, and is handled
+ // by hasFilterParams below. Anything else unrecognized falls back to All.
+ const tabsFromUrl: DashboardsTab[] = [DashboardsTab.Yours, DashboardsTab.CrossProject]
+ const tab = tabsFromUrl.includes(requestedTab) ? requestedTab : DashboardsTab.All
if (values.currentTab !== tab) {
actions.setCurrentTab(tab)
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 586a456ccdcc..cd7448f040fc 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6083,6 +6083,7 @@ export enum ActivityScope {
GENERATED_WIDGET = 'GeneratedWidget',
CANVAS = 'Canvas',
DASHBOARD = 'Dashboard',
+ CROSS_PROJECT_DASHBOARD = 'CrossProjectDashboard',
REPLAY = 'Replay',
REPLAY_SCANNER = 'ReplayScanner',
VISION_ALERT_CONFIGURATION = 'VisionAlertConfiguration',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e7f785f8374e..00035c73bf92 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3002,6 +3002,9 @@ importers:
products/cross_project_dashboards:
dependencies:
+ '@posthog/brand':
+ specifier: 'catalog:'
+ version: 0.12.3([email protected])
'@posthog/icons':
specifier: 'catalog:'
diff --git a/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx b/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx
new file mode 100644
index 000000000000..3f8551444abe
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx
@@ -0,0 +1,94 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { addCrossProjectTileLogic } from './addCrossProjectTileLogic'
+
+export interface AddCrossProjectTileModalProps {
+ dashboardId: string
+}
+
+export function AddCrossProjectTileModal({ dashboardId }: AddCrossProjectTileModalProps): JSX.Element {
+ const logic = addCrossProjectTileLogic({ dashboardId })
+ const {
+ isOpen,
+ projectId,
+ selectedInsight,
+ projectOptions,
+ insightPage,
+ insightOptions,
+ insightPageLoading,
+ canAdd,
+ isAdding,
+ } = useValues(logic)
+ const { closeModal, setProjectId, setInsight, setInsightSearch, loadMoreInsights, addTile } = useActions(logic)
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={closeModal}
+ title="Add an insight"
+ description="Pick a project, then an insight from it. The tile shows that project's data."
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={addTile}
+ disabledReason={!canAdd ? 'Pick a project and an insight first' : undefined}
+ loading={isAdding}
+ data-attr="cross-project-add-tile-confirm"
+ >
+ Add to dashboard
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4 min-w-100">
+ <LemonField.Pure label="Project">
+ <LemonSelect
+ value={projectId}
+ onChange={setProjectId}
+ options={projectOptions}
+ placeholder="Select a project"
+ data-attr="cross-project-add-tile-project"
+ fullWidth
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Insight">
+ <LemonInputSelect
+ mode="single"
+ value={selectedInsight ? [String(selectedInsight.id)] : []}
+ onChange={(keys) =>
+ setInsight(insightPage.insights.find((insight) => String(insight.id) === keys[0]) ?? null)
+ }
+ onInputChange={setInsightSearch}
+ options={insightOptions}
+ // The search runs on the server, so the list is already the answer to it.
+ disableFiltering
+ // Loaded pages can pass the 100 options the plain list stops at.
+ virtualized
+ placeholder={projectId ? 'Search insights' : 'Select a project first'}
+ disabledReason={!projectId ? 'Select a project first' : undefined}
+ loading={insightPageLoading}
+ action={
+ insightPage.hasMore
+ ? {
+ children: 'Load more insights',
+ onClick: loadMoreInsights,
+ disabledReason: insightPageLoading ? 'Loading insights' : undefined,
+ }
+ : undefined
+ }
+ data-attr="cross-project-add-tile-insight"
+ fullWidth
+ />
+ </LemonField.Pure>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx
new file mode 100644
index 000000000000..14d1e9e690d2
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx
@@ -0,0 +1,317 @@
+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
+import type { Layout, LayoutItem } from 'react-grid-layout'
+import { GridBackground } from 'react-grid-layout/extras'
+
+import type { EditModeEdge } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+// The single-project grid's styles live here, and nothing else on this page loads them.
+import 'scenes/dashboard/DashboardItems.scss'
+import {
+ continueDragGestureInEditMode,
+ continueResizeGestureInEditMode,
+ whenPressBecomesDrag,
+} from 'scenes/dashboard/editLayoutGesture'
+import { useDashboardLayoutInteraction } from 'scenes/dashboard/useDashboardLayoutInteraction'
+
+import type { DashboardLayoutSize, InsightColor } from '~/types'
+
+import type { CrossProjectDashboardFilters, CrossProjectTileProject } from './crossProjectDashboardLogic'
+import {
+ GRID_BREAKPOINTS,
+ GRID_COLUMN_COUNTS,
+ GRID_MARGIN,
+ GRID_ROW_HEIGHT,
+ type ResponsiveTileLayouts,
+} from './crossProjectLayouts'
+import { CrossProjectTile } from './CrossProjectTile'
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+const DRAG_AUTO_SCROLL_THRESHOLD = 100
+const DRAG_AUTO_SCROLL_SPEED = 50
+const CONTAINER_PADDING: [number, number] = [0, 0]
+
+// Single-project edit mode's handle, cancel and edge set.
+const DRAG_HANDLE = '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle'
+const DRAG_CANCEL = 'a,table,button,input,.Popover'
+const RESIZE_HANDLES = ['s', 'e', 'se', 'n', 'w', 'nw', 'ne', 'sw'] as const
+const NOT_A_DRAG_HANDLE =
+ 'input,textarea,button,select,a,p,h4,[contenteditable="true"],[role="textbox"],.ProseMirror,.LemonMarkdown'
+
+export interface CrossProjectDashboardGridProps {
+ tiles: readonly CrossProjectDashboardTileApi[]
+ layouts: Partial<ResponsiveTileLayouts>
+ layoutEditMode: boolean
+ onEnterLayoutEdit: () => void
+ tileProjects: Record<number, CrossProjectTileProject>
+ timezonesDiverge: boolean
+ missingPropertyKeys: Record<number, string[]>
+ dashboardFilters: CrossProjectDashboardFilters
+ onLayoutsChange: (layouts: Partial<ResponsiveTileLayouts>) => void
+ onSetTileColor: (tileId: string, color: InsightColor | null) => void
+ onSetTileOverride: (tile: CrossProjectDashboardTileApi) => void
+ onRemoveTile: (tileId: string) => void
+}
+
+export function CrossProjectDashboardGrid({
+ tiles,
+ layouts,
+ layoutEditMode,
+ onEnterLayoutEdit,
+ tileProjects,
+ timezonesDiverge,
+ missingPropertyKeys,
+ dashboardFilters,
+ onLayoutsChange,
+ onSetTileColor,
+ onSetTileOverride,
+ onRemoveTile,
+}: CrossProjectDashboardGridProps): JSX.Element {
+ const { width, containerRef, mounted } = useContainerWidth()
+ const [containerHeight, setContainerHeight] = useState(0)
+ const [resizingTileId, setResizingTileId] = useState<string | null>(null)
+ const scrollContainerRef = useRef<HTMLElement | null>(null)
+ const scrollContainerRectRef = useRef<DOMRect | null>(null)
+ const scrollAnimationRef = useRef<number | null>(null)
+
+ const updateLayouts = useCallback(
+ (next: Partial<Record<DashboardLayoutSize, Layout>>) => onLayoutsChange(next as Partial<ResponsiveTileLayouts>),
+ [onLayoutsChange]
+ )
+
+ const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =
+ useDashboardLayoutInteraction({ layoutEditMode, updateLayouts })
+
+ // Debounce width changes to the grid. Rapidly crossing the width leaves tiles squashed at one column.
+ const [gridWidth, setGridWidth] = useState(width)
+ useEffect(() => {
+ const timer = setTimeout(() => setGridWidth(width), 100)
+ return () => clearTimeout(timer)
+ }, [width])
+
+ useEffect(() => {
+ if (!mounted || !containerRef.current) {
+ return
+ }
+ const element = containerRef.current
+ const observer = new ResizeObserver((entries) => {
+ // Height commits during a gesture re-render every tile for the grid background and lag the cursor.
+ if (interactionInProgress.current) {
+ return
+ }
+ for (const entry of entries) {
+ if (entry.target === element) {
+ setContainerHeight(entry.contentRect.height)
+ }
+ }
+ })
+ setContainerHeight(element.clientHeight)
+ observer.observe(element)
+ return () => observer.disconnect()
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- refs are stable
+ }, [mounted, containerRef])
+
+ const isMobileView = !!width && width <= GRID_BREAKPOINTS.sm
+ const canEditLayout = layoutEditMode && !isMobileView
+ const canEnterEditModeFromEdge = !layoutEditMode && !isMobileView
+ const dragConfig = useMemo(
+ () => ({ enabled: canEditLayout, handle: DRAG_HANDLE, cancel: DRAG_CANCEL, bounded: true }),
+ [canEditLayout]
+ )
+ const resizeConfig = useMemo(() => ({ enabled: canEditLayout, handles: RESIZE_HANDLES }), [canEditLayout])
+
+ const onEnterEditModeFromEdge = useMemo(
+ () =>
+ canEnterEditModeFromEdge
+ ? (e: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => {
+ whenPressBecomesDrag(e, (moveEvent) => {
+ onEnterLayoutEdit()
+ continueResizeGestureInEditMode(e, edge, moveEvent)
+ })
+ }
+ : undefined,
+ [canEnterEditModeFromEdge, onEnterLayoutEdit]
+ )
+ const onDragHandleMouseDown = useMemo(
+ () =>
+ canEnterEditModeFromEdge
+ ? (e: React.MouseEvent) => {
+ const target = e.target as Element | null
+ if (!target?.closest('.react-grid-item') || target.closest(NOT_A_DRAG_HANDLE)) {
+ return
+ }
+ e.preventDefault()
+ e.stopPropagation()
+ whenPressBecomesDrag(e, (moveEvent) => {
+ onEnterLayoutEdit()
+ continueDragGestureInEditMode(e, moveEvent)
+ })
+ }
+ : undefined,
+ [canEnterEditModeFromEdge, onEnterLayoutEdit]
+ )
+
+ const finishGesture = useCallback(() => {
+ finishInteraction()
+ // Remeasure once the gesture settles, since height updates were suppressed during it.
+ requestAnimationFrame(() => {
+ if (containerRef.current) {
+ setContainerHeight(containerRef.current.clientHeight)
+ }
+ })
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- ref reads inside requestAnimationFrame aren't valid deps
+ }, [finishInteraction])
+
+ const handleResizeStart = useCallback(
+ (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {
+ if (newItem) {
+ startInteraction(layout, newItem, 'resize')
+ }
+ },
+ [startInteraction]
+ )
+
+ const handleResize = useCallback((_layout: unknown, _oldItem: unknown, newItem: LayoutItem | null) => {
+ // Setting state to the same id bails out of re-rendering, so this re-renders once per gesture.
+ setResizingTileId(newItem?.i ?? null)
+ }, [])
+
+ const handleResizeStop = useCallback(() => {
+ setResizingTileId(null)
+ finishGesture()
+ }, [finishGesture])
+
+ const handleDragStart = useCallback(
+ (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {
+ if (!newItem) {
+ return
+ }
+ startInteraction(layout, newItem, 'drag')
+ scrollContainerRef.current = document.getElementById('main-content')
+ scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
+ },
+ [startInteraction]
+ )
+
+ const handleDrag = useCallback(
+ (_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: unknown) => {
+ if (scrollAnimationRef.current) {
+ cancelAnimationFrame(scrollAnimationRef.current)
+ scrollAnimationRef.current = null
+ }
+ const scrollContainer = scrollContainerRef.current
+ const containerRect = scrollContainerRectRef.current
+ if (!scrollContainer || !containerRect) {
+ return
+ }
+ const mouseY = (e as MouseEvent).clientY
+ let scrollSpeed = 0
+ if (mouseY < containerRect.top + DRAG_AUTO_SCROLL_THRESHOLD) {
+ scrollSpeed = -DRAG_AUTO_SCROLL_SPEED
+ } else if (mouseY > containerRect.bottom - DRAG_AUTO_SCROLL_THRESHOLD) {
+ scrollSpeed = DRAG_AUTO_SCROLL_SPEED
+ }
+ if (scrollSpeed !== 0) {
+ const scroll = (): void => {
+ const atTop = scrollSpeed < 0 && scrollContainer.scrollTop === 0
+ const atBottom =
+ scrollSpeed > 0 &&
+ scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight
+ if (atTop || atBottom) {
+ return
+ }
+ scrollContainer.scrollBy(0, scrollSpeed)
+ scrollAnimationRef.current = requestAnimationFrame(scroll)
+ }
+ scrollAnimationRef.current = requestAnimationFrame(scroll)
+ }
+ },
+ []
+ )
+
+ const handleDragStop = useCallback(() => {
+ if (scrollAnimationRef.current) {
+ cancelAnimationFrame(scrollAnimationRef.current)
+ scrollAnimationRef.current = null
+ }
+ scrollContainerRef.current = null
+ scrollContainerRectRef.current = null
+ finishGesture()
+ }, [finishGesture])
+
+ return (
+ <div
+ className="dashboard-items-wrapper"
+ ref={containerRef as RefObject<HTMLDivElement>}
+ data-attr="cross-project-dashboard-grid"
+ >
+ {layoutEditMode && isMobileView && (
+ <LemonBanner type="warning" className="mb-4">
+ Layout editing is disabled on smaller screens. Please zoom out or use a larger screen to move or
+ resize tiles.
+ </LemonBanner>
+ )}
+ {mounted && (
+ <div className="relative">
+ {canEditLayout && (
+ <GridBackground
+ width={gridWidth}
+ cols={GRID_COLUMN_COUNTS.sm}
+ rowHeight={GRID_ROW_HEIGHT}
+ margin={GRID_MARGIN}
+ containerPadding={CONTAINER_PADDING}
+ rows="auto"
+ height={containerHeight}
+ color="var(--color-bg-surface-secondary)"
+ />
+ )}
+ <ReactGridLayout
+ width={gridWidth}
+ className={
+ layoutEditMode
+ ? // Dragging is bounded to the grid's height, so the padding leaves room to drop a tile in a new row.
+ 'dashboard-edit-mode box-content pb-[40vh]'
+ : 'dashboard-view-mode mb-8'
+ }
+ dragConfig={dragConfig}
+ resizeConfig={resizeConfig}
+ layouts={layouts as Partial<Record<DashboardLayoutSize, Layout>>}
+ compactor={gridCompactor}
+ rowHeight={GRID_ROW_HEIGHT}
+ margin={GRID_MARGIN}
+ containerPadding={CONTAINER_PADDING}
+ onLayoutChange={handleLayoutChange}
+ breakpoints={GRID_BREAKPOINTS}
+ cols={GRID_COLUMN_COUNTS}
+ onResizeStart={handleResizeStart}
+ onResize={handleResize}
+ onResizeStop={handleResizeStop}
+ onDragStart={handleDragStart}
+ onDrag={handleDrag}
+ onDragStop={handleDragStop}
+ >
+ {tiles.map((tile) => (
+ <CrossProjectTile
+ key={tile.id}
+ tile={tile}
+ projectName={tileProjects[tile.project_id]?.name}
+ projectTimezone={tileProjects[tile.project_id]?.timezone}
+ showTimezone={timezonesDiverge}
+ missingPropertyKeys={missingPropertyKeys[tile.project_id]}
+ dashboardFilters={dashboardFilters}
+ isResizing={resizingTileId === tile.id}
+ showResizeHandles={canEditLayout}
+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}
+ onDragHandleMouseDown={onDragHandleMouseDown}
+ onSetColor={(color) => onSetTileColor(tile.id, color)}
+ onSetOverride={() => onSetTileOverride(tile)}
+ onRemove={() => onRemoveTile(tile.id)}
+ />
+ ))}
+ </ReactGridLayout>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardLayoutActions.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardLayoutActions.tsx
new file mode 100644
index 000000000000..24076c316780
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardLayoutActions.tsx
@@ -0,0 +1,78 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGridMasonry } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
+import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
+
+import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
+
+/** Mirrors the single-project buttons, which read dashboardLogic, with own data-attrs to stay out of their analytics. */
+export function CrossProjectDashboardLayoutActions(): JSX.Element | null {
+ const { layoutEditMode, layoutSaving, tiles, dashboardLoading } = useValues(crossProjectDashboardLogic)
+ const { enterLayoutEdit, cancelLayoutEdit, saveLayout } = useActions(crossProjectDashboardLogic)
+
+ if (!layoutEditMode) {
+ return tiles.length > 0 ? (
+ <Shortcut
+ name="EnterCrossProjectDashboardEditMode"
+ keybind={[keyBinds.edit]}
+ intent="Enter edit mode"
+ interaction="click"
+ >
+ <LemonButton
+ type="secondary"
+ data-attr="cross-project-dashboard-edit-mode-button"
+ onClick={enterLayoutEdit}
+ size="small"
+ icon={<IconGridMasonry fontSize="16" />}
+ tooltip="Customize dashboard"
+ tooltipPlacement="top"
+ >
+ Customize
+ </LemonButton>
+ </Shortcut>
+ ) : null
+ }
+
+ return (
+ <>
+ <Shortcut
+ name="CancelCrossProjectDashboardEdit"
+ keybind={[keyBinds.escape]}
+ intent="Cancel edit mode"
+ interaction="click"
+ >
+ <LemonButton
+ data-attr="cross-project-dashboard-edit-mode-discard"
+ type="secondary"
+ onClick={cancelLayoutEdit}
+ size="small"
+ tooltip="Discard layout changes and exit layout editing"
+ >
+ Cancel
+ </LemonButton>
+ </Shortcut>
+ <Shortcut
+ name="SaveCrossProjectDashboard"
+ keybind={[keyBinds.edit, keyBinds.save]}
+ intent="Save dashboard layout"
+ interaction="click"
+ >
+ <LemonButton
+ data-attr="cross-project-dashboard-edit-mode-save"
+ type="primary"
+ onClick={saveLayout}
+ loading={layoutSaving}
+ size="small"
+ tooltip="Save dashboard layout"
+ tooltipPlacement="bottom"
+ disabledReason={dashboardLoading ? 'Wait for dashboard to finish loading' : undefined}
+ >
+ Save layout
+ </LemonButton>
+ </Shortcut>
+ </>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardScene.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardScene.tsx
new file mode 100644
index 000000000000..9f7b3f6b4236
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardScene.tsx
@@ -0,0 +1,191 @@
+import { useActions, useValues } from 'kea'
+
+import * as chartPng from '@posthog/brand/hoggies/png/chart'
+import { IconPlus } from '@posthog/icons'
+import { LemonButton, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { NotFound } from 'lib/components/NotFound'
+import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import type { IntervalType } from '~/types'
+
+import { addCrossProjectTileLogic } from './addCrossProjectTileLogic'
+import { AddCrossProjectTileModal } from './AddCrossProjectTileModal'
+import { CrossProjectDashboardGrid } from './CrossProjectDashboardGrid'
+import { CrossProjectDashboardLayoutActions } from './CrossProjectDashboardLayoutActions'
+import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
+import { openCrossProjectTileOverrideDialog } from './openCrossProjectTileOverrideDialog'
+
+const HedgehogChart = pngHoggie(chartPng)
+
+export const scene: SceneExport = {
+ component: CrossProjectDashboardScene,
+ logic: crossProjectDashboardLogic,
+ paramsToProps: ({ params: { id } }): (typeof crossProjectDashboardLogic)['props'] => ({ id }),
+}
+
+export function CrossProjectDashboardScene(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const {
+ dashboard,
+ dashboardLoading,
+ tiles,
+ dashboardFilters,
+ tileProjects,
+ timezonesDiverge,
+ missingPropertyKeys,
+ layoutEditMode,
+ gridLayouts,
+ } = useValues(crossProjectDashboardLogic)
+ const {
+ removeTile,
+ setDates,
+ setInterval,
+ setPendingLayouts,
+ enterLayoutEdit,
+ setTileOverride,
+ setTileColor,
+ setProperties,
+ updateDashboard,
+ deleteDashboard,
+ } = useActions(crossProjectDashboardLogic)
+ const { requestOpenModal } = useActions(addCrossProjectTileLogic({ dashboardId: dashboard?.id ?? '' }))
+
+ if (!featureFlags[FEATURE_FLAGS.CROSS_PROJECT_DASHBOARDS]) {
+ return <NotFound object="page" />
+ }
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={dashboard?.name ?? ''}
+ description={dashboard?.description ?? null}
+ resourceType={{ type: 'dashboard' }}
+ onNameChange={(name) => updateDashboard({ name })}
+ onDescriptionChange={(description) => updateDashboard({ description })}
+ canEdit={!!dashboard}
+ isLoading={dashboardLoading && !dashboard}
+ saveOnBlur
+ renameDebounceMs={0}
+ descriptionMaxLength={4000}
+ actions={
+ dashboard ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <DateFilter
+ dateFrom={dashboardFilters.date_from ?? null}
+ dateTo={dashboardFilters.date_to ?? null}
+ onChange={setDates}
+ />
+ <LemonSelect<IntervalType | null>
+ size="small"
+ value={dashboardFilters.interval ?? null}
+ onChange={setInterval}
+ dropdownMatchSelectWidth={false}
+ data-attr="cross-project-interval-filter"
+ options={[
+ { value: null, label: 'Default interval' },
+ { value: 'hour', label: 'Hour' },
+ { value: 'day', label: 'Day' },
+ { value: 'week', label: 'Week' },
+ { value: 'month', label: 'Month' },
+ ]}
+ />
+ <CrossProjectDashboardLayoutActions />
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={requestOpenModal}
+ data-attr="cross-project-add-tile"
+ >
+ Add insight
+ </LemonButton>
+ <More
+ data-attr="cross-project-dashboard-more"
+ overlay={
+ <LemonButton
+ status="danger"
+ fullWidth
+ onClick={deleteDashboard}
+ data-attr="cross-project-dashboard-delete"
+ >
+ Delete dashboard
+ </LemonButton>
+ }
+ />
+ </div>
+ ) : undefined
+ }
+ />
+ {dashboard ? (
+ <PropertyFilters
+ pageKey={`cross-project-dashboard-${dashboard.id}`}
+ propertyFilters={dashboardFilters.properties ?? []}
+ onChange={setProperties}
+ taxonomicGroupTypes={[
+ // Only groups whose filter travels by name. A cohort, group or flag filter
+ // carries an id that means something different in each project, and the API
+ // refuses it.
+ TaxonomicFilterGroupType.EventProperties,
+ TaxonomicFilterGroupType.PersonProperties,
+ TaxonomicFilterGroupType.EventMetadata,
+ ]}
+ />
+ ) : null}
+ {/* A reload after a filter change keeps the grid mounted, so only the first load shows a skeleton. */}
+ {dashboardLoading && !dashboard ? (
+ <LemonSkeleton className="h-60 w-full" />
+ ) : !dashboard ? (
+ <p>This dashboard is not available.</p>
+ ) : tiles.length === 0 ? (
+ // Same illustration and layout as the empty single-project dashboard.
+ <ProductIntroduction
+ thingName="cross-project-insight"
+ titleOverride="Build your dashboard"
+ description="Add insights from any project you have access to. Each tile shows data from its own project."
+ customHog={HedgehogChart}
+ hogLayout="responsive"
+ useMainContentContainerQueries
+ className="mt-2 mb-2 py-4 @min-[48rem]/main-content:py-14"
+ actionElementOverride={
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={requestOpenModal}
+ data-attr="cross-project-dashboard-empty-add-insight"
+ >
+ Add insight
+ </LemonButton>
+ }
+ />
+ ) : (
+ <CrossProjectDashboardGrid
+ missingPropertyKeys={missingPropertyKeys}
+ tiles={tiles}
+ tileProjects={tileProjects}
+ timezonesDiverge={timezonesDiverge}
+ dashboardFilters={dashboardFilters}
+ layouts={gridLayouts}
+ layoutEditMode={layoutEditMode}
+ onEnterLayoutEdit={enterLayoutEdit}
+ onLayoutsChange={setPendingLayouts}
+ onSetTileOverride={(tile) =>
+ openCrossProjectTileOverrideDialog(tile, (overrides) => setTileOverride(tile.id, overrides))
+ }
+ onSetTileColor={setTileColor}
+ onRemoveTile={removeTile}
+ />
+ )}
+ {dashboard ? <AddCrossProjectTileModal dashboardId={dashboard.id} /> : null}
+ </SceneContent>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx
new file mode 100644
index 000000000000..44e0e388bd66
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx
@@ -0,0 +1,101 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonModal, LemonTable, LemonTableColumn } from '@posthog/lemon-ui'
+
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+
+import { crossProjectDashboardsListLogic } from './crossProjectDashboardsListLogic'
+import type { CrossProjectDashboardListItemApi } from './generated/api.schemas'
+
+/** The list of cross-project dashboards, usable as a scene or as a tab on the dashboards page. The page header holds its "New" button. */
+export function CrossProjectDashboardsList(): JSX.Element {
+ const { dashboards, dashboardsLoading, isNewModalOpen, newName, isCreating } = useValues(
+ crossProjectDashboardsListLogic
+ )
+ const { closeNewModal, setNewName, createDashboard, deleteDashboard } = useActions(crossProjectDashboardsListLogic)
+
+ const columns: LemonTableColumn<
+ CrossProjectDashboardListItemApi,
+ keyof CrossProjectDashboardListItemApi | undefined
+ >[] = [
+ {
+ title: 'Name',
+ dataIndex: 'name',
+ render: (_, dashboard) => (
+ <LemonTableLink
+ to={`/cross-project-dashboards/${dashboard.id}`}
+ title={dashboard.name}
+ description={dashboard.description}
+ />
+ ),
+ },
+ {
+ title: 'Projects',
+ dataIndex: 'project_count',
+ },
+ {
+ title: 'Tiles',
+ dataIndex: 'tile_count',
+ },
+ {
+ width: 48,
+ render: (_, dashboard) => (
+ <More
+ data-attr="cross-project-dashboard-list-more"
+ overlay={
+ <LemonButton
+ status="danger"
+ fullWidth
+ onClick={() => deleteDashboard(dashboard)}
+ data-attr="cross-project-dashboard-list-delete"
+ >
+ Delete dashboard
+ </LemonButton>
+ }
+ />
+ ),
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-4">
+ <LemonTable
+ dataSource={dashboards}
+ columns={columns}
+ loading={dashboardsLoading}
+ data-attr="cross-project-dashboards-table"
+ emptyState="No cross-project dashboards yet. Create one to put insights from several projects on one page."
+ />
+ <LemonModal
+ isOpen={isNewModalOpen}
+ onClose={closeNewModal}
+ title="New cross-project dashboard"
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeNewModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={createDashboard}
+ disabledReason={!newName.trim() ? 'Give the dashboard a name first' : undefined}
+ loading={isCreating}
+ data-attr="cross-project-dashboard-new-confirm"
+ >
+ Create
+ </LemonButton>
+ </>
+ }
+ >
+ <LemonInput
+ value={newName}
+ onChange={setNewName}
+ placeholder="Company overview"
+ autoFocus
+ data-attr="cross-project-dashboard-new-name"
+ />
+ </LemonModal>
+ </div>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardsScene.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardsScene.tsx
new file mode 100644
index 000000000000..3481d09ed573
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardsScene.tsx
@@ -0,0 +1,38 @@
+import { useValues } from 'kea'
+
+import { NotFound } from 'lib/components/NotFound'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { CrossProjectDashboardsList } from './CrossProjectDashboardsList'
+import { crossProjectDashboardsListLogic } from './crossProjectDashboardsListLogic'
+import { NewCrossProjectDashboardButton } from './NewCrossProjectDashboardButton'
+
+export const scene: SceneExport = {
+ component: CrossProjectDashboardsScene,
+ logic: crossProjectDashboardsListLogic,
+}
+
+export function CrossProjectDashboardsScene(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ if (!featureFlags[FEATURE_FLAGS.CROSS_PROJECT_DASHBOARDS]) {
+ return <NotFound object="page" />
+ }
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Cross-project dashboards"
+ description="Put insights from several projects on one page. Each tile shows one project."
+ resourceType={{ type: 'dashboard' }}
+ actions={<NewCrossProjectDashboardButton />}
+ />
+ <CrossProjectDashboardsList />
+ </SceneContent>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectTile.test.tsx b/products/cross_project_dashboards/frontend/CrossProjectTile.test.tsx
new file mode 100644
index 000000000000..ed0b2eb72ac8
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectTile.test.tsx
@@ -0,0 +1,153 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { CrossProjectTile } from './CrossProjectTile'
+import * as tileFetch from './crossProjectTileFetch'
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+jest.mock('lib/components/Cards/InsightCard/InsightCard', () => ({
+ InsightCard: ({
+ insight,
+ ribbonColor,
+ projectId,
+ className,
+ children,
+ }: {
+ insight: { name: string }
+ ribbonColor?: string | null
+ projectId?: number
+ className?: string
+ children?: React.ReactNode
+ }) => (
+ <div
+ data-attr="insight-card"
+ data-ribbon={ribbonColor ?? 'none'}
+ data-project={projectId ?? 'none'}
+ className={className}
+ >
+ {insight.name}
+ {children}
+ </div>
+ ),
+}))
+
+const tile = (overrides: Partial<CrossProjectDashboardTileApi> = {}): CrossProjectDashboardTileApi =>
+ ({
+ id: 'tile-1',
+ project_id: 42,
+ insight_id: 7,
+ layouts: {},
+ color: null,
+ filters_overrides: {},
+ ...overrides,
+ }) as CrossProjectDashboardTileApi
+
+describe('CrossProjectTile', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it('renders the insight once its project answers', async () => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue({
+ insight: { name: 'Signups' } as any,
+ unavailable: null,
+ })
+
+ render(<CrossProjectTile tile={tile()} />)
+
+ await waitFor(() => expect(screen.getByText('Signups')).toBeInTheDocument())
+ })
+
+ it('gives the insight card the tile color, so a stored color is actually shown', async () => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue({
+ insight: { name: 'Signups' } as any,
+ unavailable: null,
+ })
+
+ render(<CrossProjectTile tile={tile({ color: 'green' })} />)
+
+ await waitFor(() => expect(screen.getByText('Signups')).toBeInTheDocument())
+ expect(document.querySelector('[data-attr="insight-card"]')).toHaveAttribute('data-ribbon', 'green')
+ })
+
+ it('tells the card which project the insight lives in, so its links open that project', async () => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue({
+ insight: { name: 'Signups' } as any,
+ unavailable: null,
+ })
+
+ render(<CrossProjectTile tile={tile({ project_id: 54 })} />)
+
+ await waitFor(() => expect(screen.getByText('Signups')).toBeInTheDocument())
+ expect(document.querySelector('[data-attr="insight-card"]')).toHaveAttribute('data-project', '54')
+ })
+
+ it.each([
+ ['a loaded insight', { insight: { name: 'Signups' } as any, unavailable: null }, '[data-attr="insight-card"]'],
+ [
+ 'an unavailable insight',
+ { insight: null, unavailable: 'no-access' as const },
+ '[data-attr="cross-project-tile-unavailable"]',
+ ],
+ ])('puts the grid class and handles on the card itself for %s', async (_label, result, cardSelector) => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue(result)
+
+ render(
+ <CrossProjectTile tile={tile()} className="react-grid-item">
+ <span data-attr="grid-resize-handle" />
+ </CrossProjectTile>
+ )
+
+ await waitFor(() => expect(document.querySelector(cardSelector)).toBeInTheDocument())
+ const card = document.querySelector(cardSelector)
+ expect(card).toHaveClass('react-grid-item')
+ expect(card?.querySelector('[data-attr="grid-resize-handle"]')).toBeInTheDocument()
+ })
+
+ it('renders an unavailable tile without a name when access is denied', async () => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue({
+ insight: null,
+ unavailable: 'no-access',
+ })
+
+ render(<CrossProjectTile tile={tile()} projectName="Hedgebox EU" />)
+
+ await waitFor(() => expect(screen.getByText(/do not have access/i)).toBeInTheDocument())
+ expect(screen.queryByText('Signups')).not.toBeInTheDocument()
+ expect(screen.queryByText('Hedgebox EU')).not.toBeInTheDocument()
+ })
+
+ it('renders an unavailable tile when the insight is gone', async () => {
+ jest.spyOn(tileFetch, 'fetchCrossProjectTile').mockResolvedValue({
+ insight: null,
+ unavailable: 'not-found',
+ })
+
+ render(<CrossProjectTile tile={tile()} />)
+
+ await waitFor(() => expect(screen.getByText(/no longer exists/i)).toBeInTheDocument())
+ })
+
+ it('fetches from the tile own project, with the tile override over the dashboard filters', async () => {
+ const spy = jest
+ .spyOn(tileFetch, 'fetchCrossProjectTile')
+ .mockResolvedValue({ insight: { name: 'X' } as any, unavailable: null })
+
+ render(
+ <CrossProjectTile
+ tile={tile({ project_id: 99, insight_id: 3, filters_overrides: { date_from: '-7d' } })}
+ dashboardFilters={{ date_from: '-30d', interval: 'week' }}
+ />
+ )
+
+ await waitFor(() => expect(spy).toHaveBeenCalledWith(99, 3, { date_from: '-7d', interval: 'week' }))
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx
new file mode 100644
index 000000000000..dddd69e4a99a
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx
@@ -0,0 +1,196 @@
+import clsx from 'clsx'
+import React, { useEffect, useState } from 'react'
+
+import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+
+import { CardMeta, Resizeable } from 'lib/components/Cards/CardMeta'
+import { DashboardResizeHandles } from 'lib/components/Cards/handles'
+import { EditModeEdge, EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
+import { InsightCard, type InsightCardProps } from 'lib/components/Cards/InsightCard/InsightCard'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { InsightErrorState } from 'scenes/insights/EmptyStates/EmptyStates'
+
+import { DashboardPlacement, type DashboardTile, type InsightColor, type InsightModel } from '~/types'
+
+import type { CrossProjectDashboardFilters } from './crossProjectDashboardLogic'
+import type { TileUnavailableReason } from './crossProjectTileFetch'
+import { fetchCrossProjectTile } from './crossProjectTileFetch'
+import { mergeTileFilters } from './crossProjectTileFilters'
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+// The card forwards refs, but its export's type hides that, and the grid needs the ref to drag the card.
+const GridInsightCard = InsightCard as unknown as React.ForwardRefExoticComponent<
+ InsightCardProps & React.RefAttributes<HTMLDivElement>
+>
+
+const UNAVAILABLE_COPY: Record<TileUnavailableReason, string> = {
+ 'no-access': 'You do not have access to this insight. Ask an admin of its project for access.',
+ 'not-found': 'This insight no longer exists. Remove the tile or point it at another insight.',
+ failed: 'This tile could not load. Refresh the page to try again.',
+}
+
+/** The card reads only `id`, `filters_overrides` and `show_description`, and our id is a UUID where `DashboardTile` declares a number. */
+function asCardTile(tile: CrossProjectDashboardTileApi): DashboardTile {
+ return {
+ id: tile.id,
+ filters_overrides: tile.filters_overrides,
+ show_description: null,
+ color: tile.color,
+ layouts: tile.layouts,
+ } as unknown as DashboardTile
+}
+
+/** react-grid-layout injects style, className, mouse handlers, ref and resize handles into its direct child. */
+export interface CrossProjectTileProps extends React.HTMLAttributes<HTMLDivElement>, Resizeable {
+ tile: CrossProjectDashboardTileApi
+ projectName?: string
+ projectTimezone?: string
+ /** True when the dashboard's tiles do not all share one time zone. */
+ showTimezone?: boolean
+ missingPropertyKeys?: string[]
+ dashboardFilters?: CrossProjectDashboardFilters
+ isResizing?: boolean
+ canEnterEditModeFromEdge?: boolean
+ onEnterEditModeFromEdge?: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => void
+ onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
+ onSetColor?: (color: InsightColor | null) => void
+ onSetOverride?: () => void
+ onRemove?: () => void
+}
+
+function CrossProjectTileInternal(
+ {
+ tile,
+ projectName,
+ projectTimezone,
+ showTimezone,
+ missingPropertyKeys,
+ dashboardFilters,
+ isResizing,
+ canEnterEditModeFromEdge,
+ onEnterEditModeFromEdge,
+ onDragHandleMouseDown,
+ onSetColor,
+ onSetOverride,
+ onRemove,
+ showResizeHandles,
+ className,
+ children,
+ ...divProps
+ }: CrossProjectTileProps,
+ ref: React.ForwardedRef<HTMLDivElement>
+): JSX.Element {
+ const [insight, setInsight] = useState<InsightModel | null>(null)
+ const [unavailable, setUnavailable] = useState<TileUnavailableReason | null>(null)
+ const [loading, setLoading] = useState(true)
+
+ const filters = mergeTileFilters(dashboardFilters, tile.filters_overrides as CrossProjectDashboardFilters)
+ // Compared by value, so a re-render that rebuilds the filters object does not refetch the tile.
+ const filtersKey = JSON.stringify(filters)
+
+ useEffect(() => {
+ let cancelled = false
+ setLoading(true)
+ const parsed = filtersKey === '{}' ? undefined : JSON.parse(filtersKey)
+ void fetchCrossProjectTile(tile.project_id, tile.insight_id, parsed).then((result) => {
+ if (cancelled) {
+ return
+ }
+ setInsight(result.insight)
+ setUnavailable(result.unavailable)
+ setLoading(false)
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [tile.project_id, tile.insight_id, filtersKey])
+
+ // Each tile answers from one project, so the project has to stay visible: without it two
+ // tiles side by side read as one combined number. An unreachable insight gets no label,
+ // because the reader is not entitled to the project's name either.
+ const projectHeading =
+ insight && projectName ? (
+ <span className="flex items-center gap-1 min-w-0" data-attr="cross-project-tile-meta">
+ <span className="truncate">{projectName}</span>
+ {showTimezone && projectTimezone ? (
+ <Tooltip
+ title={`This project reports in ${projectTimezone}. Tiles in other time zones cover different day boundaries.`}
+ >
+ <LemonTag type="muted" size="small">
+ {projectTimezone}
+ </LemonTag>
+ </Tooltip>
+ ) : null}
+ {missingPropertyKeys?.length ? (
+ <Tooltip
+ title={`This project has never recorded ${missingPropertyKeys.join(', ')}, so the filter matches nothing here.`}
+ >
+ <LemonTag type="warning" size="small" data-attr="cross-project-tile-missing-key">
+ Filter not in this project
+ </LemonTag>
+ </Tooltip>
+ ) : null}
+ </span>
+ ) : null
+
+ if (insight && !unavailable && !loading) {
+ return (
+ <GridInsightCard
+ ref={ref}
+ // The card spreads the grid's mouse handlers onto its root, but its props type does not declare them.
+ {...(divProps as Pick<InsightCardProps, 'style'>)}
+ className={className}
+ insight={insight}
+ tile={asCardTile(tile)}
+ projectId={tile.project_id}
+ contextHeading={projectHeading}
+ ribbonColor={tile.color as InsightColor | null}
+ updateColor={onSetColor ? (color) => onSetColor(color ?? null) : undefined}
+ setOverride={onSetOverride}
+ removeFromDashboard={onRemove}
+ showResizeHandles={showResizeHandles}
+ isResizing={isResizing}
+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}
+ onDragHandleMouseDown={onDragHandleMouseDown}
+ placement={DashboardPlacement.Dashboard}
+ >
+ {children}
+ </GridInsightCard>
+ )
+ }
+
+ // Loading and unavailable tiles keep the card's shell, so they drag and resize like the rest.
+ return (
+ <div
+ className={clsx('DashboardTileCard InsightCard border', className)}
+ data-attr={loading ? 'cross-project-tile-loading' : 'cross-project-tile-unavailable'}
+ ref={ref}
+ {...divProps}
+ >
+ <CardMeta
+ showEditingControls={!!onRemove}
+ onMouseDown={onDragHandleMouseDown}
+ moreButtons={
+ onRemove ? (
+ <LemonButton status="danger" onClick={onRemove} fullWidth>
+ Remove from dashboard
+ </LemonButton>
+ ) : undefined
+ }
+ />
+ {loading ? (
+ <LemonSkeleton className="flex-1 m-2" />
+ ) : (
+ <InsightErrorState title={UNAVAILABLE_COPY[unavailable ?? 'failed']} excludeDetail />
+ )}
+ {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
+ )}
+ {showResizeHandles && <DashboardResizeHandles />}
+ {children}
+ </div>
+ )
+}
+
+export const CrossProjectTile = React.forwardRef<HTMLDivElement, CrossProjectTileProps>(CrossProjectTileInternal)
diff --git a/products/cross_project_dashboards/frontend/NewCrossProjectDashboardButton.tsx b/products/cross_project_dashboards/frontend/NewCrossProjectDashboardButton.tsx
new file mode 100644
index 000000000000..1818b9845481
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/NewCrossProjectDashboardButton.tsx
@@ -0,0 +1,16 @@
+import { useActions } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { crossProjectDashboardsListLogic } from './crossProjectDashboardsListLogic'
+
+/** The page header action wherever the cross-project list shows. The list renders the modal it opens. */
+export function NewCrossProjectDashboardButton(): JSX.Element {
+ const { openNewModal } = useActions(crossProjectDashboardsListLogic)
+
+ return (
+ <LemonButton type="primary" size="small" onClick={openNewModal} data-attr="cross-project-dashboard-new">
+ New cross-project dashboard
+ </LemonButton>
+ )
+}
diff --git a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts
new file mode 100644
index 000000000000..77945b135197
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts
@@ -0,0 +1,104 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+
+import { addCrossProjectTileLogic } from './addCrossProjectTileLogic'
+import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
+import { crossProjectDashboardsRetrieve } from './generated/api'
+
+jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))
+
+jest.mock('products/product_analytics/frontend/generated/api', () => ({
+ __esModule: true,
+ insightsList: jest.fn(),
+}))
+
+jest.mock('./generated/api', () => ({
+ __esModule: true,
+ crossProjectDashboardsRetrieve: jest.fn(),
+}))
+
+const mockedDialogOpen = LemonDialog.open as jest.Mock
+const mockedInsightsList = insightsList as jest.Mock
+const mockedRetrieve = crossProjectDashboardsRetrieve as jest.Mock
+
+const DASHBOARD_ID = '01a0f19d-1c44-715a-a679-188869bd033f'
+
+const TILE = { id: 'tile-1', project_id: 53, insight_id: 266, layouts: {}, color: null, filters_overrides: {} }
+
+describe('addCrossProjectTileLogic', () => {
+ let dashboardLogic: ReturnType<typeof crossProjectDashboardLogic.build>
+ let logic: ReturnType<typeof addCrossProjectTileLogic.build>
+
+ beforeEach(async () => {
+ mockedDialogOpen.mockReset()
+ mockedInsightsList.mockReset()
+ mockedRetrieve.mockResolvedValue({ id: DASHBOARD_ID, name: 'Across projects', filters: {}, tiles: [TILE] })
+ initKeaTests()
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({ id: 'org-1', name: 'Org' } as any)
+ dashboardLogic = crossProjectDashboardLogic({ id: DASHBOARD_ID })
+ dashboardLogic.mount()
+ logic = addCrossProjectTileLogic({ dashboardId: DASHBOARD_ID })
+ logic.mount()
+ await expectLogic(dashboardLogic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ dashboardLogic.unmount()
+ })
+
+ it('asks before an added insight reloads the dashboard over unsaved layout changes', () => {
+ dashboardLogic.actions.enterLayoutEdit()
+ dashboardLogic.actions.setPendingLayouts({ sm: [{ i: 'tile-1', x: 6, y: 0, w: 6, h: 5 }] })
+
+ logic.actions.requestOpenModal()
+
+ expect(logic.values.isOpen).toBe(false)
+ expect(dashboardLogic.values.layoutEditMode).toBe(true)
+
+ mockedDialogOpen.mock.calls[0][0].primaryButton.onClick()
+
+ expect(logic.values.isOpen).toBe(true)
+ expect(dashboardLogic.values.layoutEditMode).toBe(false)
+ })
+
+ it('finds an insight past the first page by searching the selected project and loading more', async () => {
+ // One insight per page, numbered by offset, with a second page only for the search.
+ mockedInsightsList.mockImplementation(async (_projectId, params) => ({
+ results: [{ id: params.offset + 1, name: `${params.search ?? 'all'} ${params.offset + 1}` }],
+ next: params.search && params.offset === 0 ? 'next-page' : null,
+ }))
+
+ logic.actions.setProjectId(54)
+ logic.actions.setInsightSearch('signups')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedInsightsList).toHaveBeenLastCalledWith(
+ '54',
+ expect.objectContaining({ search: 'signups', offset: 0 })
+ )
+ expect(logic.values.insightPage).toEqual({ insights: [{ id: 1, name: 'signups 1' }], hasMore: true })
+
+ logic.actions.loadMoreInsights()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedInsightsList).toHaveBeenLastCalledWith(
+ '54',
+ expect.objectContaining({ search: 'signups', offset: 1 })
+ )
+ expect(logic.values.insightPage).toEqual({
+ insights: [
+ { id: 1, name: 'signups 1' },
+ { id: 2, name: 'signups 2' },
+ ],
+ hasMore: false,
+ })
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts
new file mode 100644
index 000000000000..63bd32992d66
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts
@@ -0,0 +1,290 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import type { LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+
+import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
+import { crossProjectDashboardsTilesCreate } from './generated/api'
+
+export interface InsightOption {
+ id: number
+ name: string
+}
+
+export interface InsightPage {
+ insights: InsightOption[]
+ hasMore: boolean
+}
+
+export interface AddCrossProjectTileLogicProps {
+ dashboardId: string
+}
+
+const INSIGHT_PAGE_SIZE = 50
+const INSIGHT_SEARCH_DEBOUNCE_MS = 300
+const EMPTY_INSIGHT_PAGE: InsightPage = { insights: [], hasMore: false }
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface addCrossProjectTileLogicValues {
+ canAdd: boolean
+ insightOptions: LemonInputSelectOption[]
+ insightPage: InsightPage
+ insightPageLoading: boolean
+ insightSearch: string
+ isAdding: boolean
+ isOpen: boolean
+ projectId: number | null
+ projectOptions: {
+ label: string
+ value: number
+ }[]
+ selectedInsight: InsightOption | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface addCrossProjectTileLogicActions {
+ addTile: () => {
+ value: true
+ }
+ addTileFailure: () => {
+ value: true
+ }
+ closeModal: () => {
+ value: true
+ }
+ loadInsights: () => any
+ loadInsightsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadInsightsSuccess: (
+ insightPage: InsightPage,
+ payload?: any
+ ) => {
+ insightPage: InsightPage
+ payload?: any
+ }
+ loadMoreInsights: () => any
+ loadMoreInsightsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreInsightsSuccess: (
+ insightPage: InsightPage,
+ payload?: any
+ ) => {
+ insightPage: InsightPage
+ payload?: any
+ }
+ openModal: () => {
+ value: true
+ }
+ requestOpenModal: () => {
+ value: true
+ }
+ setInsight: (insight: InsightOption | null) => {
+ insight: InsightOption | null
+ }
+ setInsightSearch: (search: string) => {
+ search: string
+ }
+ setProjectId: (projectId: number | null) => {
+ projectId: number | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface addCrossProjectTileLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ projectOptions: (currentOrganization: null | import('~/types').OrganizationType) => {
+ label: string
+ value: number
+ }[]
+ insightOptions: (insightPage: InsightPage, selectedInsight: InsightOption | null) => LemonInputSelectOption[]
+ canAdd: (projectId: number | null, selectedInsight: InsightOption | null) => boolean
+ }
+}
+
+export type addCrossProjectTileLogicType = MakeLogicType<
+ addCrossProjectTileLogicValues,
+ addCrossProjectTileLogicActions,
+ AddCrossProjectTileLogicProps,
+ addCrossProjectTileLogicMeta
+>
+
+export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([
+ path((key) => ['products', 'cross_project_dashboards', 'frontend', 'addCrossProjectTileLogic', key]),
+ props({} as AddCrossProjectTileLogicProps),
+ key((props) => props.dashboardId),
+ actions({
+ requestOpenModal: true,
+ openModal: true,
+ closeModal: true,
+ setProjectId: (projectId: number | null) => ({ projectId }),
+ setInsightSearch: (search: string) => ({ search }),
+ setInsight: (insight: InsightOption | null) => ({ insight }),
+ addTile: true,
+ addTileFailure: true,
+ }),
+ reducers({
+ isOpen: [false, { openModal: () => true, closeModal: () => false }],
+ projectId: [null as number | null, { setProjectId: (_, { projectId }) => projectId, closeModal: () => null }],
+ insightSearch: [
+ '',
+ {
+ setInsightSearch: (_, { search }) => search,
+ setProjectId: () => '',
+ closeModal: () => '',
+ },
+ ],
+ selectedInsight: [
+ null as InsightOption | null,
+ {
+ setInsight: (_, { insight }) => insight,
+ setProjectId: () => null,
+ closeModal: () => null,
+ },
+ ],
+ isAdding: [false, { addTile: () => true, addTileFailure: () => false, closeModal: () => false }],
+ }),
+ loaders(({ values }) => {
+ const fetchInsightPage = async (projectId: number, search: string, offset: number): Promise<InsightPage> => {
+ const response = await insightsList(String(projectId), {
+ basic: true,
+ limit: INSIGHT_PAGE_SIZE,
+ offset,
+ search: search.trim() || undefined,
+ })
+ return {
+ insights: response.results.map((insight) => ({
+ id: insight.id,
+ name: insight.name || insight.derived_name || `Insight ${insight.id}`,
+ })),
+ hasMore: !!response.next,
+ }
+ }
+
+ // A response for a project or search the person has since changed belongs to a different list.
+ const isStale = (projectId: number, search: string): boolean =>
+ values.projectId !== projectId || values.insightSearch !== search
+
+ return {
+ insightPage: [
+ EMPTY_INSIGHT_PAGE,
+ {
+ loadInsights: async (): Promise<InsightPage> => {
+ const { projectId, insightSearch } = values
+ if (!projectId) {
+ return EMPTY_INSIGHT_PAGE
+ }
+ const page = await fetchInsightPage(projectId, insightSearch, 0)
+ return isStale(projectId, insightSearch) ? values.insightPage : page
+ },
+ loadMoreInsights: async (): Promise<InsightPage> => {
+ const { projectId, insightSearch, insightPage } = values
+ if (!projectId) {
+ return insightPage
+ }
+ const next = await fetchInsightPage(projectId, insightSearch, insightPage.insights.length)
+ if (isStale(projectId, insightSearch)) {
+ return values.insightPage
+ }
+ return { insights: [...values.insightPage.insights, ...next.insights], hasMore: next.hasMore }
+ },
+ },
+ ],
+ }
+ }),
+ selectors({
+ projectOptions: [
+ () => [organizationLogic.selectors.currentOrganization],
+ (organization: null | import('~/types').OrganizationType) =>
+ (organization?.projects ?? []).map((project) => ({ value: project.id, label: project.name })),
+ ],
+ // Keeps the picked insight in the options, so the field still shows its name after the search moves on.
+ insightOptions: [
+ (s) => [s.insightPage, s.selectedInsight],
+ (insightPage: InsightPage, selectedInsight: InsightOption | null): LemonInputSelectOption[] => {
+ const insights =
+ selectedInsight && !insightPage.insights.some((insight) => insight.id === selectedInsight.id)
+ ? [selectedInsight, ...insightPage.insights]
+ : insightPage.insights
+ return insights.map((insight) => ({ key: String(insight.id), label: insight.name }))
+ },
+ ],
+ canAdd: [
+ (s) => [s.projectId, s.selectedInsight],
+ (projectId: number | null, selectedInsight: InsightOption | null) => !!projectId && !!selectedInsight,
+ ],
+ }),
+ listeners(({ values, props, actions }) => ({
+ requestOpenModal: () => {
+ const dashboardLogic = crossProjectDashboardLogic.findMounted({ id: props.dashboardId })
+ // Adding a tile reloads the dashboard, and the reload drops any layout edit in progress.
+ const leaveLayoutEditAndOpen = (): void => {
+ if (dashboardLogic?.values.layoutEditMode) {
+ dashboardLogic.actions.exitLayoutEdit()
+ }
+ actions.openModal()
+ }
+ if (!dashboardLogic?.values.hasUnsavedLayoutChanges) {
+ leaveLayoutEditAndOpen()
+ return
+ }
+ LemonDialog.open({
+ title: 'Discard unsaved changes?',
+ description:
+ 'You have unsaved layout changes. Adding an insight reloads the dashboard and discards them.',
+ primaryButton: {
+ children: 'Discard changes',
+ status: 'danger',
+ onClick: leaveLayoutEditAndOpen,
+ 'data-attr': 'cross-project-dashboard-add-tile-discard-confirm',
+ },
+ secondaryButton: { children: 'Keep editing' },
+ })
+ },
+ setProjectId: () => {
+ actions.loadInsights()
+ },
+ setInsightSearch: async (_, breakpoint) => {
+ await breakpoint(INSIGHT_SEARCH_DEBOUNCE_MS)
+ actions.loadInsights()
+ },
+ addTile: async () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId || !values.projectId || !values.selectedInsight) {
+ actions.closeModal()
+ return
+ }
+ try {
+ await crossProjectDashboardsTilesCreate(organizationId, props.dashboardId, {
+ project_id: values.projectId,
+ insight_id: values.selectedInsight.id,
+ } as any)
+ actions.closeModal()
+ // findMounted, not a direct reference: referencing another logic's actions
+ // mounts it and fires its afterMount.
+ crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.actions.loadDashboard()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not add that insight. Try again.')
+ actions.addTileFailure()
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadInsights()
+ }),
+])
diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardActivityDescriber.tsx b/products/cross_project_dashboards/frontend/crossProjectDashboardActivityDescriber.tsx
new file mode 100644
index 000000000000..7e73240ac1bf
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardActivityDescriber.tsx
@@ -0,0 +1,145 @@
+import { Link } from '@posthog/lemon-ui'
+
+import {
+ ActivityChange,
+ ActivityLogItem,
+ ActivityLogSummary,
+ ActivityLogUserName,
+ ChangeMapping,
+ Description,
+ HumanizedChange,
+ defaultDescriber,
+ detectBoolean,
+} from 'lib/components/ActivityLog/humanizeActivity'
+import { urls } from 'scenes/urls'
+
+function nameAndLink(logItem?: ActivityLogItem): JSX.Element {
+ return logItem?.item_id ? (
+ <Link to={urls.crossProjectDashboard(String(logItem.item_id))}>
+ {logItem?.detail?.name || 'Unknown dashboard'}
+ </Link>
+ ) : logItem?.detail?.name ? (
+ <>{logItem.detail.name}</>
+ ) : (
+ <i>Unknown dashboard</i>
+ )
+}
+
+function summaryFor(logItem: ActivityLogItem, action: Description): ActivityLogSummary {
+ return {
+ actor: <ActivityLogUserName logItem={logItem} />,
+ action,
+ target: <>Cross-project dashboard · {nameAndLink(logItem)}</>,
+ }
+}
+
+const FIELD_DESCRIBERS: Record<string, (change: ActivityChange, logItem: ActivityLogItem) => ChangeMapping | null> = {
+ name: (change, logItem) => ({
+ description: [
+ <>
+ renamed "{String(change.before)}" to <strong>"{nameAndLink(logItem)}"</strong>
+ </>,
+ ],
+ summary: [
+ <>
+ renamed "{String(change.before)}" to "{String(change.after)}"
+ </>,
+ ],
+ suffix: <></>,
+ }),
+ description: (_change, logItem) => ({
+ description: [<>changed the description of</>],
+ summary: [<>changed the description</>],
+ suffix: <>{nameAndLink(logItem)}</>,
+ }),
+ filters: (_change, logItem) => ({
+ description: [<>changed the filters on</>],
+ summary: [<>changed the filters</>],
+ suffix: <>{nameAndLink(logItem)}</>,
+ }),
+ tiles: (change, logItem) => {
+ const verb = change.action === 'created' ? 'added' : change.action === 'deleted' ? 'removed' : 'changed'
+ const preposition = change.action === 'created' ? 'to' : change.action === 'deleted' ? 'from' : 'on'
+ return {
+ description: [
+ <>
+ {verb} a tile {preposition}
+ </>,
+ ],
+ summary: [<>{verb} a tile</>],
+ suffix: <>{nameAndLink(logItem)}</>,
+ }
+ },
+ deleted: (change, logItem) => {
+ const action = detectBoolean(change.after) ? 'deleted' : 'restored'
+ return {
+ description: [<>{action}</>],
+ summary: [<>{action} the dashboard</>],
+ suffix: <>{nameAndLink(logItem)}</>,
+ }
+ },
+}
+
+export function crossProjectDashboardActivityDescriber(
+ logItem: ActivityLogItem,
+ asNotification?: boolean
+): HumanizedChange {
+ if (logItem.scope !== 'CrossProjectDashboard') {
+ console.error('cross-project dashboard describer received a non-dashboard activity')
+ return { description: null }
+ }
+
+ if (logItem.activity === 'created') {
+ return {
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> created the cross-project dashboard {nameAndLink(logItem)}
+ </>
+ ),
+ summary: summaryFor(logItem, <>created</>),
+ }
+ }
+
+ if (logItem.activity === 'deleted') {
+ return {
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> deleted the cross-project dashboard {logItem.detail.name}
+ </>
+ ),
+ summary: summaryFor(logItem, <>deleted</>),
+ }
+ }
+
+ if (logItem.activity === 'updated') {
+ const descriptions: Description[] = []
+ const summaries: Description[] = []
+ let suffix: Description | undefined
+
+ for (const change of logItem.detail.changes ?? []) {
+ const describe = change.field ? FIELD_DESCRIBERS[change.field] : undefined
+ const mapping = describe?.(change, logItem)
+ if (!mapping?.description) {
+ continue
+ }
+ descriptions.push(...mapping.description)
+ summaries.push(...(mapping.summary ?? mapping.description))
+ suffix = mapping.suffix
+ }
+
+ if (descriptions.length === 0) {
+ return defaultDescriber(logItem, asNotification)
+ }
+
+ return {
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> {descriptions} {suffix}
+ </>
+ ),
+ summary: summaryFor(logItem, <>{summaries}</>),
+ }
+ }
+
+ return defaultDescriber(logItem, asNotification)
+}
diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts
new file mode 100644
index 000000000000..fe7463ec6631
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts
@@ -0,0 +1,228 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
+import {
+ crossProjectDashboardsDestroy,
+ crossProjectDashboardsPartialUpdate,
+ crossProjectDashboardsRetrieve,
+ crossProjectDashboardsTilesPartialUpdate,
+} from './generated/api'
+
+jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))
+
+jest.mock('./generated/api', () => ({
+ __esModule: true,
+ crossProjectDashboardsDestroy: jest.fn(),
+ crossProjectDashboardsRetrieve: jest.fn(),
+ crossProjectDashboardsPartialUpdate: jest.fn(),
+ crossProjectDashboardsTilesDestroy: jest.fn(),
+ crossProjectDashboardsTilesPartialUpdate: jest.fn(),
+}))
+
+const mockedDialogOpen = LemonDialog.open as jest.Mock
+const mockedDestroy = crossProjectDashboardsDestroy as jest.Mock
+const mockedRetrieve = crossProjectDashboardsRetrieve as jest.Mock
+const mockedPartialUpdate = crossProjectDashboardsPartialUpdate as jest.Mock
+const mockedTilePartialUpdate = crossProjectDashboardsTilesPartialUpdate as jest.Mock
+
+const DASHBOARD_ID = '01a0f19d-1c44-715a-a679-188869bd033f'
+
+const TILE = { id: 'tile-1', project_id: 53, insight_id: 266, layouts: {}, color: null, filters_overrides: {} }
+
+const dashboardWith = (filters: Record<string, unknown>): Record<string, unknown> => ({
+ id: DASHBOARD_ID,
+ name: 'Pageviews across projects',
+ filters,
+ tiles: [TILE],
+})
+
+describe('crossProjectDashboardLogic', () => {
+ let logic: ReturnType<typeof crossProjectDashboardLogic.build>
+
+ // The mock persists what it was sent, so a reload reads back the saved filters as the API would.
+ let stored: Record<string, unknown> = {}
+
+ const mountWith = async (filters: Record<string, unknown>): Promise<void> => {
+ stored = filters
+ logic = crossProjectDashboardLogic({ id: DASHBOARD_ID })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ mockedDialogOpen.mockReset()
+ mockedDestroy.mockReset()
+ mockedRetrieve.mockReset()
+ mockedPartialUpdate.mockReset()
+ mockedTilePartialUpdate.mockReset()
+ mockedTilePartialUpdate.mockImplementation(async (_org, _id, tileId, body) => ({
+ ...TILE,
+ id: tileId,
+ ...body,
+ }))
+ stored = {}
+ mockedRetrieve.mockImplementation(async () => dashboardWith(stored))
+ mockedPartialUpdate.mockImplementation(async (_org, _id, body) => {
+ stored = body.filters
+ return dashboardWith(stored)
+ })
+ initKeaTests()
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({ id: 'org-1', name: 'Org' } as any)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // A date change must not clobber the rest of the blob, and must not write a bound nobody chose:
+ // the backend also stores property filters here, and a null bound would override each insight's own.
+ it.each([
+ ['drops the bound that was not chosen', {}, '-7d', null, { date_from: '-7d' }],
+ ['replaces a previous range', { date_from: '-30d' }, '-7d', null, { date_from: '-7d' }],
+ [
+ 'keeps filters it does not own',
+ { properties: [{ type: 'event', key: 'browser', value: 'Chrome' }] },
+ '-7d',
+ null,
+ { properties: [{ type: 'event', key: 'browser', value: 'Chrome' }], date_from: '-7d' },
+ ],
+ ['clears both bounds', { date_from: '-7d', date_to: '-1d' }, null, null, {}],
+ [
+ 'writes an explicit range',
+ {},
+ '2026-01-01',
+ '2026-01-31',
+ { date_from: '2026-01-01', date_to: '2026-01-31' },
+ ],
+ ])('setDates %s', async (_name, existing, dateFrom, dateTo, expected) => {
+ await mountWith(existing as Record<string, unknown>)
+
+ logic.actions.setDates(dateFrom as string | null, dateTo as string | null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedPartialUpdate).toHaveBeenCalledTimes(1)
+ expect(mockedPartialUpdate.mock.calls[0][2]).toEqual({ filters: expected })
+ })
+
+ it('puts the saved filters in state, so the tiles refetch on the new range', async () => {
+ await mountWith({})
+
+ logic.actions.setDates('-7d', null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.dashboardFilters).toEqual({ date_from: '-7d' })
+ })
+
+ it('keeps both of two quick filter edits instead of letting the second overwrite the first', async () => {
+ await mountWith({})
+
+ logic.actions.setDates('-7d', null)
+ logic.actions.setInterval('week')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedPartialUpdate).toHaveBeenLastCalledWith('org-1', DASHBOARD_ID, {
+ filters: { date_from: '-7d', interval: 'week' },
+ })
+ expect(logic.values.dashboardFilters).toEqual({ date_from: '-7d', interval: 'week' })
+ })
+ it.each([
+ [
+ 'a tile override',
+ (l: typeof logic) => l.actions.setTileOverride('tile-1', { date_from: '-7d' }),
+ { filters_overrides: { date_from: '-7d' } },
+ ],
+ ['a tile color', (l: typeof logic) => l.actions.setTileColor('tile-1', 'green'), { color: 'green' }],
+ ])('saves %s on the tile and updates it in place, without reloading', async (_label, act, body) => {
+ await mountWith({})
+ expect(mockedRetrieve).toHaveBeenCalledTimes(1)
+
+ act(logic)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedTilePartialUpdate).toHaveBeenCalledWith('org-1', DASHBOARD_ID, 'tile-1', body)
+ expect(mockedRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.tiles[0]).toMatchObject(body)
+ })
+ it.each([
+ ['opens the cross-project tab of the dashboards page', async () => undefined, true],
+ [
+ 'stays on the dashboard when the delete fails',
+ async () => {
+ throw { detail: 'You cannot delete this dashboard.' }
+ },
+ false,
+ ],
+ ])('a confirmed delete %s', async (_label, destroy, navigates) => {
+ mockedDestroy.mockImplementation(destroy)
+ await mountWith({})
+
+ logic.actions.deleteDashboard()
+ expect(mockedDestroy).not.toHaveBeenCalled()
+ await mockedDialogOpen.mock.calls[0][0].primaryButton.onClick().catch(() => {})
+
+ expect(mockedDestroy).toHaveBeenCalledWith('org-1', DASHBOARD_ID)
+ expect(router.values.location.pathname.endsWith('/dashboard')).toBe(navigates)
+ expect(router.values.searchParams.tab).toEqual(navigates ? 'cross-project' : undefined)
+ })
+ const MOVED = { sm: [{ i: 'tile-1', x: 6, y: 0, w: 6, h: 5 }] }
+
+ it.each([
+ ['Save layout writes the move once and leaves edit mode', 'saveLayout', true, { x: 6, y: 0 }],
+ ['Cancel writes nothing and puts the tile back', 'cancelLayoutEdit', false, { x: 0, y: 0 }],
+ ] as const)('%s', async (_label, finish, writes, gridPosition) => {
+ await mountWith({})
+ logic.actions.enterLayoutEdit()
+ logic.actions.setPendingLayouts(MOVED)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockedTilePartialUpdate).not.toHaveBeenCalled()
+
+ logic.actions[finish]()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedTilePartialUpdate).toHaveBeenCalledTimes(writes ? 1 : 0)
+ expect(mockedRetrieve).toHaveBeenCalledTimes(1)
+ expect(logic.values.layoutEditMode).toBe(false)
+ expect(logic.values.gridLayouts.sm?.[0]).toMatchObject(gridPosition)
+ })
+
+ it('saves nothing when the grid only reports the default position of a tile nobody moved', async () => {
+ await mountWith({})
+ logic.actions.enterLayoutEdit()
+ logic.actions.setPendingLayouts({ sm: [{ i: 'tile-1', x: 0, y: 0, w: 6, h: 5 }] })
+
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
+ logic.actions.saveLayout()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedTilePartialUpdate).not.toHaveBeenCalled()
+ expect(logic.values.layoutEditMode).toBe(false)
+ })
+ it('writes the layout once when Save is pressed again while the first save runs', async () => {
+ let release: () => void = () => {}
+ mockedTilePartialUpdate.mockImplementation(
+ (_org, _id, tileId, body) =>
+ new Promise((resolve) => {
+ release = () => resolve({ ...TILE, id: tileId, ...body })
+ })
+ )
+ await mountWith({})
+ logic.actions.enterLayoutEdit()
+ logic.actions.setPendingLayouts(MOVED)
+
+ logic.actions.saveLayout()
+ logic.actions.saveLayout()
+ expect(logic.values.layoutSaving).toBe(true)
+ release()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedTilePartialUpdate).toHaveBeenCalledTimes(1)
+ expect(logic.values.layoutSaving).toBe(false)
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts
new file mode 100644
index 000000000000..66766f683b9b
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts
@@ -0,0 +1,503 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { beforeUnload, combineUrl, router } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { DashboardsTab } from 'scenes/dashboard/dashboards/dashboardsLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { urls } from 'scenes/urls'
+
+import type { AnyPropertyFilter, IntervalType, TeamBasicType } from '~/types'
+
+import { changedTileLayouts, layoutsDiffer, layoutsForTiles, type ResponsiveTileLayouts } from './crossProjectLayouts'
+import { findMissingPropertyKeys, propertyKeysIn } from './crossProjectPropertyKeys'
+import {
+ crossProjectDashboardsDestroy,
+ crossProjectDashboardsPartialUpdate,
+ crossProjectDashboardsRetrieve,
+ crossProjectDashboardsTilesDestroy,
+ crossProjectDashboardsTilesPartialUpdate,
+} from './generated/api'
+import type {
+ CrossProjectDashboardApi,
+ CrossProjectDashboardTileApi,
+ PatchedCrossProjectDashboardApi,
+} from './generated/api.schemas'
+import { openDeleteCrossProjectDashboardDialog } from './openDeleteCrossProjectDashboardDialog'
+
+export interface CrossProjectDashboardLogicProps {
+ id: string
+}
+
+export interface CrossProjectDashboardFilters {
+ date_from?: string | null
+ date_to?: string | null
+ interval?: IntervalType | null
+ properties?: AnyPropertyFilter[]
+}
+
+export type CrossProjectDashboardDetails = Pick<PatchedCrossProjectDashboardApi, 'name' | 'description'>
+
+export interface CrossProjectTileProject {
+ name: string
+ timezone: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface crossProjectDashboardLogicValues {
+ dashboard: CrossProjectDashboardApi | null
+ dashboardFilters: CrossProjectDashboardFilters
+ dashboardLoading: boolean
+ gridLayouts: Partial<ResponsiveTileLayouts>
+ hasUnsavedLayoutChanges: boolean
+ layoutEditMode: boolean
+ layoutSaving: boolean
+ missingPropertyKeys: Record<number, string[]>
+ missingPropertyKeysLoading: boolean
+ pendingLayouts: Partial<ResponsiveTileLayouts> | null
+ projectIds: number[]
+ savedLayouts: ResponsiveTileLayouts
+ tileProjects: Record<number, CrossProjectTileProject>
+ tiles: readonly CrossProjectDashboardTileApi[]
+ timezonesDiverge: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface crossProjectDashboardLogicActions {
+ cancelLayoutEdit: () => {
+ value: true
+ }
+ checkPropertyKeys: () => any
+ checkPropertyKeysFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ checkPropertyKeysSuccess: (
+ missingPropertyKeys: Record<number, string[]>,
+ payload?: any
+ ) => {
+ missingPropertyKeys: Record<number, string[]>
+ payload?: any
+ }
+ deleteDashboard: () => {
+ value: true
+ }
+ enterLayoutEdit: () => {
+ value: true
+ }
+ exitLayoutEdit: () => {
+ value: true
+ }
+ loadDashboard: () => {
+ value: true
+ }
+ loadDashboardFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDashboardSuccess: (
+ dashboard: CrossProjectDashboardApi | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ dashboard: CrossProjectDashboardApi | null
+ payload?: {
+ value: true
+ }
+ }
+ removeTile: (tileId: string) => {
+ tileId: string
+ }
+ saveLayout: () => {
+ value: true
+ }
+ saveLayoutFailed: () => {
+ value: true
+ }
+ saveLayoutStarted: () => {
+ value: true
+ }
+ setDates: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ }
+ setInterval: (interval: IntervalType | null) => {
+ interval: IntervalType | null
+ }
+ setPendingLayouts: (layouts: Partial<ResponsiveTileLayouts>) => {
+ layouts: Partial<ResponsiveTileLayouts>
+ }
+ setProperties: (properties: AnyPropertyFilter[]) => {
+ properties: AnyPropertyFilter[]
+ }
+ setTileColor: (
+ tileId: string,
+ color: string | null
+ ) => {
+ color: string | null
+ tileId: string
+ }
+ setTileOverride: (
+ tileId: string,
+ overrides: CrossProjectDashboardFilters
+ ) => {
+ overrides: CrossProjectDashboardFilters
+ tileId: string
+ }
+ updateDashboard: (details: CrossProjectDashboardDetails) => {
+ details: CrossProjectDashboardDetails
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface crossProjectDashboardLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ tiles: (dashboard: CrossProjectDashboardApi | null) => readonly CrossProjectDashboardTileApi[]
+ projectIds: (tiles: readonly CrossProjectDashboardTileApi[]) => number[]
+ dashboardFilters: (dashboard: CrossProjectDashboardApi | null) => CrossProjectDashboardFilters
+ tileProjects: (
+ currentOrganization: null | import('~/types').OrganizationType
+ ) => Record<number, CrossProjectTileProject>
+ timezonesDiverge: (
+ tiles: readonly CrossProjectDashboardTileApi[],
+ tileProjects: Record<number, CrossProjectTileProject>
+ ) => boolean
+ savedLayouts: (tiles: readonly CrossProjectDashboardTileApi[]) => ResponsiveTileLayouts
+ hasUnsavedLayoutChanges: (
+ layoutEditMode: boolean,
+ savedLayouts: ResponsiveTileLayouts,
+ pendingLayouts: Partial<ResponsiveTileLayouts> | null
+ ) => boolean
+ gridLayouts: (
+ hasUnsavedLayoutChanges: boolean,
+ pendingLayouts: Partial<ResponsiveTileLayouts> | null,
+ savedLayouts: ResponsiveTileLayouts
+ ) => Partial<ResponsiveTileLayouts>
+ }
+}
+
+export type crossProjectDashboardLogicType = MakeLogicType<
+ crossProjectDashboardLogicValues,
+ crossProjectDashboardLogicActions,
+ CrossProjectDashboardLogicProps,
+ crossProjectDashboardLogicMeta
+>
+
+export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([
+ path((key) => ['products', 'cross_project_dashboards', 'frontend', 'crossProjectDashboardLogic', key]),
+ props({} as CrossProjectDashboardLogicProps),
+ key((props) => props.id),
+ actions({
+ loadDashboard: true,
+ removeTile: (tileId: string) => ({ tileId }),
+ setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setInterval: (interval: IntervalType | null) => ({ interval }),
+ enterLayoutEdit: true,
+ exitLayoutEdit: true,
+ setPendingLayouts: (layouts: Partial<ResponsiveTileLayouts>) => ({ layouts }),
+ saveLayout: true,
+ saveLayoutStarted: true,
+ saveLayoutFailed: true,
+ cancelLayoutEdit: true,
+ setTileOverride: (tileId: string, overrides: CrossProjectDashboardFilters) => ({ tileId, overrides }),
+ setTileColor: (tileId: string, color: string | null) => ({ tileId, color }),
+ setProperties: (properties: AnyPropertyFilter[]) => ({ properties }),
+ updateDashboard: (details: CrossProjectDashboardDetails) => ({ details }),
+ deleteDashboard: true,
+ }),
+ reducers({
+ layoutEditMode: [false, { enterLayoutEdit: () => true, exitLayoutEdit: () => false }],
+ layoutSaving: [
+ false,
+ { saveLayoutStarted: () => true, saveLayoutFailed: () => false, exitLayoutEdit: () => false },
+ ],
+ pendingLayouts: [
+ null as Partial<ResponsiveTileLayouts> | null,
+ {
+ setPendingLayouts: (_, { layouts }) => layouts,
+ enterLayoutEdit: () => null,
+ exitLayoutEdit: () => null,
+ },
+ ],
+ }),
+ loaders(({ props, values }) => ({
+ missingPropertyKeys: [
+ {} as Record<number, string[]>,
+ {
+ checkPropertyKeys: async () => {
+ return await findMissingPropertyKeys(
+ values.projectIds,
+ propertyKeysIn(values.dashboardFilters.properties)
+ )
+ },
+ },
+ ],
+ dashboard: [
+ null as CrossProjectDashboardApi | null,
+ {
+ loadDashboard: async () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return null
+ }
+ return await crossProjectDashboardsRetrieve(organizationId, props.id)
+ },
+ },
+ ],
+ })),
+ selectors({
+ tiles: [(s) => [s.dashboard], (dashboard: CrossProjectDashboardApi | null) => dashboard?.tiles ?? []],
+ projectIds: [
+ (s) => [s.tiles],
+ (tiles: CrossProjectDashboardTileApi[]) => Array.from(new Set(tiles.map((tile) => tile.project_id))),
+ ],
+ dashboardFilters: [
+ (s) => [s.dashboard],
+ (dashboard: CrossProjectDashboardApi | null) =>
+ ((dashboard?.filters as CrossProjectDashboardFilters | undefined) ??
+ {}) as CrossProjectDashboardFilters,
+ ],
+ // Only projects the organization listing returns, so a project the reader cannot reach
+ // has no entry and its tile stays unlabeled.
+ tileProjects: [
+ () => [organizationLogic.selectors.currentOrganization],
+ (currentOrganization: { teams?: TeamBasicType[] } | null) =>
+ Object.fromEntries(
+ (currentOrganization?.teams ?? []).map((team) => [
+ team.id,
+ { name: team.name, timezone: team.timezone },
+ ])
+ ) as Record<number, CrossProjectTileProject>,
+ ],
+ timezonesDiverge: [
+ (s) => [s.tiles, s.tileProjects],
+ (tiles: readonly CrossProjectDashboardTileApi[], tileProjects: Record<number, CrossProjectTileProject>) => {
+ const zones = new Set(tiles.map((tile) => tileProjects[tile.project_id]?.timezone).filter(Boolean))
+ return zones.size > 1
+ },
+ ],
+ savedLayouts: [(s) => [s.tiles], (tiles: readonly CrossProjectDashboardTileApi[]) => layoutsForTiles(tiles)],
+ hasUnsavedLayoutChanges: [
+ (s) => [s.layoutEditMode, s.savedLayouts, s.pendingLayouts],
+ (
+ layoutEditMode: boolean,
+ savedLayouts: ResponsiveTileLayouts,
+ pendingLayouts: Partial<ResponsiveTileLayouts> | null
+ ) => layoutEditMode && layoutsDiffer(savedLayouts, pendingLayouts),
+ ],
+ // Keeps the grid controlled, so switching back to the saved layout on cancel moves the tiles back.
+ gridLayouts: [
+ (s) => [s.hasUnsavedLayoutChanges, s.pendingLayouts, s.savedLayouts],
+ (
+ hasUnsavedLayoutChanges: boolean,
+ pendingLayouts: Partial<ResponsiveTileLayouts> | null,
+ savedLayouts: ResponsiveTileLayouts
+ ): Partial<ResponsiveTileLayouts> =>
+ hasUnsavedLayoutChanges && pendingLayouts ? pendingLayouts : savedLayouts,
+ ],
+ }),
+ listeners(({ props, actions, values }) => {
+ // Saves send the whole filters object, so they run one at a time to never start from a stale copy.
+ // A rename joins the same queue, so a late response cannot put back filters that a newer save replaced.
+ let saves: Promise<boolean> = Promise.resolve(true)
+ const saveDashboard = (
+ changes: () => PatchedCrossProjectDashboardApi,
+ errorMessage: string
+ ): Promise<boolean> => {
+ saves = saves.then(async () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return false
+ }
+ try {
+ actions.loadDashboardSuccess(
+ await crossProjectDashboardsPartialUpdate(organizationId, props.id, changes())
+ )
+ return true
+ } catch (error: any) {
+ lemonToast.error(error?.detail || errorMessage)
+ actions.loadDashboard()
+ return false
+ }
+ })
+ return saves
+ }
+ const saveFilters = (
+ update: (filters: CrossProjectDashboardFilters) => void,
+ errorMessage: string
+ ): Promise<boolean> =>
+ saveDashboard(() => {
+ const filters: CrossProjectDashboardFilters = { ...values.dashboardFilters }
+ update(filters)
+ return { filters }
+ }, errorMessage)
+
+ const applySavedTiles = (saved: CrossProjectDashboardTileApi[]): void => {
+ if (!values.dashboard) {
+ return
+ }
+ const byId = new Map(saved.map((tile) => [tile.id, tile]))
+ actions.loadDashboardSuccess({
+ ...values.dashboard,
+ tiles: values.dashboard.tiles.map((tile) => byId.get(tile.id) ?? tile),
+ })
+ }
+
+ return {
+ updateDashboard: async ({ details }) => {
+ await saveDashboard(() => details, 'Could not save that change. Try again.')
+ },
+ deleteDashboard: () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId || !values.dashboard) {
+ return
+ }
+ openDeleteCrossProjectDashboardDialog(values.dashboard.name, async () => {
+ await crossProjectDashboardsDestroy(organizationId, props.id)
+ router.actions.push(combineUrl(urls.dashboards(), { tab: DashboardsTab.CrossProject }).url)
+ })
+ },
+ setDates: async ({ dateFrom, dateTo }) => {
+ await saveFilters((filters) => {
+ // An unset bound is dropped, so the stored blob carries only the bounds actually chosen
+ // and each tile keeps its own insight's value for the other one.
+ dateFrom ? (filters.date_from = dateFrom) : delete filters.date_from
+ dateTo ? (filters.date_to = dateTo) : delete filters.date_to
+ }, 'Could not apply that date range. Try again.')
+ },
+ setInterval: async ({ interval }) => {
+ await saveFilters((filters) => {
+ interval ? (filters.interval = interval) : delete filters.interval
+ }, 'Could not apply that interval. Try again.')
+ },
+ enterLayoutEdit: () => {
+ lemonToast.info('Now editing the dashboard. Press E or click Save to persist changes.')
+ },
+ saveLayout: async () => {
+ if (values.layoutSaving) {
+ return
+ }
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId || !values.hasUnsavedLayoutChanges || !values.pendingLayouts) {
+ actions.exitLayoutEdit()
+ return
+ }
+ const updates = changedTileLayouts(values.tiles, values.pendingLayouts)
+ actions.saveLayoutStarted()
+ try {
+ const saved = await Promise.all(
+ updates.map((update) =>
+ crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, update.tileId, {
+ layouts: update.layouts,
+ })
+ )
+ )
+ // A reload would unmount the grid and refetch every tile.
+ applySavedTiles(saved)
+ actions.exitLayoutEdit()
+ lemonToast.success('Dashboard saved')
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not save the layout. Try again.')
+ actions.saveLayoutFailed()
+ }
+ },
+ cancelLayoutEdit: () => {
+ const promptEnabled =
+ !!featureFlagLogic.values.featureFlags[FEATURE_FLAGS.DASHBOARD_LAYOUT_DISCARD_PROMPT]
+ if (!promptEnabled || !values.hasUnsavedLayoutChanges) {
+ actions.exitLayoutEdit()
+ return
+ }
+ LemonDialog.open({
+ title: 'Discard unsaved changes?',
+ description:
+ 'You have unsaved layout changes. If you discard now, the dashboard will revert to its last saved state.',
+ primaryButton: {
+ children: 'Discard changes',
+ status: 'danger',
+ onClick: () => actions.exitLayoutEdit(),
+ 'data-attr': 'cross-project-dashboard-edit-mode-discard-confirm',
+ },
+ secondaryButton: { children: 'Keep editing' },
+ })
+ },
+ setProperties: async ({ properties }) => {
+ const saved = await saveFilters((filters) => {
+ properties.length > 0 ? (filters.properties = properties) : delete filters.properties
+ }, 'Could not apply that filter. Try again.')
+ if (saved) {
+ // Checked here rather than on open: the answer only changes when the filter does.
+ actions.checkPropertyKeys()
+ }
+ },
+ setTileOverride: async ({ tileId, overrides }) => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return
+ }
+ try {
+ const saved = await crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, tileId, {
+ filters_overrides: overrides,
+ })
+ applySavedTiles([saved])
+ lemonToast.success('Tile filters saved')
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not save the tile filters. Try again.')
+ }
+ },
+ setTileColor: async ({ tileId, color }) => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return
+ }
+ try {
+ applySavedTiles([
+ await crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, tileId, { color }),
+ ])
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not change the tile color. Try again.')
+ }
+ },
+ removeTile: async ({ tileId }) => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return
+ }
+ try {
+ await crossProjectDashboardsTilesDestroy(organizationId, props.id, tileId)
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not remove that tile. Try again.')
+ }
+ actions.loadDashboard()
+ },
+ }
+ }),
+ beforeUnload(({ values, actions }) => ({
+ enabled: (newLocation) => {
+ if (!values.hasUnsavedLayoutChanges) {
+ return false
+ }
+ // An in-page navigation, such as opening a side panel, keeps the edits.
+ return !(newLocation && newLocation.pathname === router.values.location.pathname)
+ },
+ message: 'Leave dashboard?\nChanges you made to the layout will be discarded.',
+ onConfirm: () => actions.exitLayoutEdit(),
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDashboard()
+ }),
+])
diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.test.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.test.ts
new file mode 100644
index 000000000000..6c1226978681
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.test.ts
@@ -0,0 +1,39 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { crossProjectDashboardsListLogic } from './crossProjectDashboardsListLogic'
+import { crossProjectDashboardsCreate, crossProjectDashboardsList } from './generated/api'
+
+jest.mock('./generated/api', () => ({
+ __esModule: true,
+ crossProjectDashboardsList: jest.fn(),
+ crossProjectDashboardsCreate: jest.fn(),
+}))
+
+describe('crossProjectDashboardsListLogic', () => {
+ beforeEach(() => {
+ ;(crossProjectDashboardsList as jest.Mock).mockResolvedValue({ results: [] })
+ ;(crossProjectDashboardsCreate as jest.Mock).mockRejectedValue({ detail: 'Name is too long.' })
+ initKeaTests()
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({ id: 'org-1', name: 'Org' } as any)
+ })
+
+ it('keeps the modal open with the typed name when creating fails, so the user can retry', async () => {
+ const logic = crossProjectDashboardsListLogic()
+ logic.mount()
+ logic.actions.openNewModal()
+ logic.actions.setNewName('Quarterly overview')
+
+ logic.actions.createDashboard()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.isNewModalOpen).toBe(true)
+ expect(logic.values.newName).toBe('Quarterly overview')
+ expect(logic.values.isCreating).toBe(false)
+ logic.unmount()
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts
new file mode 100644
index 000000000000..dc4f3506dace
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts
@@ -0,0 +1,132 @@
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import {
+ crossProjectDashboardsCreate,
+ crossProjectDashboardsDestroy,
+ crossProjectDashboardsList,
+} from './generated/api'
+import type { CrossProjectDashboardListItemApi } from './generated/api.schemas'
+import { openDeleteCrossProjectDashboardDialog } from './openDeleteCrossProjectDashboardDialog'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface crossProjectDashboardsListLogicValues {
+ dashboards: CrossProjectDashboardListItemApi[]
+ dashboardsLoading: boolean
+ isCreating: boolean
+ isNewModalOpen: boolean
+ newName: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface crossProjectDashboardsListLogicActions {
+ closeNewModal: () => {
+ value: true
+ }
+ createDashboard: () => {
+ value: true
+ }
+ createDashboardFailure: () => {
+ value: true
+ }
+ deleteDashboard: (dashboard: CrossProjectDashboardListItemApi) => {
+ dashboard: CrossProjectDashboardListItemApi
+ }
+ loadDashboards: () => any
+ loadDashboardsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDashboardsSuccess: (
+ dashboards: CrossProjectDashboardListItemApi[],
+ payload?: any
+ ) => {
+ dashboards: CrossProjectDashboardListItemApi[]
+ payload?: any
+ }
+ openNewModal: () => {
+ value: true
+ }
+ setNewName: (name: string) => {
+ name: string
+ }
+}
+
+export type crossProjectDashboardsListLogicType = MakeLogicType<
+ crossProjectDashboardsListLogicValues,
+ crossProjectDashboardsListLogicActions
+>
+
+export const crossProjectDashboardsListLogic = kea<crossProjectDashboardsListLogicType>([
+ path(['products', 'cross_project_dashboards', 'frontend', 'crossProjectDashboardsListLogic']),
+ actions({
+ openNewModal: true,
+ closeNewModal: true,
+ setNewName: (name: string) => ({ name }),
+ createDashboard: true,
+ createDashboardFailure: true,
+ deleteDashboard: (dashboard: CrossProjectDashboardListItemApi) => ({ dashboard }),
+ }),
+ reducers({
+ isNewModalOpen: [false, { openNewModal: () => true, closeNewModal: () => false }],
+ newName: ['', { setNewName: (_, { name }) => name, closeNewModal: () => '' }],
+ isCreating: [
+ false,
+ { createDashboard: () => true, createDashboardFailure: () => false, closeNewModal: () => false },
+ ],
+ }),
+ loaders({
+ dashboards: [
+ [] as CrossProjectDashboardListItemApi[],
+ {
+ loadDashboards: async () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return []
+ }
+ const response = await crossProjectDashboardsList(organizationId)
+ return response.results
+ },
+ },
+ ],
+ }),
+ listeners(({ values, actions }) => ({
+ createDashboard: async () => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId || !values.newName.trim()) {
+ actions.closeNewModal()
+ return
+ }
+ try {
+ const created = await crossProjectDashboardsCreate(organizationId, {
+ name: values.newName.trim(),
+ } as any)
+ actions.closeNewModal()
+ router.actions.push(`/cross-project-dashboards/${created.id}`)
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not create that dashboard. Try again.')
+ actions.createDashboardFailure()
+ }
+ },
+ deleteDashboard: ({ dashboard }) => {
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ return
+ }
+ openDeleteCrossProjectDashboardDialog(dashboard.name, async () => {
+ await crossProjectDashboardsDestroy(organizationId, dashboard.id)
+ actions.loadDashboards()
+ })
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDashboards()
+ }),
+])
diff --git a/products/cross_project_dashboards/frontend/crossProjectLayouts.test.ts b/products/cross_project_dashboards/frontend/crossProjectLayouts.test.ts
new file mode 100644
index 000000000000..2dd49f82353f
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectLayouts.test.ts
@@ -0,0 +1,76 @@
+import { changedTileLayouts, layoutsForTiles } from './crossProjectLayouts'
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+const tile = (id: string, layouts?: Record<string, unknown>): CrossProjectDashboardTileApi =>
+ ({ id, project_id: 1, insight_id: 2, layouts }) as CrossProjectDashboardTileApi
+
+describe('crossProjectLayouts', () => {
+ describe('layoutsForTiles', () => {
+ it('flows unpositioned tiles two per row instead of stacking them at the origin', () => {
+ const result = layoutsForTiles([tile('a'), tile('b'), tile('c')])
+
+ expect(result.sm.map(({ i, x, y, w }) => ({ i, x, y, w }))).toEqual([
+ { i: 'a', x: 0, y: 0, w: 6 },
+ { i: 'b', x: 6, y: 0, w: 6 },
+ { i: 'c', x: 0, y: 5, w: 6 },
+ ])
+ })
+
+ it('uses one column at the narrow breakpoint', () => {
+ const result = layoutsForTiles([tile('a'), tile('b')])
+
+ expect(result.xs.map(({ i, x, y, w }) => ({ i, x, y, w }))).toEqual([
+ { i: 'a', x: 0, y: 0, w: 1 },
+ { i: 'b', x: 0, y: 5, w: 1 },
+ ])
+ })
+
+ it('prefers a stored layout over the default', () => {
+ const result = layoutsForTiles([tile('a', { sm: { x: 3, y: 7, w: 4, h: 2 } })])
+
+ expect(result.sm[0]).toEqual({ i: 'a', x: 3, y: 7, w: 4, h: 2 })
+ })
+ })
+
+ describe('changedTileLayouts', () => {
+ it('writes nothing when the grid reports the arrangement already stored', () => {
+ const tiles = [tile('a', { sm: { x: 0, y: 0, w: 6, h: 5 }, xs: { x: 0, y: 0, w: 1, h: 5 } })]
+
+ const updates = changedTileLayouts(tiles, {
+ sm: [{ i: 'a', x: 0, y: 0, w: 6, h: 5 }],
+ xs: [{ i: 'a', x: 0, y: 0, w: 1, h: 5 }],
+ })
+
+ expect(updates).toEqual([])
+ })
+
+ it('writes only the tile that moved', () => {
+ const tiles = [tile('a', { sm: { x: 0, y: 0, w: 6, h: 5 } }), tile('b', { sm: { x: 6, y: 0, w: 6, h: 5 } })]
+
+ const updates = changedTileLayouts(tiles, {
+ sm: [
+ { i: 'a', x: 0, y: 0, w: 6, h: 5 },
+ { i: 'b', x: 6, y: 5, w: 6, h: 5 },
+ ],
+ })
+
+ expect(updates.map((update) => update.tileId)).toEqual(['b'])
+ expect(updates[0].layouts.sm).toEqual({ x: 6, y: 5, w: 6, h: 5 })
+ })
+
+ it('treats a first arrangement of an unpositioned tile as a change', () => {
+ const updates = changedTileLayouts([tile('a')], { sm: [{ i: 'a', x: 2, y: 1, w: 4, h: 3 }] })
+
+ expect(updates).toHaveLength(1)
+ expect(updates[0].layouts.sm).toEqual({ x: 2, y: 1, w: 4, h: 3 })
+ })
+
+ it('keeps a stored size the grid did not report', () => {
+ const tiles = [tile('a', { sm: { x: 0, y: 0, w: 6, h: 5 }, xs: { x: 0, y: 3, w: 1, h: 5 } })]
+
+ const updates = changedTileLayouts(tiles, { sm: [{ i: 'a', x: 1, y: 0, w: 6, h: 5 }] })
+
+ expect(updates[0].layouts.xs).toEqual({ x: 0, y: 3, w: 1, h: 5 })
+ })
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectLayouts.ts b/products/cross_project_dashboards/frontend/crossProjectLayouts.ts
new file mode 100644
index 000000000000..075314a29754
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectLayouts.ts
@@ -0,0 +1,101 @@
+import type { LayoutItem } from 'react-grid-layout'
+
+import type { DashboardLayoutSize, TileLayout } from '~/types'
+
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+/** Same grid as single-project dashboards, so the two read as one product. */
+export const GRID_BREAKPOINTS: Record<DashboardLayoutSize, number> = { sm: 768, xs: 0 }
+export const GRID_COLUMN_COUNTS: Record<DashboardLayoutSize, number> = { sm: 12, xs: 1 }
+export const GRID_ROW_HEIGHT = 80
+export const GRID_MARGIN: [number, number] = [16, 16]
+
+const DEFAULT_WIDTH: Record<DashboardLayoutSize, number> = { sm: 6, xs: 1 }
+const DEFAULT_HEIGHT = 5
+
+export type ResponsiveTileLayouts = Record<DashboardLayoutSize, LayoutItem[]>
+
+const SIZES: DashboardLayoutSize[] = ['sm', 'xs']
+
+const storedLayout = (tile: CrossProjectDashboardTileApi, size: DashboardLayoutSize): TileLayout | null => {
+ const layouts = tile.layouts as Record<string, TileLayout> | undefined
+ const layout = layouts?.[size]
+ return layout && typeof layout.w === 'number' && typeof layout.h === 'number' ? layout : null
+}
+
+/** Never written back, so a dashboard nobody arranged stays distinct from one arranged to look like the default. */
+const defaultLayout = (index: number, size: DashboardLayoutSize): TileLayout => {
+ const width = DEFAULT_WIDTH[size]
+ const perRow = Math.max(1, Math.floor(GRID_COLUMN_COUNTS[size] / width))
+ return {
+ x: (index % perRow) * width,
+ y: Math.floor(index / perRow) * DEFAULT_HEIGHT,
+ w: width,
+ h: DEFAULT_HEIGHT,
+ }
+}
+
+export function layoutsForTiles(tiles: readonly CrossProjectDashboardTileApi[]): ResponsiveTileLayouts {
+ return Object.fromEntries(
+ SIZES.map((size) => [
+ size,
+ tiles.map((tile, index) => ({ ...(storedLayout(tile, size) ?? defaultLayout(index, size)), i: tile.id })),
+ ])
+ ) as ResponsiveTileLayouts
+}
+
+const samePosition = (a: TileLayout | null, b: TileLayout): boolean =>
+ !!a && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h
+
+export interface TileLayoutUpdate {
+ tileId: string
+ layouts: Record<string, TileLayout>
+}
+
+/** The grid reports a change on mount and on every resize, so only a tile that differs from what is stored counts. */
+export function changedTileLayouts(
+ tiles: readonly CrossProjectDashboardTileApi[],
+ next: Partial<ResponsiveTileLayouts>
+): TileLayoutUpdate[] {
+ const updates: TileLayoutUpdate[] = []
+
+ for (const tile of tiles) {
+ const layouts: Record<string, TileLayout> = {}
+ let moved = false
+
+ for (const size of SIZES) {
+ const proposed = next[size]?.find((item) => item.i === tile.id)
+ if (!proposed) {
+ const kept = storedLayout(tile, size)
+ if (kept) {
+ layouts[size] = { x: kept.x, y: kept.y, w: kept.w, h: kept.h }
+ }
+ continue
+ }
+ layouts[size] = { x: proposed.x, y: proposed.y, w: proposed.w, h: proposed.h }
+ if (!samePosition(storedLayout(tile, size), proposed)) {
+ moved = true
+ }
+ }
+
+ if (moved) {
+ updates.push({ tileId: tile.id, layouts })
+ }
+ }
+
+ return updates
+}
+
+/** Compared against what the grid shows, defaults included, so an edit that moved nothing is no change. */
+export function layoutsDiffer(saved: ResponsiveTileLayouts, next: Partial<ResponsiveTileLayouts> | null): boolean {
+ if (!next) {
+ return false
+ }
+ return SIZES.some((size) => {
+ const shown = new Map(saved[size].map((item) => [item.i, item]))
+ return (next[size] ?? []).some((item) => {
+ const current = shown.get(item.i)
+ return !current || !samePosition(current, item)
+ })
+ })
+}
diff --git a/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.test.ts b/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.test.ts
new file mode 100644
index 000000000000..9a41d6d0bff6
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.test.ts
@@ -0,0 +1,71 @@
+import { propertyDefinitionsList } from '~/generated/core/api'
+
+import { findMissingPropertyKeys, propertyKeysIn } from './crossProjectPropertyKeys'
+
+jest.mock('~/generated/core/api', () => ({ __esModule: true, propertyDefinitionsList: jest.fn() }))
+
+const mockedList = propertyDefinitionsList as jest.Mock
+
+describe('crossProjectPropertyKeys', () => {
+ beforeEach(() => {
+ mockedList.mockReset()
+ })
+
+ describe('propertyKeysIn', () => {
+ it('collects each key once per type', () => {
+ expect(
+ propertyKeysIn([
+ { key: 'browser', type: 'event' },
+ { key: 'browser', type: 'event' },
+ { key: 'plan', type: 'person' },
+ ])
+ ).toEqual([
+ { key: 'browser', type: 'event' },
+ { key: 'plan', type: 'person' },
+ ])
+ })
+
+ it('leaves out filter types the property definitions endpoint cannot answer for', () => {
+ expect(propertyKeysIn([{ key: 'distinct_id', type: 'event_metadata' }, { key: 'plan' }])).toEqual([])
+ })
+
+ it('returns nothing for filters that carry no key', () => {
+ expect(propertyKeysIn([{ value: 'x' }, null, 'nonsense'])).toEqual([])
+ expect(propertyKeysIn(undefined)).toEqual([])
+ })
+ })
+
+ describe('findMissingPropertyKeys', () => {
+ it('reports a key the project has never recorded', async () => {
+ mockedList.mockResolvedValue({ results: [] })
+
+ expect(await findMissingPropertyKeys([7], [{ key: 'plan', type: 'event' }])).toEqual({ 7: ['plan'] })
+ })
+
+ it('asks for a person property as a person property, not as the default event type', async () => {
+ mockedList.mockResolvedValue({ results: [{ name: 'email' }] })
+
+ expect(await findMissingPropertyKeys([7], [{ key: 'email', type: 'person' }])).toEqual({})
+ expect(mockedList).toHaveBeenCalledWith('7', expect.objectContaining({ type: 'person' }))
+ })
+
+ it('does not report a key the project has, even when the search returns near matches', async () => {
+ mockedList.mockResolvedValue({ results: [{ name: 'plan_tier' }, { name: 'plan' }] })
+
+ expect(await findMissingPropertyKeys([7], [{ key: 'plan', type: 'event' }])).toEqual({})
+ })
+
+ it('treats an unreachable project as no answer rather than a missing key', async () => {
+ // A 403 means the reader cannot see the project, not that the key is absent. Reporting
+ // it as missing would warn about a tile whose data is fine.
+ mockedList.mockRejectedValue({ status: 403 })
+
+ expect(await findMissingPropertyKeys([7], [{ key: 'plan', type: 'event' }])).toEqual({})
+ })
+
+ it('asks nothing when there are no keys to check', async () => {
+ expect(await findMissingPropertyKeys([7, 8], [])).toEqual({})
+ expect(mockedList).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.ts b/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.ts
new file mode 100644
index 000000000000..08c7397e2d83
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectPropertyKeys.ts
@@ -0,0 +1,82 @@
+import { propertyDefinitionsList } from '~/generated/core/api'
+
+type CheckableType = 'event' | 'person'
+
+// The endpoint reads any other type as an event property, which would flag an existing key as missing.
+const CHECKABLE_TYPES: ReadonlySet<string> = new Set<CheckableType>(['event', 'person'])
+
+function isCheckableType(type: unknown): type is CheckableType {
+ return typeof type === 'string' && CHECKABLE_TYPES.has(type)
+}
+
+const MAX_CONCURRENT_CHECKS = 4
+
+interface KeyCheck {
+ projectId: number
+ key: string
+ missing: boolean
+}
+
+export interface PropertyKeyRef {
+ key: string
+ type: CheckableType
+}
+
+/** Property keys a filter refers to, with their type, in the order the reader added them. */
+export function propertyKeysIn(properties: unknown): PropertyKeyRef[] {
+ if (!Array.isArray(properties)) {
+ return []
+ }
+ const seen = new Set<string>()
+ const refs: PropertyKeyRef[] = []
+ for (const property of properties) {
+ const { key, type } = (property && typeof property === 'object' ? property : {}) as Record<string, unknown>
+ if (typeof key !== 'string' || !key || !isCheckableType(type)) {
+ continue
+ }
+ if (!seen.has(`${type}:${key}`)) {
+ seen.add(`${type}:${key}`)
+ refs.push({ key, type })
+ }
+ }
+ return refs
+}
+
+/**
+ * A filter travels by key name, so a key one project never recorded silently empties that tile.
+ * Checked on filter apply only, because a check on open costs a request per project and key.
+ */
+export async function findMissingPropertyKeys(
+ projectIds: number[],
+ refs: PropertyKeyRef[]
+): Promise<Record<number, string[]>> {
+ if (projectIds.length === 0 || refs.length === 0) {
+ return {}
+ }
+
+ const pairs = projectIds.flatMap((projectId) => refs.map((ref) => ({ projectId, ...ref })))
+ const check = async ({ projectId, key, type }: { projectId: number } & PropertyKeyRef): Promise<KeyCheck> => {
+ try {
+ const response = await propertyDefinitionsList(String(projectId), { search: key, type, limit: 100 })
+ const found = response.results.some((definition) => definition.name === key)
+ return { projectId, key, missing: !found }
+ } catch {
+ // A project the reader cannot reach answers 403. That is not a missing key, and
+ // claiming it is would put a warning on a tile whose data is fine.
+ return { projectId, key, missing: false }
+ }
+ }
+
+ const results: KeyCheck[] = []
+ for (let start = 0; start < pairs.length; start += MAX_CONCURRENT_CHECKS) {
+ results.push(...(await Promise.all(pairs.slice(start, start + MAX_CONCURRENT_CHECKS).map(check))))
+ }
+
+ const missing: Record<number, string[]> = {}
+ for (const result of results) {
+ if (result.missing) {
+ missing[result.projectId] = [...(missing[result.projectId] ?? []), result.key]
+ }
+ }
+ return missing
+}
diff --git a/products/cross_project_dashboards/frontend/crossProjectTileFetch.test.ts b/products/cross_project_dashboards/frontend/crossProjectTileFetch.test.ts
new file mode 100644
index 000000000000..9ebbc9ef853c
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectTileFetch.test.ts
@@ -0,0 +1,76 @@
+import { insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+
+import { fetchCrossProjectTile } from './crossProjectTileFetch'
+
+jest.mock('products/product_analytics/frontend/generated/api', () => ({
+ __esModule: true,
+ insightsRetrieve: jest.fn(),
+}))
+
+const mockedRetrieve = insightsRetrieve as jest.Mock
+
+describe('fetchCrossProjectTile', () => {
+ beforeEach(() => {
+ mockedRetrieve.mockReset()
+ })
+
+ it('fetches from the tile own project, not the current one', async () => {
+ mockedRetrieve.mockResolvedValue({ id: 7, name: 'Signups' })
+
+ await fetchCrossProjectTile(42, 7)
+
+ expect(mockedRetrieve).toHaveBeenCalledTimes(1)
+ expect(mockedRetrieve).toHaveBeenCalledWith('42', 7, expect.anything())
+ })
+
+ it('returns the insight when the project endpoint answers', async () => {
+ mockedRetrieve.mockResolvedValue({ id: 7, name: 'Signups' })
+
+ const result = await fetchCrossProjectTile(42, 7)
+
+ expect(result.unavailable).toBeNull()
+ expect(result.insight).toEqual({ id: 7, name: 'Signups' })
+ })
+
+ it('reports no access on 403 and carries no insight', async () => {
+ mockedRetrieve.mockRejectedValue({ status: 403 })
+
+ const result = await fetchCrossProjectTile(42, 7)
+
+ expect(result.unavailable).toBe('no-access')
+ expect(result.insight).toBeNull()
+ })
+
+ it('reports not found on 404', async () => {
+ mockedRetrieve.mockRejectedValue({ status: 404 })
+
+ const result = await fetchCrossProjectTile(42, 7)
+
+ expect(result.unavailable).toBe('not-found')
+ expect(result.insight).toBeNull()
+ })
+
+ it('reports a generic failure on any other error', async () => {
+ mockedRetrieve.mockRejectedValue({ status: 500 })
+
+ const result = await fetchCrossProjectTile(42, 7)
+
+ expect(result.unavailable).toBe('failed')
+ })
+
+ it('passes dashboard filters through as filters_override', async () => {
+ mockedRetrieve.mockResolvedValue({ id: 7 })
+
+ await fetchCrossProjectTile(42, 7, { date_from: '-7d' })
+
+ expect(JSON.parse(mockedRetrieve.mock.calls[0][2].filters_override)).toEqual({ date_from: '-7d' })
+ })
+
+ it('omits filters_override when there are no filters', async () => {
+ mockedRetrieve.mockResolvedValue({ id: 7 })
+
+ await fetchCrossProjectTile(42, 7, {})
+
+ expect(mockedRetrieve.mock.calls[0][2]).not.toHaveProperty('filters_override')
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts b/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts
new file mode 100644
index 000000000000..24f0931796f9
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts
@@ -0,0 +1,63 @@
+import type { InsightModel } from '~/types'
+
+import { insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+import type { InsightsRetrieveParams } from 'products/product_analytics/frontend/generated/api.schemas'
+
+export type TileUnavailableReason = 'no-access' | 'not-found' | 'failed'
+
+export interface TileFetchResult {
+ insight: InsightModel | null
+ unavailable: TileUnavailableReason | null
+}
+
+/**
+ * ClickHouse allows an organization six concurrent dashboard queries, and this dashboard puts no
+ * cap on tiles, so the tiles queue here instead of arriving together and starving each other.
+ */
+const MAX_CONCURRENT_TILE_FETCHES = 4
+
+let inFlight = 0
+const waiting: (() => void)[] = []
+
+async function acquireSlot(): Promise<void> {
+ if (inFlight < MAX_CONCURRENT_TILE_FETCHES) {
+ inFlight += 1
+ return
+ }
+ await new Promise<void>((resolve) => waiting.push(resolve))
+ inFlight += 1
+}
+
+function releaseSlot(): void {
+ inFlight -= 1
+ waiting.shift()?.()
+}
+
+/** The project's own insight endpoint applies the reader's access, quota and cache key, so a reader without access gets a 403. */
+export async function fetchCrossProjectTile(
+ projectId: number,
+ insightId: number,
+ filtersOverride?: Record<string, unknown>
+): Promise<TileFetchResult> {
+ const params: InsightsRetrieveParams = { refresh: 'blocking' }
+ if (filtersOverride && Object.keys(filtersOverride).length > 0) {
+ params.filters_override = JSON.stringify(filtersOverride)
+ }
+
+ await acquireSlot()
+ try {
+ const insight = await insightsRetrieve(String(projectId), insightId, params)
+ // InsightCard needs an InsightModel. The endpoint returns one, but its schema leaves out `saved`.
+ return { insight: insight as unknown as InsightModel, unavailable: null }
+ } catch (error: any) {
+ if (error?.status === 403) {
+ return { insight: null, unavailable: 'no-access' }
+ }
+ if (error?.status === 404) {
+ return { insight: null, unavailable: 'not-found' }
+ }
+ return { insight: null, unavailable: 'failed' }
+ } finally {
+ releaseSlot()
+ }
+}
diff --git a/products/cross_project_dashboards/frontend/crossProjectTileFilters.test.ts b/products/cross_project_dashboards/frontend/crossProjectTileFilters.test.ts
new file mode 100644
index 000000000000..7d12f279baff
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectTileFilters.test.ts
@@ -0,0 +1,27 @@
+import { mergeTileFilters } from './crossProjectTileFilters'
+
+describe('mergeTileFilters', () => {
+ it.each([
+ [
+ 'follows the dashboard when the tile overrides nothing',
+ { date_from: '-30d', interval: 'day' },
+ undefined,
+ { date_from: '-30d', interval: 'day' },
+ ],
+ [
+ 'lets the tile win on the key it sets and keeps inheriting the rest',
+ { date_from: '-30d', interval: 'week' },
+ { date_from: '-7d' },
+ { date_from: '-7d', interval: 'week' },
+ ],
+ [
+ 'does not treat an absent tile key as an override that clears the dashboard value',
+ { date_from: '-30d' },
+ { date_to: null, interval: null },
+ { date_from: '-30d' },
+ ],
+ ['returns an empty set when neither side carries filters', undefined, undefined, {}],
+ ] as const)('%s', (_label, dashboard, tile, expected) => {
+ expect(mergeTileFilters(dashboard as any, tile as any)).toEqual(expected)
+ })
+})
diff --git a/products/cross_project_dashboards/frontend/crossProjectTileFilters.ts b/products/cross_project_dashboards/frontend/crossProjectTileFilters.ts
new file mode 100644
index 000000000000..2c442edce760
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/crossProjectTileFilters.ts
@@ -0,0 +1,18 @@
+import type { CrossProjectDashboardFilters } from './crossProjectDashboardLogic'
+
+const KEYS: (keyof CrossProjectDashboardFilters)[] = ['date_from', 'date_to', 'interval']
+
+/** The tile's own keys win over the dashboard's, so a tile that overrides only its dates keeps the dashboard's interval. */
+export function mergeTileFilters(
+ dashboardFilters?: CrossProjectDashboardFilters,
+ tileFilters?: CrossProjectDashboardFilters
+): CrossProjectDashboardFilters {
+ const filters: CrossProjectDashboardFilters = { ...dashboardFilters }
+ for (const key of KEYS) {
+ const value = tileFilters?.[key]
+ if (value !== undefined && value !== null) {
+ filters[key] = value as never
+ }
+ }
+ return filters
+}
diff --git a/products/cross_project_dashboards/frontend/openCrossProjectTileOverrideDialog.tsx b/products/cross_project_dashboards/frontend/openCrossProjectTileOverrideDialog.tsx
new file mode 100644
index 000000000000..fffc7e7f38c0
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/openCrossProjectTileOverrideDialog.tsx
@@ -0,0 +1,75 @@
+import { LemonSelect } from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import type { IntervalType } from '~/types'
+
+import type { CrossProjectDashboardFilters } from './crossProjectDashboardLogic'
+import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
+
+interface DateRangeValue {
+ date_from?: string | null
+ date_to?: string | null
+}
+
+/** Single-project's "Set override" dialog, limited to dates and interval because other overrides resolve against one project. */
+export function openCrossProjectTileOverrideDialog(
+ tile: CrossProjectDashboardTileApi,
+ onSave: (overrides: CrossProjectDashboardFilters) => void
+): void {
+ const current = (tile.filters_overrides ?? {}) as CrossProjectDashboardFilters
+
+ LemonDialog.openForm({
+ title: 'Override tile filters',
+ maxWidth: '40rem',
+ initialValues: {
+ dateRange: { date_from: current.date_from ?? null, date_to: current.date_to ?? null },
+ interval: current.interval ?? null,
+ },
+ content: (
+ <div className="flex flex-col gap-4">
+ <LemonField name="dateRange" label="Date range">
+ {({ value, onChange }: { value: DateRangeValue; onChange: (value: DateRangeValue) => void }) => (
+ <DateFilter
+ showCustom
+ dateFrom={value?.date_from ?? null}
+ dateTo={value?.date_to ?? null}
+ onChange={(dateFrom, dateTo) => onChange({ date_from: dateFrom, date_to: dateTo })}
+ />
+ )}
+ </LemonField>
+ <LemonField name="interval" label="Interval">
+ <LemonSelect<IntervalType | null>
+ options={[
+ { value: null, label: 'Follow the dashboard' },
+ { value: 'hour', label: 'Hour' },
+ { value: 'day', label: 'Day' },
+ { value: 'week', label: 'Week' },
+ { value: 'month', label: 'Month' },
+ ]}
+ />
+ </LemonField>
+ </div>
+ ),
+ tertiaryButton: {
+ children: 'Clear all overrides',
+ onClick: () => onSave({}),
+ },
+ onSubmit: (values) => {
+ const dateRange = (values.dateRange ?? {}) as DateRangeValue
+ const overrides: CrossProjectDashboardFilters = {}
+ if (dateRange.date_from) {
+ overrides.date_from = dateRange.date_from
+ }
+ if (dateRange.date_to) {
+ overrides.date_to = dateRange.date_to
+ }
+ if (values.interval) {
+ overrides.interval = values.interval as IntervalType
+ }
+ onSave(overrides)
+ },
+ })
+}
diff --git a/products/cross_project_dashboards/frontend/openDeleteCrossProjectDashboardDialog.ts b/products/cross_project_dashboards/frontend/openDeleteCrossProjectDashboardDialog.ts
new file mode 100644
index 000000000000..93ab6efdde7c
--- /dev/null
+++ b/products/cross_project_dashboards/frontend/openDeleteCrossProjectDashboardDialog.ts
@@ -0,0 +1,26 @@
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+/** Asks before `deleteDashboard` runs, and keeps the dialog open when the delete fails so the person can retry. */
+export function openDeleteCrossProjectDashboardDialog(name: string, deleteDashboard: () => Promise<void>): void {
+ LemonDialog.open({
+ title: 'Delete dashboard?',
+ description: `This deletes "${name}" for everyone in your organization. The insights on it stay in their projects.`,
+ shouldAwaitSubmit: true,
+ primaryButton: {
+ children: 'Delete dashboard',
+ status: 'danger',
+ 'data-attr': 'cross-project-dashboard-delete-confirm',
+ onClick: async () => {
+ try {
+ await deleteDashboard()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not delete that dashboard. Try again.')
+ throw error
+ }
+ lemonToast.success('Dashboard deleted')
+ },
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+}
diff --git a/products/cross_project_dashboards/manifest.tsx b/products/cross_project_dashboards/manifest.tsx
index 4a6f7cdda9d1..deebb5e6cef8 100644
--- a/products/cross_project_dashboards/manifest.tsx
+++ b/products/cross_project_dashboards/manifest.tsx
@@ -1,21 +1,32 @@
-/**
- * Product manifest for cross_project_dashboards.
- *
- * Defines scenes, routes, URLs, and navigation for this product.
- */
import { ProductManifest } from '../../frontend/src/types'
export const manifest: ProductManifest = {
name: 'CrossProjectDashboards',
scenes: {
- // Define scenes here
+ CrossProjectDashboards: {
+ name: 'Cross-project dashboards',
+ import: () => import('./frontend/CrossProjectDashboardsScene'),
+ // Organization-scoped, not project-scoped: a dashboard here holds insights from
+ // several projects, so it cannot live under /project/:id.
+ organizationBased: true,
+ activityScope: 'CrossProjectDashboard',
+ description: 'Put insights from several projects on one page.',
+ },
+ CrossProjectDashboard: {
+ name: 'Cross-project dashboard',
+ import: () => import('./frontend/CrossProjectDashboardScene'),
+ organizationBased: true,
+ activityScope: 'CrossProjectDashboard',
+ },
},
routes: {
- // Define routes here
+ '/cross-project-dashboards': ['CrossProjectDashboards', 'crossProjectDashboards'],
+ '/cross-project-dashboards/:id': ['CrossProjectDashboard', 'crossProjectDashboard'],
},
redirects: {},
urls: {
- // Define URL helpers here
+ crossProjectDashboards: (): string => '/cross-project-dashboards',
+ crossProjectDashboard: (id: string): string => `/cross-project-dashboards/${id}`,
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/products/cross_project_dashboards/mcp/tools.yaml b/products/cross_project_dashboards/mcp/tools.yaml
index c29d99be284e..1540ae4d75f7 100644
--- a/products/cross_project_dashboards/mcp/tools.yaml
+++ b/products/cross_project_dashboards/mcp/tools.yaml
@@ -6,7 +6,7 @@
# All other fields (title, description, enrich_url, etc.) are yours to configure.
category: Cross-project dashboards
feature: cross_project_dashboards
-url_prefix: /
+url_prefix: /cross-project-dashboards
ui_apps: {}
tools:
cross-project-dashboard-tiles-list:
@@ -40,6 +40,7 @@ tools:
readOnly: true
destructive: false
idempotent: true
+ enrich_url: '{id}'
title: Get one cross-project dashboard
description: >
One dashboard with its tiles. Each tile names the project and the insight it points at, never the insight's
@@ -55,6 +56,7 @@ tools:
readOnly: true
destructive: false
idempotent: true
+ enrich_url: '{id}'
list: true
title: List cross-project dashboards
description: >
diff --git a/products/cross_project_dashboards/package.json b/products/cross_project_dashboards/package.json
index cbb2b41d994b..c36b14cb7247 100644
--- a/products/cross_project_dashboards/package.json
+++ b/products/cross_project_dashboards/package.json
@@ -15,6 +15,7 @@
"kea-test-utils": "catalog:"
},
"peerDependencies": {
+ "@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
"@types/react": "*",
"react": "*",
diff --git a/services/mcp/src/tools/generated/cross_project_dashboards.ts b/services/mcp/src/tools/generated/cross_project_dashboards.ts
index 9b09fd803f68..22c5462951db 100644
--- a/services/mcp/src/tools/generated/cross_project_dashboards.ts
+++ b/services/mcp/src/tools/generated/cross_project_dashboards.ts
@@ -30,7 +30,7 @@ const crossProjectDashboardTilesList = (): ToolBase<
offset: params.offset,
},
})
- return await withPostHogUrl(context, result, '/')
+ return await withPostHogUrl(context, result, '/cross-project-dashboards')
},
})
@@ -41,7 +41,7 @@ const CrossProjectDashboardsGetSchema = () => {
const crossProjectDashboardsGet = (): ToolBase<
ReturnType<typeof CrossProjectDashboardsGetSchema>,
- Schemas.CrossProjectDashboard
+ WithPostHogUrl<Schemas.CrossProjectDashboard>
> => ({
name: 'cross-project-dashboards-get',
schema: CrossProjectDashboardsGetSchema(),
@@ -51,7 +51,7 @@ const crossProjectDashboardsGet = (): ToolBase<
method: 'GET',
path: `/api/organizations/${encodeURIComponent(String(orgId))}/cross_project_dashboards/${encodeURIComponent(String(params.id))}/`,
})
- return result
+ return await withPostHogUrl(context, result, `/cross-project-dashboards/${result.id}`)
},
})
@@ -76,7 +76,18 @@ const crossProjectDashboardsList = (): ToolBase<
offset: params.offset,
},
})
- return await withPostHogUrl(context, result, '/')
+ return await withPostHogUrl(
+ context,
+ {
+ ...result,
+ results: await Promise.all(
+ (result.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/cross-project-dashboards/${item.id}`)
+ )
+ ),
+ },
+ '/cross-project-dashboards'
+ )
},
})
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index ec03847b2fa1..952f08b20398 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -419,6 +419,16 @@
"params": [],
"scope": "global"
},
+ "crossProjectDashboard": {
+ "template": "/cross-project-dashboards/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "crossProjectDashboards": {
+ "template": "/cross-project-dashboards",
+ "params": [],
+ "scope": "project"
+ },
"customCss": {
"template": "/themes/custom-css",
"params": [],
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.json
index d558beedda43..f4d784820165 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}\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\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/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/scout-trials\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/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\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/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\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}\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\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/cross-project-dashboards\n/cross-project-dashboards/{id}\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/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/scout-trials\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/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\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/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\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"
}
},