: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(homepage): replace starred grid with PostHog AI suggestions (#92965)
Rafael Audiberte3eae63e1b2b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a116768c576e..f80dbea1d0f2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8257,13 +8257,13 @@ snapshots:scenes-app-posthog-ai-tools--thread-with-sql-query-overflow--light:hash: v1.k794b7964.998984fe26c3f9ce26629da81e63f19891aa45441c08b9ae5dccf1d497c9bddd.DdAh6vm68mAVp3cDCyYG54XXY4qjsjbYA_Zd7aY-AHYscenes-app-project-homepage--no-primary-dashboard--dark:- hash: v1.k794b7964.af9b4385991c80eee5264faf1d07d49b87761318e2305fb5514958086edc1f58.ZJdq0-sDWJFgyjsPctN1fx7YpMsXFoi-1o_vlTuOAhI+ hash: v1.k794b7964.70707572ec3098ed0c916ac56ec8618ccd95b7b270cffb5a5425d447622912d5.Izwpm_cSdfGfQ1bysk9MbTHFu8B9R1YDo0NDluAAgnAscenes-app-project-homepage--no-primary-dashboard--light:- hash: v1.k794b7964.7c3fdb6ce7a31af8bd8ace431cfaadd663f8ffe276f49bf223e8bc638ecfa450.C6gh9sndZStKZhEfFjDYY3T0mgsXPGH_Q0v92i3hqzg+ hash: v1.k794b7964.45567c13e93e1def5dabfea7b6a4a5a47253482e6dd5c587be257ae5b9374639.fFB5rU1nd1nzktqGMRc5P0xZg5nJcxhywEnhdqT9awoscenes-app-project-homepage--project-homepage--dark:- hash: v1.k794b7964.af9b4385991c80eee5264faf1d07d49b87761318e2305fb5514958086edc1f58.1tkbdKT7hTynpGkCGRVO93dX9A-VwsbzjNwGjSkHRLg+ hash: v1.k794b7964.70707572ec3098ed0c916ac56ec8618ccd95b7b270cffb5a5425d447622912d5.Dayhp1AO69NWJL7h-i4nDDzqeXSh_3lNJjcRDBvOASUscenes-app-project-homepage--project-homepage--light:- hash: v1.k794b7964.7c3fdb6ce7a31af8bd8ace431cfaadd663f8ffe276f49bf223e8bc638ecfa450.8_eynLhjWE_werwIrum7FChveeSzc4NQvUjA_X43guQ+ hash: v1.k794b7964.45567c13e93e1def5dabfea7b6a4a5a47253482e6dd5c587be257ae5b9374639.IC346vxEHrTKcFor0vVTajrOk8lCGCu3C5pdFW2iTOQscenes-app-replay-vision--observation-detail--dark:hash: v1.k794b7964.2fe170e544ea302e2e752a2b742f8dcf49710909f54cdc6c911b245fa9403391.POKP1RHFnlV8cfwSDsAsUOY76QdhwKfc4Xryvh1TPkIscenes-app-replay-vision--observation-detail--light:diff --git a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsxindex b4527fa3fca0..336f4bcb8fd4 100644--- a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx+++ b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx@@ -11,12 +11,12 @@ import { maxSettingsLogic } from 'scenes/settings/environment/maxSettingsLogic'import { AgentMode } from '~/queries/schema/schema-assistant-messages'-import { HOMEPAGE_CAPABILITIES } from '../maxCapabilities'import { QUESTION_SUGGESTIONS_DATA, RESEARCH_SUGGESTIONS_DATA, maxLogic } from '../maxLogic'import { maxThreadLogic } from '../maxThreadLogic'-import { CAPABILITY_CARDS_HEIGHT_PX, CapabilityBadges, CapabilitySuggestions } from './CapabilityBadges'+import { HOMEPAGE_SUGGESTION_TOPICS } from '../suggestionTopics'import { FloatingSuggestionsDisplay } from './FloatingSuggestionsDisplay'import { SidebarQuestionInput } from './SidebarQuestionInput'+import { SUGGESTION_CARDS_HEIGHT_PX, TopicBadges, TopicSuggestions } from './TopicBadges'export function SidebarQuestionInputWithSuggestions({hideSuggestions = false,@@ -30,16 +30,15 @@ export function SidebarQuestionInputWithSuggestions({const { coreMemory, coreMemoryLoading } = useValues(maxSettingsLogic)const [settingsModalOpen, setSettingsModalOpen] = useState(false)- const [selectedCapability, setSelectedCapability] = useState<string | null>(null)+ const [selectedTopic, setSelectedTopic] = useState<string | null>(null)const handleSettingsClick = (): void => {setSettingsModalOpen(true)}- // Capability badges replace the pills — except in Research mode, which keeps its own tailored suggestions.+ // SuggestionTopic badges replace the pills — except in Research mode, which keeps its own tailored suggestions.const showBadges = agentMode !== AgentMode.Research- const selectedCapabilityData =- HOMEPAGE_CAPABILITIES.find((capability) => capability.key === selectedCapability) ?? null+ const selectedTopicData = HOMEPAGE_SUGGESTION_TOPICS.find((topic) => topic.key === selectedTopic) ?? nullconst tip =!coreMemoryLoading && !coreMemory?.text@@ -55,7 +54,7 @@ export function SidebarQuestionInputWithSuggestions({if (activeSuggestionGroup) {setActiveGroup(null)}- setSelectedCapability(null)+ setSelectedTopic(null)}}><SidebarQuestionInput />@@ -69,18 +68,18 @@ export function SidebarQuestionInputWithSuggestions({<h3 className="text-center text-xs font-medium mb-0 text-secondary">{tip}</h3>{showBadges ? (<div className="flex flex-col items-center gap-6 w-full">- <CapabilityBadges- capabilities={HOMEPAGE_CAPABILITIES}- selectedKey={selectedCapability}+ <TopicBadges+ topics={HOMEPAGE_SUGGESTION_TOPICS}+ selectedKey={selectedTopic}onSelect={(key) => {setFillInHint(null)- setSelectedCapability(key)+ setSelectedTopic(key)}}/>- {selectedCapabilityData && (- <div className="w-full overflow-hidden" style={{ height: CAPABILITY_CARDS_HEIGHT_PX }}>- <CapabilitySuggestions- capability={selectedCapabilityData}+ {selectedTopicData && (+ <div className="w-full overflow-hidden" style={{ height: SUGGESTION_CARDS_HEIGHT_PX }}>+ <TopicSuggestions+ topic={selectedTopicData}onType={setQuestion}onSubmit={(text) => askMax(text)}onFillIn={(hint) => {diff --git a/frontend/src/scenes/max/components/SuggestionCard.tsx b/frontend/src/scenes/max/components/SuggestionCard.tsxnew file mode 100644index 000000000000..8ac1a37b1f6c--- /dev/null+++ b/frontend/src/scenes/max/components/SuggestionCard.tsx@@ -0,0 +1,48 @@+import { LemonButton } from '@posthog/lemon-ui'++export interface SuggestionCardProps {+ title: string+ description?: string+ icon?: JSX.Element+ onClick: () => void+ /** Hover-style highlight, e.g. for keyboard navigation on the homepage. */+ active?: boolean+ className?: string+ onMouseEnter?: () => void+ onMouseLeave?: () => void+ 'data-attr'?: string+}++/**+ * One suggestion row: icon + bold title + caption. Shared between the topic cards and the+ * homepage suggestions list so the two surfaces render identically.+ */+export function SuggestionCard({+ title,+ description,+ icon,+ onClick,+ active,+ className,+ onMouseEnter,+ onMouseLeave,+ 'data-attr': dataAttr,+}: SuggestionCardProps): JSX.Element {+ return (+ <LemonButton+ className={className}+ fullWidth+ onClick={onClick}+ icon={icon}+ active={active}+ data-attr={dataAttr}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ >+ <div className="flex flex-col text-left leading-tight min-w-0">+ <span className="text-sm font-semibold truncate">{title}</span>+ {description && <span className="text-xs text-secondary font-normal truncate">{description}</span>}+ </div>+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/max/components/CapabilityBadges.tsx b/frontend/src/scenes/max/components/TopicBadges.tsxsimilarity index 63%rename from frontend/src/scenes/max/components/CapabilityBadges.tsxrename to frontend/src/scenes/max/components/TopicBadges.tsxindex 0e235c9567fd..c881557237c9 100644--- a/frontend/src/scenes/max/components/CapabilityBadges.tsx+++ b/frontend/src/scenes/max/components/TopicBadges.tsx@@ -9,40 +9,39 @@ import { cn } from 'lib/utils/css-classes'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { FileSystemIconType } from '~/queries/schema/schema-general'-import { CODE_CAPABILITY, Capability, CapabilitySuggestion } from '../maxCapabilities'+import { CODE_BADGE, SuggestionTopic, TopicSuggestion } from '../suggestionTopics'import { nextTypingDelayMs } from '../utils/typing'+import { SuggestionCard } from './SuggestionCard'// Colors the product icons (via iconForType's ProductIconWrapper). Applied inside the components so// they look identical on every surface, not only where an ancestor happens to set it (e.g. /home).-const COLORFUL_ICONS = 'group/colorful-product-icons colorful-product-icons-true'+export const COLORFUL_ICONS = 'group/colorful-product-icons colorful-product-icons-true'/*** Baseline height of the suggestion-cards / recents-grid swap area. Each surface can grow beyond it* when its content needs more space.*/-export const CAPABILITY_CARDS_HEIGHT_PX = 184+export const SUGGESTION_CARDS_HEIGHT_PX = 184-function badgeIcon(capability: Capability): JSX.Element {- return capability.icon ?? iconForType(capability.iconType)+function badgeIcon(topic: SuggestionTopic): JSX.Element {+ return topic.icon ?? iconForType(topic.iconType)}-export interface CapabilityBadgesProps {- capabilities: Capability[]+export interface TopicBadgesProps {+ topics: SuggestionTopic[]selectedKey: string | nullonSelect: (key: string | null) => voidclassName?: string}-/** Row of PostHog AI capability badges (+ the Desktop beta badge). Selection is owned by the parent. */-export function CapabilityBadges({- capabilities,- selectedKey,- onSelect,- className,-}: CapabilityBadgesProps): JSX.Element | null {+// pinned: the `capability-*` data-attr values below predate the topic naming and are frozen;+// autocapture dashboards depend on them, so the rename stops at code symbols.++/** Row of PostHog AI topic badges (+ the Desktop beta badge). Selection is owned by the parent. */+export function TopicBadges({ topics, selectedKey, onSelect, className }: TopicBadgesProps): JSX.Element | null {const isProductAutonomyEnabled = useFeatureFlag('PRODUCT_AUTONOMY')- if (!capabilities.length) {+ if (!topics.length) {return null}@@ -54,17 +53,17 @@ export function CapabilityBadges({className)}>- {capabilities.map((capability) => (+ {topics.map((topic) => (<LemonButton- key={capability.key}+ key={topic.key}size="small"type="secondary"- active={selectedKey === capability.key}- icon={badgeIcon(capability)}- onClick={() => onSelect(selectedKey === capability.key ? null : capability.key)}- data-attr={`capability-badge-${capability.key}`}+ active={selectedKey === topic.key}+ icon={badgeIcon(topic)}+ onClick={() => onSelect(selectedKey === topic.key ? null : topic.key)}+ data-attr={`capability-badge-${topic.key}`}>- {capability.label}+ {topic.label}</LemonButton>))}@@ -72,12 +71,12 @@ export function CapabilityBadges({<LemonButtonsize="small"type="secondary"- to={CODE_CAPABILITY.to}+ to={CODE_BADGE.to}icon={<IconCode />}data-attr="capability-badge-code"><span className="flex items-center gap-1.5">- {CODE_CAPABILITY.label}+ {CODE_BADGE.label}<LemonTag type="warning" size="small">Beta</LemonTag>@@ -88,8 +87,8 @@ export function CapabilityBadges({)}-export interface CapabilitySuggestionsProps {- capability: Capability+export interface TopicSuggestionsProps {+ topic: SuggestionTopic/** Called per keystroke of the typewriter animation, and once more with the full prompt. */onType: (text: string) => void/** Send the fully typed prompt to PostHog AI. */@@ -100,22 +99,16 @@ export interface CapabilitySuggestionsProps {}/**- * The suggestion cards for a selected capability. Fills its parent's baseline height (`h-full`).+ * The suggestion cards for a selected topic. Fills its parent's baseline height (`h-full`).*/-export function CapabilitySuggestions({- capability,- onType,- onSubmit,- onFillIn,- className,-}: CapabilitySuggestionsProps): JSX.Element {+export function TopicSuggestions({ topic, onType, onSubmit, onFillIn, className }: TopicSuggestionsProps): JSX.Element {// Cancels an in-flight typewriter animation (new click, or unmount).const cancelTypingRef = useRef<(() => void) | null>(null)useEffect(() => () => cancelTypingRef.current?.(), [])// Type the prompt at a human pace, then either send it, or — for a fill-in prompt — add a// trailing space and hand the hint to the parent so it can show the postfix cue.- const runSuggestion = (suggestion: CapabilitySuggestion): void => {+ const runSuggestion = (suggestion: TopicSuggestion): void => {cancelTypingRef.current?.()const { content, requiresUserInput, hint } = suggestionlet cancelled = false@@ -153,35 +146,38 @@ export function CapabilitySuggestions({// Docs-style: a plain question list (like production's Docs suggestions), reading as an// explanation rather than an action. Card-style: icon + bold title + description.- const isDocs = capability.variant === 'docs'+ const isDocs = topic.variant === 'docs'return (<divclassName={cn('w-full h-full px-3 flex flex-col gap-px', COLORFUL_ICONS, className)}data-attr="capability-suggestions">- {capability.suggestions.map((suggestion) => {- const iconType: FileSystemIconType = suggestion.iconType ?? capability.iconType+ {topic.suggestions.map((suggestion) => {+ const iconType: FileSystemIconType = suggestion.iconType ?? topic.iconType+ if (isDocs) {+ return (+ <LemonButton+ key={suggestion.content}+ className="flex-1 min-h-0"+ fullWidth+ type="tertiary"+ onClick={() => runSuggestion(suggestion)}+ data-attr={`capability-suggestion-${topic.key}`}+ >+ <span className="text-sm font-normal text-left truncate w-full">{suggestion.content}</span>+ </LemonButton>+ )+ }return (- <LemonButton+ <SuggestionCardkey={suggestion.content}className="flex-1 min-h-0"- fullWidth- type={isDocs ? 'tertiary' : undefined}+ title={suggestion.title ?? suggestion.content}+ description={suggestion.description}+ icon={iconForType(iconType)}onClick={() => runSuggestion(suggestion)}- icon={isDocs ? undefined : iconForType(iconType)}- data-attr={`capability-suggestion-${capability.key}`}- >- {isDocs ? (- <span className="text-sm font-normal text-left truncate w-full">{suggestion.content}</span>- ) : (- <div className="flex flex-col text-left leading-tight min-w-0">- <span className="text-sm font-semibold truncate">{suggestion.title}</span>- <span className="text-xs text-secondary font-normal truncate">- {suggestion.description}- </span>- </div>- )}- </LemonButton>+ data-attr={`capability-suggestion-${topic.key}`}+ />)})}</div>diff --git a/frontend/src/scenes/max/maxCapabilities.tsx b/frontend/src/scenes/max/suggestionTopics.tsxsimilarity index 83%rename from frontend/src/scenes/max/maxCapabilities.tsxrename to frontend/src/scenes/max/suggestionTopics.tsxindex de3bbd6bebae..06c5e339b61f 100644--- a/frontend/src/scenes/max/maxCapabilities.tsx+++ b/frontend/src/scenes/max/suggestionTopics.tsx@@ -4,15 +4,15 @@ import { urls } from 'scenes/urls'import { FileSystemIconType } from '~/queries/schema/schema-general'-/** One suggestion inside a capability. `content` is the prompt sent to PostHog AI. */-export interface CapabilitySuggestion {+/** One suggestion inside a topic. `content` is the prompt sent to PostHog AI. */+export interface TopicSuggestion {/*** The prompt sent to PostHog AI. For `requiresUserInput` cards this is the instruction prefix* (no trailing "…"); the input shows it as a hint and the user's text is appended on send.- * For docs-style capabilities this is also the text shown in the list.+ * For docs-style topics this is also the text shown in the list.*/content: string- /** Card-style display; omit for docs-style capabilities (which render `content` as plain text). */+ /** Card-style display; omit for docs-style topics (which render `content` as plain text). */title?: stringdescription?: string/**@@ -22,11 +22,11 @@ export interface CapabilitySuggestion {*/requiresUserInput?: booleanhint?: string- /** Icon override for the card; falls back to the capability's icon. */+ /** Icon override for the card; falls back to the topic's icon. */iconType?: FileSystemIconType}-export interface Capability {+export interface SuggestionTopic {key: stringlabel: stringiconType: FileSystemIconType@@ -35,14 +35,14 @@ export interface Capability {/*** 'cards' (default): icon + title + description cards. 'docs': a plain question list (like* production's Docs suggestions) so it reads as an explanation, not an action. Card-style- * capabilities should have exactly 4 suggestions so every block is the same height.+ * topics should have exactly 4 suggestions so every block is the same height.*/variant?: 'cards' | 'docs'- suggestions: CapabilitySuggestion[]+ suggestions: TopicSuggestion[]}/** Shared across both experiment arms — routes to the PostHog Desktop beta in the inbox. */-export const CODE_CAPABILITY = {+export const CODE_BADGE = {key: 'code',label: 'Code',to: urls.inbox(),@@ -50,30 +50,51 @@ export const CODE_CAPABILITY = {}/**- * A few docs prompts included in every arm so newcomers can learn about PostHog. Rendered as a- * plain question list (docs variant), matching the Docs suggestions we show in production.+ * A few docs prompts included in every arm so newcomers can learn about PostHog. The sidebar+ * renders these as a plain question list (docs variant), matching the Docs suggestions we show+ * in production; the homepage suggestion cards use the title/description pair instead.*/-const LEARN_CAPABILITY: Capability = {+const LEARN_TOPIC: SuggestionTopic = {key: 'learn',label: 'Learn',iconType: 'default_icon_type',icon: <IconBook />,variant: 'docs',suggestions: [- { content: 'How can I create a feature flag?' },- { content: 'Where do I watch session replays?' },- { content: 'Help me set up an experiment' },- { content: 'Explain autocapture' },- { content: 'How can I capture an exception?' },+ {+ title: 'Create a feature flag',+ description: 'How flags work and how to set one up',+ content: 'How can I create a feature flag?',+ },+ {+ title: 'Watch session replays',+ description: 'Where to find recordings of real user sessions',+ content: 'Where do I watch session replays?',+ },+ {+ title: 'Set up an experiment',+ description: 'Get help configuring your first A/B test',+ content: 'Help me set up an experiment',+ },+ {+ title: 'Understand autocapture',+ description: 'What events PostHog collects automatically',+ content: 'Explain autocapture',+ },+ {+ title: 'Capture exceptions',+ description: 'Send errors to error tracking',+ content: 'How can I capture an exception?',+ },],}/**- * Capability badges on the homepage and the PostHog AI sidebar, one per PostHog product. Prompt+ * Suggestion topics on the homepage and the PostHog AI sidebar, one per PostHog product. Prompt* content is drawn from the existing `QUESTION_SUGGESTIONS_DATA` on the PostHog AI scene so the* two surfaces stay in sync.*/-export const HOMEPAGE_CAPABILITIES: Capability[] = [+export const HOMEPAGE_SUGGESTION_TOPICS: SuggestionTopic[] = [{key: 'analytics',label: 'Analytics',@@ -275,5 +296,5 @@ export const HOMEPAGE_CAPABILITIES: Capability[] = [},],},- LEARN_CAPABILITY,+ LEARN_TOPIC,]diff --git a/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx b/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsxindex a8e002150c3f..e0d2463947f6 100644--- a/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx+++ b/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx@@ -1,9 +1,8 @@import { BindLogic, useActions, useAsyncActions, useValues } from 'kea'-import { router } from 'kea-router'import posthog from 'posthog-js'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { IconArrowRight, IconClock, IconInfo, IconMicrophone, IconPin, IconStar } from '@posthog/icons'+import { IconArrowRight, IconClock, IconInfo, IconMicrophone, IconPin, IconSparkles } from '@posthog/icons'import { LemonButton, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import { Search } from 'lib/components/Search/Search'@@ -14,19 +13,16 @@ import { Label } from 'lib/ui/Label/Label'import { TextareaPrimitive } from 'lib/ui/TextareaPrimitive/TextareaPrimitive'import { cn } from 'lib/utils/css-classes'import { uuid } from 'lib/utils/dom'-import {- CAPABILITY_CARDS_HEIGHT_PX,- CapabilityBadges,- CapabilitySuggestions,-} from 'scenes/max/components/CapabilityBadges'import { FillInHint } from 'scenes/max/components/FillInHint'import { SidebarQuestionInput } from 'scenes/max/components/SidebarQuestionInput'+import { SuggestionCard } from 'scenes/max/components/SuggestionCard'+import { SUGGESTION_CARDS_HEIGHT_PX, COLORFUL_ICONS, TopicBadges } from 'scenes/max/components/TopicBadges'import { handsFreeLogic } from 'scenes/max/handsFreeLogic'import { Intro } from 'scenes/max/Intro'-import { HOMEPAGE_CAPABILITIES } from 'scenes/max/maxCapabilities'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { maxLogic } from 'scenes/max/maxLogic'import { MaxThreadLogicProps, maxThreadLogic } from 'scenes/max/maxThreadLogic'+import { HOMEPAGE_SUGGESTION_TOPICS } from 'scenes/max/suggestionTopics'import { AIAccessRequest } from 'scenes/settings/organization/AIAccessRequest'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { userLogic } from 'scenes/userLogic'@@ -34,8 +30,15 @@ import { userLogic } from 'scenes/userLogic'import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { FileSystemIconType } from '~/queries/schema/schema-general'-import { HomepageGridItem, HomepageGridItemKind, aiFirstHomepageLogic } from './aiFirstHomepageLogic'+import {+ HomepageGridItem,+ HomepageGridItemKind,+ PINNED_DASHBOARDS_LIMIT,+ RAIL_ROW_BUDGET,+ aiFirstHomepageLogic,+} from './aiFirstHomepageLogic'import { HOMEPAGE_TAB_ID } from './constants'+import { SUGGESTIONS_LIMIT } from './homepageSuggestions'function IdleInput(): JSX.Element {const { query, fillInHint } = useValues(aiFirstHomepageLogic)@@ -68,7 +71,8 @@ function IdleInput(): JSX.Element {}return (- <form onSubmit={handleSubmit} className="flex flex-col items-center w-full px-3">+ // The input stays at readable width even when the idle scene around it is wider+ <form onSubmit={handleSubmit} className="flex flex-col items-center w-full max-w-180 mx-auto px-3"><labelhtmlFor="homepage-input"className="min-h-[40px] group input-like flex flex-col items-start relative w-full bg-fill-input border border-primary focus-within:ring-primary rounded-lg justify-stretch overflow-hidden"@@ -246,6 +250,9 @@ export function HomepageAiInput(): JSX.Element {}function GridItemIcon({ item }: { item: HomepageGridItem }): JSX.Element | null {+ if (item.icon) {+ return <>{item.icon}</>+ }if (item.itemType) {return (<ProductIconWrapper type={item.itemType}>@@ -253,41 +260,48 @@ function GridItemIcon({ item }: { item: HomepageGridItem }): JSX.Element | null</ProductIconWrapper>)}+ if (item.kind === 'suggestion') {+ return <IconSparkles className="text-tertiary" />+ }return null}-interface GridColumn {+interface RailSection {label: string- kind: HomepageGridItem['kind']+ kind: HomepageGridItemKindicon: React.ReactNode- emptyLabel: string- emptyTooltip: React.ReactNode+ /** Copy for the resolved-but-empty state. A section without it hides entirely when empty. */+ emptyState?: { label: string; tooltip: React.ReactNode }}-const GRID_COLUMNS: GridColumn[] = [+// The navigation rail next to the suggestions list: compact links to existing resources.+// Recents carry no empty state: they fill by themselves as the user browses, so an empty+// section has nothing actionable to say and just takes space.+const RAIL_SECTIONS: RailSection[] = [{label: 'Pinned dashboards',kind: 'dashboard',icon: <IconPin className="size-3" />,- emptyLabel: 'No pinned dashboards',- emptyTooltip: 'Pin dashboards by clicking "Pin" in the dashboard context panel',+ emptyState: {+ label: 'No pinned dashboards',+ tooltip: 'Pin dashboards by clicking "Pin" in the dashboard context panel',+ },},{label: 'Recents',kind: 'recent',icon: <IconClock className="size-3" />,- emptyLabel: 'No recents',- emptyTooltip: 'Recents are auto-populated when you visit a resource',- },- {- label: 'Starred',- kind: 'starred',- icon: <IconStar className="size-3" />,- emptyLabel: 'No starred items',- emptyTooltip: 'Add items to starred by clicking "add to starred" in the context panel',},]+const SKELETON_ROWS_BY_KIND: Record<HomepageGridItemKind, number> = {+ dashboard: PINNED_DASHBOARDS_LIMIT,+ // Recents share the rail budget with pinned dashboards, so their guaranteed floor is+ // whatever a full pinned section leaves over+ recent: RAIL_ROW_BUDGET - PINNED_DASHBOARDS_LIMIT,+ suggestion: SUGGESTIONS_LIMIT,+}+const GRID_SKELETON_COUNTS_KEY = 'homepage-grid-skeleton-counts'function getStoredSkeletonCounts(): Record<string, number> | null {@@ -299,43 +313,150 @@ function getStoredSkeletonCounts(): Record<string, number> | null {}}-function IdleGrid(): JSX.Element {- const { gridItems, query, dashboardsLoading, recentItemsLoading, starredItemsLoading } =- useValues(aiFirstHomepageLogic)+interface GridRowProps {+ item: HomepageGridItem+ highlighted: boolean+ onHighlight: (highlighted: boolean) => void+}- // [col, row] position of the highlighted item, null = nothing highlighted+function GridRow({ item, highlighted, onHighlight }: GridRowProps): JSX.Element {+ const { gridItemClicked, activateGridItem } = useActions(aiFirstHomepageLogic)+ return (+ <div role="row">+ <Link+ to={item.href}+ role="gridcell"+ title={item.label}+ buttonProps={{+ menuItem: true,+ fullWidth: true,+ className: 'truncate -outline-offset-2',+ }}+ // Items with an href navigate through the anchor itself, so the click handler+ // only reports; suggestions have no href and the handler performs the action too.+ onClick={() => (item.href ? gridItemClicked(item) : activateGridItem(item))}+ data-attr={`homepage-grid-${item.kind}`}+ data-highlighted={highlighted ? 'true' : undefined}+ onMouseEnter={() => onHighlight(true)}+ onMouseLeave={() => onHighlight(false)}+ >+ <GridItemIcon item={item} />+ <span className="truncate">{item.label}</span>+ </Link>+ </div>+ )+}++function SuggestionRow({ item, highlighted, onHighlight }: GridRowProps): JSX.Element {+ const { activateGridItem } = useActions(aiFirstHomepageLogic)+ return (+ // data-highlighted lives on the wrapper so keyboard navigation can scroll to it;+ // the visual highlight rides the card's own active state.+ <div role="row" data-highlighted={highlighted ? 'true' : undefined}>+ <SuggestionCard+ title={item.label}+ description={item.description}+ icon={<GridItemIcon item={item} />}+ onClick={() => activateGridItem(item)}+ active={highlighted}+ data-attr={`homepage-grid-${item.kind}`}+ onMouseEnter={() => onHighlight(true)}+ onMouseLeave={() => onHighlight(false)}+ />+ </div>+ )+}++function GridSkeletons({+ kind,+ counts,+}: {+ kind: HomepageGridItemKind+ counts: Record<string, number> | null+}): JSX.Element {+ // Stored counts can predate the current row caps, so clamp to keep the layout stable+ const rows = Math.min(counts?.[kind] ?? SKELETON_ROWS_BY_KIND[kind], SKELETON_ROWS_BY_KIND[kind])+ return (+ <>+ {Array.from({ length: rows }).map((_, i) => (+ <div key={`skeleton-${i}`}>+ {/* Suggestion cards are two-line units, taller than the single-line rail rows */}+ <LemonSkeleton className={kind === 'suggestion' ? 'h-[45px]' : 'h-[30px]'} />+ </div>+ ))}+ </>+ )+}++function RailEmptyState({+ kind,+ emptyState,+}: {+ kind: HomepageGridItemKind+ emptyState: NonNullable<RailSection['emptyState']>+}): JSX.Element {+ return (+ <div+ className="px-3 py-2 border border-dashed rounded text-xs text-tertiary"+ data-attr={`homepage-grid-empty-${kind}`}+ >+ {emptyState.label}{' '}+ <Tooltip title={emptyState.tooltip} delayMs={0}>+ <IconInfo className="size-3 text-tertiary" data-attr={`homepage-grid-empty-tooltip-${kind}`} />+ </Tooltip>+ </div>+ )+}++function IdleGrid(): JSX.Element {+ const {+ gridItems,+ displayedSuggestionItems,+ query,+ dashboardsLoading,+ recentItemsLoading,+ suggestionItemsLoading,+ selectedTopic,+ } = useValues(aiFirstHomepageLogic)+ const { activateGridItem } = useActions(aiFirstHomepageLogic)++ // [col, row] position of the highlighted item, null = nothing highlighted.+ // Column 0 is the suggestions list, column 1 the whole rail (dashboards then recents).const [highlight, setHighlight] = useState<[number, number] | null>(null)const gridRef = useRef<HTMLDivElement>(null)const [skeletonCounts, setSkeletonCounts] = useState(getStoredSkeletonCounts)- const columns = useMemo(() => {- return GRID_COLUMNS.map((col) => ({- ...col,- items: gridItems.filter((item) => item.kind === col.kind),- }))- }, [gridItems])+ const railItemsByKind = useMemo(+ () => ({+ dashboard: gridItems.filter((item) => item.kind === 'dashboard'),+ recent: gridItems.filter((item) => item.kind === 'recent'),+ }),+ [gridItems]+ )++ const columns = useMemo(+ () => [+ { key: 'suggestions', items: displayedSuggestionItems },+ { key: 'rail', items: [...railItemsByKind.dashboard, ...railItemsByKind.recent] },+ ],+ [displayedSuggestionItems, railItemsByKind]+ )// Persist item counts when loading finishes so skeletons match on next visituseEffect(() => {- const isLoading = dashboardsLoading || recentItemsLoading || starredItemsLoading+ const isLoading = dashboardsLoading || recentItemsLoading || suggestionItemsLoadingif (isLoading) {return}- const counts: Record<string, number> = {}- for (const col of columns) {- counts[col.kind] = col.items.length+ const counts: Record<string, number> = {+ dashboard: railItemsByKind.dashboard.length,+ recent: railItemsByKind.recent.length,+ suggestion: displayedSuggestionItems.length,}localStorage.setItem(GRID_SKELETON_COUNTS_KEY, JSON.stringify(counts))setSkeletonCounts(counts)- }, [dashboardsLoading, recentItemsLoading, starredItemsLoading, columns])-- const handleItemClick = useCallback((item: HomepageGridItem) => {- if (item.href) {- posthog.capture('homepage grid item clicked', { kind: item.kind, href: item.href })- router.actions.push(item.href)- }- }, [])+ }, [dashboardsLoading, recentItemsLoading, suggestionItemsLoading, railItemsByKind, displayedSuggestionItems])// Clear highlight when user starts typinguseEffect(() => {@@ -416,7 +537,7 @@ function IdleGrid(): JSX.Element {e.preventDefault()const item = colItems[row]if (item) {- handleItemClick(item)+ activateGridItem(item)}break}@@ -428,7 +549,7 @@ function IdleGrid(): JSX.Element {}}},- [highlight, columns, handleItemClick]+ [highlight, columns, activateGridItem])// Scroll highlighted item into view@@ -442,21 +563,21 @@ function IdleGrid(): JSX.Element {}}, [highlight])- const loadingByKind: Record<HomepageGridItemKind, boolean> = {- dashboard: dashboardsLoading,- recent: recentItemsLoading,- starred: starredItemsLoading,+ const railHighlightOffset: Record<'dashboard' | 'recent', number> = {+ dashboard: 0,+ recent: railItemsByKind.dashboard.length,}// Collapse-on-typing is handled by the shared wrapper in HomepageInput, so this renders the- // grid content directly (no self-collapse) — keeping the badges and grid in one animated box.+ // grid content directly (no self-collapse), keeping the badges and grid in one animated box.return (<divref={gridRef}role="grid"data-attr="homepage-grid"- // Only shown at @xl+ where the homepage columns sit in a row.- className="flex flex-col @xl/main-content:flex-row gap-8 @xl/main-content:gap-2 w-full px-3 outline-none mt-8"+ // Only shown at @xl+ where the suggestions list and the rail sit side by side.+ // shrink-0 so the collapse-on-typing animation clips instead of squeezing.+ className="flex gap-6 w-full px-3 outline-none shrink-0"tabIndex={-1}onFocus={(e) => {// Only auto-highlight when focused via keyboard (ArrowDown from input)@@ -470,124 +591,102 @@ function IdleGrid(): JSX.Element {}}onKeyDown={handleGridKeyDown}>- {columns.map((col, colIndex) => (- <div- key={col.kind}- role="rowgroup"- className="flex-1 min-w-0 flex flex-col gap-px"- data-attr={`homepage-grid-column-${col.kind}`}- >- <Label className="px-2 mb-1 flex items-center gap-1" intent="menu">- {col.icon}- {col.label}- </Label>- {loadingByKind[col.kind] &&- col.items.length === 0 &&- (skeletonCounts === null || (skeletonCounts[col.kind] ?? 0) > 0) ? (- Array.from({ length: skeletonCounts?.[col.kind] ?? 3 }).map((_, i) => (- <div key={`skeleton-${i}`}>- <LemonSkeleton className="h-[30px]" />- </div>- ))- ) : col.items.length === 0 ? (- <div- className="px-3 py-2 border border-dashed rounded text-xs text-tertiary"- data-attr={`homepage-grid-empty-${col.kind}`}- >- {col.emptyLabel}{' '}- <Tooltip title={col.emptyTooltip} delayMs={0}>- <IconInfo- className="size-3 text-tertiary"- data-attr={`homepage-grid-empty-tooltip-${col.kind}`}- />- </Tooltip>+ {/* Suggestions list, or the selected topic's suggestions in the same slot */}+ <div+ role="rowgroup"+ className={cn('flex-[2] min-w-0 flex flex-col gap-px', COLORFUL_ICONS)}+ data-attr="homepage-grid-column-suggestion"+ style={{ minHeight: SUGGESTION_CARDS_HEIGHT_PX }}+ >+ <Label className="px-2 mb-1 flex items-center gap-1" intent="menu">+ <IconSparkles className="size-3" />+ Ask PostHog AI+ </Label>+ {/* The static fill means the list is never empty, so gate on the sources+ having resolved; a selected topic is static data and never loads */}+ {!selectedTopic && suggestionItemsLoading ? (+ <GridSkeletons kind="suggestion" counts={skeletonCounts} />+ ) : (+ displayedSuggestionItems.map((item, rowIndex) => (+ <SuggestionRow+ key={item.id}+ item={item}+ highlighted={highlight?.[0] === 0 && highlight?.[1] === rowIndex}+ onHighlight={(over) => setHighlight(over ? [0, rowIndex] : null)}+ />+ ))+ )}+ </div>++ {/* Navigation rail: pinned dashboards and recents */}+ <div role="rowgroup" className="flex-1 min-w-0 flex flex-col gap-px" data-attr="homepage-grid-column-nav">+ {RAIL_SECTIONS.map((section) => {+ const items = railItemsByKind[section.kind as 'dashboard' | 'recent']+ const loading = section.kind === 'dashboard' ? dashboardsLoading : recentItemsLoading+ const offset = railHighlightOffset[section.kind as 'dashboard' | 'recent']+ if (!loading && items.length === 0 && !section.emptyState) {+ return null+ }+ return (+ <div key={section.kind} className="flex flex-col gap-px [&:not(:first-child)]:mt-3">+ <Label className="px-2 mb-1 flex items-center gap-1" intent="menu">+ {section.icon}+ {section.label}+ </Label>+ {loading && items.length === 0 ? (+ <GridSkeletons kind={section.kind} counts={skeletonCounts} />+ ) : items.length === 0 && section.emptyState ? (+ <RailEmptyState kind={section.kind} emptyState={section.emptyState} />+ ) : (+ items.map((item, index) => (+ <GridRow+ key={item.id}+ item={item}+ highlighted={highlight?.[0] === 1 && highlight?.[1] === offset + index}+ onHighlight={(over) => setHighlight(over ? [1, offset + index] : null)}+ />+ ))+ )}</div>- ) : (- col.items.map((item, rowIndex) => (- <div key={item.id} role="row">- <Link- to={item.href}- role="gridcell"- title={item.label}- buttonProps={{- menuItem: true,- fullWidth: true,- className: 'truncate -outline-offset-2',- }}- data-attr={`homepage-grid-${item.kind}`}- data-highlighted={- highlight?.[0] === colIndex && highlight?.[1] === rowIndex ? 'true' : undefined- }- onMouseEnter={() => setHighlight([colIndex, rowIndex])}- onMouseLeave={() => setHighlight(null)}- >- <GridItemIcon item={item} />- <span className="truncate">{item.label}</span>- </Link>- </div>- ))- )}- </div>- ))}+ )+ })}+ </div></div>)}export function HomepageInput(): JSX.Element {- const { mode, query, selectedCapability } = useValues(aiFirstHomepageLogic)- const { setQuery, submitQuery, setSelectedCapability, setFillInHint } = useActions(aiFirstHomepageLogic)+ const { mode, query, selectedTopic } = useValues(aiFirstHomepageLogic)+ const { setSelectedTopic } = useActions(aiFirstHomepageLogic)const { user } = useValues(userLogic)- const selectedCapabilityData =- HOMEPAGE_CAPABILITIES.find((capability) => capability.key === selectedCapability) ?? null-return (- <div className="w-full max-w-180 mx-auto py-2 ">+ // Idle gets extra width for the suggestions grid; AI and search keep the chat width+ <div className={cn('w-full mx-auto py-2', mode === 'idle' ? 'max-w-240' : 'max-w-180')}>{mode === 'idle' && (<div className="flex flex-col items-center gap-3 pb-(--scene-layout-header-height)"><Intro forceHeadline={`Hello ${user?.first_name || 'there'}`} forceSubheadline={null} /><IdleInput />- {/* Badges + (cards | recents grid) collapse together as a single box when the user- starts typing / leaves idle. Hidden on mobile — only shown at @xl, where the grid- lays its columns in a row. */}+ {/* Badges + grid collapse together as a single box when the user starts typing /+ leaves idle. Hidden on mobile — only shown at @xl, where the suggestions list+ and the rail sit side by side. */}<divclassName="w-full hidden @xl/main-content:grid transition-[grid-template-rows] duration-200 ease-out motion-reduce:duration-0"style={{ gridTemplateRows: query.trim() ? '0fr' : '1fr' }}aria-hidden={!!query.trim()}>{/* shrink-0 on the children so collapsing just clips them away (top-down) rather- than squeezing their heights, which would reflow the cards/grid mid-animation.+ than squeezing their heights, which would reflow the grid mid-animation.gap-6 spaces the badges from the row below — it's part of the flex column'slaid-out height, so it's counted in the collapse and the vertical centering. */}<div className="overflow-hidden flex flex-col items-center gap-6">- <CapabilityBadges+ <TopicBadgesclassName="shrink-0"- capabilities={HOMEPAGE_CAPABILITIES}- selectedKey={selectedCapability}- onSelect={setSelectedCapability}+ topics={HOMEPAGE_SUGGESTION_TOPICS}+ selectedKey={selectedTopic}+ onSelect={setSelectedTopic}/>- {/* Capability suggestions need a fixed basis; the idle grid uses its intrinsic height. */}- <div- className="w-full shrink-0 overflow-hidden"- style={{- height: selectedCapabilityData ? CAPABILITY_CARDS_HEIGHT_PX : 'auto',- minHeight: CAPABILITY_CARDS_HEIGHT_PX,- }}- >- {selectedCapabilityData ? (- <CapabilitySuggestions- capability={selectedCapabilityData}- onType={setQuery}- onSubmit={() => submitQuery('ai')}- onFillIn={(hint) => {- setFillInHint(hint)- document.querySelector<HTMLElement>('#homepage-input')?.focus()- }}- />- ) : (- <IdleGrid />- )}- </div>+ <IdleGrid /></div></div></div>diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.tsindex aa4102dfc226..ce3f5b128655 100644--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts@@ -7,7 +7,6 @@ import { maxLogic } from 'scenes/max/maxLogic'import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'-import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'import { useMocks } from '~/mocks/jest'import { dashboardsModel } from '~/models/dashboardsModel'import { recentItemsModel } from '~/models/recentItemsModel'@@ -81,7 +80,7 @@ describe('aiFirstHomepageLogic', () => {expect(router.values.searchParams.ask).toEqual(sandboxFlagOn ? 'what is my dau' : undefined)})- it('shows up to eight pinned dashboards, recents, and starred items', () => {+ it('shares the rail row budget between pinned and recents, and fills suggestions to four', () => {const createFileSystemEntries = (prefix: string): FileSystemEntry[] =>Array.from({ length: 9 }, (_, index) => ({id: `${prefix}-${index}`,@@ -100,13 +99,76 @@ describe('aiFirstHomepageLogic', () => {})) as DashboardBasicType[],})recentItemsModel.actions.loadRecentsSuccess(createFileSystemEntries('Recent'))- projectTreeDataLogic.actions.loadShortcutsSuccess([- ...createFileSystemEntries('Starred'),- { id: 'starred-folder', path: 'Starred folder', type: 'folder' },- ])-- expect(logic.values.gridItems.filter((item) => item.kind === 'dashboard')).toHaveLength(8)- expect(logic.values.gridItems.filter((item) => item.kind === 'recent')).toHaveLength(8)- expect(logic.values.gridItems.filter((item) => item.kind === 'starred')).toHaveLength(8)++ const dashboards = logic.values.gridItems.filter((item) => item.kind === 'dashboard')+ expect(dashboards).toHaveLength(4)+ // Nine pinned dashboards render as three rows plus a link to the rest+ expect(dashboards[3]).toMatchObject({ id: 'dashboard-overflow', label: 'And 6 more', href: urls.dashboards() })+ // A full pinned section leaves two of the rail's six budgeted rows for recents+ expect(logic.values.gridItems.filter((item) => item.kind === 'recent')).toHaveLength(2)+ const suggestions = logic.values.gridItems.filter((item) => item.kind === 'suggestion')+ expect(suggestions).toHaveLength(4)+ // The recent insights collapse into one insight prompt; static prompts fill the rest+ expect(suggestions.filter((item) => item.source === 'recent')).toHaveLength(1)+ expect(suggestions.filter((item) => item.source === 'static')).toHaveLength(3)+ })++ it('activating a prompt suggestion types it into the input and submits to PostHog AI', async () => {+ const prompt = 'What is my DAU?'+ router.actions.push(urls.projectHomepage())++ jest.useFakeTimers()+ try {+ logic.actions.activateGridItem({+ id: 'suggestion-static-analytics-0',+ label: prompt,+ kind: 'suggestion',+ source: 'static',+ prompt,+ })+ // The prompt animates in character by character rather than appearing at once+ expect(logic.values.query.length).toBeLessThan(prompt.length)+ // Run the typewriter to completion (per-character delays plus the pre-submit pause)+ jest.advanceTimersByTime(10_000)+ } finally {+ jest.useRealTimers()+ }+ await expectLogic(logic).toMatchValues({ mode: 'ai', query: prompt })+ })++ it('typing over the suggestion typewriter cancels it and nothing submits', async () => {+ router.actions.push(urls.projectHomepage())++ jest.useFakeTimers()+ try {+ logic.actions.activateGridItem({+ id: 'suggestion-static-analytics-0',+ label: 'What is my DAU?',+ kind: 'suggestion',+ source: 'static',+ prompt: 'What is my DAU?',+ })+ jest.advanceTimersByTime(100)+ // The user types over the half-typed suggestion: their input must win+ logic.actions.setQuery('my own question')+ jest.advanceTimersByTime(10_000)+ } finally {+ jest.useRealTimers()+ }+ await expectLogic(logic).toMatchValues({ mode: 'idle', query: 'my own question' })+ })++ it('activating a continue-conversation suggestion restores that conversation', async () => {+ router.actions.push(urls.projectHomepage())++ logic.actions.activateGridItem({+ id: 'suggestion-continue-conv-1',+ label: 'Continue "Retention dip"',+ kind: 'suggestion',+ source: 'continue',+ conversationId: 'conv-1',+ })+ await expectLogic(logic).delay(1).toMatchValues({ mode: 'ai' })+ expect(maxLogic({ panelId: HOMEPAGE_TAB_ID }).values.conversationId).toEqual('conv-1')})})diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.tsindex 37124f4656c7..be1da79c17c0 100644--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts@@ -6,11 +6,12 @@ import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { handsFreeLogic } from 'scenes/max/handsFreeLogic'import { type PhaiViewMode, maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { maxLogic, parseCommandString } from 'scenes/max/maxLogic'+import { HOMEPAGE_SUGGESTION_TOPICS } from 'scenes/max/suggestionTopics'+import { nextTypingDelayMs } from 'scenes/max/utils/typing'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'-import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'import { dashboardsModel } from '~/models/dashboardsModel'import { recentItemsModel } from '~/models/recentItemsModel'@@ -18,12 +19,13 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'import { sceneLogic } from '~/scenes/sceneLogic'import { emptySceneParams } from '~/scenes/scenes'import { Scene, SceneTab } from '~/scenes/sceneTypes'-import { DashboardBasicType, SidePanelTab } from '~/types'+import { Conversation, ConversationType, DashboardBasicType, SidePanelTab } from '~/types'import type { Node } from '../../../queries/schema/schema-general'-import type { TeamPublicType, TeamType } from '../../../types'+import type { ConversationDetail, TeamPublicType, TeamType } from '../../../types'import type { DashboardType, QueryBasedInsightModel } from '../../../types'import { HOMEPAGE_IDLE_DRAFT_KEY, HOMEPAGE_TAB_ID } from './constants'+import { buildSuggestionItems, topicSuggestionItems } from './homepageSuggestions'export type HomepageMode = 'idle' | 'search' | 'ai'export type AnimationPhase = 'idle' | 'moving' | 'separator' | 'content'@@ -33,22 +35,35 @@ export interface LayoutState {animationPhase: AnimationPhase}-export type HomepageGridItemKind = 'dashboard' | 'recent' | 'starred'+export type HomepageGridItemKind = 'dashboard' | 'recent' | 'suggestion'export interface HomepageGridItem {id: string- /** The raw FileSystemEntry ID, used for shortcut deletion. */- entryId?: string- /** The original FileSystemEntry, used for adding to starred. */- entry?: FileSystemEntrylabel: string+ /** Caption under the label on suggestion cards, naming what the suggestion is about. */+ description?: stringicon?: React.ReactNodehref?: stringkind: HomepageGridItemKinditemType?: string | null+ /** Prompt submitted to PostHog AI when a suggestion is activated. */+ prompt?: string+ /** Conversation opened when a continue-conversation suggestion is activated. */+ conversationId?: string+ /** When set, activation types `prompt` into the input and waits for the user to complete it. */+ fillInHint?: string+ /** Where a suggestion came from, captured on click so the sources can be compared. */+ source?: 'continue' | 'recent' | 'static' | 'topic'}-const GRID_LIMIT = 8+// The rail shares a fixed row budget between pinned dashboards and recents, so it cannot+// outgrow the suggestions list next to it: recents expand into whatever pinned doesn't use.+export const RAIL_ROW_BUDGET = 6+export const PINNED_DASHBOARDS_LIMIT = 4++// The suggestion typewriter runs faster than the shared human-pace curve: on the homepage the+// prompt is already fully visible on the card, so the animation is a cue, not a reveal.+const TYPING_SPEEDUP_FACTOR = 0.7const PREVIOUS_HOMEPAGE_KEY = 'ai-first-previous-homepage'@@ -75,23 +90,35 @@ function savePreviousHomepage(tab: SceneTab | null): void {}}+// pinned: analytics event name and property names; renaming breaks dashboards+function reportGridItemClicked(item: HomepageGridItem): void {+ posthog.capture('homepage grid item clicked', {+ kind: item.kind,+ href: item.href,+ prompt: item.prompt,+ source: item.source,+ })+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiFirstHomepageLogicValues {dashboardsLoading: boolean // dashboardsModelpinnedDashboards: (DashboardBasicType | DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>>)[] // dashboardsModel+ conversationHistory: ConversationDetail[] // maxGlobalLogic+ conversationHistoryLoading: boolean // maxGlobalLogiceffectivePhaiView: PhaiViewMode // maxGlobalLogicconversationId: string | null // maxLogicthreadLogicKey: string // maxLogic- cachedStarred: FileSystemEntry[] // projectTreeDataLogic- shortcutDataHasLoaded: boolean // projectTreeDataLogiccachedRecents: FileSystemEntry[] // recentItemsModelrecentsHasLoaded: boolean // recentItemsModelhomepage: SceneTab | null // sceneLogicchatDraftFor: (tabId: string | undefined) => string // tabUiStateLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogicanimationPhase: AnimationPhase+ displayedSuggestionItems: HomepageGridItem[]fillInHint: string | nullgridItems: HomepageGridItem[]+ lastConversation: Conversation | nulllayoutState: LayoutStatemode: HomepageModepinnedDashboardItems: HomepageGridItem[]@@ -99,9 +126,9 @@ export interface aiFirstHomepageLogicValues {query: stringrecentItems: FileSystemEntry[]recentItemsLoading: boolean- selectedCapability: string | null- starredItems: FileSystemEntry[]- starredItemsLoading: boolean+ selectedTopic: string | null+ suggestionItems: HomepageGridItem[]+ suggestionItemsLoading: booleanthreadStarted: boolean}@@ -129,9 +156,15 @@ export interface aiFirstHomepageLogicActions {draft: stringtabId: string} // tabUiStateLogic+ activateGridItem: (item: HomepageGridItem) => {+ item: HomepageGridItem+ }enterAiMode: (trigger: string) => {trigger: string}+ gridItemClicked: (item: HomepageGridItem) => {+ item: HomepageGridItem+ }returnToIdle: () => {value: true}@@ -150,7 +183,7 @@ export interface aiFirstHomepageLogicActions {setQuery: (query: string) => {query: string}- setSelectedCapability: (key: string | null) => {+ setSelectedTopic: (key: string | null) => {key: string | null}startHandsFreeChat: () => {@@ -164,10 +197,23 @@ export interface aiFirstHomepageLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiFirstHomepageLogicMeta {__keaTypeGenInternalSelectorTypes: {- recentItems: (cachedRecents: FileSystemEntry[]) => FileSystemEntry[]+ recentItems: (+ cachedRecents: FileSystemEntry[],+ pinnedDashboardItems: HomepageGridItem[],+ dashboardsLoading: boolean+ ) => FileSystemEntry[]recentItemsLoading: (recentsHasLoaded: boolean) => boolean- starredItems: (cachedStarred: FileSystemEntry[]) => FileSystemEntry[]- starredItemsLoading: (shortcutDataHasLoaded: boolean) => boolean+ lastConversation: (conversationHistory: ConversationDetail[]) => Conversation | null+ suggestionItems: (lastConversation: Conversation | null, recentItems: FileSystemEntry[]) => HomepageGridItem[]+ displayedSuggestionItems: (+ selectedTopic: string | null,+ suggestionItems: HomepageGridItem[]+ ) => HomepageGridItem[]+ suggestionItemsLoading: (+ conversationHistoryLoading: boolean,+ conversationHistory: ConversationDetail[],+ recentItemsLoading: boolean+ ) => booleanmode: (layoutState: LayoutState) => HomepageModeanimationPhase: (layoutState: LayoutState) => AnimationPhasepinnedDashboardItems: (@@ -176,7 +222,7 @@ export interface aiFirstHomepageLogicMeta {gridItems: (pinnedDashboardItems: HomepageGridItem[],recentItems: FileSystemEntry[],- starredItems: FileSystemEntry[]+ suggestionItems: HomepageGridItem[]) => HomepageGridItem[]}}@@ -203,12 +249,10 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([['pinnedDashboards', 'dashboardsLoading'],recentItemsModel,['recents as cachedRecents', 'recentsHasLoaded'],- projectTreeDataLogic,- ['shortcutData as cachedStarred', 'shortcutDataHasLoaded'],tabUiStateLogic,['chatDraftFor'],maxGlobalLogic,- ['effectivePhaiView'],+ ['effectivePhaiView', 'conversationHistory', 'conversationHistoryLoading'],],actions: [maxLogic({ panelId: HOMEPAGE_TAB_ID }),@@ -231,9 +275,13 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([returnToIdle: true,setPreviousHomepage: (tab: SceneTab | null) => ({ tab }),revertToPreviousHomepage: true,- setSelectedCapability: (key: string | null) => ({ key }),+ setSelectedTopic: (key: string | null) => ({ key }),// Postfix hint shown after a fill-in suggestion's typed-in prefix (e.g. "insert feature name").setFillInHint: (hint: string | null) => ({ hint }),+ // Capture-only, for grid links whose navigation the Link component already handles.+ gridItemClicked: (item: HomepageGridItem) => ({ item }),+ // Capture plus perform: submit a suggestion prompt, continue a conversation, or navigate.+ activateGridItem: (item: HomepageGridItem) => ({ item }),}),reducers({@@ -281,10 +329,10 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([setPreviousHomepage: (_, { tab }) => tab,},],- selectedCapability: [+ selectedTopic: [null as string | null,{- setSelectedCapability: (_, { key }) => key,+ setSelectedTopic: (_, { key }) => key,submitQuery: () => null,returnToIdle: () => null,},@@ -293,7 +341,7 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([null as string | null,{setFillInHint: (_, { hint }) => hint,- setSelectedCapability: () => null,+ setSelectedTopic: () => null,submitQuery: () => null,returnToIdle: () => null,},@@ -302,18 +350,52 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([selectors({recentItems: [- (s) => [s.cachedRecents],- (cachedRecents: FileSystemEntry[]): FileSystemEntry[] => cachedRecents.slice(0, GRID_LIMIT),+ (s) => [s.cachedRecents, s.pinnedDashboardItems, s.dashboardsLoading],+ (+ cachedRecents: FileSystemEntry[],+ pinnedDashboardItems: HomepageGridItem[],+ dashboardsLoading: boolean+ ): FileSystemEntry[] => {+ // While dashboards load, assume a full pinned section so recents grow into the+ // freed rows once it resolves, instead of rendering long and then shrinking.+ const pinnedRows = dashboardsLoading ? PINNED_DASHBOARDS_LIMIT : pinnedDashboardItems.length+ return cachedRecents.slice(0, RAIL_ROW_BUDGET - pinnedRows)+ },],recentItemsLoading: [(s) => [s.recentsHasLoaded], (recentsHasLoaded: boolean): boolean => !recentsHasLoaded],- starredItems: [- (s) => [s.cachedStarred],- (cachedStarred: FileSystemEntry[]): FileSystemEntry[] =>- cachedStarred.filter((e) => e.type !== 'folder').slice(0, GRID_LIMIT),+ lastConversation: [+ (s) => [s.conversationHistory],+ (conversationHistory: ConversationDetail[]): Conversation | null =>+ // The API returns conversations newest-first. Tool-call and deep-research rows+ // aren't resumable chats, and a conversation without a title has nothing to show.+ conversationHistory.find(+ (conversation) => conversation.type === ConversationType.Assistant && !!conversation.title+ ) ?? null,+ ],+ suggestionItems: [+ (s) => [s.lastConversation, s.recentItems],+ (lastConversation: Conversation | null, recentItems: FileSystemEntry[]): HomepageGridItem[] =>+ buildSuggestionItems(lastConversation, recentItems),+ ],+ // What the suggestions list actually shows: a selected topic's suggestions, or the+ // personalized default. One shape, so both states render through the same component.+ displayedSuggestionItems: [+ (s) => [s.selectedTopic, s.suggestionItems],+ (selectedTopic: string | null, suggestionItems: HomepageGridItem[]): HomepageGridItem[] => {+ const topic = HOMEPAGE_SUGGESTION_TOPICS.find((c) => c.key === selectedTopic)+ return topic ? topicSuggestionItems(topic) : suggestionItems+ },],- starredItemsLoading: [- (s) => [s.shortcutDataHasLoaded],- (shortcutDataHasLoaded: boolean): boolean => !shortcutDataHasLoaded,+ // Static fill means suggestions exist from the first render, but showing them before the+ // personalized sources resolve would swap the list under the user's cursor. A history+ // reload with cached conversations doesn't count as loading, so revisits render instantly.+ suggestionItemsLoading: [+ (s) => [s.conversationHistoryLoading, s.conversationHistory, s.recentItemsLoading],+ (+ conversationHistoryLoading: boolean,+ conversationHistory: ConversationDetail[],+ recentItemsLoading: boolean+ ): boolean => (conversationHistoryLoading && conversationHistory.length === 0) || recentItemsLoading,],mode: [(s) => [s.layoutState], (layoutState: LayoutState): HomepageMode => layoutState.mode],animationPhase: [@@ -331,55 +413,141 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([>>)[]- ): HomepageGridItem[] =>- pinnedDashboards.slice(0, GRID_LIMIT).map(- (d: DashboardBasicType): HomepageGridItem => ({- id: `dashboard-${d.id}`,- label: d.name || `Dashboard ${d.id}`,- href: urls.dashboard(d.id),+ ): HomepageGridItem[] => {+ const toGridItem = (d: DashboardBasicType): HomepageGridItem => ({+ id: `dashboard-${d.id}`,+ label: d.name || `Dashboard ${d.id}`,+ href: urls.dashboard(d.id),+ kind: 'dashboard',+ itemType: 'dashboard',+ })+ if (pinnedDashboards.length <= PINNED_DASHBOARDS_LIMIT) {+ return pinnedDashboards.map(toGridItem)+ }+ // Swap the last row for a link to the full list, so the section stays at+ // PINNED_DASHBOARDS_LIMIT rows instead of silently dropping the overflow.+ const shown = pinnedDashboards.slice(0, PINNED_DASHBOARDS_LIMIT - 1)+ return [+ ...shown.map(toGridItem),+ {+ id: 'dashboard-overflow',+ label: `And ${pinnedDashboards.length - shown.length} more`,+ href: urls.dashboards(),kind: 'dashboard',- itemType: 'dashboard',- })- ),+ },+ ]+ },],gridItems: [- (s) => [s.pinnedDashboardItems, s.recentItems, s.starredItems],+ (s) => [s.pinnedDashboardItems, s.recentItems, s.suggestionItems],(pinnedDashboardItems: HomepageGridItem[],recentItems: FileSystemEntry[],- starredItems: FileSystemEntry[]+ suggestionItems: HomepageGridItem[]): HomepageGridItem[] => {- const toGridItem = (entry: FileSystemEntry, kind: HomepageGridItemKind): HomepageGridItem => {+ const toGridItem = (entry: FileSystemEntry): HomepageGridItem => {const name = splitPath(entry.path).pop()return {- id: `${kind}-${entry.id}`,- entryId: entry.id,- entry,+ id: `recent-${entry.id}`,label: name ? unescapePath(name) : entry.path,href: entry.href || '#',- kind,+ kind: 'recent',itemType: entry.type ?? null,}}return [...pinnedDashboardItems,- ...recentItems.map((e: FileSystemEntry) => toGridItem(e, 'recent')),- ...starredItems.map((e: FileSystemEntry) => toGridItem(e, 'starred')),+ ...recentItems.map((e: FileSystemEntry) => toGridItem(e)),+ ...suggestionItems,]},],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({+ gridItemClicked: ({ item }) => {+ reportGridItemClicked(item)+ },+ activateGridItem: ({ item }) => {+ reportGridItemClicked(item)+ if (item.conversationId) {+ // The legacy homepage restores a conversation in place; the new PostHog AI surface+ // owns its own route, so hand the conversation to /ai there (same split as submitQuery).+ if (values.effectivePhaiView === 'new') {+ router.actions.push(urls.ai(item.conversationId))+ } else {+ actions.openConversation(item.conversationId)+ actions.submitQuery('ai')+ }+ } else if (item.prompt) {+ const content = item.prompt+ const fillInHint = item.fillInHint+ // Type the prompt at a human pace (parity with the topic panels in the Max+ // sidebar), then submit it, or hand a fill-in prompt's hint cue to the input.+ // Re-adding under the same key cancels a still-running animation when the user+ // clicks another suggestion; the setQuery listener cancels it when the user+ // types over it.+ cache.disposables.add(() => {+ let timer: ReturnType<typeof setTimeout> | undefined+ const typeQuery = (text: string): void => {+ // Remember what the animation wrote, so the setQuery listener can tell+ // an animation tick from the user typing over it+ cache.suggestionTypingText = text+ actions.setQuery(text)+ }+ const finish = (): void => {+ if (fillInHint) {+ // A fill-in prompt is a prefix: leave it in the input with the hint+ // cue and let the user complete it instead of submitting.+ typeQuery(`${content} `)+ actions.setFillInHint(fillInHint)+ document.querySelector<HTMLElement>('#homepage-input')?.focus()+ } else {+ actions.submitQuery('ai')+ }+ cache.disposables.dispose('suggestionTyping')+ }+ const typeTo = (i: number): void => {+ typeQuery(content.slice(0, i))+ timer =+ i >= content.length+ ? setTimeout(finish, 250)+ : setTimeout(+ () => typeTo(i + 1),+ nextTypingDelayMs(content[i - 1] ?? '', content[i]) * TYPING_SPEEDUP_FACTOR+ )+ }+ typeTo(1)+ return () => {+ cache.suggestionTypingText = null+ if (timer) {+ clearTimeout(timer)+ }+ }+ }, 'suggestionTyping')+ } else if (item.href) {+ router.actions.push(item.href)+ }+ },setQuery: ({ query }) => {+ // A query that isn't what the typewriter just wrote means the user typed or cleared+ // the input mid-animation: their input wins, so stop the animation and its submit+ if (cache.suggestionTypingText != null && query !== cache.suggestionTypingText) {+ cache.disposables.dispose('suggestionTyping')+ }if (values.mode === 'idle') {actions.setChatDraftForTab(HOMEPAGE_IDLE_DRAFT_KEY, query)}},returnToIdle: () => {+ cache.disposables.dispose('suggestionTyping')actions.setChatDraftForTab(HOMEPAGE_IDLE_DRAFT_KEY, '')},submitQuery: async ({ mode }, breakpoint) => {+ // A manual submit mid-animation sends what's in the input; the typewriter must not+ // keep typing into the started thread (no-op when the animation already finished)+ cache.disposables.dispose('suggestionTyping')+// Once the draft has been submitted, it's no longer a draft — clear it so we don't// resurrect it as "unsent input" the next time the homepage is mounted.actions.setChatDraftForTab(HOMEPAGE_IDLE_DRAFT_KEY, '')diff --git a/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.ts b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.tsnew file mode 100644index 000000000000..7e3f3ec77565--- /dev/null+++ b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.ts@@ -0,0 +1,54 @@+import { FileSystemEntry } from '~/queries/schema/schema-general'+import { Conversation, ConversationStatus, ConversationType } from '~/types'++import { SUGGESTIONS_LIMIT, buildSuggestionItems } from './homepageSuggestions'++const conversation: Conversation = {+ id: 'conv-1',+ title: 'Retention dip investigation',+ type: ConversationType.Assistant,+ status: ConversationStatus.Idle,+ user: { id: 1 } as Conversation['user'],+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++describe('buildSuggestionItems', () => {+ it('orders continue, recents-derived prompts, then static fill', () => {+ const recents: FileSystemEntry[] = [+ { id: '1', path: 'Marketing dashboard', type: 'dashboard' },+ { id: '2', path: 'Signup funnel', type: 'insight/funnels' },+ // Same type as the first entry, so it must not produce a second dashboard prompt+ { id: '3', path: 'Another dashboard', type: 'dashboard' },+ // No prompt template for this type+ { id: '4', path: 'Scratch notebook', type: 'notebook' },+ ]++ const items = buildSuggestionItems(conversation, recents)++ expect(items).toHaveLength(SUGGESTIONS_LIMIT)+ expect(items[0]).toMatchObject({ kind: 'suggestion', source: 'continue', conversationId: 'conv-1' })+ expect(items[0].description).toEqual('Retention dip investigation')+ expect(items[1].source).toEqual('recent')+ expect(items[1].prompt).toContain('Marketing dashboard')+ expect(items[1].description).toEqual('Marketing dashboard')+ expect(items[2].source).toEqual('recent')+ expect(items[2].prompt).toContain('Signup funnel')+ expect(items.slice(3).every((item) => item.source === 'static')).toBe(true)+ })++ it('falls back to static prompts alone, all complete and unique', () => {+ const items = buildSuggestionItems(null, [])++ expect(items).toHaveLength(SUGGESTIONS_LIMIT)+ // A fill-in topic suggestion has no complete prompt, so every emitted item must carry one+ expect(items.every((item) => item.source === 'static' && !!item.prompt)).toBe(true)+ expect(new Set(items.map((item) => item.id)).size).toBe(items.length)+ })++ it('skips a conversation without a title', () => {+ const items = buildSuggestionItems({ ...conversation, title: null }, [])++ expect(items.every((item) => item.source === 'static')).toBe(true)+ })+})diff --git a/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.ts b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.tsnew file mode 100644index 000000000000..23ce5ebc02c5--- /dev/null+++ b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.ts@@ -0,0 +1,196 @@+import { HOMEPAGE_SUGGESTION_TOPICS, SuggestionTopic, TopicSuggestion } from 'scenes/max/suggestionTopics'++import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'+import { FileSystemEntry } from '~/queries/schema/schema-general'+import { Conversation } from '~/types'++import type { HomepageGridItem } from './aiFirstHomepageLogic'++// Matches the 4 suggestions every topic panel shows, so toggling a topic badge+// swaps 4 identical card units for 4 others and the layout never shifts.+export const SUGGESTIONS_LIMIT = 4+const RECENT_PROMPTS_LIMIT = 2++interface RecentPromptTemplate {+ title: string+ prompt: (name: string) => string+}++// Prompt templates keyed by file-system entry type. Entry types can carry a subtype+// suffix (e.g. `insight/trends`), so lookups match on the segment before `/`.+// Types without a template produce no prompt: a generic question about an arbitrary+// entity reads as filler, not as a suggestion grounded in the user's activity.+// `title` is the card headline; the entity name goes in the caption, and `prompt`+// grounds the full question with the name for the agent. Each type carries several+// templates, mixing analysis with a next step in another product; one is picked per+// entity by a stable hash so the suggestion varies across entities without flickering+// across renders.+const RECENT_PROMPT_TEMPLATES: Record<string, RecentPromptTemplate[]> = {+ dashboard: [+ { title: 'What changed this week?', prompt: (name) => `What changed in "${name}" this week?` },+ {+ title: 'Find anomalies',+ prompt: (name) => `Are there anomalies in the metrics on the "${name}" dashboard?`,+ },+ ],+ insight: [+ { title: 'Explain what this shows', prompt: (name) => `Explain what "${name}" shows` },+ { title: 'Explain recent changes', prompt: (name) => `Why did "${name}" change recently?` },+ {+ title: 'Watch the users behind it',+ prompt: (name) => `Find session recordings of the users behind "${name}"`,+ },+ ],+ experiment: [+ { title: 'How is this experiment doing?', prompt: (name) => `How is the "${name}" experiment doing?` },+ {+ title: 'Should I ship it?',+ prompt: (name) => `Has the "${name}" experiment reached significance? Should I ship it?`,+ },+ ],+ feature_flag: [+ {+ title: 'Analyze the impact of this flag',+ prompt: (name) => `Analyze how the "${name}" feature flag affects user behavior and key metrics`,+ },+ {+ title: 'Turn this flag into an experiment',+ prompt: (name) => `Create an experiment to measure the impact of the "${name}" feature flag`,+ },+ {+ title: 'Check if this flag can be removed',+ prompt: (name) => `Is the "${name}" flag fully rolled out? Check if it is safe to remove from my code`,+ },+ ],+ survey: [+ { title: 'Summarize the responses', prompt: (name) => `Summarize the responses to "${name}"` },+ {+ title: 'Find themes in the responses',+ prompt: (name) => `What are the main themes in the responses to "${name}"?`,+ },+ ],+}++// Stable per-entity template pick: varied across entities, constant across renders.+function pickTemplate(templates: RecentPromptTemplate[], entityId: string): RecentPromptTemplate {+ let hash = 0+ for (let i = 0; i < entityId.length; i++) {+ hash = (hash * 31 + entityId.charCodeAt(i)) >>> 0+ }+ return templates[hash % templates.length]+}++function entryName(entry: FileSystemEntry): string | null {+ const name = splitPath(entry.path).pop()+ return name ? unescapePath(name) : null+}++// A topic without a product icon (e.g. Learn) sets a placeholder iconType plus an explicit+// icon element; prefer the element so the card doesn't render the dashed placeholder circle.+function suggestionVisual(+ topic: SuggestionTopic,+ suggestion: TopicSuggestion+): Pick<HomepageGridItem, 'icon' | 'itemType'> {+ if (!suggestion.iconType && topic.icon) {+ return { icon: topic.icon, itemType: null }+ }+ return { itemType: suggestion.iconType ?? topic.iconType }+}++/**+ * Composes the homepage "Suggestions" column: continue the last conversation, then prompts+ * inferred from recently visited items, then static topic prompts as fill. The static+ * fill guarantees the column is never empty once its sources have loaded.+ */+export function buildSuggestionItems(+ lastConversation: Conversation | null,+ recentItems: FileSystemEntry[]+): HomepageGridItem[] {+ const items: HomepageGridItem[] = []++ if (lastConversation?.title) {+ items.push({+ id: `suggestion-continue-${lastConversation.id}`,+ label: 'Continue your last conversation',+ description: lastConversation.title,+ kind: 'suggestion',+ source: 'continue',+ conversationId: lastConversation.id,+ })+ }++ // One prompt per entity type, so two recently viewed dashboards don't produce two+ // near-identical questions.+ const usedTypePrefixes = new Set<string>()+ for (const entry of recentItems) {+ if (usedTypePrefixes.size >= RECENT_PROMPTS_LIMIT) {+ break+ }+ const typePrefix = (entry.type ?? '').split('/')[0]+ const templates = RECENT_PROMPT_TEMPLATES[typePrefix]+ const name = entryName(entry)+ if (!templates || !name || usedTypePrefixes.has(typePrefix)) {+ continue+ }+ usedTypePrefixes.add(typePrefix)+ const template = pickTemplate(templates, entry.id)+ items.push({+ id: `suggestion-recent-${entry.id}`,+ label: template.title,+ description: name,+ kind: 'suggestion',+ source: 'recent',+ prompt: template.prompt(name),+ itemType: entry.type ?? null,+ })+ }++ // Fill with static prompts, round-robin across topics so the fill covers different+ // products instead of exhausting one topic's list first. Fill-in suggestions+ // (`requiresUserInput`) are prefixes waiting for user text, so submitting one directly+ // would send an incomplete prompt: skip them.+ const maxDepth = Math.max(...HOMEPAGE_SUGGESTION_TOPICS.map((topic) => topic.suggestions.length))+ for (let depth = 0; depth < maxDepth && items.length < SUGGESTIONS_LIMIT; depth++) {+ for (const topic of HOMEPAGE_SUGGESTION_TOPICS) {+ if (items.length >= SUGGESTIONS_LIMIT) {+ break+ }+ const suggestion = topic.suggestions[depth]+ if (!suggestion || suggestion.requiresUserInput || suggestion.hint) {+ continue+ }+ items.push({+ id: `suggestion-static-${topic.key}-${depth}`,+ // Docs-style suggestions carry only `content`, so fall back to it as the headline+ label: suggestion.title ?? suggestion.content,+ description: suggestion.description,+ kind: 'suggestion',+ source: 'static',+ prompt: suggestion.content,+ ...suggestionVisual(topic, suggestion),+ })+ }+ }++ return items.slice(0, SUGGESTIONS_LIMIT)+}++/**+ * Maps a topic's suggestions to grid items, so the badge-filtered view renders through+ * the exact same list component as the default suggestions.+ */+export function topicSuggestionItems(topic: SuggestionTopic): HomepageGridItem[] {+ // Some topics carry more suggestions than the homepage shows (e.g. Learn has 5); cap at+ // the shared limit so toggling a topic badge never changes the list height.+ return topic.suggestions.slice(0, SUGGESTIONS_LIMIT).map((suggestion, index) => ({+ id: `suggestion-topic-${topic.key}-${index}`,+ label: suggestion.title ?? suggestion.content,+ description: suggestion.description,+ kind: 'suggestion',+ source: 'topic',+ prompt: suggestion.content,+ ...suggestionVisual(topic, suggestion),+ // Fill-in suggestions type a prefix and wait for the user to complete it+ fillInHint: suggestion.requiresUserInput ? (suggestion.hint ?? 'the details') : undefined,+ }))+}