: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
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import type { DashboardBasicApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
import { navigateToHref } from 'lib/utils/navigateToHref'
import { 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 { userLogic } from 'scenes/userLogic'
import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'
import { pinnedDashboardsModel } from '~/models/pinnedDashboardsModel'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { sceneLogic } from '~/scenes/sceneLogic'
import { emptySceneParams } from '~/scenes/scenes'
import { Scene, SceneTab } from '~/scenes/sceneTypes'
import { SidePanelTab } from '~/types'
import { tasksList } from 'products/tasks/frontend/generated/api'
import {
TaskListItemApi,
TaskOriginProductEnumApi,
TasksListOrdering,
} from 'products/tasks/frontend/generated/api.schemas'
import type { ConversationDetail, TeamPublicType, TeamType, UserType } from '../../../types'
import { HOMEPAGE_IDLE_DRAFT_KEY, HOMEPAGE_TAB_ID } from './constants'
import { ResumableChat, buildSuggestionItems, pickLastChat, topicSuggestionItems } from './homepageSuggestions'
export type HomepageMode = 'idle' | 'search' | 'ai'
export type AnimationPhase = 'idle' | 'moving' | 'separator' | 'content'
export interface LayoutState {
mode: HomepageMode
animationPhase: AnimationPhase
}
export type HomepageGridItemKind = 'dashboard' | 'recent' | 'suggestion'
export interface HomepageGridItem {
id: string
label: string
/** Caption under the label on suggestion cards, naming what the suggestion is about. */
description?: string
icon?: React.ReactNode
href?: string
kind: HomepageGridItemKind
itemType?: 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
/** Sandbox task opened when a continue-conversation suggestion is activated. */
taskId?: 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'
}
// 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.7
const PREVIOUS_HOMEPAGE_KEY = 'ai-first-previous-homepage'
function getStorageKey(): string {
const teamId = teamLogic.findMounted()?.values.currentTeamId ?? 'null'
return `${PREVIOUS_HOMEPAGE_KEY}-${teamId}`
}
function loadPreviousHomepage(): SceneTab | null {
try {
const stored = localStorage.getItem(getStorageKey())
return stored ? JSON.parse(stored) : null
} catch {
return null
}
}
function savePreviousHomepage(tab: SceneTab | null): void {
const key = getStorageKey()
if (tab) {
localStorage.setItem(key, JSON.stringify(tab))
} else {
localStorage.removeItem(key)
}
}
// 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 {
conversationHistory: ConversationDetail[] // maxGlobalLogic
conversationHistoryLoading: boolean // maxGlobalLogic
effectivePhaiView: PhaiViewMode // maxGlobalLogic
isPhaiSandboxFlagOn: boolean // maxGlobalLogic
conversationId: string | null // maxLogic
threadLogicKey: string // maxLogic
dashboardsLoading: boolean // pinnedDashboardsModel
pinnedDashboards: DashboardBasicApi[] // pinnedDashboardsModel
cachedRecents: FileSystemEntry[] // recentItemsModel
recentsHasLoaded: boolean // recentItemsModel
homepage: SceneTab | null // sceneLogic
chatDraftFor: (tabId: string | undefined) => string // tabUiStateLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
animationPhase: AnimationPhase
displayedSuggestionItems: HomepageGridItem[]
fillInHint: string | null
gridItems: HomepageGridItem[]
lastChat: ResumableChat | null
latestWebTask: TaskListItemApi | null
latestWebTaskLoading: boolean
layoutState: LayoutState
mode: HomepageMode
pinnedDashboardItems: HomepageGridItem[]
previousHomepage: SceneTab | null
query: string
recentItems: FileSystemEntry[]
recentItemsLoading: boolean
selectedTopic: string | null
suggestionItems: HomepageGridItem[]
suggestionItemsLoading: boolean
threadStarted: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiFirstHomepageLogicActions {
openConversation: (conversationId: string) => {
conversationId: string
} // maxLogic
setQuestion: (question: string) => {
question: string
} // maxLogic
startNewConversation: () => {
value: true
} // maxLogic
setHomepage: (
tab: SceneTab | null,
homepageSource?: 'dashboards list' | undefined
) => {
homepageSource: 'dashboards list' | undefined
tab: SceneTab | null
} // sceneLogic
setChatDraftForTab: (
tabId: string | undefined,
draft: string
) => {
draft: string
tabId: string
} // tabUiStateLogic
activateGridItem: (item: HomepageGridItem) => {
item: HomepageGridItem
}
enterAiMode: (trigger: string) => {
trigger: string
}
gridItemClicked: (item: HomepageGridItem) => {
item: HomepageGridItem
}
loadLatestWebTask: (_: void) => void
loadLatestWebTaskFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadLatestWebTaskSuccess: (
latestWebTask: TaskListItemApi | null,
payload?: void
) => {
latestWebTask: TaskListItemApi | null
payload?: void
}
returnToIdle: () => {
value: true
}
revertToPreviousHomepage: () => {
value: true
}
setAnimationPhase: (phase: AnimationPhase) => {
phase: AnimationPhase
}
setFillInHint: (hint: string | null) => {
hint: string | null
}
setPreviousHomepage: (tab: SceneTab | null) => {
tab: SceneTab | null
}
setQuery: (query: string) => {
query: string
}
setSelectedTopic: (key: string | null) => {
key: string | null
}
submitQuery: (mode: 'ai' | 'search') => {
mode: 'ai' | 'search'
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiFirstHomepageLogicMeta {
__keaTypeGenInternalSelectorTypes: {
recentItems: (
cachedRecents: FileSystemEntry[],
pinnedDashboardItems: HomepageGridItem[],
dashboardsLoading: boolean
) => FileSystemEntry[]
recentItemsLoading: (recentsHasLoaded: boolean) => boolean
lastChat: (
conversationHistory: ConversationDetail[],
latestWebTask: TaskListItemApi | null
) => ResumableChat | null
suggestionItems: (lastChat: ResumableChat | null, recentItems: FileSystemEntry[]) => HomepageGridItem[]
displayedSuggestionItems: (
selectedTopic: string | null,
suggestionItems: HomepageGridItem[]
) => HomepageGridItem[]
suggestionItemsLoading: (
conversationHistoryLoading: boolean,
conversationHistory: ConversationDetail[],
latestWebTaskLoading: boolean,
recentItemsLoading: boolean
) => boolean
mode: (layoutState: LayoutState) => HomepageMode
animationPhase: (layoutState: LayoutState) => AnimationPhase
pinnedDashboardItems: (pinnedDashboards: DashboardBasicApi[]) => HomepageGridItem[]
gridItems: (
pinnedDashboardItems: HomepageGridItem[],
recentItems: FileSystemEntry[],
suggestionItems: HomepageGridItem[]
) => HomepageGridItem[]
}
}
export type aiFirstHomepageLogicType = MakeLogicType<
aiFirstHomepageLogicValues,
aiFirstHomepageLogicActions,
Record<string, any>,
aiFirstHomepageLogicMeta
>
export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([
path(['scenes', 'project-homepage', 'ai-first', 'aiFirstHomepageLogic']),
connect(() => ({
values: [
maxLogic({ panelId: HOMEPAGE_TAB_ID }),
['threadLogicKey', 'conversationId'],
teamLogic,
['currentTeam', 'currentTeamId'],
userLogic,
['user'],
sceneLogic,
['homepage'],
pinnedDashboardsModel,
['pinnedDashboards', 'pinnedDashboardsLoading as dashboardsLoading'],
recentItemsModel,
['recents as cachedRecents', 'recentsHasLoaded'],
tabUiStateLogic,
['chatDraftFor'],
maxGlobalLogic,
['effectivePhaiView', 'isPhaiSandboxFlagOn', 'conversationHistory', 'conversationHistoryLoading'],
],
actions: [
maxLogic({ panelId: HOMEPAGE_TAB_ID }),
['openConversation', 'startNewConversation', 'setQuestion'],
sceneLogic,
['setHomepage'],
tabUiStateLogic,
['setChatDraftForTab'],
],
})),
actions({
submitQuery: (mode: 'search' | 'ai') => ({ mode }),
enterAiMode: (trigger: string) => ({ trigger }),
setQuery: (query: string) => ({ query }),
setAnimationPhase: (phase: AnimationPhase) => ({ phase }),
returnToIdle: true,
setPreviousHomepage: (tab: SceneTab | null) => ({ tab }),
revertToPreviousHomepage: true,
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 }),
}),
loaders(({ values }) => ({
latestWebTask: [
null as TaskListItemApi | null,
{
loadLatestWebTask: async (_: void, breakpoint) => {
// Without the `created_by` pin the server answers with tasks other people shared.
if (!values.currentTeamId || !values.user?.id) {
return null
}
// `posthog_ai` keeps only chats started in the web UI, not Slack or desktop tasks.
const response = await tasksList(String(values.currentTeamId), {
origin_product: TaskOriginProductEnumApi.PosthogAi,
created_by: values.user.id,
ordering: TasksListOrdering.LastActivityAt,
limit: 1,
})
breakpoint()
return response.results[0] ?? null
},
},
],
})),
reducers({
// Single reducer for mode + phase so transitions are atomic
layoutState: [
{ mode: 'idle', animationPhase: 'idle' } as LayoutState,
{
submitQuery: (state, { mode }): LayoutState => {
// Re-submit in the same mode with content already visible — no-op
if (state.mode === mode && state.animationPhase === 'content') {
return state
}
return { mode, animationPhase: 'moving' }
},
enterAiMode: (state): LayoutState => {
if (state.mode === 'ai') {
return state
}
return { mode: 'ai', animationPhase: 'moving' }
},
setAnimationPhase: (state, { phase }): LayoutState => ({
...state,
animationPhase: phase,
}),
returnToIdle: (): LayoutState => ({ mode: 'idle', animationPhase: 'idle' }),
},
],
query: [
'',
{
setQuery: (_, { query }) => query,
returnToIdle: () => '',
},
],
threadStarted: [
false,
{
submitQuery: (_, { mode }) => mode === 'ai',
returnToIdle: () => false,
},
],
previousHomepage: [
null as SceneTab | null,
{
setPreviousHomepage: (_, { tab }) => tab,
},
],
selectedTopic: [
null as string | null,
{
setSelectedTopic: (_, { key }) => key,
submitQuery: () => null,
returnToIdle: () => null,
},
],
fillInHint: [
null as string | null,
{
setFillInHint: (_, { hint }) => hint,
setSelectedTopic: () => null,
submitQuery: () => null,
returnToIdle: () => null,
},
],
}),
selectors({
recentItems: [
(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],
lastChat: [
(s) => [s.conversationHistory, s.latestWebTask],
(conversationHistory: ConversationDetail[], latestWebTask: TaskListItemApi | null): ResumableChat | null =>
pickLastChat(conversationHistory, latestWebTask),
],
suggestionItems: [
(s) => [s.lastChat, s.recentItems],
(lastChat: ResumableChat | null, recentItems: FileSystemEntry[]): HomepageGridItem[] =>
buildSuggestionItems(lastChat, 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
},
],
// 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.latestWebTaskLoading, s.recentItemsLoading],
(
conversationHistoryLoading: boolean,
conversationHistory: ConversationDetail[],
latestWebTaskLoading: boolean,
recentItemsLoading: boolean
): boolean =>
(conversationHistoryLoading && conversationHistory.length === 0) ||
latestWebTaskLoading ||
recentItemsLoading,
],
mode: [(s) => [s.layoutState], (layoutState: LayoutState): HomepageMode => layoutState.mode],
animationPhase: [
(s) => [s.layoutState],
(layoutState: LayoutState): AnimationPhase => layoutState.animationPhase,
],
pinnedDashboardItems: [
(s) => [s.pinnedDashboards],
(pinnedDashboards: DashboardBasicApi[]): HomepageGridItem[] => {
const toGridItem = (d: DashboardBasicApi): 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)
}
// Reserve the final row for the full list when the capped response fills the rail.
const shown = pinnedDashboards.slice(0, PINNED_DASHBOARDS_LIMIT - 1)
return [
...shown.map(toGridItem),
{
id: 'dashboard-overflow',
label: 'View all dashboards',
href: urls.dashboards(),
kind: 'dashboard',
},
]
},
],
gridItems: [
(s) => [s.pinnedDashboardItems, s.recentItems, s.suggestionItems],
(
pinnedDashboardItems: HomepageGridItem[],
recentItems: FileSystemEntry[],
suggestionItems: HomepageGridItem[]
): HomepageGridItem[] => {
const toGridItem = (entry: FileSystemEntry): HomepageGridItem => {
const name = splitPath(entry.path).pop()
return {
id: `recent-${entry.id}`,
label: name ? unescapePath(name) : entry.path,
href: entry.href || '#',
kind: 'recent',
itemType: entry.type ?? null,
}
}
return [
...pinnedDashboardItems,
...recentItems.map((e: FileSystemEntry) => toGridItem(e)),
...suggestionItems,
]
},
],
}),
listeners(({ actions, values, cache }) => ({
gridItemClicked: ({ item }) => {
reportGridItemClicked(item)
},
activateGridItem: ({ item }) => {
reportGridItemClicked(item)
if (item.taskId) {
// A sandbox task only renders on the new PostHog AI surface, whatever view is chosen.
router.actions.push(urls.aiTask(item.taskId))
} else 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) {
navigateToHref(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, '')
// The homepage chat only drives the legacy runtime, so on the new PostHog AI surface a prompt
// submitted here would start a LangGraph conversation that surface never shows. Hand it to
// /ai instead, which seeds its composer from `ask` and submits it. An AI submit with no
// prompt is a chat being restored from `?mode=ai&chat=…` — that still opens here.
if (mode === 'ai' && values.effectivePhaiView === 'new' && values.query.trim()) {
router.actions.push(urls.ai(undefined, values.query))
// Undo the mode flip the reducers just made, so the legacy homepage thread never mounts
// and fires a second, competing send while the route change lands.
actions.returnToIdle()
return
}
if (mode === 'ai' && !values.conversationId) {
actions.startNewConversation()
}
// Reducer kept phase as 'content' for same-mode re-submits — nothing to animate
if (values.animationPhase === 'content') {
return
}
await breakpoint(300)
actions.setAnimationPhase('separator')
await breakpoint(200)
actions.setAnimationPhase('content')
},
enterAiMode: async ({ trigger }, breakpoint) => {
// Animate into AI mode without starting a conversation
await breakpoint(300)
actions.setAnimationPhase('separator')
await breakpoint(200)
actions.setAnimationPhase('content')
// Set the trigger character after animation so the slash menu doesn't appear mid-transition
if (trigger) {
actions.setQuestion(trigger)
}
},
setPreviousHomepage: ({ tab }) => {
savePreviousHomepage(tab)
},
revertToPreviousHomepage: () => {
const prev = values.previousHomepage
if (prev) {
actions.setHomepage(prev)
actions.setPreviousHomepage(null)
router.actions.push(prev.pathname || '/', prev.search || '', prev.hash || '')
}
},
})),
actionToUrl(({ values }) => ({
submitQuery: ({ mode: submittedMode }) => {
const { mode, query } = values
// On the new PostHog AI surface the homepage never owns an AI route: a submit with a prompt
// is navigated to /ai by the listener (which reads the query before clearing it), and one
// without is a restore that arrived on this URL already. Keyed off the submitted mode rather
// than `values.mode`, which the listener may already have reset.
if (submittedMode === 'ai' && values.effectivePhaiView === 'new') {
return undefined
}
if (mode === 'ai') {
return [
urls.projectHomepage(),
{ mode, chat: values.threadLogicKey || undefined },
undefined,
{ replace: false },
]
}
return [urls.projectHomepage(), { mode, q: query || undefined }, undefined, { replace: false }]
},
enterAiMode: () => {
return [urls.projectHomepage(), { mode: 'ai' }, undefined, { replace: false }]
},
})),
urlToAction(({ actions, values }) => ({
[urls.projectHomepage()]: (_, searchParams, hashParams) => {
// A `#panel=max:<prompt>` link (e.g. app.posthog.com/#panel=max:...) means "open PostHog
// AI prefilled". Here the homepage already IS the full-scene PostHog AI, so consume the
// prompt into this scene instead of stacking a redundant Max side panel on top of it.
const panelHash = typeof hashParams.panel === 'string' ? hashParams.panel : undefined
if (panelHash) {
const [panel, ...rest] = panelHash.split(':')
if (panel === SidePanelTab.Max) {
const { question } = parseCommandString(rest.join(':'))
if (question) {
actions.setQuestion(question)
}
// enterAiMode rewrites the URL to ?mode=ai (dropping the hash), and closeSidePanel
// clears the panel hash too — so both undo the side panel that already opened and
// stop it replaying on refresh.
actions.enterAiMode('')
sidePanelStateLogic.actions.closeSidePanel(SidePanelTab.Max)
return
}
}
const urlMode = (searchParams.mode as HomepageMode) || 'idle'
const urlQuery = searchParams.q != null ? String(searchParams.q) : ''
const urlChat = (searchParams.chat as string) || ''
if (urlMode === 'idle' && values.mode !== 'idle') {
actions.returnToIdle()
} else if (urlMode === 'ai' && values.mode !== 'ai') {
if (urlChat) {
actions.openConversation(urlChat)
actions.submitQuery('ai')
} else {
actions.enterAiMode('')
}
} else if (urlMode === 'search' && values.mode !== 'search') {
actions.setQuery(urlQuery)
actions.submitQuery('search')
} else if (urlMode === 'search' && urlQuery !== values.query) {
actions.setQuery(urlQuery)
} else if (urlMode === 'idle' && !values.query) {
// Restore unsent input typed before the user left the homepage.
// urlToAction also runs on first mount, so this handles initial restore too.
const persistedDraft = values.chatDraftFor(HOMEPAGE_IDLE_DRAFT_KEY)
if (persistedDraft) {
actions.setQuery(persistedDraft)
}
}
},
})),
afterMount(({ actions, values }) => {
// Sandbox chats exist only for users with the flag, so everyone else skips the request.
if (values.isPhaiSandboxFlagOn) {
actions.loadLatestWebTask()
}
// Capture the previous homepage on first visit so we can revert later
const stored = loadPreviousHomepage()
if (stored) {
actions.setPreviousHomepage(stored)
} else {
// First time on AI-first homepage — snapshot what the user would have seen before
const currentHomepage = values.homepage
if (currentHomepage) {
// User had a custom homepage set
actions.setPreviousHomepage(currentHomepage)
} else {
// No custom homepage — they would have seen the primary dashboard or search
const dashboardId = values.currentTeam?.primary_dashboard
if (dashboardId) {
actions.setPreviousHomepage({
id: `homepage-dashboard-${dashboardId}`,
pathname: urls.dashboard(dashboardId),
search: '',
hash: '',
title: 'Default dashboard',
iconType: 'dashboard',
sceneId: Scene.Dashboard,
sceneKey: `dashboard-${dashboardId}`,
sceneParams: emptySceneParams,
})
}
// If no dashboard either, previousHomepage stays null — no revert button shown
}
}
const { searchParams } = router.values
const urlMode = (searchParams.mode as HomepageMode) || 'idle'
const urlQuery = searchParams.q != null ? String(searchParams.q) : ''
const urlChat = (searchParams.chat as string) || ''
if (urlMode === 'ai') {
if (urlChat) {
actions.openConversation(urlChat)
actions.submitQuery('ai')
} else {
actions.enterAiMode('')
}
} else if (urlMode === 'search' && urlQuery) {
actions.setQuery(urlQuery)
actions.submitQuery('search')
}
// Idle-mode draft restore happens in urlToAction (also fires on mount).
}),
])