: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(ui): preserve per tab UI state across internal tab switches (#58224)
Big John69213f5c6430
diff --git a/frontend/src/lib/logic/tabUiStateLogic.test.ts b/frontend/src/lib/logic/tabUiStateLogic.test.tsnew file mode 100644index 000000000000..9f7d8197b611--- /dev/null+++ b/frontend/src/lib/logic/tabUiStateLogic.test.ts@@ -0,0 +1,232 @@+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'++import { dataTableLogic } from '~/queries/nodes/DataTable/dataTableLogic'+import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'+import { initKeaTests } from '~/test/init'++jest.mock('~/queries/query')++const VIZ_KEY = 'tab-ui-state-test'+const TAB_A = 'tab-a'+const TAB_B = 'tab-b'++const dataTableQuery: DataTableNode = setLatestVersionsOnQuery({+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.EventsQuery, select: ['*'] },+})++describe('tabUiStateLogic', () => {+ beforeEach(() => {+ initKeaTests()+ featureFlagLogic.mount()+ tabUiStateLogic.mount()+ })++ it('toggles expanded rows scoped by tabId + vizKey', () => {+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, VIZ_KEY, 3)+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, VIZ_KEY, 7)+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, VIZ_KEY)).toEqual([3, 7])++ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, VIZ_KEY, 3)+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, VIZ_KEY)).toEqual([7])+ })++ it('isolates expanded rows between tabs', () => {+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, VIZ_KEY, 1)+ tabUiStateLogic.actions.toggleExpandedRow(TAB_B, VIZ_KEY, 99)++ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, VIZ_KEY)).toEqual([1])+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_B, VIZ_KEY)).toEqual([99])+ })++ it('isolates expanded rows between vizKeys within the same tab', () => {+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, 'viz-1', 5)+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, 'viz-2', 9)++ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, 'viz-1')).toEqual([5])+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, 'viz-2')).toEqual([9])+ })++ it('clears all UI state for a tab', () => {+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, 'viz-1', 1)+ tabUiStateLogic.actions.toggleExpandedRow(TAB_A, 'viz-2', 2)+ tabUiStateLogic.actions.toggleExpandedRow(TAB_B, 'viz-1', 3)++ tabUiStateLogic.actions.clearTabUiState(TAB_A)++ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, 'viz-1')).toEqual([])+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, 'viz-2')).toEqual([])+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_B, 'viz-1')).toEqual([3])+ })++ it('returns empty array for unknown tab/vizKey', () => {+ expect(tabUiStateLogic.values.expandedRowsFor('unknown-tab', 'unknown-viz')).toEqual([])+ expect(tabUiStateLogic.values.expandedRowsFor(undefined, 'unknown-viz')).toEqual([])+ })++ it('survives dataTableLogic unmount and remount with the same tabId/vizKey', () => {+ // Mount, toggle a row, then unmount — simulating React tab switch.+ let logic = dataTableLogic({+ dataKey: 'dk',+ vizKey: VIZ_KEY,+ tabId: TAB_A,+ query: dataTableQuery,+ })+ logic.mount()+ logic.actions.toggleRowExpanded(4)+ expect(logic.values.expandedRows).toEqual([4])+ logic.unmount()++ // Remount with the same identity — state must come back from tabUiStateLogic.+ logic = dataTableLogic({+ dataKey: 'dk',+ vizKey: VIZ_KEY,+ tabId: TAB_A,+ query: dataTableQuery,+ })+ logic.mount()+ expect(logic.values.expandedRows).toEqual([4])+ logic.unmount()+ })++ it('isolates expanded rows when callers use distinct vizKeys per tab', () => {+ const logicA = dataTableLogic({+ dataKey: 'dk-a',+ vizKey: `viz-${TAB_A}`,+ tabId: TAB_A,+ query: dataTableQuery,+ })+ logicA.mount()+ logicA.actions.toggleRowExpanded(1)++ const logicB = dataTableLogic({+ dataKey: 'dk-b',+ vizKey: `viz-${TAB_B}`,+ tabId: TAB_B,+ query: dataTableQuery,+ })+ logicB.mount()+ expect(logicB.values.expandedRows).toEqual([])+ logicB.actions.toggleRowExpanded(2)++ expect(logicA.values.expandedRows).toEqual([1])+ expect(logicB.values.expandedRows).toEqual([2])++ logicA.unmount()+ logicB.unmount()++ // State survives both unmounts — the global owns it.+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_A, `viz-${TAB_A}`)).toEqual([1])+ expect(tabUiStateLogic.values.expandedRowsFor(TAB_B, `viz-${TAB_B}`)).toEqual([2])+ })++ describe('savedQueriesByTabAndScene', () => {+ const queryA = setLatestVersionsOnQuery({+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.EventsQuery, select: ['event'] },+ })+ const queryB = setLatestVersionsOnQuery({+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.EventsQuery, select: ['timestamp'] },+ })++ it('persists and reads queries scoped by tabId + sceneKey', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'sessions', queryB)++ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'events')).toEqual(queryA)+ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'sessions')).toEqual(queryB)+ })++ it('isolates saved queries between tabs', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_B, 'events', queryB)++ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'events')).toEqual(queryA)+ expect(tabUiStateLogic.values.savedQueryFor(TAB_B, 'events')).toEqual(queryB)+ })++ it('returns null for unknown tab/sceneKey', () => {+ expect(tabUiStateLogic.values.savedQueryFor('unknown', 'events')).toBeNull()+ expect(tabUiStateLogic.values.savedQueryFor(undefined, 'events')).toBeNull()+ })++ it('clears the slot when called with null', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', null)++ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'events')).toBeNull()+ })++ it('null clear of one sceneKey leaves the other intact', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'sessions', queryB)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', null)++ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'events')).toBeNull()+ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'sessions')).toEqual(queryB)+ })++ it('null clear of last sceneKey drops the tab entry entirely', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', null)++ expect(tabUiStateLogic.values.savedQueriesByTabAndScene[TAB_A]).toBeUndefined()+ })++ it('null clear is a no-op for unknown tab/sceneKey', () => {+ const before = tabUiStateLogic.values.savedQueriesByTabAndScene+ tabUiStateLogic.actions.setSavedQueryForTab('never-set', 'events', null)+ expect(tabUiStateLogic.values.savedQueriesByTabAndScene).toBe(before)+ })++ it('clearTabUiState wipes saved queries for that tab', () => {+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_A, 'events', queryA)+ tabUiStateLogic.actions.setSavedQueryForTab(TAB_B, 'events', queryB)++ tabUiStateLogic.actions.clearTabUiState(TAB_A)++ expect(tabUiStateLogic.values.savedQueryFor(TAB_A, 'events')).toBeNull()+ expect(tabUiStateLogic.values.savedQueryFor(TAB_B, 'events')).toEqual(queryB)+ })+ })++ describe('chatDraftsByTab', () => {+ it('persists and reads drafts per tabId', () => {+ tabUiStateLogic.actions.setChatDraftForTab(TAB_A, 'rozepsano')+ expect(tabUiStateLogic.values.chatDraftFor(TAB_A)).toBe('rozepsano')+ })++ it('isolates drafts between tabs', () => {+ tabUiStateLogic.actions.setChatDraftForTab(TAB_A, 'one')+ tabUiStateLogic.actions.setChatDraftForTab(TAB_B, 'two')++ expect(tabUiStateLogic.values.chatDraftFor(TAB_A)).toBe('one')+ expect(tabUiStateLogic.values.chatDraftFor(TAB_B)).toBe('two')+ })++ it('returns empty string for unknown tab', () => {+ expect(tabUiStateLogic.values.chatDraftFor('unknown')).toBe('')+ expect(tabUiStateLogic.values.chatDraftFor(undefined)).toBe('')+ })++ it('drops the slot when set to empty string', () => {+ tabUiStateLogic.actions.setChatDraftForTab(TAB_A, 'rozepsano')+ tabUiStateLogic.actions.setChatDraftForTab(TAB_A, '')++ expect(tabUiStateLogic.values.chatDraftsByTab[TAB_A]).toBeUndefined()+ })++ it('clearTabUiState wipes chat drafts for that tab', () => {+ tabUiStateLogic.actions.setChatDraftForTab(TAB_A, 'one')+ tabUiStateLogic.actions.setChatDraftForTab(TAB_B, 'two')++ tabUiStateLogic.actions.clearTabUiState(TAB_A)++ expect(tabUiStateLogic.values.chatDraftFor(TAB_A)).toBe('')+ expect(tabUiStateLogic.values.chatDraftFor(TAB_B)).toBe('two')+ })+ })+})diff --git a/frontend/src/lib/logic/tabUiStateLogic.ts b/frontend/src/lib/logic/tabUiStateLogic.tsnew file mode 100644index 000000000000..a67c4ba8a6f3--- /dev/null+++ b/frontend/src/lib/logic/tabUiStateLogic.ts@@ -0,0 +1,133 @@+import { actions, kea, path, reducers, selectors } from 'kea'++import type { Node } from '~/queries/schema/schema-general'++import type { tabUiStateLogicType } from './tabUiStateLogicType'++const NO_TAB = '__no_tab__'++export type ExpandedRowsByTabAndVizKey = Record<string, Record<string, number[]>>+export type SavedQueriesByTabAndScene = Record<string, Record<string, Node>>+export type ChatDraftsByTab = Record<string, string>++export const tabUiStateLogic = kea<tabUiStateLogicType>([+ path(['lib', 'logic', 'tabUiStateLogic']),+ actions({+ toggleExpandedRow: (tabId: string | undefined, vizKey: string, rowIndex: number) => ({+ tabId: tabId ?? NO_TAB,+ vizKey,+ rowIndex,+ }),+ clearTabUiState: (tabId: string) => ({ tabId }),+ setSavedQueryForTab: (tabId: string | undefined, sceneKey: string, query: Node | null) => ({+ tabId: tabId ?? NO_TAB,+ sceneKey,+ query,+ }),+ setChatDraftForTab: (tabId: string | undefined, draft: string) => ({+ tabId: tabId ?? NO_TAB,+ draft,+ }),+ }),+ reducers({+ expandedRowsByTabAndVizKey: [+ {} as ExpandedRowsByTabAndVizKey,+ {+ toggleExpandedRow: (state, { tabId, vizKey, rowIndex }) => {+ const tabState = state[tabId] ?? {}+ const existing = tabState[vizKey] ?? []+ const next = existing.includes(rowIndex)+ ? existing.filter((r: number) => r !== rowIndex)+ : [...existing, rowIndex]+ return { ...state, [tabId]: { ...tabState, [vizKey]: next } }+ },+ clearTabUiState: (state, { tabId }) => {+ if (!(tabId in state)) {+ return state+ }+ const next = { ...state }+ delete next[tabId]+ return next+ },+ },+ ],+ savedQueriesByTabAndScene: [+ {} as SavedQueriesByTabAndScene,+ {+ setSavedQueryForTab: (state, { tabId, sceneKey, query }) => {+ if (query === null) {+ // Clear: drop the scene slot, and the whole tab entry if it becomes empty.+ const tabState = state[tabId]+ if (!tabState || !(sceneKey in tabState)) {+ return state+ }+ const nextTabState = { ...tabState }+ delete nextTabState[sceneKey]+ if (Object.keys(nextTabState).length === 0) {+ const next = { ...state }+ delete next[tabId]+ return next+ }+ return { ...state, [tabId]: nextTabState }+ }+ return {+ ...state,+ [tabId]: { ...state[tabId], [sceneKey]: query },+ }+ },+ clearTabUiState: (state, { tabId }) => {+ if (!(tabId in state)) {+ return state+ }+ const next = { ...state }+ delete next[tabId]+ return next+ },+ },+ ],+ chatDraftsByTab: [+ {} as ChatDraftsByTab,+ {+ setChatDraftForTab: (state, { tabId, draft }) => {+ if (draft === '') {+ if (!(tabId in state)) {+ return state+ }+ const next = { ...state }+ delete next[tabId]+ return next+ }+ return { ...state, [tabId]: draft }+ },+ clearTabUiState: (state, { tabId }) => {+ if (!(tabId in state)) {+ return state+ }+ const next = { ...state }+ delete next[tabId]+ return next+ },+ },+ ],+ }),+ selectors({+ expandedRowsFor: [+ (s) => [s.expandedRowsByTabAndVizKey],+ (state): ((tabId: string | undefined, vizKey: string) => number[]) =>+ (tabId, vizKey) =>+ state[tabId ?? NO_TAB]?.[vizKey] ?? [],+ ],+ savedQueryFor: [+ (s) => [s.savedQueriesByTabAndScene],+ (state): ((tabId: string | undefined, sceneKey: string) => Node | null) =>+ (tabId, sceneKey) =>+ state[tabId ?? NO_TAB]?.[sceneKey] ?? null,+ ],+ chatDraftFor: [+ (s) => [s.chatDraftsByTab],+ (state): ((tabId: string | undefined) => string) =>+ (tabId) =>+ state[tabId ?? NO_TAB] ?? '',+ ],+ }),+])diff --git a/frontend/src/queries/Query/Query.tsx b/frontend/src/queries/Query/Query.tsxindex f6e953699f63..2d9ae9d7e454 100644--- a/frontend/src/queries/Query/Query.tsx+++ b/frontend/src/queries/Query/Query.tsx@@ -87,6 +87,8 @@ export interface QueryProps<Q extends Node> {dataAttr?: string/** Attach ourselves to another logic, such as the scene logic */attachTo?: BuiltLogic | LogicWrapper+ /** Owning internal tab; used to scope per-tab UI state across tab unmounts */+ tabId?: string}export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | null {@@ -142,6 +144,7 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | nulluniqueKey={uniqueKey}readOnly={readOnly}dataAttr={dataAttr}+ tabId={props.tabId}/>)} else if (isDataVisualizationNode(query)) {diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsxindex e082d9200f39..bd8704ed8aaf 100644--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx@@ -1,7 +1,7 @@import './DataTable.scss'import clsx from 'clsx'-import { BindLogic, BuiltLogic, LogicWrapper, useValues } from 'kea'+import { BindLogic, BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'import { useCallback, useState } from 'react'import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'@@ -125,6 +125,8 @@ interface DataTableProps {dataAttr?: string/** Attach ourselves to another logic, such as the scene logic */attachTo?: BuiltLogic | LogicWrapper+ /** Owning internal tab; used to scope per-tab UI state across tab unmounts */+ tabId?: string}const eventGroupTypes = [@@ -146,6 +148,7 @@ export function DataTable({readOnly,dataAttr,attachTo,+ tabId,}: DataTableProps): JSX.Element {const [uniqueNodeKey] = useState(() => uniqueNode++)const [dataKey] = useState(() => `DataNode.${uniqueKey || uniqueNodeKey}`)@@ -193,14 +196,22 @@ export function DataTable({const dataTableLogicProps: DataTableLogicProps = {query,- vizKey,+ vizKey: uniqueKey ? String(uniqueKey) : vizKey,dataKey,dataNodeLogicKey: dataNodeLogicProps.key,context,+ tabId,}- const { dataTableRows, columnsInQuery, columnsInResponse, queryWithDefaults, canSort, sourceFeatures } = useValues(- dataTableLogic(dataTableLogicProps)- )+ const {+ dataTableRows,+ columnsInQuery,+ columnsInResponse,+ queryWithDefaults,+ canSort,+ sourceFeatures,+ expandedRows,+ } = useValues(dataTableLogic(dataTableLogicProps))+ const { toggleRowExpanded } = useActions(dataTableLogic(dataTableLogicProps))useAttachedLogic(dataNodeLogic(dataNodeLogicProps), attachTo)useAttachedLogic(dataTableLogic(dataTableLogicProps), attachTo)@@ -928,6 +939,14 @@ export function DataTable({? context.expandable: expandable && columnsInResponse?.includes('*')? {+ ...(tabId !== undefined+ ? {+ isRowExpanded: (_, rowIndex) =>+ expandedRows.includes(rowIndex),+ onRowExpand: (_, rowIndex) => toggleRowExpanded(rowIndex),+ onRowCollapse: (_, rowIndex) => toggleRowExpanded(rowIndex),+ }+ : {}),expandedRowRender: function renderExpand({ result }) {if ((isEventsQuery(query.source) ||diff --git a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts b/frontend/src/queries/nodes/DataTable/dataTableLogic.tsindex 3e39ca5c05e8..9a3e06bad9b7 100644--- a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts+++ b/frontend/src/queries/nodes/DataTable/dataTableLogic.ts@@ -1,8 +1,9 @@-import { actions, connect, kea, key, path, props, propsChanged, reducers, selectors } from 'kea'+import { actions, connect, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { objectsEqual, sortedKeys } from 'lib/utils'import { RequiredExcept } from 'lib/utils/types'import { teamLogic } from 'scenes/teamLogic'@@ -31,6 +32,8 @@ export interface DataTableLogicProps {context?: QueryContext<DataTableNode>// Override the data logic node key if neededdataNodeLogicKey?: string+ // Used to scope per-tab UI state (e.g. expanded rows) so it survives tab switches+ tabId?: string}export interface DataTableRow {@@ -55,7 +58,10 @@ export const dataTableLogic = kea<dataTableLogicType>([return props.vizKey}),path(['queries', 'nodes', 'DataTable', 'dataTableLogic']),- actions({ setColumnsInQuery: (columns: HogQLExpression[]) => ({ columns }) }),+ actions({+ setColumnsInQuery: (columns: HogQLExpression[]) => ({ columns }),+ toggleRowExpanded: (rowIndex: number) => ({ rowIndex }),+ }),reducers(({ props }) => ({columnsInQuery: [getColumnsForQuery(props.query), { setColumnsInQuery: (_, { columns }) => columns }],})),@@ -65,6 +71,8 @@ export const dataTableLogic = kea<dataTableLogicType>([['featureFlags'],teamLogic,['currentTeam'],+ tabUiStateLogic,+ ['expandedRowsFor'],dataNodeLogic({key: props.dataNodeLogicKey ?? props.dataKey,query: props.query.source,@@ -76,9 +84,27 @@ export const dataTableLogic = kea<dataTableLogicType>([}),['response', 'responseLoading', 'responseError'],],+ actions: [tabUiStateLogic, ['toggleExpandedRow']],+ })),+ listeners(({ props, actions }) => ({+ toggleRowExpanded: ({ rowIndex }) => {+ if (props.tabId === undefined) {+ return+ }+ actions.toggleExpandedRow(props.tabId, props.vizKey, rowIndex)+ },})),selectors({context: [() => [(_, props) => props.context], (context) => context],+ expandedRows: [+ (s) => [s.expandedRowsFor, (_, p) => p.tabId, (_, p) => p.vizKey],+ (+ expandedRowsFor: (tabId: string | undefined, vizKey: string) => number[],+ tabId: string | undefined,+ vizKey: string+ ): number[] => expandedRowsFor(tabId, vizKey),+ { resultEqualityCheck: objectsEqual },+ ],sourceKind: [(_, p) => [p.query], (query): NodeKind | null => query.source?.kind],sourceFeatures: [(_, p) => [p.query, (_, props) => props.context],diff --git a/frontend/src/scenes/activity/explore/EventsScene.tsx b/frontend/src/scenes/activity/explore/EventsScene.tsxindex 4b87867df7b0..718472c10810 100644--- a/frontend/src/scenes/activity/explore/EventsScene.tsx+++ b/frontend/src/scenes/activity/explore/EventsScene.tsx@@ -14,8 +14,8 @@ import { ActivityTab } from '~/types'import { eventsSceneLogic } from './eventsSceneLogic'export function EventsScene({ tabId }: { tabId?: string } = {}): JSX.Element {- const { query } = useValues(eventsSceneLogic)- const { setQuery } = useActions(eventsSceneLogic)+ const { query } = useValues(eventsSceneLogic({ tabId }))+ const { setQuery } = useActions(eventsSceneLogic({ tabId }))return (<SceneContent>@@ -30,6 +30,7 @@ export function EventsScene({ tabId }: { tabId?: string } = {}): JSX.Element {<QueryattachTo={eventsSceneLogic({ tabId })}uniqueKey={`events-scene-${tabId}`}+ tabId={tabId}query={query}setQuery={setQuery}context={{diff --git a/frontend/src/scenes/activity/explore/SessionsScene.tsx b/frontend/src/scenes/activity/explore/SessionsScene.tsxindex e34374dc8faa..9971522d54e9 100644--- a/frontend/src/scenes/activity/explore/SessionsScene.tsx+++ b/frontend/src/scenes/activity/explore/SessionsScene.tsx@@ -16,8 +16,8 @@ import { createSessionsRowTransformer, getSessionsColumns } from './sessionsColuimport { sessionsSceneLogic } from './sessionsSceneLogic'export function SessionsScene({ tabId }: { tabId?: string } = {}): JSX.Element {- const { query } = useValues(sessionsSceneLogic)- const { setQuery } = useActions(sessionsSceneLogic)+ const { query } = useValues(sessionsSceneLogic({ tabId }))+ const { setQuery } = useActions(sessionsSceneLogic({ tabId }))// Create the row transformer based on the current queryconst dataTableRowsTransformer = useMemo(() => createSessionsRowTransformer(query as DataTableNode), [query])@@ -35,6 +35,7 @@ export function SessionsScene({ tabId }: { tabId?: string } = {}): JSX.Element {<QueryattachTo={sessionsSceneLogic({ tabId })}uniqueKey={`sessions-scene-${tabId}`}+ tabId={tabId}query={query}setQuery={setQuery}context={{diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsxindex f03a7ff941c1..2d2aae58c3ba 100644--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx@@ -1,12 +1,12 @@import equal from 'fast-deep-equal'-import { actions, connect, kea, path, reducers, selectors } from 'kea'+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { UrlToActionPayload } from 'kea-router/lib/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'-import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { objectsEqual } from 'lib/utils'import { applyTestAccountFilter, getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'import { sceneConfigurations } from 'scenes/scenes'@@ -21,9 +21,14 @@ import { ActivityTab, Breadcrumb } from '~/types'import type { eventsSceneLogicType } from './eventsSceneLogicType'+export interface EventsSceneLogicProps {+ tabId?: string+}+export const eventsSceneLogic = kea<eventsSceneLogicType>([- path(['scenes', 'events', 'eventsSceneLogic']),- tabAwareScene(),+ props({} as EventsSceneLogicProps),+ key((props) => props.tabId || 'scene'),+ path((key) => ['scenes', 'events', 'eventsSceneLogic', key]),connect(() => ({values: [teamLogic,@@ -32,11 +37,27 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([['featureFlags'],filterTestAccountsDefaultsLogic,['filterTestAccountsDefault'],+ tabUiStateLogic,+ ['savedQueryFor'],],+ actions: [tabUiStateLogic, ['setSavedQueryForTab']],})),actions({ setQuery: (query: Node) => ({ query }) }),reducers({ savedQuery: [null as Node | null, { setQuery: (_, { query }) => query }] }),+ listeners(({ props, actions, values }) => ({+ setQuery: ({ query }) => {+ // No owning tab → no removeTab cleanup will ever clear this slot.+ // sceneKey is constant ('events') so it'd be a single overwriting slot under+ // '__no_tab__', but we still skip it for consistency with dataTableLogic and+ // because persistence semantically requires a tab.+ if (props.tabId === undefined) {+ return+ }+ const isDefault = objectsEqual(query, values.defaultQuery)+ actions.setSavedQueryForTab(props.tabId, 'events', isDefault ? null : query)+ },+ })),selectors({defaultQuery: [(s) => [s.currentTeam, s.filterTestAccountsDefault],@@ -73,14 +94,16 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([],})),- tabAwareUrlToAction(({ actions, values }) => {+ tabAwareUrlToAction(({ actions, values, props }) => {const eventsQueryHandler: UrlToActionPayload[keyof UrlToActionPayload] = (_, __, { q: queryParam }): void => {if (!equal(queryParam, values.query)) {// nothing in the URLif (!queryParam) {- // set the default unless it's already there- if (!objectsEqual(values.query, values.defaultQuery)) {- actions.setQuery(values.defaultQuery)+ // restore from per-tab persisted query if present, else fall back to default+ const persisted = values.savedQueryFor(props.tabId, 'events')+ const target = persisted ?? values.defaultQuery+ if (!objectsEqual(values.query, target)) {+ actions.setQuery(target)}} else {if (typeof queryParam === 'object') {diff --git a/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx b/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsxindex 04c678760e01..b6033b64d8c4 100644--- a/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx+++ b/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx@@ -1,11 +1,11 @@import equal from 'fast-deep-equal'-import { actions, connect, kea, path, reducers, selectors } from 'kea'+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { UrlToActionPayload } from 'kea-router/lib/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'-import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { objectsEqual } from 'lib/utils'import { applyTestAccountFilter, getDefaultSessionsSceneQuery } from 'scenes/activity/explore/defaults'import { sceneConfigurations } from 'scenes/scenes'@@ -19,15 +19,38 @@ import { ActivityTab, Breadcrumb } from '~/types'import type { sessionsSceneLogicType } from './sessionsSceneLogicType'+export interface SessionsSceneLogicProps {+ tabId?: string+}+export const sessionsSceneLogic = kea<sessionsSceneLogicType>([- path(['scenes', 'sessions', 'sessionsSceneLogic']),- tabAwareScene(),+ props({} as SessionsSceneLogicProps),+ key((props) => props.tabId || 'scene'),+ path((key) => ['scenes', 'sessions', 'sessionsSceneLogic', key]),connect(() => ({- values: [teamLogic, ['currentTeam'], filterTestAccountsDefaultsLogic, ['filterTestAccountsDefault']],+ values: [+ teamLogic,+ ['currentTeam'],+ filterTestAccountsDefaultsLogic,+ ['filterTestAccountsDefault'],+ tabUiStateLogic,+ ['savedQueryFor'],+ ],+ actions: [tabUiStateLogic, ['setSavedQueryForTab']],})),actions({ setQuery: (query: Node) => ({ query }) }),reducers({ savedQuery: [null as Node | null, { setQuery: (_, { query }) => query }] }),+ listeners(({ props, actions, values }) => ({+ setQuery: ({ query }) => {+ // No owning tab → no removeTab cleanup will reach this slot. See eventsSceneLogic.+ if (props.tabId === undefined) {+ return+ }+ const isDefault = objectsEqual(query, values.defaultQuery)+ actions.setSavedQueryForTab(props.tabId, 'sessions', isDefault ? null : query)+ },+ })),selectors({defaultQuery: [(s) => [s.currentTeam, s.filterTestAccountsDefault],@@ -55,17 +78,19 @@ export const sessionsSceneLogic = kea<sessionsSceneLogicType>([],})),- tabAwareUrlToAction(({ actions, values }) => {+ tabAwareUrlToAction(({ actions, values, props }) => {const sessionsQueryHandler: UrlToActionPayload[keyof UrlToActionPayload] = (_, __, { q: queryParam }): void => {// If query hasn't changed, do nothingif (equal(queryParam, values.query)) {return}- // Handle missing query param - set default if needed+ // Handle missing query param - restore from per-tab persisted query, else fall back to defaultif (!queryParam) {- if (!objectsEqual(values.query, values.defaultQuery)) {- actions.setQuery(values.defaultQuery)+ const persisted = values.savedQueryFor(props.tabId, 'sessions')+ const target = persisted ?? values.defaultQuery+ if (!objectsEqual(values.query, target)) {+ actions.setQuery(target)}return}diff --git a/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts b/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.tsindex 400b3eefffa6..c8062624cd54 100644--- a/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts+++ b/frontend/src/scenes/activity/live/liveEventsTableSceneLogic.ts@@ -1,6 +1,5 @@-import { kea, path, props, selectors } from 'kea'+import { kea, key, path, props, selectors } from 'kea'-import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'@@ -13,9 +12,9 @@ export interface LiveEventsTableSceneProps {}export const liveEventsTableSceneLogic = kea<liveEventsTableSceneLogicType>([- path(['scenes', 'activity', 'live-events', 'liveEventsTableSceneLogic']),- tabAwareScene(),props({} as LiveEventsTableSceneProps),+ key((props) => props.tabId || 'scene'),+ path((key) => ['scenes', 'activity', 'live-events', 'liveEventsTableSceneLogic', key]),selectors(() => ({breadcrumbs: [() => [],diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex 950b2c90b7cb..9cf79c852b7a 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -1,4 +1,4 @@-import { actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { router } from 'kea-router'import { subscriptions } from 'kea-subscriptions'@@ -8,8 +8,8 @@ import api from 'lib/api'import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'-import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { objectsEqual, uuid } from 'lib/utils'import { sceneLogic } from 'scenes/sceneLogic'import { Scene, SceneTab } from 'scenes/sceneTypes'@@ -135,9 +135,11 @@ function updateInactiveTab(tabId: string, props: Partial<SceneTab>): void {}export const maxLogic = kea<maxLogicType>([- path(['scenes', 'max', 'maxLogic']),- props({} as { tabId: string | 'sidepanel'; onAcceptSessionFilters?: (filters: RecordingUniversalFilters) => void }),- tabAwareScene(),+ props(+ {} as { tabId?: string | 'sidepanel'; onAcceptSessionFilters?: (filters: RecordingUniversalFilters) => void }+ ),+ key((props) => props.tabId || 'scene'),+ path((key) => ['scenes', 'max', 'maxLogic', key]),connect(() => ({values: [@@ -157,12 +159,16 @@ export const maxLogic = kea<maxLogicType>([// Actions are lazy-loaded. In order to display their names in the UI, we're loading them here.actionsModel({ params: 'include_count=1' }),['actions'],+ tabUiStateLogic,+ ['chatDraftFor'],],actions: [maxContextLogic,['resetContext'],maxGlobalLogic,['loadConversationHistory', 'prependOrReplaceConversation', 'loadConversationHistorySuccess'],+ tabUiStateLogic,+ ['setChatDraftForTab'],],})),@@ -416,8 +422,18 @@ export const maxLogic = kea<maxLogicType>([}),listeners(({ actions, values, props }) => ({+ setQuestion: ({ question }) => {+ // Side panel Max stays mounted across the whole app, so its question reducer+ // already survives navigation — and there's no removeTab cleanup for it,+ // which would turn the persisted draft into a memory leak.+ if (props.tabId && props.tabId !== 'sidepanel') {+ actions.setChatDraftForTab(props.tabId, question)+ }+ },incrActiveStreamingThreads: () => {- updateInactiveTab(props.tabId, { iconType: 'loading', badge: false })+ if (props.tabId) {+ updateInactiveTab(props.tabId, { iconType: 'loading', badge: false })+ }},decrActiveStreamingThreads: () => {// Reducer runs before listener, so activeStreamingThreads is already decremented.@@ -425,7 +441,9 @@ export const maxLogic = kea<maxLogicType>([if (values.activeStreamingThreads > 0) {return}- updateInactiveTab(props.tabId, { iconType: 'chat', badge: true })+ if (props.tabId) {+ updateInactiveTab(props.tabId, { iconType: 'chat', badge: true })+ }},// Listen for when the side panel state changes and check for initial prompt[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {@@ -547,6 +565,9 @@ export const maxLogic = kea<maxLogicType>([startNewConversation: () => {actions.resetContext()actions.focusInput()+ if (props.tabId && props.tabId !== 'sidepanel') {+ actions.setChatDraftForTab(props.tabId, '')+ }},})),@@ -554,13 +575,22 @@ export const maxLogic = kea<maxLogicType>([// This subscription covers inactive tabs, which titleAndIcon doesn't reach.subscriptions(({ props }) => ({chatTitle: (title: string | null) => {- if (title && title !== CHAT_TITLE_NEW && title !== CHAT_TITLE_HISTORY) {+ if (title && title !== CHAT_TITLE_NEW && title !== CHAT_TITLE_HISTORY && props.tabId) {updateInactiveTab(props.tabId, { title })}},})),- afterMount(({ actions, values }) => {+ afterMount(({ actions, values, props }) => {+ // Restore per-tab chat draft (typed but unsent input that should survive scene unmount).+ // Side panel Max is excluded — it stays mounted globally, doesn't go through removeTab cleanup.+ if (!values.question && props.tabId && props.tabId !== 'sidepanel') {+ const draft = values.chatDraftFor(props.tabId)+ if (draft) {+ actions.setQuestion(draft)+ }+ }+// Restore pending prompt from sessionStorage (e.g., after OAuth redirect during consent flow)if (!values.question) {try {diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex f3a271fc2e16..57824bf2c0a3 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -305,10 +305,11 @@ export function PersonScene({ tabId }: { tabId?: string }): JSX.Element | null {label: <span data-attr="persons-events-tab">Events</span>,content: (<Query- uniqueKey="person-profile-events"+ uniqueKey={`person-profile-events-${tabId}`}attachTo={mountedPersonsLogic}query={eventsQuery}setQuery={(q) => setEventsQuery(q)}+ tabId={tabId}context={{insightProps: {dashboardItemId: `new-${PERSON_EVENTS_CONTEXT_KEY}`,@@ -372,12 +373,28 @@ export function PersonScene({ tabId }: { tabId?: string }): JSX.Element | null {{key: PersonsTabType.EXCEPTIONS,label: <span data-attr="persons-exceptions-tab">Exceptions</span>,- content: <Query query={exceptionsQuery} setQuery={(q) => setExceptionsQuery(q)} />,+ content: (+ <Query+ uniqueKey={`person-profile-exceptions-${tabId}`}+ attachTo={mountedPersonsLogic}+ query={exceptionsQuery}+ setQuery={(q) => setExceptionsQuery(q)}+ tabId={tabId}+ />+ ),},{key: PersonsTabType.SURVEY_RESPONSES,label: <span data-attr="persons-survey-responses-tab">Surveys</span>,- content: <Query query={surveyResponsesQuery} setQuery={(q) => setSurveyResponsesQuery(q)} />,+ content: (+ <Query+ uniqueKey={`person-profile-surveys-${tabId}`}+ attachTo={mountedPersonsLogic}+ query={surveyResponsesQuery}+ setQuery={(q) => setSurveyResponsesQuery(q)}+ tabId={tabId}+ />+ ),},{key: PersonsTabType.COHORTS,diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.tsindex 1fa1261d50bd..486787d21c2d 100644--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts@@ -1,6 +1,7 @@import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { maxLogic } from 'scenes/max/maxLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -16,7 +17,7 @@ import { Scene, SceneTab } from '~/scenes/sceneTypes'import { DashboardBasicType } from '~/types'import type { aiFirstHomepageLogicType } from './aiFirstHomepageLogicType'-import { HOMEPAGE_TAB_ID } from './constants'+import { HOMEPAGE_IDLE_DRAFT_KEY, HOMEPAGE_TAB_ID } from './constants'export type HomepageMode = 'idle' | 'search' | 'ai'export type AnimationPhase = 'idle' | 'moving' | 'separator' | 'content'@@ -85,12 +86,16 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([['recents as cachedRecents', 'recentsHasLoaded'],projectTreeDataLogic,['shortcutData as cachedStarred', 'shortcutDataHasLoaded'],+ tabUiStateLogic,+ ['chatDraftFor'],],actions: [maxLogic({ tabId: HOMEPAGE_TAB_ID }),['openConversation', 'startNewConversation', 'setQuestion'],sceneLogic,['setHomepage'],+ tabUiStateLogic,+ ['setChatDraftForTab'],],})),@@ -205,7 +210,19 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([}),listeners(({ actions, values }) => ({+ setQuery: ({ query }) => {+ if (values.mode === 'idle') {+ actions.setChatDraftForTab(HOMEPAGE_IDLE_DRAFT_KEY, query)+ }+ },+ returnToIdle: () => {+ actions.setChatDraftForTab(HOMEPAGE_IDLE_DRAFT_KEY, '')+ },submitQuery: async ({ mode }, breakpoint) => {+ // 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, '')+if (mode === 'ai' && !values.conversationId) {actions.startNewConversation()}@@ -285,6 +302,13 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([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)+ }}},})),@@ -338,5 +362,6 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([actions.setQuery(urlQuery)actions.submitQuery('search')}+ // Idle-mode draft restore happens in urlToAction (also fires on mount).}),])diff --git a/frontend/src/scenes/project-homepage/ai-first/constants.ts b/frontend/src/scenes/project-homepage/ai-first/constants.tsindex 346098189989..06a630c2c16b 100644--- a/frontend/src/scenes/project-homepage/ai-first/constants.ts+++ b/frontend/src/scenes/project-homepage/ai-first/constants.ts@@ -1 +1,6 @@export const HOMEPAGE_TAB_ID = 'homepage-ai'++// Storage key for the homepage's idle-mode search/AI input draft in tabUiStateLogic.chatDraftsByTab.+// Intentionally distinct from HOMEPAGE_TAB_ID so the homepage Max chat draft (keyed by+// HOMEPAGE_TAB_ID) doesn't collide with the idle-input draft.+export const HOMEPAGE_IDLE_DRAFT_KEY = 'homepage-ai:idle'diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex 5a91c7622bf3..f379b19bb809 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -11,6 +11,7 @@ import { TeamMembershipLevel } from 'lib/constants'import { trackFileSystemLogView } from 'lib/hooks/useFileSystemLogView'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner'+import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'import { getRelativeNextPath, identifierToHuman } from 'lib/utils'import { getAppContext, getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'import { isChunkLoadError } from 'lib/utils/isChunkLoadError'@@ -1019,6 +1020,7 @@ export const sceneLogic = kea<sceneLogicType>([}},removeTab: ({ tab, options }) => {+ tabUiStateLogic.findMounted()?.actions.clearTabUiState(tab.id)const closeSource = options?.source ?? 'unknown'posthog.capture('tab closed', {tab_id: tab.id,