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(product-analytics): clarify how to customize the dashboard (#125359)

Daniel Parkera6607ddde558
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a5c0ce1e5885..f40a28ad477b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14803,25 +14803,25 @@ snapshots:
scenes-app-product-analytics-home-chart-card--primary--light:
hash: v1.k794b7964.3029d681745bb041a125cd38a82c90d88e8c1c4f1c94e983f1a2afe002b399c7.P2tcznoufujQ1-OR3EiKU0wghPvd46O5Xx0NK-v0k3Y
scenes-app-product-analytics-home-dashboard-starter--ai-unavailable--dark:
- hash: v1.k794b7964.ca3354bec47eaee1eb0fae23d182a64d8d0cd713567705afcac953c6c19ef250.wzNkYipTommWToi3oQ5z-aFFAuXUaxC43BcjqhMU7MQ
+ hash: v1.k794b7964.4961981e44afc1b380d86fefc8c49d4aae78f8c8d3c4e475d30ee3c227785de0.JfqQiF5A9umixLPG_898JQw6e47a59dCvTJRL47GE5w
scenes-app-product-analytics-home-dashboard-starter--ai-unavailable--light:
- hash: v1.k794b7964.c12ccda55b30daba0b4e7d75c3d756ea6c71a5c1f6857f3bbf1fa75c08d9d058.L5YldxnOc04bbvuxKTRk2SyQK3tqQ8UcaXA3-bIobgU
+ hash: v1.k794b7964.7d2132b8e09bdcdb0f90b78b77317fccd4ba99abb74354989066d85c5ca1beb9.J0zJ_UHA0Q5ZPECO4Wd5LmcKa2XbYHp999P4_AI2s48
scenes-app-product-analytics-home-dashboard-starter--creating-with-ai--dark:
- hash: v1.k794b7964.97e975c0c86805c9965fffc76bf4bcdeaa6cea0902c05d75b2c5bb2ffcff48ed.fqswmyImhQNt_FiYZuxn72GF00W6wgHSc_3v09E91BM
+ hash: v1.k794b7964.4a7be6bd2b299f66e526e4c6e7ccbdc4b49fb54aee94d5b1a382b0ef1635aa8e.iga9ZEwAfA7Wa0XFGBVV19asPM7GcdS1toTHlzWZsH8
scenes-app-product-analytics-home-dashboard-starter--creating-with-ai--light:
- hash: v1.k794b7964.7e2dcf46facadac0aad15ae614b6fff91c89b106f90eecf57df28816a7fddc02.1SX6H1XTurkL_ptYLeWaP85m95qbk5lBPBKHPyfxOcc
+ hash: v1.k794b7964.1635be4b16f8d8c05fd87ace49846387f717d18e5dfeaab7fe1717472659091f.b5c2wbgH-ZyJoCLBbPp8yQq2cBy8sKT63kJ-T5It1Zg
scenes-app-product-analytics-home-dashboard-starter--default--dark:
- hash: v1.k794b7964.cde090e3502edcb7a4bb7a44e6cef04bbfe4b12e39abc97d790f5d7249e8f2d9.N6oOnegrNLGQ_vYcK96iQ-MbN9x1rN3hRCzI66JVCd0
+ hash: v1.k794b7964.001473c625d67675378260f61bb01aed5b1b8b271ee25e646d619e4c1db69ccb.oAw6xySLnu44T-DoYmQVr2OCSpqK5Y8e30ZT3UaGlR0
scenes-app-product-analytics-home-dashboard-starter--default--light:
- hash: v1.k794b7964.26b8cb70fc4ca32258deca6f79f93bb278697aea07ac3d96caf96ee46fc506c8.XosQwFr2PN4U2qqYJDCaLuVINpJhduDtk9VwssP33Ao
+ hash: v1.k794b7964.786f2dc9e81023c98950ea919ae959653bee537aa6abd42e61fb675d5b8feca3.9SA9R77NI4v5H5sh14dF6_CqhI81Xdct0taZqNrWDto
scenes-app-product-analytics-home-dashboard-starter--narrow--dark:
- hash: v1.k794b7964.01d01b3843732f6177aade2c39becc7202ad453a18cda1f497e4a15e92c6a63d.AasvsiQogtVBtdczIu4akOIaup7k6_EI5_uCxBcNQQ0
+ hash: v1.k794b7964.9493106a48661ae97d8806fe679e42eb8cb1d6525c51d42890ba5b99a0fbde77.h5zuuh1cvPfoH-wLoBP6UtJMQI08ICsWdWURd2Ux_q4
scenes-app-product-analytics-home-dashboard-starter--narrow--light:
- hash: v1.k794b7964.bbde0c6e0991a3f0db34a0fbca9613762516093e2caa56acc1afc31190d0263a.GZqzUp6SCY9ENtc0FcOv2wsgRHb1voVqylP7KI73oes
+ hash: v1.k794b7964.6efe4fd821e7998a183eb6d33db4a487ec71fd35cf2fe6e0614c956a8cec7449.6xWxegB41pF29DImyI9O1IeC79kYTof0dtkbGM9KQI0
scenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--dark:
- hash: v1.k794b7964.05e649d1fffdae1a3ab3e04ac3f9e4250dbfa1458bf627fcbef13552f3cd8987.5DIsAmvBW_GRTUuaeOfyldf8S5ZbrKIye5C_QKVOz_0
+ hash: v1.k794b7964.62b167adcafc76a8c01a26d37939afcc00b9f7ace66910a5236526f1bf11144f.RCmivZXFHuoNRG0x8wPDho2x2ThctzI-lFv0SsJvjF4
scenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--light:
- hash: v1.k794b7964.d046e7c378631fbc809bf0516603a283be253fbfe9ee3c8670ef9f048240f8a5.Eup-VPPpS0s9a1iCk1V6W9Qo2fJ_05f1XcZfa5Alfw8
+ hash: v1.k794b7964.3ee8965d914ac6af5d66285e6733dded35a1cf679a8a3a9ab0ea0d5eb948e004.Vn5DPuXlDMqEHmhNLH1MtedCQWZV3-1Wo-hG8HxSdlc
scenes-app-product-analytics-home-overview--before-ingestion--dark:
hash: v1.k794b7964.c6719ac435ec9e335d235a619e587df0c2042dd8398292f09b68a49e073af467.rXNWamLv05QF9cI9nWYAhCxBuecO6fh4oabPA_NGBqA
scenes-app-product-analytics-home-overview--before-ingestion--light:
diff --git a/frontend/src/lib/components/AnalyticsMetricCard/AnalyticsMetricCard.tsx b/frontend/src/lib/components/AnalyticsMetricCard/AnalyticsMetricCard.tsx
index 6225539bb77d..040309dc3e9d 100644
--- a/frontend/src/lib/components/AnalyticsMetricCard/AnalyticsMetricCard.tsx
+++ b/frontend/src/lib/components/AnalyticsMetricCard/AnalyticsMetricCard.tsx
@@ -19,8 +19,8 @@ export interface AnalyticsMetricCardProps extends Omit<
'children' | 'series'
> {
title: ReactNode
- /** Render the change pill next to the headline instead of in the title row. */
- changeInline?: boolean
+ /** Render the change pill after the subtitle instead of in the title row. */
+ changeBesideSubtitle?: boolean
loading?: boolean
error?: ReactNode
emptyMessage?: ReactNode
@@ -45,7 +45,7 @@ export function AnalyticsMetricCard({
className,
dataAttr,
title,
- changeInline = false,
+ changeBesideSubtitle = false,
...metricProps
}: AnalyticsMetricCardProps): JSX.Element {
const Content = onClick ? 'button' : 'div'
@@ -101,23 +101,28 @@ export function AnalyticsMetricCard({
</span>
) : (
<Metric {...metricProps} className="w-full px-3">
- {(label || !changeInline) && (
+ {(label || !changeBesideSubtitle) && (
// The spare height goes above the headline, so a wrapped title does not move it.
- <MetricHeader className={clsx(!changeInline && 'flex-1', !label && 'justify-end')}>
+ <MetricHeader className={clsx(!changeBesideSubtitle && 'flex-1', !label && 'justify-end')}>
{label && <MetricTitle>{label}</MetricTitle>}
- {!changeInline && <MetricDelta />}
+ {!changeBesideSubtitle && <MetricDelta />}
</MetricHeader>
)}
- {changeInline ? (
- // Wraps so a narrow card moves the pill under the number instead of clipping it.
- <div className="flex flex-wrap items-center justify-between gap-2">
+ {changeBesideSubtitle ? (
+ <>
<MetricValue className={clsx(label && 'mt-2')} />
- <MetricDelta />
- </div>
+ {/* The subtitle truncates, so the pill never wraps when hover changes the text width. */}
+ <div className="mt-1 flex flex-1 items-start gap-2">
+ <MetricSubtitle className="min-w-0 flex-1 truncate" />
+ <MetricDelta className="ml-auto shrink-0" />
+ </div>
+ </>
) : (
- <MetricValue className="mt-2" />
+ <>
+ <MetricValue className="mt-2" />
+ <MetricSubtitle className="mt-1" />
+ </>
)}
- <MetricSubtitle className={clsx('mt-1', changeInline && 'flex-1')} />
<MetricSparkline className="-mx-3 -mb-3 mt-3" />
</Metric>
)}
diff --git a/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx b/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
index e78b46598b11..f2fe80afa97c 100644
--- a/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
+++ b/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
@@ -49,7 +49,9 @@ export function SceneDashboardChoiceModal({ scene }: SceneDashboardChoiceModalPr
closeSceneDashboardChoiceModal()
}}
>
- {scene === Scene.ProductAnalyticsHomeTab ? 'Use default dashboard' : 'Reset to "new tab"'}
+ {scene === Scene.ProductAnalyticsHomeTab
+ ? 'Reset to PostHog default'
+ : 'Reset to "new tab"'}
</LemonButton>
) : null}
<LemonButton
@@ -96,7 +98,7 @@ export function SceneDashboardChoiceModal({ scene }: SceneDashboardChoiceModalPr
) : (
<strong className="set-default-text">
{scene === Scene.ProductAnalyticsHomeTab
- ? 'Set as Home dashboard'
+ ? 'Show on this page'
: 'Set as default'}
</strong>
)}
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts
index defc863d524d..14e34effe7bd 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts
@@ -28,6 +28,7 @@ export interface DataNodeRegisteredProps {
export interface CollectionNodeLoadMeta {
isCached?: boolean
+ lastRefresh?: string | null
}
export interface DataNodeCollectionProps {
@@ -37,6 +38,7 @@ export interface DataNodeCollectionProps {
export interface DataNodeStatus {
isLoading: boolean
hasError: boolean
+ lastRefresh?: string | null
}
export type DataNodeStatusMap = Record<string, DataNodeStatus | undefined>
@@ -183,7 +185,10 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([
return { ...state, [payload.id]: { isLoading: true, hasError: false } }
},
collectionNodeLoadDataSuccess: (state, payload) => {
- return { ...state, [payload.id]: { isLoading: false, hasError: false } }
+ return {
+ ...state,
+ [payload.id]: { isLoading: false, hasError: false, lastRefresh: payload.meta?.lastRefresh },
+ }
},
collectionNodeLoadDataFailure: (state, payload) => {
return { ...state, [payload.id]: { isLoading: false, hasError: true } }
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index c42c11c76d34..b0d9c0c1eb3a 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -2283,6 +2283,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
props.onData?.(response as Record<string, unknown> | null | undefined)
actions.collectionNodeLoadDataSuccess(props.key, {
isCached: !!response && typeof response === 'object' && 'is_cached' in response && !!response.is_cached,
+ lastRefresh: values.lastRefresh,
})
if ('query' in props.query) {
cache.localResults[JSON.stringify(props.query.query)] = response
diff --git a/frontend/src/scenes/analytics/AnalyticsProductHome.test.tsx b/frontend/src/scenes/analytics/AnalyticsProductHome.test.tsx
index 26f1a2908748..0d901bb24af9 100644
--- a/frontend/src/scenes/analytics/AnalyticsProductHome.test.tsx
+++ b/frontend/src/scenes/analytics/AnalyticsProductHome.test.tsx
@@ -11,7 +11,12 @@ import { initKeaTests } from '~/test/init'
import { AnalyticsProductHome } from './AnalyticsProductHome'
jest.mock('products/product_analytics/frontend/insights/home/HomeTab', () => ({
- HomeTab: () => <div>Product analytics dashboard</div>,
+ HomeTab: ({ page }: { page: { title: JSX.Element } }) => (
+ <>
+ {page.title}
+ <div>Product analytics dashboard</div>
+ </>
+ ),
}))
jest.mock('products/product_analytics/frontend/insights/home/HomeDashboardModals', () => ({
@@ -56,15 +61,15 @@ describe('AnalyticsProductHome', () => {
})
test.each([
- ['the default dashboard', null, 'Make my own dashboard'],
- ['a custom Home dashboard', 42, 'Home dashboard options'],
- ])('lets the user change Home from %s', (_scenario, homeDashboardId, expectedControl) => {
+ ['the default dashboard', null, 'home-tab-choose-dashboard'],
+ ['a custom dashboard', 42, 'home-tab-dashboard-options'],
+ ])('shows a labeled Customize control for %s', (_scenario, homeDashboardId, expectedDataAttr) => {
featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: true })
teamLogic.mount()
teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, home_tab_dashboard: homeDashboardId })
- render(<AnalyticsProductHome />)
+ const { container } = render(<AnalyticsProductHome />)
- expect(screen.queryByText(expectedControl) ?? screen.queryByLabelText(expectedControl)).not.toBeNull()
+ expect(container.querySelector(`[data-attr="${expectedDataAttr}"]`)?.textContent).toBe('Customize')
})
})
diff --git a/frontend/src/scenes/analytics/AnalyticsProductHome.tsx b/frontend/src/scenes/analytics/AnalyticsProductHome.tsx
index 861be9c21c2c..0db6255369f3 100644
--- a/frontend/src/scenes/analytics/AnalyticsProductHome.tsx
+++ b/frontend/src/scenes/analytics/AnalyticsProductHome.tsx
@@ -24,13 +24,19 @@ export function AnalyticsProductHome(): JSX.Element {
}
return (
<SceneContent>
- <SceneTitleSection
- name="Product analytics"
- description="How people use your product, ready-made by PostHog."
- resourceType={{ type: 'analytics', forceIcon: <AnalyticsTypeIcon type="insight" /> }}
- actions={<HomeDashboardMenu />}
+ <HomeTab
+ page={{
+ title: (
+ <SceneTitleSection
+ name="Product analytics"
+ description="How people use your product, ready-made by PostHog."
+ resourceType={{ type: 'analytics', forceIcon: <AnalyticsTypeIcon type="insight" /> }}
+ actions={<HomeDashboardMenu />}
+ />
+ ),
+ dashboardHeaderActions: <HomeDashboardMenu inDashboardHeader />,
+ }}
/>
- <HomeTab />
<HomeDashboardModals />
<AnalyticsCreateModals />
</SceneContent>
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index a72c750687f4..20c5e439bba0 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -66,6 +66,12 @@ interface DashboardProps {
showCreateAnomalyAlertButton?: boolean
/** Shows the dashboard without tile menus or drag-to-edit controls. */
readOnly?: boolean
+ /** Extra controls for the dashboard header, when a page shows the dashboard as its main content. */
+ headerActions?: JSX.Element
+ /** Uses less vertical space above the tiles, for a page where the dashboard is a product's home. */
+ compact?: boolean
+ /** The parent page reloads the dashboard when PostHog AI adds charts to it, so the header does not. */
+ parentReloadsOnAIChanges?: boolean
}
export const parseDashboardId = (id: string | undefined): number => {
@@ -98,12 +104,21 @@ export function Dashboard({
backTo,
showCreateAnomalyAlertButton,
readOnly,
+ headerActions,
+ compact,
+ parentReloadsOnAIChanges,
}: DashboardProps): JSX.Element {
useMountedLogic(dataThemeLogic({ themes }))
return (
<BindLogic logic={dashboardLogic} props={{ id: parseDashboardId(id), placement, dashboard, readOnly }}>
- <DashboardScene backTo={backTo} showCreateAnomalyAlertButton={showCreateAnomalyAlertButton} />
+ <DashboardScene
+ backTo={backTo}
+ showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
+ headerActions={headerActions}
+ compact={compact}
+ parentReloadsOnAIChanges={parentReloadsOnAIChanges}
+ />
</BindLogic>
)
}
@@ -111,9 +126,15 @@ export function Dashboard({
function DashboardScene({
backTo,
showCreateAnomalyAlertButton,
+ headerActions,
+ compact,
+ parentReloadsOnAIChanges,
}: {
backTo?: { url: string; name: string }
showCreateAnomalyAlertButton?: boolean
+ headerActions?: JSX.Element
+ compact?: boolean
+ parentReloadsOnAIChanges?: boolean
}): JSX.Element {
const {
placement,
@@ -182,9 +203,13 @@ function DashboardScene({
}
return (
- <SceneContent className={cn('dashboard')}>
+ <SceneContent className={cn('dashboard', compact && 'gap-y-2')}>
{placement == DashboardPlacement.Dashboard && (
- <DashboardHeader loading={!dashboard && !dashboardFailedToLoad} />
+ <DashboardHeader
+ loading={!dashboard && !dashboardFailedToLoad}
+ extraActions={headerActions}
+ reloadOnAIChanges={!parentReloadsOnAIChanges}
+ />
)}
{placement == DashboardPlacement.Dashboard && !!dashboard?.id && (
<DashboardSubscribeNudgeTrigger dashboardId={dashboard.id} />
@@ -254,7 +279,7 @@ function DashboardScene({
<DashboardQueryScanBanner />
<DashboardWarehouseSyncBanner />
- <SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0">
+ <SceneStickyBar showBorderBottom={false} className={cn('flex gap-2 space-y-0', compact && 'py-1')}>
<DashboardFilterBar backTo={backTo} />
{layoutEditMode &&
canEditDashboard &&
diff --git a/frontend/src/scenes/dashboard/DashboardHeader.tsx b/frontend/src/scenes/dashboard/DashboardHeader.tsx
index 69fd9d9c5571..ed63d75d2a21 100644
--- a/frontend/src/scenes/dashboard/DashboardHeader.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeader.tsx
@@ -27,7 +27,15 @@ export function insightIsAddedToDashboard(input: Record<string, unknown> | null,
return Array.isArray(input?.dashboards) && input.dashboards.some((id) => Number(id) === dashboardId)
}
-export function DashboardHeader({ loading = false }: { loading?: boolean }): JSX.Element | null {
+export function DashboardHeader({
+ loading = false,
+ extraActions,
+ reloadOnAIChanges = true,
+}: {
+ loading?: boolean
+ extraActions?: JSX.Element
+ reloadOnAIChanges?: boolean
+}): JSX.Element | null {
const { dashboard, dashboardLoading, dashboardMode, dashboardEditing, canEditDashboard } = useValues(dashboardLogic)
const { setDashboardMode, loadDashboard } = useActions(dashboardLogic)
const { updateDashboard } = useActions(dashboardsModel)
@@ -40,7 +48,7 @@ export function DashboardHeader({ loading = false }: { loading?: boolean }): JSX
useMcpToolApplyBack({
tools: ['insight-create', 'insight-update'],
targetKey: `dashboard:${dashboard?.id ?? 'unloaded'}`,
- active: !!dashboard && canEditDashboard,
+ active: reloadOnAIChanges && !!dashboard && canEditDashboard,
onApply: (_event, { innerInput }) => {
if (dashboard && insightIsAddedToDashboard(innerInput, dashboard.id)) {
loadDashboard({ action: DashboardLoadAction.Update })
@@ -116,7 +124,12 @@ export function DashboardHeader({ loading = false }: { loading?: boolean }): JSX
}
: undefined
}
- actions={todayRailNav && dashboard ? <QuillDashboardHeaderActions /> : actions}
+ actions={
+ <>
+ {todayRailNav && dashboard ? <QuillDashboardHeaderActions /> : actions}
+ {extraActions}
+ </>
+ }
/>
</>
)
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index e2baec4150e9..6c712d14ef66 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -3091,35 +3091,38 @@ describe('dashboardLogic', () => {
}
})
- it('restores filters when browser history changes the URL', async () => {
- await expectLogic(logic).toFinishAllListeners()
+ it.each(['/dashboard/5', urls.analyticsProductHome()])(
+ 'restores filters when browser history changes the URL on %s',
+ async (pathname) => {
+ await expectLogic(logic).toFinishAllListeners()
- await expectLogic(logic, () => {
- logic.actions.setDates('-30d', null)
- }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-30d', null)
+ }).toFinishAllListeners()
- const searchParams = {
- [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d', date_to: null }),
- }
- await expectLogic(logic, () => {
- router.actions.locationChanged({
- method: 'POP',
- pathname: '/dashboard/5',
- search: '',
- searchParams,
- hash: '',
- hashParams: {},
- url: '/dashboard/5',
- })
- }).toFinishAllListeners()
+ const searchParams = {
+ [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d', date_to: null }),
+ }
+ await expectLogic(logic, () => {
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname,
+ search: '',
+ searchParams,
+ hash: '',
+ hashParams: {},
+ url: pathname,
+ })
+ }).toFinishAllListeners()
- expect(logic.values.currentDashboardSettings.filters).toEqual(
- expect.objectContaining({ date_from: '-7d', date_to: null })
- )
- expect(logic.values.filtersOverrideForLoad).toEqual(
- expect.objectContaining({ date_from: '-7d', date_to: null })
- )
- })
+ expect(logic.values.currentDashboardSettings.filters).toEqual(
+ expect.objectContaining({ date_from: '-7d', date_to: null })
+ )
+ expect(logic.values.filtersOverrideForLoad).toEqual(
+ expect.objectContaining({ date_from: '-7d', date_to: null })
+ )
+ }
+ )
})
describe('external filter overrides', () => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 54e169f668ed..cfea4631b5c2 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -6739,84 +6739,96 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
})),
- urlToAction(({ values, actions }) => ({
- '/dashboard/:id/subscriptions(/:subscriptionId)': ({ subscriptionId }) => {
- const id = subscriptionId
- ? subscriptionId == 'new'
- ? subscriptionId
- : parseInt(subscriptionId, 10)
- : undefined
- actions.setSubscriptionMode(true, id)
- actions.setTextTileId(null)
- actions.setButtonTileId(null)
- actions.setDashboardMode(null, DashboardEventSource.Browser)
- actions.setDashboardEditing(null, DashboardEventSource.Browser)
- },
+ urlToAction(({ values, actions }) => {
+ const restoreSettingsFromHistory = (searchParams: Record<string, any>): void => {
+ const current = values.currentDashboardSettings
+ const settings: DashboardSettings = {
+ filters: combineSavedAndUrlFilters(
+ values.savedDashboardSettings.filters,
+ parseURLFilters(searchParams)
+ ),
+ // Browser history carries SQL variables as well as filters. Until the variable
+ // definitions load there is nothing to map the URL values onto, so the current
+ // values stay.
+ variables: values.initialVariablesLoaded
+ ? { ...values.savedDashboardSettings.variables, ...values.urlVariables }
+ : current.variables,
+ }
- '/dashboard/:id': (_params, searchParams, _hashParams, { method }) => {
- actions.revealHighlightedInsight()
- actions.setSubscriptionMode(false, undefined)
- actions.setTextTileId(null)
- actions.setButtonTileId(null)
- if (method === 'POP' && values.dashboard) {
- const current = values.currentDashboardSettings
- const settings: DashboardSettings = {
- filters: combineSavedAndUrlFilters(
- values.savedDashboardSettings.filters,
- parseURLFilters(searchParams)
- ),
- // Browser history carries SQL variables as well as filters. Until the variable
- // definitions load there is nothing to map the URL values onto, so the current
- // values stay.
- variables: values.initialVariablesLoaded
- ? { ...values.savedDashboardSettings.variables, ...values.urlVariables }
- : current.variables,
+ // Back and Forward also arrive from routes that leave the settings alone, such as the
+ // sharing page. Rebuilding the settings there would re-query every tile and cancel a
+ // refresh in flight for values the dashboard already holds.
+ if (
+ !dashboardFiltersEqual(current.filters, settings.filters) ||
+ !equal(current.variables, settings.variables)
+ ) {
+ actions.setDashboardSettingsDraft(settings)
+ if (values.canAutoPreview) {
+ actions.refreshDashboardItems({
+ action: RefreshDashboardItemsAction.Preview,
+ forceRefresh: false,
+ })
}
+ }
+ }
- // Back and Forward also arrive from routes that leave the settings alone, such as the
- // sharing page. Rebuilding the settings there would re-query every tile and cancel a
- // refresh in flight for values the dashboard already holds.
- if (
- !dashboardFiltersEqual(current.filters, settings.filters) ||
- !equal(current.variables, settings.variables)
- ) {
- actions.setDashboardSettingsDraft(settings)
- if (values.canAutoPreview) {
- actions.refreshDashboardItems({
- action: RefreshDashboardItemsAction.Preview,
- forceRefresh: false,
- })
- }
+ return {
+ '/dashboard/:id/subscriptions(/:subscriptionId)': ({ subscriptionId }) => {
+ const id = subscriptionId
+ ? subscriptionId == 'new'
+ ? subscriptionId
+ : parseInt(subscriptionId, 10)
+ : undefined
+ actions.setSubscriptionMode(true, id)
+ actions.setTextTileId(null)
+ actions.setButtonTileId(null)
+ actions.setDashboardMode(null, DashboardEventSource.Browser)
+ actions.setDashboardEditing(null, DashboardEventSource.Browser)
+ },
+
+ '/dashboard/:id': (_params, searchParams, _hashParams, { method }) => {
+ actions.revealHighlightedInsight()
+ actions.setSubscriptionMode(false, undefined)
+ actions.setTextTileId(null)
+ actions.setButtonTileId(null)
+ if (method === 'POP' && values.dashboard) {
+ restoreSettingsFromHistory(searchParams)
}
- }
- if (values.dashboardMode === DashboardMode.Sharing) {
+ if (values.dashboardMode === DashboardMode.Sharing) {
+ actions.setDashboardMode(null, DashboardEventSource.Browser)
+ }
+ switch (searchParams.tileType) {
+ case 'text':
+ actions.openTextTileModal()
+ break
+ case 'image':
+ actions.openImageTileModal()
+ break
+ case 'button':
+ actions.openButtonTileModal()
+ break
+ }
+ },
+ '/dashboard/:id/sharing': () => {
+ actions.setSubscriptionMode(false, undefined)
+ actions.setTextTileId(null)
+ actions.setButtonTileId(null)
+ actions.setDashboardMode(DashboardMode.Sharing, DashboardEventSource.Browser)
+ },
+ '/dashboard/:id/tiles/:tileId': ({ tileId }) => {
+ actions.setSubscriptionMode(false, undefined)
actions.setDashboardMode(null, DashboardEventSource.Browser)
- }
- switch (searchParams.tileType) {
- case 'text':
- actions.openTextTileModal()
- break
- case 'image':
- actions.openImageTileModal()
- break
- case 'button':
- actions.openButtonTileModal()
- break
- }
- },
- '/dashboard/:id/sharing': () => {
- actions.setSubscriptionMode(false, undefined)
- actions.setTextTileId(null)
- actions.setButtonTileId(null)
- actions.setDashboardMode(DashboardMode.Sharing, DashboardEventSource.Browser)
- },
- '/dashboard/:id/tiles/:tileId': ({ tileId }) => {
- actions.setSubscriptionMode(false, undefined)
- actions.setDashboardMode(null, DashboardEventSource.Browser)
- actions.setDashboardEditing(null, DashboardEventSource.Browser)
- const parsedTileId = parseDashboardTileId(tileId)
- actions.setTextTileId(parsedTileId)
- actions.setButtonTileId(parsedTileId)
- },
- })),
+ actions.setDashboardEditing(null, DashboardEventSource.Browser)
+ const parsedTileId = parseDashboardTileId(tileId)
+ actions.setTextTileId(parsedTileId)
+ actions.setButtonTileId(parsedTileId)
+ },
+ // The product analytics page shows a full dashboard at its own URL.
+ [urls.analyticsProductHome()]: (_params, searchParams, _hashParams, { method }) => {
+ if (method === 'POP' && values.dashboard && values.placement === DashboardPlacement.Dashboard) {
+ restoreSettingsFromHistory(searchParams)
+ }
+ },
+ }
+ }),
])
diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.ts
index 2b6d247ad319..ea293b1b7927 100644
--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts
+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts
@@ -269,6 +269,15 @@ export type newDashboardLogicType = MakeLogicType<
newDashboardLogicMeta
>
+export function openHomeDashboardAIChat(dashboardId: number): void {
+ sidePanelStateLogic.actions.openSidePanel(
+ SidePanelTab.Max,
+ autoRunMaxPrompt(
+ `Help me build my product analytics dashboard (dashboard ID ${dashboardId}). Ask me what I want to track, then add relevant insights to this dashboard.`
+ )
+ )
+}
+
export const newDashboardLogic = kea<newDashboardLogicType>([
props({} as NewDashboardLogicProps),
key(({ featureFlagId }) => featureFlagId ?? 'new'),
@@ -439,21 +448,16 @@ export const newDashboardLogic = kea<newDashboardLogicType>([
await teamLogic.asyncActions.updateCurrentTeam({ home_tab_dashboard: result.id })
// Loader failures finish asyncActions without throwing, so confirm the saved selection.
if (teamLogic.values.currentTeam?.home_tab_dashboard !== result.id) {
- lemonToast.error('Could not set this dashboard as Home. Please try again.')
+ lemonToast.error("Couldn't show this dashboard in product analytics. Try again.")
return
}
} catch {
- lemonToast.error('Could not set this dashboard as Home. Please try again.')
+ lemonToast.error("Couldn't show this dashboard in product analytics. Try again.")
return
}
}
if (openAI) {
- sidePanelStateLogic.actions.openSidePanel(
- SidePanelTab.Max,
- autoRunMaxPrompt(
- `Help me build my product analytics Home dashboard (dashboard ID ${result.id}). Ask me what I want to track, then add relevant insights to this dashboard.`
- )
- )
+ openHomeDashboardAIChat(result.id)
}
},
})),
diff --git a/products/product_analytics/frontend/insights/home/HomeDashboardMenu.tsx b/products/product_analytics/frontend/insights/home/HomeDashboardMenu.tsx
index 3fdd6fc772ca..58e43ffda5a4 100644
--- a/products/product_analytics/frontend/insights/home/HomeDashboardMenu.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeDashboardMenu.tsx
@@ -1,55 +1,67 @@
import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-import { IconEllipsis } from '@posthog/icons'
+import { IconChevronDown, IconEllipsis } from '@posthog/icons'
import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@posthog/quill'
import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
import { homeDashboardChoiceLogic } from './homeDashboardChoiceLogic'
-/** Opens, changes, or removes the dashboard that replaces the default product analytics Home. */
-export function HomeDashboardMenu(): JSX.Element {
+/** Opens, changes, or removes the dashboard that replaces the default product analytics dashboard. */
+export function HomeDashboardMenu({
+ inDashboardHeader = false,
+}: {
+ /** The dashboard header has its own Customize button, so this menu only changes which dashboard shows. */
+ inDashboardHeader?: boolean
+}): JSX.Element {
const { currentTeam } = useValues(teamLogic)
- const { push } = useActions(router)
- const { openHomeDashboardStarter, restorePostHogHome } = useActions(homeDashboardChoiceLogic)
+ const { openHomeDashboardStarter, editHomeDashboard, restorePostHogHome } = useActions(homeDashboardChoiceLogic)
const homeDashboardId = currentTeam?.home_tab_dashboard
if (!homeDashboardId) {
return (
<Button variant="outline" onClick={openHomeDashboardStarter} data-attr="home-tab-choose-dashboard">
- Make my own dashboard
+ Customize
</Button>
)
}
return (
<DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- size="icon"
- aria-label="Home dashboard options"
- tooltip="Home dashboard options"
- data-attr="home-tab-dashboard-options"
- />
- }
- >
- <IconEllipsis />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-48">
- <DropdownMenuItem
- onClick={() => push(urls.dashboard(homeDashboardId))}
- data-attr="home-tab-open-dashboard"
+ {inDashboardHeader ? (
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon"
+ aria-label="Dashboard options"
+ tooltip="Dashboard options"
+ data-attr="home-tab-dashboard-options"
+ />
+ }
>
- Open dashboard
- </DropdownMenuItem>
+ <IconEllipsis />
+ </DropdownMenuTrigger>
+ ) : (
+ <DropdownMenuTrigger render={<Button variant="outline" data-attr="home-tab-dashboard-options" />}>
+ Customize
+ <IconChevronDown />
+ </DropdownMenuTrigger>
+ )}
+ <DropdownMenuContent align="end" className="min-w-48">
+ {!inDashboardHeader && (
+ <DropdownMenuItem
+ onClick={() => editHomeDashboard(homeDashboardId)}
+ data-attr="home-tab-open-dashboard"
+ >
+ Edit dashboard
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={openHomeDashboardStarter} data-attr="home-tab-choose-dashboard">
- Change Home dashboard
+ Show a different dashboard
</DropdownMenuItem>
<DropdownMenuItem onClick={restorePostHogHome} data-attr="home-tab-restore-posthog-home">
- Use default dashboard
+ Reset to PostHog default
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
index 9da7d2277ee9..2ce6bd6f863e 100644
--- a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
@@ -31,8 +31,9 @@ export function HomeDashboardStarterModal({
const creationDisabledReason = creatingWithAI ? 'Creating your dashboard…' : undefined
const choices = [
{
- title: 'Copy default dashboard',
- description: 'Start with the charts you see on Home, then edit, add, or remove them.',
+ title: 'Copy and edit the default dashboard',
+ description:
+ 'Copy the charts on this page so you can edit, add, or remove them. You can reset to the PostHog default at any time.',
icon: <IconCopy />,
onClick: onCopyPostHogHome,
dataAttr: 'home-dashboard-copy-posthog-home',
@@ -59,7 +60,7 @@ export function HomeDashboardStarterModal({
},
{
title: 'Choose an existing dashboard',
- description: 'Use one of this project’s dashboards for Home.',
+ description: 'Show one of this project’s dashboards on this page.',
icon: <IconDashboard />,
onClick: onChooseExisting,
dataAttr: 'home-dashboard-choose-existing',
@@ -72,8 +73,8 @@ export function HomeDashboardStarterModal({
<LemonModal
isOpen={isOpen}
onClose={onClose}
- title="Make my own dashboard"
- description="Choose how to get started, or use a dashboard you already have."
+ title="Customize this dashboard"
+ description="Copy the default dashboard to edit it, or show a different dashboard on this page."
width="38rem"
maxWidth="calc(100vw - 2rem)"
data-attr="home-dashboard-starter-modal"
@@ -112,7 +113,7 @@ export function HomeDashboardStarterModal({
data-attr="home-dashboard-restore-posthog-home"
>
<span className="flex min-w-0 flex-col gap-0.5 py-1">
- <span className="font-semibold">Use default dashboard</span>
+ <span className="font-semibold">Reset to PostHog default</span>
<span className="whitespace-normal text-xs font-normal text-secondary">
Go back to the default product analytics dashboard.
</span>
diff --git a/products/product_analytics/frontend/insights/home/HomeTab.test.tsx b/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
index b1f4bc0664ed..ad4ffe73c3b5 100644
--- a/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
@@ -8,6 +8,9 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
+import { DashboardType } from '~/types'
+
+import { toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'
import { HomeTab } from './HomeTab'
import { homeTabDashboardProps } from './homeTabDashboardLogic'
@@ -16,16 +19,45 @@ jest.mock('./HomeTabDefault', () => ({
HomeTabDefault: () => <div>PostHog Home</div>,
}))
jest.mock('scenes/dashboard/Dashboard', () => ({
- Dashboard: ({ id }: { id: string }) => <div>Home dashboard {id}</div>,
+ Dashboard: ({
+ id,
+ placement,
+ readOnly,
+ headerActions,
+ }: {
+ id: string
+ placement: string
+ readOnly?: boolean
+ headerActions?: JSX.Element
+ }) => (
+ <>
+ <div>Home dashboard {id}</div>
+ <div>{`placement: ${placement}, read-only: ${!!readOnly}`}</div>
+ {headerActions}
+ </>
+ ),
}))
+const PAGE = { title: <div>Page title</div>, dashboardHeaderActions: <div>Customize menu</div> }
+
describe('HomeTab', () => {
afterEach(cleanup)
it.each([
- ['the opinionated Home dashboard', null, 'PostHog Home'],
- ['a selected Home dashboard', 42, 'Home dashboard 42'],
- ])('renders %s', (_scenario, existingDashboardId, expectedContent) => {
+ ['the opinionated Home dashboard', null, undefined, ['PostHog Home']],
+ [
+ 'a selected dashboard inside the Insights tab',
+ 42,
+ undefined,
+ ['Home dashboard 42', 'placement: builtin, read-only: true'],
+ ],
+ [
+ 'a selected dashboard as the whole page, with its own header',
+ 42,
+ PAGE,
+ ['Home dashboard 42', 'placement: dashboard, read-only: false', 'Customize menu'],
+ ],
+ ])('renders %s', (_scenario, existingDashboardId, page, expectedContents) => {
initKeaTests()
teamLogic.mount()
teamLogic.actions.loadCurrentTeamSuccess({
@@ -33,10 +65,71 @@ describe('HomeTab', () => {
home_tab_dashboard: existingDashboardId,
})
+ render(<HomeTab page={page} />)
+ for (const expectedContent of expectedContents) {
+ expect(screen.getByText(expectedContent)).toBeInTheDocument()
+ }
+ expect(screen.queryByText('Page title')).not.toBeInTheDocument()
+ })
+
+ it.each([
+ ['offers a way back when the selected dashboard has no charts', [], false, 'This dashboard has no charts yet'],
+ ['shows the selected dashboard when it has charts', [{ id: 1, deleted: false }], false, 'Home dashboard 42'],
+ [
+ 'keeps the dashboard error and retry when a reload of an empty dashboard fails',
+ [],
+ true,
+ 'Home dashboard 42',
+ ],
+ ])('%s', (_scenario, tiles, reloadFails, expectedContent) => {
+ initKeaTests()
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ home_tab_dashboard: 42,
+ })
render(<HomeTab />)
+
+ act(() => {
+ dashboardLogic(homeTabDashboardProps(42)).actions.loadDashboardSuccess({
+ id: 42,
+ tiles,
+ } as unknown as DashboardType)
+ if (reloadFails) {
+ dashboardLogic(homeTabDashboardProps(42)).actions.loadDashboardFailure('Network error')
+ }
+ })
+
expect(screen.getByText(expectedContent)).toBeInTheDocument()
})
+ it('keeps the same AI listener when the first chart replaces the empty state', () => {
+ initKeaTests()
+ toolStreamEventsLogic.mount()
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ home_tab_dashboard: 42,
+ })
+ render(<HomeTab page={PAGE} />)
+ const loadDashboard = (tiles: unknown[]): void =>
+ act(() => {
+ dashboardLogic(homeTabDashboardProps(42, 'page')).actions.loadDashboardSuccess({
+ id: 42,
+ tiles,
+ user_access_level: 'editor',
+ } as unknown as DashboardType)
+ })
+
+ loadDashboard([])
+ const listenersOnEmptyDashboard = Object.keys(toolStreamEventsLogic.values.toolListeners)
+ loadDashboard([{ id: 1, deleted: false }])
+
+ expect(screen.getByText('Home dashboard 42')).toBeInTheDocument()
+ expect(listenersOnEmptyDashboard).toHaveLength(1)
+ expect(Object.keys(toolStreamEventsLogic.values.toolListeners)).toEqual(listenersOnEmptyDashboard)
+ })
+
it('falls back to PostHog Home and reloads the team when the selected dashboard is gone', () => {
initKeaTests()
teamLogic.mount()
diff --git a/products/product_analytics/frontend/insights/home/HomeTab.tsx b/products/product_analytics/frontend/insights/home/HomeTab.tsx
index 6c71c76a2c60..9d0ca4f905b4 100644
--- a/products/product_analytics/frontend/insights/home/HomeTab.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTab.tsx
@@ -7,10 +7,17 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
-import { HomeTabDashboard } from './HomeTabDashboard'
+import { HomeTabDashboard, HomeTabPage } from './HomeTabDashboard'
import { HomeTabDefault } from './HomeTabDefault'
-export function HomeTab({ dashboardActions }: { dashboardActions?: ReactNode }): JSX.Element {
+export function HomeTab({
+ dashboardActions,
+ page,
+}: {
+ dashboardActions?: ReactNode
+ /** Set when Home is the whole page: a custom dashboard then shows as the full, editable dashboard. */
+ page?: HomeTabPage
+}): JSX.Element {
const { currentTeam, currentTeamLoading } = useValues(teamLogic)
const { isLoading: dashboardCreationLoading } = useValues(newDashboardLogic)
@@ -20,29 +27,45 @@ export function HomeTab({ dashboardActions }: { dashboardActions?: ReactNode }):
if (!currentTeam && currentTeamLoading) {
return (
- <div className="flex min-h-80 flex-col gap-3 py-3" aria-label="Loading product analytics Home">
- <LemonSkeleton.Row repeat={3} />
+ <>
+ {page?.title}
+ <div className="flex min-h-80 flex-col gap-3 py-3" aria-label="Loading product analytics Home">
+ <LemonSkeleton.Row repeat={3} />
+ </div>
+ </>
+ )
+ }
+
+ if (currentTeam?.home_tab_dashboard && !dashboardCreationLoading) {
+ return (
+ <div className="@container/home-tab pb-4 @min-[48rem]/saved-insights:py-3">
+ <HomeTabDashboard
+ dashboardId={currentTeam.home_tab_dashboard}
+ dashboardActions={dashboardActions}
+ page={page}
+ />
</div>
)
}
return (
- <div className="@container/home-tab pb-4 @min-[48rem]/saved-insights:py-3">
- {dashboardCreationLoading ? (
- <div
- className="flex min-h-80 flex-col gap-3 py-3"
- role="status"
- aria-live="polite"
- aria-label="Creating your Home dashboard"
- >
- <div className="font-semibold">Creating your Home dashboard…</div>
- <LemonSkeleton.Row repeat={3} />
- </div>
- ) : currentTeam?.home_tab_dashboard ? (
- <HomeTabDashboard dashboardId={currentTeam.home_tab_dashboard} dashboardActions={dashboardActions} />
- ) : (
- <HomeTabDefault dashboardActions={dashboardActions} />
- )}
- </div>
+ <>
+ {page?.title}
+ <div className="@container/home-tab pb-4 @min-[48rem]/saved-insights:py-3">
+ {dashboardCreationLoading ? (
+ <div
+ className="flex min-h-80 flex-col gap-3 py-3"
+ role="status"
+ aria-live="polite"
+ aria-label="Creating your dashboard"
+ >
+ <div className="font-semibold">Creating your dashboard…</div>
+ <LemonSkeleton.Row repeat={3} />
+ </div>
+ ) : (
+ <HomeTabDefault dashboardActions={dashboardActions} />
+ )}
+ </div>
+ </>
)
}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx b/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx
index da0331673cf7..029598681161 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx
@@ -1,27 +1,101 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import type { ReactNode } from 'react'
import { Dashboard } from 'scenes/dashboard/Dashboard'
+import { DASHBOARD_CANNOT_EDIT_MESSAGE, insightIsAddedToDashboard } from 'scenes/dashboard/DashboardHeader'
+import { DashboardLoadAction } from 'scenes/dashboard/dashboardLogic'
+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+
+import { homeDashboardChoiceLogic } from './homeDashboardChoiceLogic'
import { homeTabDashboardLogic, homeTabDashboardProps } from './homeTabDashboardLogic'
import { HomeTabDefault } from './HomeTabDefault'
+import { HomeTabEmptyDashboard } from './HomeTabEmptyDashboard'
+
+export interface HomeTabPage {
+ /** The page title, shown when Home does not show the full dashboard. */
+ title: JSX.Element
+ /** Controls added to the dashboard header when the full dashboard is the page. */
+ dashboardHeaderActions: JSX.Element
+}
export function HomeTabDashboard({
dashboardId,
dashboardActions,
+ page,
}: {
dashboardId: number
dashboardActions?: ReactNode
+ page?: HomeTabPage
}): JSX.Element {
- const { dashboardMissing } = useValues(homeTabDashboardLogic({ dashboardId }))
+ const display = page ? 'page' : 'embedded'
+ const logic = homeTabDashboardLogic({ dashboardId, display })
+ const { dashboardMissing, dashboardEmpty, canEditDashboard } = useValues(logic)
+ const { loadDashboard } = useActions(logic)
+ const { currentTeamLoading } = useValues(teamLogic)
+ const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
+ const { continueHomeDashboardWithAI, restorePostHogHome } = useActions(homeDashboardChoiceLogic)
+
+ // A running AI response delivers only to the listener it claimed at send time. One listener for both the
+ // empty state and the dashboard keeps that claim when the first chart replaces the empty state.
+ useMcpToolApplyBack({
+ tools: ['insight-create', 'insight-update'],
+ targetKey: `dashboard:${dashboardId}`,
+ active: !dashboardMissing && canEditDashboard,
+ onApply: (_event, { innerInput }) => {
+ if (insightIsAddedToDashboard(innerInput, dashboardId)) {
+ loadDashboard({ action: DashboardLoadAction.Update })
+ }
+ },
+ })
if (dashboardMissing) {
- return <HomeTabDefault dashboardActions={dashboardActions} />
+ return (
+ <>
+ {page?.title}
+ <HomeTabDefault dashboardActions={dashboardActions} />
+ </>
+ )
+ }
+ if (dashboardEmpty) {
+ return (
+ <>
+ {page?.title}
+ <div className="py-3">
+ <HomeTabEmptyDashboard
+ onContinueWithAI={() => continueHomeDashboardWithAI(dashboardId)}
+ onResetToDefault={restorePostHogHome}
+ resetting={currentTeamLoading}
+ aiDisabledReason={
+ !canEditDashboard
+ ? DASHBOARD_CANNOT_EDIT_MESSAGE
+ : !dataProcessingAccepted &&
+ (dataProcessingApprovalDisabledReason ??
+ 'Approve AI data processing to use PostHog AI')
+ }
+ />
+ </div>
+ </>
+ )
+ }
+ const { id, placement, readOnly } = homeTabDashboardProps(dashboardId, display)
+ if (page) {
+ return (
+ <Dashboard
+ id={String(id)}
+ placement={placement}
+ readOnly={readOnly}
+ headerActions={page.dashboardHeaderActions}
+ compact
+ parentReloadsOnAIChanges
+ />
+ )
}
- const { id, placement, readOnly } = homeTabDashboardProps(dashboardId)
return (
<div className="-mt-8">
- <Dashboard id={String(id)} placement={placement} readOnly={readOnly} />
+ <Dashboard id={String(id)} placement={placement} readOnly={readOnly} parentReloadsOnAIChanges />
</div>
)
}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
index 8cf903f51113..3502bd5f1b15 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.tsx
@@ -25,6 +25,7 @@ import {
import { HomeTabExplore } from './HomeTabExplore'
import { homeTabLoadTimeLogic } from './homeTabLoadTimeLogic'
import { homeTabChartInsightId, homeTabStatKey, homeTabStatTrendKey } from './homeTabQueryKeys'
+import { HomeTabReloadButton } from './HomeTabReloadButton'
import { HomeTabStatTiles } from './HomeTabStatTiles'
const HOME_DATE_OPTIONS = dateMapping.filter((option) => option.key !== CUSTOM_OPTION_KEY)
@@ -76,7 +77,7 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
{dashboardActions}
</div>
</div>
- <div className="home-tab-date-controls grid w-full min-w-0 grid-cols-2 gap-2 [&_.LemonButton]:h-full [&_.LemonButton__content]:truncate @max-[32rem]/home-overview:[&_.LemonButton__content]:text-xs @min-[48rem]/home-overview:flex @min-[48rem]/home-overview:w-auto @min-[48rem]/home-overview:flex-wrap">
+ <div className="home-tab-date-controls grid w-full min-w-0 grid-cols-[1fr_1fr_auto] gap-2 [&_.LemonButton]:h-full [&_.LemonButton__content]:truncate @max-[32rem]/home-overview:[&_.LemonButton__content]:text-xs @min-[48rem]/home-overview:flex @min-[48rem]/home-overview:w-auto @min-[48rem]/home-overview:flex-wrap">
<div className="min-w-0 [&_.LemonButton]:w-full @min-[48rem]/home-overview:[&_.LemonButton]:w-auto">
<DateFilter
showCustom
@@ -101,6 +102,7 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
allowCustomComparison={false}
/>
</div>
+ <HomeTabReloadButton />
</div>
</div>
diff --git a/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.stories.tsx b/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.stories.tsx
new file mode 100644
index 000000000000..d635bd252986
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.stories.tsx
@@ -0,0 +1,26 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { HomeTabEmptyDashboard } from './HomeTabEmptyDashboard'
+
+const noop = (): void => undefined
+
+const meta: Meta<typeof HomeTabEmptyDashboard> = {
+ component: HomeTabEmptyDashboard,
+ title: 'Scenes-App/Product analytics home empty dashboard',
+ args: {
+ onContinueWithAI: noop,
+ onResetToDefault: noop,
+ },
+ parameters: {
+ testOptions: { snapshotBrowsers: [] },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof HomeTabEmptyDashboard>
+
+export const Default: Story = {}
+
+export const AIUnavailable: Story = {
+ args: { aiDisabledReason: 'Approve AI data processing to use PostHog AI' },
+}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.tsx b/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.tsx
new file mode 100644
index 000000000000..a0a6f0406026
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/HomeTabEmptyDashboard.tsx
@@ -0,0 +1,48 @@
+import { IconHome, IconSparkles } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+export interface HomeTabEmptyDashboardProps {
+ onContinueWithAI: () => void
+ onResetToDefault: () => void
+ aiDisabledReason?: string | false
+ resetting?: boolean
+}
+
+export function HomeTabEmptyDashboard({
+ onContinueWithAI,
+ onResetToDefault,
+ aiDisabledReason,
+ resetting = false,
+}: HomeTabEmptyDashboardProps): JSX.Element {
+ return (
+ <div
+ className="flex flex-col items-center gap-3 rounded border border-primary px-4 py-10 text-center"
+ data-attr="home-tab-empty-dashboard"
+ >
+ <h3 className="mb-0 text-base font-semibold">This dashboard has no charts yet</h3>
+ <p className="mb-0 max-w-120 text-secondary">
+ Continue with PostHog AI to add charts, or reset to the PostHog default dashboard.
+ </p>
+ <div className="flex flex-wrap justify-center gap-2">
+ <LemonButton
+ type="primary"
+ icon={<IconSparkles />}
+ onClick={onContinueWithAI}
+ disabledReason={aiDisabledReason || undefined}
+ data-attr="home-tab-empty-dashboard-continue-ai"
+ >
+ Continue with PostHog AI
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ icon={<IconHome />}
+ onClick={onResetToDefault}
+ loading={resetting}
+ data-attr="home-tab-empty-dashboard-reset"
+ >
+ Reset to PostHog default
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabReloadButton.tsx b/products/product_analytics/frontend/insights/home/HomeTabReloadButton.tsx
new file mode 100644
index 000000000000..f2a04bfbf133
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/HomeTabReloadButton.tsx
@@ -0,0 +1,28 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { homeTabReloadLogic } from './homeTabReloadLogic'
+
+export function HomeTabReloadButton(): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const logic = homeTabReloadLogic({ teamId: currentTeamId })
+ const { areAnyLoading, reloadDisabledReason } = useValues(logic)
+ const { reloadAll } = useActions(logic)
+
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={reloadAll}
+ icon={areAnyLoading ? <Spinner textColored /> : <IconRefresh />}
+ disabledReason={reloadDisabledReason}
+ tooltip="Reload"
+ data-attr="home-tab-reload"
+ />
+ )
+}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabStatTile.tsx b/products/product_analytics/frontend/insights/home/HomeTabStatTile.tsx
index 7097570875e2..213adf2e9dd1 100644
--- a/products/product_analytics/frontend/insights/home/HomeTabStatTile.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTabStatTile.tsx
@@ -174,7 +174,7 @@ export function HomeTabStatTile({ stat, compare, selected, onSelect }: HomeTabSt
value={value ?? undefined}
showChange={compare}
change={changeFromPreviousPct != null ? { value: changeFromPreviousPct } : null}
- changeInline
+ changeBesideSubtitle
hoverChangeFromPreviousPoint
data={trend?.data}
labels={trend?.days}
diff --git a/products/product_analytics/frontend/insights/home/homeDashboardChoiceLogic.ts b/products/product_analytics/frontend/insights/home/homeDashboardChoiceLogic.ts
index 55298f56b713..76ddadbfa14c 100644
--- a/products/product_analytics/frontend/insights/home/homeDashboardChoiceLogic.ts
+++ b/products/product_analytics/frontend/insights/home/homeDashboardChoiceLogic.ts
@@ -1,12 +1,31 @@
import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'
+import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { sceneDashboardChoiceModalLogic } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'
import { UNFILED_DASHBOARDS_FOLDER } from 'scenes/dashboard/dashboardConstants'
-import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
+import { newDashboardLogic, openHomeDashboardAIChat } from 'scenes/dashboard/newDashboardLogic'
import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { getHomeTabDashboardTemplate } from './homeTabDefaultTiles'
+// pinned: analytics event name and `action` values, renaming them breaks insights built on them
+const HOME_DASHBOARD_ACTION_EVENT = 'product analytics home dashboard action'
+
+type HomeDashboardAction =
+ | 'copy_default'
+ | 'create_with_ai'
+ | 'continue_with_ai'
+ | 'start_from_template'
+ | 'choose_existing'
+ | 'edit_dashboard'
+ | 'reset_to_default'
+
+function captureHomeDashboardAction(action: HomeDashboardAction): void {
+ posthog.capture(HOME_DASHBOARD_ACTION_EVENT, { action })
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface homeDashboardChoiceLogicValues {
dashboardCreationLoading: boolean // newDashboardLogic
@@ -45,12 +64,18 @@ export interface homeDashboardChoiceLogicActions {
showDashboardPicker: () => boolean // sceneDashboardChoiceModalLogic
showSceneDashboardChoiceModal: () => boolean // sceneDashboardChoiceModalLogic
showStarterOptions: () => boolean // sceneDashboardChoiceModalLogic
+ continueHomeDashboardWithAI: (dashboardId: number) => {
+ dashboardId: number
+ }
copyPostHogHome: () => {
value: true
}
createHomeDashboardWithAI: () => {
value: true
}
+ editHomeDashboard: (dashboardId: number) => {
+ dashboardId: number
+ }
openHomeDashboardStarter: () => {
value: true
}
@@ -93,7 +118,9 @@ export const homeDashboardChoiceLogic = kea<homeDashboardChoiceLogicType>([
openHomeDashboardStarter: true,
copyPostHogHome: true,
createHomeDashboardWithAI: true,
+ continueHomeDashboardWithAI: (dashboardId: number) => ({ dashboardId }),
openHomeDashboardTemplates: true,
+ editHomeDashboard: (dashboardId: number) => ({ dashboardId }),
restorePostHogHome: true,
}),
listeners(({ actions, values }) => ({
@@ -105,6 +132,7 @@ export const homeDashboardChoiceLogic = kea<homeDashboardChoiceLogicType>([
if (values.dashboardCreationLoading) {
return
}
+ captureHomeDashboardAction('copy_default')
actions.closeSceneDashboardChoiceModal()
actions.setAsHomeTabDashboardAfterCreation(true)
actions.createDashboardFromTemplate(getHomeTabDashboardTemplate(), [], false, 'product_analytics_home_copy')
@@ -113,6 +141,7 @@ export const homeDashboardChoiceLogic = kea<homeDashboardChoiceLogicType>([
if (values.dashboardCreationLoading) {
return
}
+ captureHomeDashboardAction('create_with_ai')
actions.closeSceneDashboardChoiceModal()
actions.setAsHomeTabDashboardAfterCreation(true, true)
actions.addDashboard({
@@ -123,12 +152,25 @@ export const homeDashboardChoiceLogic = kea<homeDashboardChoiceLogicType>([
_create_in_folder: UNFILED_DASHBOARDS_FOLDER,
})
},
+ continueHomeDashboardWithAI: ({ dashboardId }) => {
+ captureHomeDashboardAction('continue_with_ai')
+ openHomeDashboardAIChat(dashboardId)
+ },
openHomeDashboardTemplates: () => {
+ captureHomeDashboardAction('start_from_template')
actions.closeSceneDashboardChoiceModal()
actions.setAsHomeTabDashboardAfterCreation(true)
actions.showNewDashboardModal()
},
+ showDashboardPicker: () => {
+ captureHomeDashboardAction('choose_existing')
+ },
+ editHomeDashboard: ({ dashboardId }) => {
+ captureHomeDashboardAction('edit_dashboard')
+ router.actions.push(urls.dashboard(dashboardId))
+ },
restorePostHogHome: () => {
+ captureHomeDashboardAction('reset_to_default')
actions.setSceneDashboardChoice(null)
actions.closeSceneDashboardChoiceModal()
},
diff --git a/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts b/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts
index c3122e29287c..bef91ff73a1f 100644
--- a/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts
+++ b/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts
@@ -3,22 +3,32 @@ import { MakeLogicType, connect, kea, key, listeners, path, props, selectors } f
import { DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
-import { DashboardPlacement, DashboardType } from '~/types'
+import { DashboardPlacement, DashboardTile, DashboardType } from '~/types'
+
+/** `embedded` shows a read-only dashboard inside another view. `page` shows the full, editable dashboard. */
+export type HomeTabDashboardDisplay = 'embedded' | 'page'
export interface HomeTabDashboardLogicProps {
dashboardId: number
+ display: HomeTabDashboardDisplay
}
-export const homeTabDashboardProps = (dashboardId: number): DashboardLogicProps => ({
- id: dashboardId,
- placement: DashboardPlacement.Builtin,
- readOnly: true,
-})
+export const homeTabDashboardProps = (
+ dashboardId: number,
+ display: HomeTabDashboardDisplay = 'embedded'
+): DashboardLogicProps =>
+ display === 'page'
+ ? { id: dashboardId, placement: DashboardPlacement.Dashboard }
+ : { id: dashboardId, placement: DashboardPlacement.Builtin, readOnly: true }
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface homeTabDashboardLogicValues {
+ canEditDashboard: boolean // dashboardLogic
dashboard: DashboardType | null // dashboardLogic
+ dashboardFailedToLoad: boolean // dashboardLogic
error404: boolean // dashboardLogic
+ tiles: DashboardTile[] // dashboardLogic
+ dashboardEmpty: boolean
dashboardMissing: boolean
}
@@ -27,6 +37,9 @@ export interface homeTabDashboardLogicActions {
dashboardNotFound: () => {
value: true
} // dashboardLogic
+ loadDashboard: (payload: { action: import('scenes/dashboard/dashboardLogic').DashboardLoadAction }) => {
+ action: import('scenes/dashboard/dashboardLogic').DashboardLoadAction
+ } // dashboardLogic
loadCurrentTeam: () => any // teamLogic
}
@@ -34,6 +47,11 @@ export interface homeTabDashboardLogicActions {
export interface homeTabDashboardLogicMeta {
key: number
__keaTypeGenInternalSelectorTypes: {
+ dashboardEmpty: (
+ dashboard: DashboardType | null,
+ tiles: DashboardTile[],
+ dashboardFailedToLoad: boolean
+ ) => boolean
dashboardMissing: (error404: boolean, dashboard: DashboardType | null) => boolean
}
}
@@ -50,15 +68,24 @@ export const homeTabDashboardLogic = kea<homeTabDashboardLogicType>([
key((props) => props.dashboardId),
path((key) => ['products', 'product_analytics', 'home', 'homeTabDashboardLogic', key]),
connect((props: HomeTabDashboardLogicProps) => ({
- values: [dashboardLogic(homeTabDashboardProps(props.dashboardId)), ['dashboard', 'error404']],
+ values: [
+ dashboardLogic(homeTabDashboardProps(props.dashboardId, props.display)),
+ ['dashboard', 'error404', 'tiles', 'dashboardFailedToLoad', 'canEditDashboard'],
+ ],
actions: [
- dashboardLogic(homeTabDashboardProps(props.dashboardId)),
- ['dashboardNotFound'],
+ dashboardLogic(homeTabDashboardProps(props.dashboardId, props.display)),
+ ['dashboardNotFound', 'loadDashboard'],
teamLogic,
['loadCurrentTeam'],
],
})),
selectors({
+ // A failed reload keeps the old tiles, so the dashboard's own error and retry show instead.
+ dashboardEmpty: [
+ (s) => [s.dashboard, s.tiles, s.dashboardFailedToLoad],
+ (dashboard: DashboardType | null, tiles: DashboardTile[], dashboardFailedToLoad: boolean): boolean =>
+ !!dashboard && tiles.length === 0 && !dashboardFailedToLoad,
+ ],
dashboardMissing: [
(s) => [s.error404, s.dashboard],
(error404: boolean, dashboard: DashboardType | null): boolean => error404 && !dashboard,
diff --git a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
index 8f9b05208a46..aad7f16397b5 100644
--- a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
+++ b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
@@ -558,12 +558,12 @@ export function getHomeTabDashboardTemplate(): DashboardTemplateType {
},
},
w: 3,
- h: 3,
+ h: 2,
}
})
const rows: HomeTabDashboardTile[][] = [
statTiles,
- [chartTile('daily_active_users', 12, 5)],
+ [chartTile('daily_active_users', 12, 3)],
[chartTile('top_pages', 6, 5), chartTile('top_screens', 6, 5)],
[chartTile('top_events', 6, 5), chartTile('retention', 6, 5)],
[chartTile('users_by_country', 8, 6), chartTile('sessions_by_device', 4, 6)],
diff --git a/products/product_analytics/frontend/insights/home/homeTabReloadLogic.test.ts b/products/product_analytics/frontend/insights/home/homeTabReloadLogic.test.ts
new file mode 100644
index 000000000000..6accacae245b
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabReloadLogic.test.ts
@@ -0,0 +1,58 @@
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { initKeaTests } from '~/test/init'
+
+import { homeTabDataCollectionId } from './homeTabQueryKeys'
+import { homeTabReloadLogic } from './homeTabReloadLogic'
+
+describe('homeTabReloadLogic', () => {
+ let logic: ReturnType<typeof homeTabReloadLogic.build>
+ let collection: ReturnType<typeof dataNodeCollectionLogic.build>
+
+ const loadTile = (id: string, minutesAgo: number | 'failed'): void => {
+ collection.actions.mountDataNode(id, { id, loadData: jest.fn(), cancelQuery: jest.fn() })
+ collection.actions.collectionNodeLoadData(id)
+ if (minutesAgo === 'failed') {
+ collection.actions.collectionNodeLoadDataFailure(id)
+ return
+ }
+ collection.actions.collectionNodeLoadDataSuccess(id, {
+ lastRefresh: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
+ })
+ }
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ jest.setSystemTime(new Date('2026-01-15T12:00:00Z'))
+ initKeaTests()
+ collection = dataNodeCollectionLogic({ key: homeTabDataCollectionId(123) })
+ collection.mount()
+ logic = homeTabReloadLogic({ teamId: 123 })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ collection.unmount()
+ jest.useRealTimers()
+ })
+
+ test.each<[string, (number | 'failed')[], boolean]>([
+ ['every result is recent', [1, 2], true],
+ ['every result is older than the interval', [6, 7], false],
+ ['the oldest result is older than the interval', [1, 6], false],
+ ['a tile failed and the other results are recent', [1, 'failed'], false],
+ ])('blocks a reload when %s', (_case, minutesAgo, blocked) => {
+ minutesAgo.forEach((minutes, index) => loadTile(`tile-${index}`, minutes))
+
+ expect(logic.values.reloadDisabledReason?.startsWith('Next reload possible') ?? false).toBe(blocked)
+ })
+
+ it('allows a reload again when the interval ends', () => {
+ loadTile('tile', 1)
+ expect(logic.values.reloadDisabledReason).toMatch(/^Next reload possible/)
+
+ jest.advanceTimersByTime(4 * 60_000)
+
+ expect(logic.values.reloadDisabledReason).toBeNull()
+ })
+})
diff --git a/products/product_analytics/frontend/insights/home/homeTabReloadLogic.ts b/products/product_analytics/frontend/insights/home/homeTabReloadLogic.ts
new file mode 100644
index 000000000000..1cab66e99ec8
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabReloadLogic.ts
@@ -0,0 +1,115 @@
+import { MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { subscriptions } from 'kea-subscriptions'
+
+import { Dayjs, dayjs, now } from 'lib/dayjs'
+import { DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES } from 'scenes/dashboard/dashboardUtils'
+
+import { DataNodeStatusMap, dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+
+import { homeTabDataCollectionId } from './homeTabQueryKeys'
+
+export interface HomeTabReloadLogicProps {
+ teamId: number | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabReloadLogicValues {
+ areAnyLoading: boolean // dataNodeCollectionLogic
+ collectionNodeStatus: DataNodeStatusMap // dataNodeCollectionLogic
+ nextAllowedReload: Dayjs | null
+ reloadDisabledReason: string | null
+ tickCount: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabReloadLogicActions {
+ reloadAll: () => {} // dataNodeCollectionLogic
+ tick: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabReloadLogicMeta {
+ key: number | 'none'
+ __keaTypeGenInternalSelectorTypes: {
+ nextAllowedReload: (collectionNodeStatus: DataNodeStatusMap) => Dayjs | null
+ reloadDisabledReason: (
+ areAnyLoading: boolean,
+ nextAllowedReload: Dayjs | null,
+ tickCount: number
+ ) => string | null
+ }
+}
+
+export type homeTabReloadLogicType = MakeLogicType<
+ homeTabReloadLogicValues,
+ homeTabReloadLogicActions,
+ HomeTabReloadLogicProps,
+ homeTabReloadLogicMeta
+>
+
+/** Blocks a forced reload of the default dashboard until its oldest result is old enough, like dashboard refresh. */
+export const homeTabReloadLogic = kea<homeTabReloadLogicType>([
+ props({} as HomeTabReloadLogicProps),
+ key(({ teamId }) => teamId ?? 'none'),
+ path((key) => ['products', 'product_analytics', 'home', 'homeTabReloadLogic', key]),
+ connect(({ teamId }: HomeTabReloadLogicProps) => ({
+ values: [
+ dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamId) }),
+ ['collectionNodeStatus', 'areAnyLoading'],
+ ],
+ actions: [dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamId) }), ['reloadAll']],
+ })),
+ actions({
+ tick: true,
+ }),
+ reducers({
+ // Recomputes the block after the deadline passes, because nothing else changes at that moment.
+ tickCount: [0, { tick: (count) => count + 1 }],
+ }),
+ selectors({
+ nextAllowedReload: [
+ (s) => [s.collectionNodeStatus],
+ (collectionNodeStatus: DataNodeStatusMap): Dayjs | null => {
+ // A failed tile has no retry of its own, so Reload must stay available to recover it.
+ if (Object.values(collectionNodeStatus).some((status) => status?.hasError)) {
+ return null
+ }
+ const refreshes = Object.values(collectionNodeStatus)
+ .map((status) => status?.lastRefresh)
+ .filter((lastRefresh): lastRefresh is string => !!lastRefresh)
+ .map((lastRefresh) => dayjs(lastRefresh))
+ if (!refreshes.length) {
+ return null
+ }
+ const oldest = refreshes.reduce((a, b) => (a.isBefore(b) ? a : b))
+ return oldest.add(DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES, 'minutes')
+ },
+ ],
+ reloadDisabledReason: [
+ (s) => [s.areAnyLoading, s.nextAllowedReload, s.tickCount],
+ (areAnyLoading: boolean, nextAllowedReload: Dayjs | null): string | null => {
+ if (areAnyLoading) {
+ return 'Loading'
+ }
+ if (nextAllowedReload?.isAfter(now())) {
+ return `Next reload possible ${nextAllowedReload.fromNow()}`
+ }
+ return null
+ },
+ ],
+ }),
+ subscriptions(({ actions, cache }) => ({
+ nextAllowedReload: (nextAllowedReload: Dayjs | null) => {
+ if (!nextAllowedReload) {
+ cache.disposables.dispose('reloadUnblockTimer')
+ return
+ }
+ cache.disposables.add(() => {
+ const timerId = setTimeout(() => actions.tick(), Math.max(0, nextAllowedReload.diff(now())))
+ return () => clearTimeout(timerId)
+ }, 'reloadUnblockTimer')
+ },
+ })),
+])
diff --git a/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx b/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
index afc2459d4f33..8377c95e31e6 100644
--- a/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
+++ b/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
@@ -89,7 +89,7 @@ export function SavedInsights(): JSX.Element {
const { notificationCount } = useValues(productAnalyticsNotificationsLogic)
const { currentTeam } = useValues(teamLogic)
const summarizeInsight = useSummarizeInsight()
- const { openHomeDashboardStarter, restorePostHogHome } = useActions(homeDashboardChoiceLogic)
+ const { openHomeDashboardStarter, editHomeDashboard, restorePostHogHome } = useActions(homeDashboardChoiceLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const { tab } = filters
@@ -304,23 +304,24 @@ export function SavedInsights(): JSX.Element {
},
]
+ const homeDashboardId = currentTeam?.home_tab_dashboard
const homeDashboardActions =
tab === SavedInsightsTabs.Home && showHomeTab ? (
- currentTeam?.home_tab_dashboard ? (
+ homeDashboardId ? (
<LemonMenu
items={[
{
- label: 'Open dashboard',
- to: urls.dashboard(currentTeam.home_tab_dashboard),
+ label: 'Edit dashboard',
+ onClick: () => editHomeDashboard(homeDashboardId),
'data-attr': 'home-tab-open-dashboard',
},
{
- label: 'Change Home dashboard',
+ label: 'Show a different dashboard',
onClick: openHomeDashboardStarter,
'data-attr': 'home-tab-choose-dashboard',
},
{
- label: 'Use default dashboard',
+ label: 'Reset to PostHog default',
onClick: restorePostHogHome,
'data-attr': 'home-tab-restore-posthog-home',
},
@@ -342,7 +343,7 @@ export function SavedInsights(): JSX.Element {
data-attr="home-tab-choose-dashboard"
onClick={openHomeDashboardStarter}
>
- Make my own dashboard
+ Customize
</LemonButton>
)
) : null