: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
fix(max): continue the newest web chat from the homepage (#106017)
posthog[bot]a4d4eac76eb8
diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.tsindex 93a95f147c23..4bd3a06c8b6b 100644--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.test.ts@@ -5,6 +5,7 @@ import type { DashboardBasicApi } from '@posthog/products-dashboards/frontend/geimport { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { maxLogic } from 'scenes/max/maxLogic'import { urls } from 'scenes/urls'@@ -173,4 +174,63 @@ describe('aiFirstHomepageLogic', () => {await expectLogic(logic).delay(1).toMatchValues({ mode: 'ai' })expect(maxLogic({ panelId: HOMEPAGE_TAB_ID }).values.conversationId).toEqual('conv-1')})++ it('suggests continuing the newest web sandbox task when it is newer than the last conversation', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/conversations/': {+ results: [+ {+ id: 'conv-1',+ title: 'Retention dip investigation',+ type: 'assistant',+ status: 'idle',+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ },+ ],+ },+ '/api/projects/:team_id/tasks/': {+ results: [+ {+ id: 'task-1',+ slug: 'TASK-1',+ title: 'Find semantic layer users',+ origin_product: 'posthog_ai',+ last_activity_at: '2026-02-01T00:00:00Z',+ },+ ],+ },+ },+ })+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PHAI_SANDBOX_MODE], {+ [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,+ })+ logic.unmount()+ logic = aiFirstHomepageLogic()+ logic.mount()+ maxGlobalLogic.actions.loadConversationHistory()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ latestWebTaskLoading: false })+ await expectLogic(maxGlobalLogic).toFinishAllListeners()++ expect(logic.values.suggestionItems[0]).toMatchObject({ source: 'continue', taskId: 'task-1' })+ })++ it('activating a continue suggestion for a sandbox task opens that task on /ai', async () => {+ router.actions.push(urls.projectHomepage())++ logic.actions.activateGridItem({+ id: 'suggestion-continue-task-1',+ label: 'Continue your last conversation',+ kind: 'suggestion',+ source: 'continue',+ taskId: 'task-1',+ })+ await expectLogic(logic).delay(1)++ expect(router.values.location.pathname).toEqual('/project/997/ai')+ expect(router.values.searchParams.task).toEqual('task-1')+ expect(logic.values.mode).toEqual('idle')+ })})diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.tsindex 4e10ce6edbac..dfb0369e6441 100644--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts@@ -1,4 +1,5 @@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'@@ -13,6 +14,7 @@ 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 { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'@@ -22,11 +24,18 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'import { sceneLogic } from '~/scenes/sceneLogic'import { emptySceneParams } from '~/scenes/scenes'import { Scene, SceneTab } from '~/scenes/sceneTypes'-import { Conversation, ConversationType, SidePanelTab } from '~/types'+import { SidePanelTab } from '~/types'-import type { ConversationDetail, TeamPublicType, TeamType } 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 { buildSuggestionItems, topicSuggestionItems } from './homepageSuggestions'+import { ResumableChat, buildSuggestionItems, pickLastChat, topicSuggestionItems } from './homepageSuggestions'export type HomepageMode = 'idle' | 'search' | 'ai'export type AnimationPhase = 'idle' | 'moving' | 'separator' | 'content'@@ -51,6 +60,8 @@ export interface HomepageGridItem {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. */@@ -106,6 +117,7 @@ export interface aiFirstHomepageLogicValues {conversationHistory: ConversationDetail[] // maxGlobalLogicconversationHistoryLoading: boolean // maxGlobalLogiceffectivePhaiView: PhaiViewMode // maxGlobalLogic+ isPhaiSandboxFlagOn: boolean // maxGlobalLogicconversationId: string | null // maxLogicthreadLogicKey: string // maxLogicdashboardsLoading: boolean // pinnedDashboardsModel@@ -115,11 +127,15 @@ export interface aiFirstHomepageLogicValues {homepage: SceneTab | null // sceneLogicchatDraftFor: (tabId: string | undefined) => string // tabUiStateLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogic+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogicanimationPhase: AnimationPhasedisplayedSuggestionItems: HomepageGridItem[]fillInHint: string | nullgridItems: HomepageGridItem[]- lastConversation: Conversation | null+ lastChat: ResumableChat | null+ latestWebTask: TaskListItemApi | null+ latestWebTaskLoading: booleanlayoutState: LayoutStatemode: HomepageModepinnedDashboardItems: HomepageGridItem[]@@ -166,6 +182,21 @@ export interface aiFirstHomepageLogicActions {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}@@ -204,8 +235,11 @@ export interface aiFirstHomepageLogicMeta {dashboardsLoading: boolean) => FileSystemEntry[]recentItemsLoading: (recentsHasLoaded: boolean) => boolean- lastConversation: (conversationHistory: ConversationDetail[]) => Conversation | null- suggestionItems: (lastConversation: Conversation | null, recentItems: FileSystemEntry[]) => HomepageGridItem[]+ lastChat: (+ conversationHistory: ConversationDetail[],+ latestWebTask: TaskListItemApi | null+ ) => ResumableChat | null+ suggestionItems: (lastChat: ResumableChat | null, recentItems: FileSystemEntry[]) => HomepageGridItem[]displayedSuggestionItems: (selectedTopic: string | null,suggestionItems: HomepageGridItem[]@@ -213,6 +247,7 @@ export interface aiFirstHomepageLogicMeta {suggestionItemsLoading: (conversationHistoryLoading: boolean,conversationHistory: ConversationDetail[],+ latestWebTaskLoading: boolean,recentItemsLoading: boolean) => booleanmode: (layoutState: LayoutState) => HomepageMode@@ -241,7 +276,9 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([maxLogic({ panelId: HOMEPAGE_TAB_ID }),['threadLogicKey', 'conversationId'],teamLogic,- ['currentTeam'],+ ['currentTeam', 'currentTeamId'],+ userLogic,+ ['user'],sceneLogic,['homepage'],pinnedDashboardsModel,@@ -251,7 +288,7 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([tabUiStateLogic,['chatDraftFor'],maxGlobalLogic,- ['effectivePhaiView', 'conversationHistory', 'conversationHistoryLoading'],+ ['effectivePhaiView', 'isPhaiSandboxFlagOn', 'conversationHistory', 'conversationHistoryLoading'],],actions: [maxLogic({ panelId: HOMEPAGE_TAB_ID }),@@ -283,6 +320,29 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([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 atomiclayoutState: [@@ -362,19 +422,15 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([},],recentItemsLoading: [(s) => [s.recentsHasLoaded], (recentsHasLoaded: boolean): boolean => !recentsHasLoaded],- 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,+ lastChat: [+ (s) => [s.conversationHistory, s.latestWebTask],+ (conversationHistory: ConversationDetail[], latestWebTask: TaskListItemApi | null): ResumableChat | null =>+ pickLastChat(conversationHistory, latestWebTask),],suggestionItems: [- (s) => [s.lastConversation, s.recentItems],- (lastConversation: Conversation | null, recentItems: FileSystemEntry[]): HomepageGridItem[] =>- buildSuggestionItems(lastConversation, recentItems),+ (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.@@ -389,12 +445,16 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([// 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],+ (s) => [s.conversationHistoryLoading, s.conversationHistory, s.latestWebTaskLoading, s.recentItemsLoading],(conversationHistoryLoading: boolean,conversationHistory: ConversationDetail[],+ latestWebTaskLoading: boolean,recentItemsLoading: boolean- ): boolean => (conversationHistoryLoading && conversationHistory.length === 0) || recentItemsLoading,+ ): boolean =>+ (conversationHistoryLoading && conversationHistory.length === 0) ||+ latestWebTaskLoading ||+ recentItemsLoading,],mode: [(s) => [s.layoutState], (layoutState: LayoutState): HomepageMode => layoutState.mode],animationPhase: [@@ -459,7 +519,10 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([},activateGridItem: ({ item }) => {reportGridItemClicked(item)- if (item.conversationId) {+ 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') {@@ -679,6 +742,11 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([})),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 laterconst stored = loadPreviousHomepage()if (stored) {diff --git a/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.ts b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.tsindex 7e3f3ec77565..57d0d6c7f446 100644--- a/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.ts+++ b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.test.ts@@ -1,7 +1,9 @@import { FileSystemEntry } from '~/queries/schema/schema-general'import { Conversation, ConversationStatus, ConversationType } from '~/types'-import { SUGGESTIONS_LIMIT, buildSuggestionItems } from './homepageSuggestions'+import type { TaskListItemApi } from 'products/tasks/frontend/generated/api.schemas'++import { ResumableChat, SUGGESTIONS_LIMIT, buildSuggestionItems, pickLastChat } from './homepageSuggestions'const conversation: Conversation = {id: 'conv-1',@@ -13,7 +15,34 @@ const conversation: Conversation = {updated_at: '2026-01-01T00:00:00Z',}-describe('buildSuggestionItems', () => {+const webTask = {+ id: 'task-1',+ slug: 'TASK-1',+ title: 'Find semantic layer users',+ origin_product: 'posthog_ai',+ updated_at: '2025-12-01T00:00:00Z',+ last_activity_at: '2026-02-01T00:00:00Z',+} as TaskListItemApi++describe('homepageSuggestions', () => {+ it.each<[string, Conversation[], TaskListItemApi | null, Pick<ResumableChat, 'kind' | 'id'> | null]>([+ // The task row's `updated_at` predates the conversation, so only `last_activity_at` shows it is newer+ ['a task active after the conversation', [conversation], webTask, { kind: 'task', id: 'task-1' }],+ [+ 'a conversation updated after the task',+ [{ ...conversation, updated_at: '2026-03-01T00:00:00Z' }],+ webTask,+ { kind: 'conversation', id: 'conv-1' },+ ],+ ['only a task', [], webTask, { kind: 'task', id: 'task-1' }],+ ['a conversation without a title', [{ ...conversation, title: null }], null, null],+ ['a tool-call conversation', [{ ...conversation, type: ConversationType.ToolCall }], null, null],+ ])('picks the last chat from %s', (_case, conversationHistory, latestWebTask, expected) => {+ const lastChat = pickLastChat(conversationHistory, latestWebTask)++ expect(lastChat === null ? null : { kind: lastChat.kind, id: lastChat.id }).toEqual(expected)+ })+it('orders continue, recents-derived prompts, then static fill', () => {const recents: FileSystemEntry[] = [{ id: '1', path: 'Marketing dashboard', type: 'dashboard' },@@ -24,7 +53,10 @@ describe('buildSuggestionItems', () => {{ id: '4', path: 'Scratch notebook', type: 'notebook' },]- const items = buildSuggestionItems(conversation, recents)+ const items = buildSuggestionItems(+ { kind: 'conversation', id: 'conv-1', title: 'Retention dip investigation' },+ recents+ )expect(items).toHaveLength(SUGGESTIONS_LIMIT)expect(items[0]).toMatchObject({ kind: 'suggestion', source: 'continue', conversationId: 'conv-1' })@@ -45,10 +77,4 @@ describe('buildSuggestionItems', () => {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.tsindex 23ce5ebc02c5..7f73b65a0ea4 100644--- a/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.ts+++ b/frontend/src/scenes/project-homepage/ai-first/homepageSuggestions.ts@@ -2,7 +2,9 @@ import { HOMEPAGE_SUGGESTION_TOPICS, SuggestionTopic, TopicSuggestion } from 'scimport { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'import { FileSystemEntry } from '~/queries/schema/schema-general'-import { Conversation } from '~/types'+import { Conversation, ConversationType } from '~/types'++import type { TaskListItemApi } from 'products/tasks/frontend/generated/api.schemas'import type { HomepageGridItem } from './aiFirstHomepageLogic'@@ -97,25 +99,60 @@ function suggestionVisual(return { itemType: suggestion.iconType ?? topic.iconType }}+/** A chat the user can resume: a legacy conversation, or a sandbox task started in the web UI. */+export interface ResumableChat {+ kind: 'conversation' | 'task'+ id: string+ title: string+}++/**+ * Picks the most recently active chat the user started in the PostHog AI web UI, across the+ * legacy conversations and the newest `posthog_ai` sandbox task.+ */+export function pickLastChat(+ conversationHistory: Conversation[],+ latestWebTask: TaskListItemApi | null+): ResumableChat | 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.+ const conversation = conversationHistory.find(+ (candidate) => candidate.type === ConversationType.Assistant && !!candidate.title+ )+ const conversationChat: ResumableChat | null = conversation?.title+ ? { kind: 'conversation', id: conversation.id, title: conversation.title }+ : null+ const taskChat: ResumableChat | null = latestWebTask?.title+ ? { kind: 'task', id: latestWebTask.id, title: latestWebTask.title }+ : null+ if (!conversationChat || !taskChat) {+ return conversationChat ?? taskChat+ }+ // A task row is often never edited while its run streams, so its activity time is the one to compare.+ const taskActiveAt = Date.parse(latestWebTask?.last_activity_at ?? latestWebTask?.updated_at ?? '') || 0+ const conversationActiveAt = Date.parse(conversation?.updated_at ?? '') || 0+ return taskActiveAt > conversationActiveAt ? taskChat : conversationChat+}+/*** 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,+ lastChat: ResumableChat | null,recentItems: FileSystemEntry[]): HomepageGridItem[] {const items: HomepageGridItem[] = []- if (lastConversation?.title) {+ if (lastChat) {items.push({- id: `suggestion-continue-${lastConversation.id}`,+ id: `suggestion-continue-${lastChat.id}`,label: 'Continue your last conversation',- description: lastConversation.title,+ description: lastChat.title,kind: 'suggestion',source: 'continue',- conversationId: lastConversation.id,+ ...(lastChat.kind === 'task' ? { taskId: lastChat.id } : { conversationId: lastChat.id }),})}