:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(product-analytics): open home by default when enabled (#103640)
Daniel Parker20634a8a526e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c359bb776719..be98be1c1ace 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10324,6 +10324,14 @@ snapshots:hash: v1.k794b7964.97eca32497e04c403e975e4114a7a144c20ac2d32ab89f98aa247136ab2d0457.l3Iw0G-o40K5hWnI2rEHDZfJTzV282b0lm5fQvP14a0scenes-app-saved-insights--error-state--light:hash: v1.k794b7964.6236e2139e033c4547aa3667b37627916d0d3b2d99cb346e98f2e18ccdd8ad14.huJk5GngTJ7oP9eYDf5S9kUO6OafLC9tKCYuxN-rbfE+ scenes-app-saved-insights--home--dark:+ hash: v1.k794b7964.2b163d6fc0eca31aaf36b963ff3c94f5ba264c2615d8a935768f6a2e0305910f.lOpK-cChQflypgIhD2qwUMj_KAb14Qwt_1PN1FL0hfQ+ scenes-app-saved-insights--home--light:+ hash: v1.k794b7964.f31e883cdd266cb1579d508ad81b86c5dab5604939b35e652be3ae906d7a8a8b.lTRMsjOK_O9weRfTRn4EsKvfY3upGoUrzQqE_Kf9e4g+ scenes-app-saved-insights--home-with-boolean-flag--dark:+ hash: v1.k794b7964.2b163d6fc0eca31aaf36b963ff3c94f5ba264c2615d8a935768f6a2e0305910f.wjW8BKxaKLHlSOZX8j6gvRR67SuOCqaK71TGZIi31TM+ scenes-app-saved-insights--home-with-boolean-flag--light:+ hash: v1.k794b7964.f31e883cdd266cb1579d508ad81b86c5dab5604939b35e652be3ae906d7a8a8b.1tIVSjGpXH8GdcXmQl4c-KMp-KFJ77ADnIaON9My4U8scenes-app-saved-insights--list-view--dark:hash: v1.k794b7964.f20f4295f774b1892a3a9f52f2f4ebbeff75798bbc343b9874e1f6a95d410a4b.U6DhbwV1uNDFfQpUKmQ4F3kpvez3A0iemwOpgsZHo-gscenes-app-saved-insights--list-view--light:diff --git a/frontend/src/lib/components/CompactList/CompactList.tsx b/frontend/src/lib/components/CompactList/CompactList.tsxindex a2e0132cfcdd..b585ad1e26e2 100644--- a/frontend/src/lib/components/CompactList/CompactList.tsx+++ b/frontend/src/lib/components/CompactList/CompactList.tsx@@ -15,6 +15,9 @@ export interface CompactListProps {viewAllURL?: stringviewAllDataAttr?: stringloading: boolean+ /** Whether the last load attempt failed. Rendered instead of `emptyMessage`, even if `items` is empty. */+ error?: boolean+ errorMessage?: EmptyMessagePropsitems: any[]emptyMessage?: EmptyMessagePropsrenderRow: (rowData: any, index: number) => JSX.Element@@ -27,6 +30,8 @@ export function CompactList({viewAllURL,viewAllDataAttr,loading,+ error,+ errorMessage,items,emptyMessage,renderRow,@@ -69,6 +74,8 @@ export function CompactList({<LemonSkeleton key={index} />))}</div>+ ) : error && errorMessage ? (+ <EmptyMessage {...errorMessage} />) : items.length === 0 && emptyMessage ? (<EmptyMessage {...emptyMessage} />) : (diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex eba3e7b0cf1a..24eab90b52a5 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -443,6 +443,7 @@ export const FEATURE_FLAGS = {PRODUCT_ANALYTICS_CHART_ALTERNATIVES: 'product-analytics-chart-alternatives', // owner: #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analytics+ PRODUCT_ANALYTICS_HOME_TAB: 'product-analytics-home-tab', // owner: #team-product-analyticsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analyticsPRODUCT_ANALYTICS_PATHS_STRIP_QUERY_STRING: 'paths-strip-query-string', // owner: #team-product-analytics, gates the "Ignore URL query strings" switch on paths insightsPRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analyticsdiff --git a/frontend/src/scenes/saved-insights/ActiveUsers.tsx b/frontend/src/scenes/saved-insights/ActiveUsers.tsxnew file mode 100644index 000000000000..d4106e5a9a0e--- /dev/null+++ b/frontend/src/scenes/saved-insights/ActiveUsers.tsx@@ -0,0 +1,47 @@+import { useActions, useValues } from 'kea'++import { IconInfo } from '@posthog/icons'++import { CompactList } from 'lib/components/CompactList/CompactList'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { urls } from 'scenes/urls'++import { ActivePersonType, activeUsersLogic } from './activeUsersLogic'+import { PersonRow } from './PersonRow'++export function ActiveUsers(): JSX.Element {+ const { persons, personsLoading, personsLoadedError } = useValues(activeUsersLogic)+ const { loadPersons } = useActions(activeUsersLogic)++ return (+ <CompactList+ title={+ <div className="flex items-center gap-1">+ Most active users+ <Tooltip title="Users with the most events in the last 7 days. For large data volumes, PostHog uses an event sample.">+ <IconInfo className="text-muted text-base" />+ </Tooltip>+ </div>+ }+ viewAllURL={urls.persons()}+ viewAllDataAttr="insights-home-tab-active-users-view-all"+ loading={personsLoading}+ error={personsLoadedError}+ errorMessage={{+ title: "Couldn't load active users",+ description: 'Something went wrong loading this list.',+ buttonText: 'Retry',+ buttonOnClick: loadPersons,+ }}+ emptyMessage={{+ title: 'No active people',+ description: 'People who have been active in your product will appear here.',+ buttonText: 'View all people',+ buttonTo: urls.persons(),+ }}+ items={persons.slice(0, 5)}+ renderRow={(person: ActivePersonType) => <PersonRow key={person.id} person={person} />}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/Activity.tsx b/frontend/src/scenes/saved-insights/Activity.tsxnew file mode 100644index 000000000000..70f50a52f6e3--- /dev/null+++ b/frontend/src/scenes/saved-insights/Activity.tsx@@ -0,0 +1,38 @@+import { useValues } from 'kea'++import { ActivityLogLogicProps, activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'+import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLogRow'+import { HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'+import { CompactList } from 'lib/components/CompactList/CompactList'+import { urls } from 'scenes/urls'++import { ActivityScope, SavedInsightsTabs } from '~/types'++const ACTIVITY_LIMIT = 5++export function Activity(): JSX.Element {+ const logic = activityLogLogic({ scope: ActivityScope.INSIGHT } satisfies ActivityLogLogicProps)+ const { humanizedActivity, activityLoading } = useValues(logic)++ return (+ <CompactList+ title="Activity"+ viewAllURL={urls.savedInsights(SavedInsightsTabs.History)}+ viewAllDataAttr="insights-home-tab-activity-view-all"+ loading={activityLoading}+ emptyMessage={{+ title: 'No activity yet',+ description: 'Activity on insights will appear here.',+ buttonText: 'View all activity',+ buttonTo: urls.savedInsights(SavedInsightsTabs.History),+ }}+ items={humanizedActivity.slice(0, ACTIVITY_LIMIT)}+ renderRow={(logItem: HumanizedActivityLogItem, index) => (+ <div key={index} className="mb-2 last:mb-0" data-attr="activity-log-item">+ <ActivityLogRow logItem={logItem} />+ </div>+ )}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/AlertRow.tsx b/frontend/src/scenes/saved-insights/AlertRow.tsxnew file mode 100644index 000000000000..6f66989a72dc--- /dev/null+++ b/frontend/src/scenes/saved-insights/AlertRow.tsx@@ -0,0 +1,33 @@+import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { AlertType } from 'products/alerts/frontend/types'++import { ProjectHomePageCompactListItem } from '../project-homepage/ProjectHomePageCompactListItem'++export function AlertRow({ alert }: { alert: AlertType }): JSX.Element {+ return (+ <ProjectHomePageCompactListItem+ title={alert.name}+ subtitle={+ alert.last_checked_at ? (+ <div className="flex items-center gap-1">+ {alert.last_value !== undefined && (+ <>+ <span className="font-medium">Value: {alert.last_value}</span>+ <span>•</span>+ </>+ )}+ <span>+ Last checked <TZLabel time={alert.last_checked_at} />+ </span>+ </div>+ ) : (+ 'Not yet checked'+ )+ }+ to={urls.alert(alert.id)}+ dataAttr="firing-alert-item"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/EventRow.tsx b/frontend/src/scenes/saved-insights/EventRow.tsxnew file mode 100644index 000000000000..431962cfbd88--- /dev/null+++ b/frontend/src/scenes/saved-insights/EventRow.tsx@@ -0,0 +1,26 @@+import { dayjs } from 'lib/dayjs'+import { eventToIcon } from 'scenes/session-recordings/player/inspector/components/PlayerInspectorListItem'+import { urls } from 'scenes/urls'++import { EventDefinition } from '~/types'++import { ProjectHomePageCompactListItem } from '../project-homepage/ProjectHomePageCompactListItem'++export function EventRow({ event }: { event: EventDefinition }): JSX.Element {+ const subtitle = event.created_at+ ? `Created ${dayjs(event.created_at).fromNow()}`+ : event.last_seen_at+ ? `Last seen ${dayjs(event.last_seen_at).fromNow()}`+ : 'Recently added'+ const EventIcon = eventToIcon(event.name)++ return (+ <ProjectHomePageCompactListItem+ to={urls.eventDefinition(event.id)}+ title={event.name}+ subtitle={subtitle}+ prefix={<EventIcon className="text-lg" />}+ dataAttr="new-event-item"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/FiringAlerts.tsx b/frontend/src/scenes/saved-insights/FiringAlerts.tsxnew file mode 100644index 000000000000..bbfeb85680c4--- /dev/null+++ b/frontend/src/scenes/saved-insights/FiringAlerts.tsx@@ -0,0 +1,36 @@+import { useValues } from 'kea'++import { CompactList } from 'lib/components/CompactList/CompactList'+import { urls } from 'scenes/urls'++import { AlertState } from '~/queries/schema/schema-general'+import { SavedInsightsTabs } from '~/types'++import { alertsLogic } from 'products/alerts/frontend/logic/alertsLogic'+import { AlertType } from 'products/alerts/frontend/types'++import { AlertRow } from './AlertRow'++export function FiringAlerts(): JSX.Element {+ const { alerts, alertsResponseLoading } = useValues(alertsLogic)+ const firingAlerts = alerts.filter((alert) => alert.state === AlertState.FIRING && alert.enabled)++ return (+ <CompactList+ title="Firing alerts"+ viewAllURL={urls.savedInsights(SavedInsightsTabs.Alerts)}+ viewAllDataAttr="insights-home-tab-firing-alerts-view-all"+ loading={alertsResponseLoading}+ emptyMessage={{+ title: 'No alerts are firing',+ description: 'PostHog will show active alerts here.',+ buttonText: 'View all alerts',+ buttonTo: urls.savedInsights(SavedInsightsTabs.Alerts),+ buttonDataAttr: 'firing-alerts-empty-view-all',+ }}+ items={firingAlerts.slice(0, 5)}+ renderRow={(alert: AlertType) => <AlertRow key={alert.id} alert={alert} />}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/HomeTab.tsx b/frontend/src/scenes/saved-insights/HomeTab.tsxnew file mode 100644index 000000000000..3e29a3efd54a--- /dev/null+++ b/frontend/src/scenes/saved-insights/HomeTab.tsx@@ -0,0 +1,33 @@+import posthog from 'posthog-js'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'++import { ActiveUsers } from './ActiveUsers'+import { Activity } from './Activity'+import { FiringAlerts } from './FiringAlerts'+import { NewEvents } from './NewEvents'+import { RecentlyViewed } from './RecentlyViewed'+import { Trending } from './Trending'++export function HomeTab(): JSX.Element {+ useOnMountEffect(() => {+ posthog.capture('product analytics home viewed')+ })++ return (+ <div className="py-4">+ <div className="flex flex-col gap-4 @min-[48rem]/main-content:flex-row @min-[48rem]/main-content:items-start">+ <div className="flex min-w-0 flex-1 flex-col gap-4">+ <RecentlyViewed />+ <FiringAlerts />+ <ActiveUsers />+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-4">+ <Trending />+ <NewEvents />+ <Activity />+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/saved-insights/InsightRow.tsx b/frontend/src/scenes/saved-insights/InsightRow.tsxindex 36fb9e623fec..474a5f64f32b 100644--- a/frontend/src/scenes/saved-insights/InsightRow.tsx+++ b/frontend/src/scenes/saved-insights/InsightRow.tsx@@ -35,8 +35,17 @@ export function InsightRow({ insight, isExpanded, onToggle, dataAttr }: InsightRplacement="left"><div- className="flex items-center gap-3 p-3 cursor-pointer hover:bg-surface-secondary rounded-t"+ role="button"+ tabIndex={0}+ aria-expanded={isExpanded}+ className="flex items-center gap-3 p-3 cursor-pointer hover:bg-surface-secondary rounded-t focus-visible:bg-surface-secondary focus-visible:outline-none"onClick={onToggle}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onToggle()+ }+ }}><div className={`transform transition-transform ${isExpanded ? 'rotate-90' : ''}`}><IconChevronRight className="text-xl" />diff --git a/frontend/src/scenes/saved-insights/NewEvents.tsx b/frontend/src/scenes/saved-insights/NewEvents.tsxnew file mode 100644index 000000000000..7fb173fb5f9b--- /dev/null+++ b/frontend/src/scenes/saved-insights/NewEvents.tsx@@ -0,0 +1,49 @@+import { useActions, useValues } from 'kea'++import { IconInfo } from '@posthog/icons'++import { CompactList } from 'lib/components/CompactList/CompactList'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { urls } from 'scenes/urls'++import { EventDefinition } from '~/types'++import { EventRow } from './EventRow'+import { newEventsLogic } from './newEventsLogic'++export function NewEvents(): JSX.Element {+ const { newEvents, newEventsLoading, newEventsLoadedError } = useValues(newEventsLogic)+ const { loadNewEvents } = useActions(newEventsLogic)++ return (+ <CompactList+ title={+ <div className="flex items-center gap-1">+ New events+ <Tooltip title="Events that PostHog saw for the first time recently.">+ <IconInfo className="text-muted text-base" />+ </Tooltip>+ </div>+ }+ viewAllURL={urls.eventDefinitions()}+ viewAllDataAttr="insights-home-tab-new-events-view-all"+ loading={newEventsLoading}+ error={newEventsLoadedError}+ errorMessage={{+ title: "Couldn't load new events",+ description: 'Something went wrong loading this list.',+ buttonText: 'Retry',+ buttonOnClick: loadNewEvents,+ }}+ emptyMessage={{+ title: 'No events found',+ description: 'Set up event capture to see events here.',+ buttonText: 'View all events',+ buttonTo: urls.eventDefinitions(),+ }}+ items={newEvents.slice(0, 5)}+ renderRow={(event: EventDefinition) => <EventRow key={event.id} event={event} />}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/PersonRow.tsx b/frontend/src/scenes/saved-insights/PersonRow.tsxnew file mode 100644index 000000000000..086af6e1b2b8--- /dev/null+++ b/frontend/src/scenes/saved-insights/PersonRow.tsx@@ -0,0 +1,34 @@+import { useActions } from 'kea'++import { dayjs } from 'lib/dayjs'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { urls } from 'scenes/urls'++import { asDisplay, asLink } from 'products/persons/frontend/person-utils'++import { ProjectHomePageCompactListItem } from '../project-homepage/ProjectHomePageCompactListItem'+import { ActivePersonType } from './activeUsersLogic'++export function PersonRow({ person }: { person: ActivePersonType }): JSX.Element {+ const { reportPersonOpenedFromNewlySeenPersonsList } = useActions(eventUsageLogic)++ return (+ <ProjectHomePageCompactListItem+ to={person.uuid ? urls.personByUUID(person.uuid) : asLink(person) || urls.persons()}+ title={asDisplay(person)}+ subtitle={+ <div className="flex items-center gap-1">+ <span className="font-medium">+ {person.activity_count} {person.activity_count === 1 ? 'event' : 'events'}+ </span>+ <span>•</span>+ <span>First seen {dayjs(person.created_at).fromNow()}</span>+ </div>+ }+ prefix={<ProfilePicture name={asDisplay(person)} />}+ onClick={reportPersonOpenedFromNewlySeenPersonsList}+ dataAttr="active-user-item"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/RecentlyViewed.tsx b/frontend/src/scenes/saved-insights/RecentlyViewed.tsxnew file mode 100644index 000000000000..ed97d9b5c2db--- /dev/null+++ b/frontend/src/scenes/saved-insights/RecentlyViewed.tsx@@ -0,0 +1,42 @@+import { useActions, useValues } from 'kea'++import { CompactList } from 'lib/components/CompactList/CompactList'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { urls } from 'scenes/urls'++import { QueryBasedInsightModel, SavedInsightsTabs } from '~/types'++import { projectHomepageLogic } from '../project-homepage/projectHomepageLogic'+import { InsightRow } from './InsightRow'++export function RecentlyViewed(): JSX.Element {+ const { recentInsights, recentInsightsLoading, expandedInsightIds } = useValues(projectHomepageLogic)+ const { loadRecentInsights, toggleInsightExpanded } = useActions(projectHomepageLogic)+ useOnMountEffect(loadRecentInsights)++ return (+ <CompactList+ title="Recently viewed"+ viewAllURL={urls.savedInsights(SavedInsightsTabs.All)}+ viewAllDataAttr="insights-home-tab-recently-viewed-view-all"+ loading={recentInsightsLoading}+ emptyMessage={{+ title: 'No recently viewed insights',+ description: 'Open an insight to find it here later.',+ buttonText: 'View insights',+ buttonTo: urls.savedInsights(SavedInsightsTabs.All),+ }}+ items={recentInsights.slice(0, 5)}+ renderRow={(insight: QueryBasedInsightModel) => (+ <InsightRow+ key={insight.short_id}+ insight={insight}+ isExpanded={expandedInsightIds.has(insight.short_id)}+ onToggle={() => toggleInsightExpanded(insight.short_id)}+ dataAttr="recently-viewed-insight-item"+ />+ )}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx b/frontend/src/scenes/saved-insights/SavedInsights.stories.tsxindex 178fe10b94e1..53ad666c03ad 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx@@ -1,5 +1,6 @@import { Meta, StoryObj } from '@storybook/react'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import { urls } from 'scenes/urls'@@ -43,6 +44,38 @@ export default metatype Story = StoryObj<{}>export const ListView: Story = {}+export const Home: Story = {+ parameters: {+ featureFlags: { [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test' },+ pageUrl: `${urls.savedInsights()}?tab=home`,+ testOptions: { viewport: { width: 1300, height: 2000 }, waitForLoadersToDisappear: true },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/insights/my_last_viewed/': [],+ '/api/environments/:team_id/insights/trending/': [],+ '/api/environments/:team_id/insights/activity': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/event_definitions/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/insights/': toPaginatedResponse(insightsJson.results.slice(0, 1)),+ '/api/projects/:team_id/alerts/': EMPTY_PAGINATED_RESPONSE,+ },+ post: {+ '/api/environments/:team_id/query/': { results: [] },+ '/api/environments/:team_id/persons/batch_by_distinct_ids/': { results: {} },+ },+ }),+ ],+}++export const HomeWithBooleanFlag: Story = {+ ...Home,+ parameters: {+ ...Home.parameters,+ featureFlags: { [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: true },+ },+}+export const EmptyState: Story = {decorators: [mswDecorator({diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex e72a9244ba42..4b9ea6cf506e 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -56,6 +56,7 @@ import { productAnalyticsNotificationsLogic } from 'products/product_analytics/fimport { isDraftInsightRow } from './draftInsight'import { DraftInsightMoreMenu, DraftInsightNameCell } from './DraftInsightRow'+import { HomeTab } from './HomeTab'import { QUERY_TYPES_METADATA } from './insightTypesMetadata'import { NewInsightButton } from './NewInsightMenu'import { SavedInsightListItem, savedInsightsLogic } from './savedInsightsLogic'@@ -105,6 +106,7 @@ export function SavedInsights(): JSX.Element {usingFilters,bulkDeleteResponseLoading,draftInsightRow,+ showHomeTab,} = useValues(savedInsightsLogic)const { currentProjectId } = useValues(projectLogic)@@ -344,6 +346,7 @@ export function SavedInsights(): JSX.Element {setSavedInsightsFilters({ tab })}}tabs={[+ ...(showHomeTab ? [{ key: SavedInsightsTabs.Home, label: 'Home' }] : []),{ key: SavedInsightsTabs.All, label: 'All insights' },{ key: SavedInsightsTabs.Yours, label: 'My insights' },{ key: SavedInsightsTabs.Alerts, label: 'Alerts' },@@ -365,7 +368,9 @@ export function SavedInsights(): JSX.Element {sceneInset/>- {tab === SavedInsightsTabs.Notifications ? (+ {tab === SavedInsightsTabs.Home && showHomeTab ? (+ <HomeTab />+ ) : tab === SavedInsightsTabs.Notifications ? (<ProductAnalyticsNotifications />) : tab === SavedInsightsTabs.History ? (<ActivityLog scope={ActivityScope.INSIGHT} />diff --git a/frontend/src/scenes/saved-insights/Trending.tsx b/frontend/src/scenes/saved-insights/Trending.tsxnew file mode 100644index 000000000000..d6d9dc28d059--- /dev/null+++ b/frontend/src/scenes/saved-insights/Trending.tsx@@ -0,0 +1,58 @@+import { useActions, useValues } from 'kea'++import { IconInfo } from '@posthog/icons'++import { CompactList } from 'lib/components/CompactList/CompactList'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { urls } from 'scenes/urls'++import { QueryBasedInsightModel, SavedInsightsTabs } from '~/types'++import { InsightRow } from './InsightRow'+import { trendingInsightsLogic } from './trendingInsightsLogic'++export function Trending(): JSX.Element {+ const { trendingInsights, trendingInsightsLoading, trendingInsightsLoadedError, expandedInsightIds } =+ useValues(trendingInsightsLogic)+ const { toggleInsightExpanded, loadTrendingInsights } = useActions(trendingInsightsLogic)++ return (+ <CompactList+ title={+ <div className="flex items-center gap-1">+ Trending+ <Tooltip title="Trending insights have the most unique views in the last 7 days.">+ <IconInfo className="text-muted text-base" />+ </Tooltip>+ </div>+ }+ viewAllURL={urls.savedInsights(SavedInsightsTabs.All)}+ viewAllDataAttr="insights-home-tab-trending-view-all"+ loading={trendingInsightsLoading}+ error={trendingInsightsLoadedError}+ errorMessage={{+ title: "Couldn't load trending insights",+ description: 'Something went wrong loading this list.',+ buttonText: 'Retry',+ buttonOnClick: loadTrendingInsights,+ }}+ emptyMessage={{+ title: 'No trending insights',+ description: 'Frequently viewed insights will appear here.',+ buttonText: 'View all insights',+ buttonTo: urls.savedInsights(SavedInsightsTabs.All),+ }}+ items={trendingInsights.slice(0, 5)}+ renderRow={(insight: QueryBasedInsightModel) => (+ <InsightRow+ key={insight.short_id}+ insight={insight}+ isExpanded={expandedInsightIds.has(insight.short_id)}+ onToggle={() => toggleInsightExpanded(insight.short_id)}+ dataAttr="trending-insight-item"+ />+ )}+ contentHeightBehavior="fit-content"+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/activeUsersLogic.ts b/frontend/src/scenes/saved-insights/activeUsersLogic.tsnew file mode 100644index 000000000000..4c87e6588d76--- /dev/null+++ b/frontend/src/scenes/saved-insights/activeUsersLogic.ts@@ -0,0 +1,73 @@+import { MakeLogicType, afterMount, kea, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { hogql } from '~/queries/utils'+import { PersonType } from '~/types'++export interface ActivePersonType extends PersonType {+ activity_count: number+}++export interface activeUsersLogicValues {+ persons: ActivePersonType[]+ personsLoading: boolean+ personsLoadedError: boolean+}++export interface activeUsersLogicActions {+ loadPersons: () => any+ loadPersonsFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }+ loadPersonsSuccess: (persons: ActivePersonType[], payload?: any) => { persons: ActivePersonType[]; payload?: any }+}++export type activeUsersLogicType = MakeLogicType<activeUsersLogicValues, activeUsersLogicActions>++export const activeUsersLogic = kea<activeUsersLogicType>([+ path(['scenes', 'saved-insights', 'activeUsersLogic']),+ loaders({+ persons: {+ __default: [] as ActivePersonType[],+ loadPersons: async () => {+ // HogQL provides activity ranking that the persons API does not support.+ const query = hogql`+ SELECT any(distinct_id), count() as activity_count+ FROM events+ SAMPLE 10000000+ WHERE timestamp > now() - INTERVAL 7 DAY+ GROUP BY person_id+ ORDER BY activity_count DESC+ LIMIT 5+ `+ const idsResponse = await api.queryHogQL(query, {+ scene: 'SavedInsights',+ productKey: 'persons',+ })+ const results = idsResponse.results || []+ const distinctIds = results.map((row) => row[0] as string)+ const counts = new Map(results.map((row) => [row[0] as string, row[1] as number]))+ const personsMap = await api.persons.getByDistinctIds(distinctIds)++ return distinctIds+ .map((distinctId) => {+ const person = personsMap[distinctId]+ return person ? { ...person, activity_count: counts.get(distinctId) || 0 } : null+ })+ .filter((person): person is ActivePersonType => person !== null)+ .sort((a, b) => b.activity_count - a.activity_count)+ },+ },+ }),+ reducers({+ personsLoadedError: [+ false,+ {+ loadPersons: () => false,+ loadPersonsSuccess: () => false,+ loadPersonsFailure: () => true,+ },+ ],+ }),+ afterMount(({ actions }) => actions.loadPersons()),+])diff --git a/frontend/src/scenes/saved-insights/newEventsLogic.ts b/frontend/src/scenes/saved-insights/newEventsLogic.tsnew file mode 100644index 000000000000..0cd623aef14d--- /dev/null+++ b/frontend/src/scenes/saved-insights/newEventsLogic.ts@@ -0,0 +1,50 @@+import { MakeLogicType, afterMount, kea, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { EventDefinition } from '~/types'++export interface newEventsLogicValues {+ newEvents: EventDefinition[]+ newEventsLoading: boolean+ newEventsLoadedError: boolean+}++export interface newEventsLogicActions {+ loadNewEvents: () => any+ loadNewEventsFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }+ loadNewEventsSuccess: (+ newEvents: EventDefinition[],+ payload?: any+ ) => {+ newEvents: EventDefinition[]+ payload?: any+ }+}++export type newEventsLogicType = MakeLogicType<newEventsLogicValues, newEventsLogicActions>++export const newEventsLogic = kea<newEventsLogicType>([+ path(['scenes', 'saved-insights', 'newEventsLogic']),+ loaders({+ newEvents: {+ __default: [] as EventDefinition[],+ loadNewEvents: async () => {+ const response = await api.eventDefinitions.list({ limit: 10, ordering: '-created_at' })+ return response.results+ },+ },+ }),+ reducers({+ newEventsLoadedError: [+ false,+ {+ loadNewEvents: () => false,+ loadNewEventsSuccess: () => false,+ loadNewEventsFailure: () => true,+ },+ ],+ }),+ afterMount(({ actions }) => actions.loadNewEvents()),+])diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.tsindex a9efd0262059..cde6120da2d4 100644--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts@@ -4,6 +4,8 @@ import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { DeleteDashboardForm, deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'import { DuplicateDashboardForm, duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'@@ -80,6 +82,7 @@ describe('savedInsightsLogic', () => {},})initKeaTests()+ featureFlagLogic.actions.setFeatureFlags([], {})sceneLogic({ scenes }).mount()router.actions.push(urls.project(MOCK_TEAM_ID, urls.savedInsights()))logic = savedInsightsLogic({ tabId: '1' })@@ -91,6 +94,84 @@ describe('savedInsightsLogic', () => {await expectLogic(logic).toDispatchActions(['setSavedInsightsFilters', 'loadInsights', 'loadInsightsSuccess'])})+ describe('default tab', () => {+ const savedInsightsUrl = urls.project(MOCK_TEAM_ID, urls.savedInsights())++ it.each([+ ['missing flag', undefined, SavedInsightsTabs.All],+ ['test variant', 'test', SavedInsightsTabs.Home],+ ['boolean enabled', true, SavedInsightsTabs.Home],+ ['control variant', 'control', SavedInsightsTabs.All],+ ['boolean disabled', false, SavedInsightsTabs.All],+ ])('uses the correct default for %s', async (_, flagValue, expectedTab) => {+ if (flagValue !== undefined) {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: flagValue,+ })+ }++ router.actions.push(savedInsightsUrl)+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ filters: partial({ tab: expectedTab }),+ })+ })++ it('keeps tab-less filtered links on All insights when Home is enabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',+ })++ router.actions.push(savedInsightsUrl, { search: 'revenue' })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ filters: partial({ tab: SavedInsightsTabs.All, search: 'revenue' }),+ })+ expect(router.values.searchParams).toEqual({ search: 'revenue' })+ })++ it('preserves an explicit tab when Home is enabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',+ })++ router.actions.push(savedInsightsUrl, { tab: SavedInsightsTabs.Yours })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ filters: partial({ tab: SavedInsightsTabs.Yours }),+ })+ })++ it('falls back to All insights when a Home link opens without the flag', async () => {+ router.actions.push(savedInsightsUrl, { tab: SavedInsightsTabs.Home })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ filters: partial({ tab: SavedInsightsTabs.All }),+ })+ expect(router.values.searchParams).toEqual({})+ })++ it('keeps All insights explicit when a flagged user selects it', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',+ })+ router.actions.push(savedInsightsUrl)+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSavedInsightsFilters({ tab: SavedInsightsTabs.All })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ filters: partial({ tab: SavedInsightsTabs.All }),+ })+ expect(router.values.searchParams).toEqual({ tab: SavedInsightsTabs.All })+ })+ })+it('always asks the API to exclude auto-generated feature flag insights', () => {expect(logic.values.paramsFromFilters).toMatchObject({ hide_feature_flag_insights: true })})diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.tsindex ef262c8bfe44..63c4d91aadce 100644--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts@@ -3,10 +3,13 @@ import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'import api, { CountedPaginatedResponse } from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { Sorting } from 'lib/lemon-ui/LemonTable'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { PaginationManual } from 'lib/lemon-ui/PaginationControl'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { objectDiffShallow, objectsEqual } from 'lib/utils/objects'@@ -69,10 +72,13 @@ export interface SavedInsightFilters {favorited: boolean | undefined | null}-export function cleanFilters(values: Partial<SavedInsightFilters>): SavedInsightFilters {+export function cleanFilters(+ values: Partial<SavedInsightFilters>,+ defaultTab: SavedInsightsTabs = SavedInsightsTabs.All+): SavedInsightFilters {return {order: values.order || '-last_modified_at', // Sync with `sorting` selector- tab: values.tab || SavedInsightsTabs.All,+ tab: values.tab || defaultTab,search: String(values.search || ''),insightType: values.insightType || 'All types',// Clearing a multi-select sends an empty array, which must read as "no filter" and not linger in the URL@@ -91,6 +97,14 @@ export function cleanFilters(values: Partial<SavedInsightFilters>): SavedInsight}}+export function getDefaultSavedInsightsTab(+ values: Partial<SavedInsightFilters>,+ showHomeTab: boolean+): SavedInsightsTabs {+ const listFilters = cleanFilters({ ...values, tab: SavedInsightsTabs.All })+ return showHomeTab && objectsEqual(listFilters, cleanFilters({})) ? SavedInsightsTabs.Home : SavedInsightsTabs.All+}+/** Query params the insights list API is called with for a given set of filters. */function insightsListParams(filters: SavedInsightFilters): Record<string, any> {return {@@ -147,6 +161,7 @@ export function hasNarrowingFilters(filters: SavedInsightFilters): boolean {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface savedInsightsLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicactiveSceneId: string | null // sceneLogiccurrentTeamId: number | null // teamLogicuser: UserType | null // userLogic@@ -166,6 +181,7 @@ export interface savedInsightsLogicValues {pagination: PaginationManualparamsFromFilters: Record<string, any>rawFilters: Partial<SavedInsightFilters> | null+ showHomeTab: booleansidePanelContext: SidePanelSceneContextsorting: Sorting | nullusingFilters: boolean@@ -323,6 +339,7 @@ export interface savedInsightsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface savedInsightsLogicMeta {__keaTypeGenInternalSelectorTypes: {+ showHomeTab: (featureFlags: FeatureFlagsSet) => booleanfilters: (rawFilters: Partial<SavedInsightFilters> | null) => SavedInsightFilterscount: (insights: InsightsResult) => numberusingFilters: (filters: SavedInsightFilters) => boolean@@ -347,7 +364,16 @@ export type savedInsightsLogicType = MakeLogicType<export const savedInsightsLogic = kea<savedInsightsLogicType>([path(['scenes', 'saved-insights', 'savedInsightsLogic']),connect(() => ({- values: [teamLogic, ['currentTeamId'], sceneLogic, ['activeSceneId'], userLogic, ['user']],+ values: [+ featureFlagLogic,+ ['featureFlags'],+ teamLogic,+ ['currentTeamId'],+ sceneLogic,+ ['activeSceneId'],+ userLogic,+ ['user'],+ ],logic: [eventUsageLogic],})),actions({@@ -506,6 +532,13 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([],}),selectors({+ showHomeTab: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => {+ const flagValue = featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]+ return flagValue === true || flagValue === 'test'+ },+ ],filters: [(s) => [s.rawFilters],(rawFilters: Partial<SavedInsightFilters> | null): SavedInsightFilters => cleanFilters(rawFilters || {}),@@ -743,6 +776,20 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([},})},+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ // showHomeTab resolves asynchronously, so a flag that flips after the URL was already+ // parsed needs the current tab re-derived, same as urlToAction does for a fresh visit+ if (sceneLogic.findMounted()?.values.activeSceneId !== Scene.SavedInsights) {+ return+ }+ if (router.values.searchParams.tab) {+ return+ }+ const defaultTab = getDefaultSavedInsightsTab(values.filters, values.showHomeTab)+ if (defaultTab !== values.filters.tab) {+ actions.setSavedInsightsFilters({ tab: defaultTab }, false)+ }+ },})),trackedActionToUrl(({ values }) => {const changeUrl = ():@@ -758,14 +805,11 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([const currentScene = sceneLogic.findMounted()?.valuesif (currentScene?.activeSceneId === Scene.SavedInsights) {const nextValues = cleanFilters(values.filters)- const urlValues = cleanFilters(router.values.searchParams)+ const defaultTab = getDefaultSavedInsightsTab(nextValues, values.showHomeTab)+ const defaultValues = cleanFilters({}, defaultTab)+ const urlValues = cleanFilters(router.values.searchParams, defaultTab)if (!objectsEqual(nextValues, urlValues)) {- return [- urls.savedInsights(),- objectDiffShallow(cleanFilters({}), nextValues),- {},- { replace: false },- ]+ return [urls.savedInsights(), objectDiffShallow(defaultValues, nextValues), {}, { replace: false }]}}}@@ -782,6 +826,13 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([return}+ if (searchParams.tab === SavedInsightsTabs.Home && !values.showHomeTab) {+ const insightsSearchParams = { ...searchParams }+ delete insightsSearchParams.tab+ router.actions.replace(urls.savedInsights(), insightsSearchParams, hashParams)+ return+ }+if (hashParams.fromItem && String(hashParams.fromItem).match(/^[0-9]+$/)) {// `fromItem` for legacy /insights url redirect supportconst insightNumericId = parseInt(hashParams.fromItem)@@ -804,7 +855,8 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([actions.loadDraftQuery()const currentFilters = cleanFilters(values.filters)- const nextFilters = cleanFilters(searchParams)+ const defaultTab = getDefaultSavedInsightsTab(searchParams, values.showHomeTab)+ const nextFilters = cleanFilters({ ...searchParams, tab: searchParams.tab || defaultTab })if (values.rawFilters === null || !objectsEqual(currentFilters, nextFilters)) {actions.setSavedInsightsFilters(nextFilters, false)}diff --git a/frontend/src/scenes/saved-insights/trendingInsightsLogic.ts b/frontend/src/scenes/saved-insights/trendingInsightsLogic.tsnew file mode 100644index 000000000000..143950d2ee9a--- /dev/null+++ b/frontend/src/scenes/saved-insights/trendingInsightsLogic.ts@@ -0,0 +1,66 @@+import { MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'+import { QueryBasedInsightModel } from '~/types'++export interface trendingInsightsLogicValues {+ expandedInsightIds: Set<string>+ trendingInsights: QueryBasedInsightModel[]+ trendingInsightsLoading: boolean+ trendingInsightsLoadedError: boolean+}++export interface trendingInsightsLogicActions {+ loadTrendingInsights: () => any+ loadTrendingInsightsFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }+ loadTrendingInsightsSuccess: (+ trendingInsights: QueryBasedInsightModel[],+ payload?: any+ ) => {+ payload?: any+ trendingInsights: QueryBasedInsightModel[]+ }+ toggleInsightExpanded: (insightShortId: string) => { insightShortId: string }+}++export type trendingInsightsLogicType = MakeLogicType<trendingInsightsLogicValues, trendingInsightsLogicActions>++export const trendingInsightsLogic = kea<trendingInsightsLogicType>([+ path(['scenes', 'saved-insights', 'trendingInsightsLogic']),+ actions({+ toggleInsightExpanded: (insightShortId: string) => ({ insightShortId }),+ }),+ loaders({+ trendingInsights: {+ __default: [] as QueryBasedInsightModel[],+ loadTrendingInsights: async () => {+ const insights = await api.insights.trending({ days: 7, limit: 5 })+ return insights.map(getQueryBasedInsightModel)+ },+ },+ }),+ reducers({+ expandedInsightIds: [+ new Set<string>(),+ {+ toggleInsightExpanded: (state, { insightShortId }) => {+ const next = new Set(state)+ next.has(insightShortId) ? next.delete(insightShortId) : next.add(insightShortId)+ return next+ },+ },+ ],+ trendingInsightsLoadedError: [+ false,+ {+ loadTrendingInsights: () => false,+ loadTrendingInsightsSuccess: () => false,+ loadTrendingInsightsFailure: () => true,+ },+ ],+ }),+ afterMount(({ actions }) => actions.loadTrendingInsights()),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 3987ac392e09..67d80cadd618 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1111,6 +1111,7 @@ export enum PropertyOperator {}export enum SavedInsightsTabs {+ Home = 'home',All = 'all',Yours = 'yours',History = 'history',