Skip to content

: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.

refactor(frontend): collapse sceneLogic tabs[] to single-scene state (#62051)

Paul D'Ambrad590266d2ff8
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 7ab4c20bf6c9..dd4c47f66d96 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -11,7 +11,6 @@ import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/kea-router'
import { identifierToHuman } from 'lib/utils/strings'
-import { getTabsSnapshotForHistory, sceneLogic } from 'scenes/sceneLogic'
import { disposablesPlugin } from '~/kea-disposables'
@@ -90,20 +89,6 @@ export function initKea({
},
replaceInitialPathInWindow:
typeof replaceInitialPathInWindow === 'undefined' ? true : replaceInitialPathInWindow,
- getRouterState: () => {
- // This state is persisted into window.history
- const logic = sceneLogic.findMounted()
- if (logic) {
- // Strip sceneParams etc. — they are not JSON-safe and break structuredClone (cyclic/deep graphs)
- const tabs = getTabsSnapshotForHistory(logic.values.tabs)
- if (typeof structuredClone !== 'undefined') {
- return { tabs: structuredClone(tabs) }
- }
- // structuredClone fails in jest for some reason, despite us being on the right versions
- return { tabs: JSON.parse(JSON.stringify(tabs)) || [] }
- }
- return undefined
- },
}),
formsPlugin,
loadersPlugin({
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsx
index 272640ea9a26..ac1164232509 100644
--- a/frontend/src/layout/navigation-3000/Navigation.tsx
+++ b/frontend/src/layout/navigation-3000/Navigation.tsx
@@ -43,8 +43,7 @@ export function Navigation({
const mainRef = useRef<HTMLElement>(null)
const { mainContentRect, isLayoutNavCollapsed, isLayoutPanelVisible, navbarWidth } = useValues(panelLayoutLogic)
const { setMainContentRef, setMainContentRect } = useActions(panelLayoutLogic)
- const { setTabScrollDepth } = useActions(sceneLogic)
- const { activeTabId, activeSceneId } = useValues(sceneLogic)
+ const { activeSceneId } = useValues(sceneLogic)
const { registerScenePanelElement } = useActions(sceneLayoutLogic)
const { scenePanelIsPresent, scenePanelOpenManual } = useValues(sceneLayoutLogic)
const { sidePanelOpen } = useValues(sidePanelStateLogic)
@@ -173,11 +172,6 @@ export function Navigation({
'lg:max-w-[calc(100%-var(--side-panel-width))] rounded-r-none': sidePanelOpen,
}
)}
- onScroll={(e) => {
- if (activeTabId) {
- setTabScrollDepth(activeTabId, e.currentTarget.scrollTop)
- }
- }}
>
<SceneLayout sceneConfig={sceneConfig}>
{!sceneMenuBarEnabled && !sceneConfig?.hideProjectNotice && (
diff --git a/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx b/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
index 6afaecb8a7cb..2ef611c0125f 100644
--- a/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
+++ b/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
@@ -27,7 +27,7 @@ export const breadcrumbsLogic = kea<breadcrumbsLogicType>([
preflightLogic,
['preflight'],
sceneLogic,
- ['sceneConfig', 'activeSceneId', 'activeTabId'],
+ ['sceneConfig', 'activeSceneId'],
userLogic,
['user', 'otherOrganizations'],
organizationLogic,
@@ -76,14 +76,12 @@ export const breadcrumbsLogic = kea<breadcrumbsLogicType>([
(state, props): Breadcrumb[] => {
const activeSceneLogic = sceneLogic.selectors.activeSceneLogic(state, props)
const activeSceneId = s.activeSceneId(state, props)
- const activeTabId = s.activeTabId(state, props)
if (activeSceneLogic && 'breadcrumbs' in activeSceneLogic.selectors) {
try {
const activeLoadedScene = sceneLogic.selectors.activeLoadedScene(state, props)
return activeSceneLogic.selectors.breadcrumbs(state, {
...(activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || props),
- tabId: activeTabId,
})
} catch {
// If the breadcrumb selector fails, we'll just ignore it and return an empty array below
@@ -101,17 +99,15 @@ export const breadcrumbsLogic = kea<breadcrumbsLogicType>([
{ resultEqualityCheck: objectsEqual },
],
projectTreeRef: [
- (s) => [
+ () => [
// Similar logic to the breadcrumbs above. This is used to find the object in the project tree.
(state, props): ProjectTreeRef | null => {
const activeSceneLogic = sceneLogic.selectors.activeSceneLogic(state, props)
- const activeTabId = s.activeTabId(state, props)
if (activeSceneLogic && 'projectTreeRef' in activeSceneLogic.selectors) {
try {
const activeLoadedScene = sceneLogic.selectors.activeLoadedScene(state, props)
return activeSceneLogic.selectors.projectTreeRef(state, {
...(activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || props),
- tabId: activeTabId,
})
} catch {
// If the breadcrumb selector fails, we'll just ignore it and return null below
diff --git a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
index fd5b4ba54c2e..11b8ec53ba5f 100644
--- a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
@@ -27,7 +27,6 @@ import { LinkListItem } from 'lib/ui/LinkListItem/LinkListItem'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { sceneLogic } from 'scenes/sceneLogic'
import { urls } from 'scenes/urls'
import { navigationLogic } from '~/layout/navigation/navigationLogic'
@@ -162,7 +161,6 @@ export function NavTabBrowse(): JSX.Element {
activePanelIdentifierFromUrlAiFirst,
pathname,
} = useValues(panelLayoutLogic)
- const { firstTabIsActive } = useValues(sceneLogic)
const isProductAutonomyEnabled = useFeatureFlag('PRODUCT_AUTONOMY')
const { recentItems, recentItemsLoading } = useValues(navRecentsLogic)
const { isEditMode, checkedItems } = useValues(inlineEditAppsLogic)
@@ -184,9 +182,7 @@ export function NavTabBrowse(): JSX.Element {
return (
<ScrollableShadows
- className={cn('flex-1', {
- 'rounded-tr': !isLayoutPanelVisible && !firstTabIsActive,
- })}
+ className="flex-1"
innerClassName="overflow-y-auto overflow-x-hidden px-2 focus-visible:outline-accent -outline-offset-2"
direction="vertical"
styledScrollbars
diff --git a/frontend/src/lib/components/AppShortcuts/AppShortcutMenu.tsx b/frontend/src/lib/components/AppShortcuts/AppShortcutMenu.tsx
index e3b26162ed19..8b2cf956a67d 100644
--- a/frontend/src/lib/components/AppShortcuts/AppShortcutMenu.tsx
+++ b/frontend/src/lib/components/AppShortcuts/AppShortcutMenu.tsx
@@ -93,13 +93,13 @@ export function AppShortcutMenu(): JSX.Element | null {
const { appShortcutMenuOpen, disabledShortcutNames } = useValues(appShortcutLogic)
const { setAppShortcutMenuOpen, toggleShortcutDisabled } = useActions(appShortcutLogic)
const { registeredAppShortcuts } = useValues(appShortcutLogic)
- const { activeTab } = useValues(sceneLogic)
+ const { sceneId } = useValues(sceneLogic)
const comboboxRef = useRef<ListBoxHandle>(null)
// Group shortcuts by scope, with scene-specific first and global last
const groupedShortcuts = useMemo(() => {
const groups: Record<string, AppShortcutType[]> = {}
- const currentScene = activeTab?.sceneId
+ const currentScene = sceneId
registeredAppShortcuts.forEach((shortcut) => {
const scope = shortcut.scope || 'global'
@@ -142,7 +142,7 @@ export function AppShortcutMenu(): JSX.Element | null {
title: titleForKey(key),
shortcuts: groups[key],
}))
- }, [registeredAppShortcuts, activeTab])
+ }, [registeredAppShortcuts, sceneId])
const handleClose = useCallback(() => {
setAppShortcutMenuOpen(false)
diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsx
index ff85fb1bb93c..5d95e320e244 100644
--- a/frontend/src/scenes/App.tsx
+++ b/frontend/src/scenes/App.tsx
@@ -79,13 +79,8 @@ export function App(): JSX.Element | null {
function AppScene(): JSX.Element | null {
const { user } = useValues(userLogic)
- const {
- activeSceneId,
- activeExportedScene,
- activeSceneComponentParamsWithTabId,
- activeSceneLogicPropsWithTabId,
- sceneConfig,
- } = useValues(sceneLogic)
+ const { activeSceneId, activeExportedScene, activeSceneComponentParams, activeSceneLogicProps, sceneConfig } =
+ useValues(sceneLogic)
const { showingDelayedSpinner } = useValues(appLogic)
const { isDarkModeOn } = useValues(themeLogic)
@@ -121,8 +116,8 @@ function AppScene(): JSX.Element | null {
if (activeExportedScene?.component) {
const { component: SceneComponent } = activeExportedScene
sceneElement = (
- <SceneAnimationRoot key={`scene-${activeSceneId}-${activeSceneLogicPropsWithTabId.tabId}`}>
- <SceneComponent user={user} {...activeSceneComponentParamsWithTabId} />
+ <SceneAnimationRoot key={`scene-${activeSceneId}`}>
+ <SceneComponent user={user} {...activeSceneComponentParams} />
</SceneAnimationRoot>
)
} else {
@@ -130,11 +125,7 @@ function AppScene(): JSX.Element | null {
}
const sceneContent = activeExportedScene?.logic ? (
- <BindLogic
- key={`bind-${activeSceneLogicPropsWithTabId.tabId}`}
- logic={activeExportedScene.logic}
- props={activeSceneLogicPropsWithTabId}
- >
+ <BindLogic key={`bind-${activeSceneId}`} logic={activeExportedScene.logic} props={activeSceneLogicProps}>
{sceneElement}
</BindLogic>
) : (
@@ -142,10 +133,7 @@ function AppScene(): JSX.Element | null {
)
const wrappedSceneElement = (
- <ErrorBoundary
- key={`error-${activeSceneLogicPropsWithTabId.tabId}`}
- exceptionProps={{ feature: activeSceneId }}
- >
+ <ErrorBoundary key={`error-${activeSceneId}`} exceptionProps={{ feature: activeSceneId }}>
{/* Keep chunk-load failures out of the scene error reporter so stale assets reload once instead. */}
<ChunkLoadErrorBoundary>{sceneContent}</ChunkLoadErrorBoundary>
</ErrorBoundary>
diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
index 6af9bb4244a0..e814b36918ef 100644
--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
@@ -69,9 +69,6 @@ describe('cohortsSceneLogic', () => {
})
initKeaTests()
sceneLogic({ scenes }).mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
logic = cohortsSceneLogic()
logic.mount()
})
diff --git a/frontend/src/scenes/comments/commentsLogic.ts b/frontend/src/scenes/comments/commentsLogic.ts
index c4b62b226876..3877c17c9f48 100644
--- a/frontend/src/scenes/comments/commentsLogic.ts
+++ b/frontend/src/scenes/comments/commentsLogic.ts
@@ -7,7 +7,6 @@ import { RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { isEmptyObject } from 'lib/utils/guards'
import { membersLogic } from 'scenes/organization/membersLogic'
-import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -47,16 +46,7 @@ export const commentsLogic = kea<commentsLogicType>([
membersLogic,
['ensureAllMembersLoaded'],
],
- values: [
- userLogic,
- ['user'],
- sceneLogic,
- ['activeTab'],
- membersLogic,
- ['meFirstMembers'],
- teamLogic,
- ['currentProjectId'],
- ],
+ values: [userLogic, ['user'], membersLogic, ['meFirstMembers'], teamLogic, ['currentProjectId']],
})),
actions({
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index c8d461966e3a..9e0b6c81b3cd 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -81,9 +81,6 @@ describe('dashboardsLogic', () => {
dashboardsModel.mount()
await expectLogic(dashboardsModel).toDispatchActions(['loadDashboardsSuccess'])
sceneLogic({ scenes }).mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
logic = dashboardsLogic({ tabId: '1' })
logic.mount()
diff --git a/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx b/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
index 92fdafd853c0..b8813c640cdf 100644
--- a/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/EditorScene.tsx
@@ -14,6 +14,7 @@ import { SQLEditorMode } from './sqlEditorModes'
export const scene: SceneExport = {
logic: editorSceneLogic,
+ paramsToProps: ({ params }) => ({ tabId: params.tabId ?? 'default' }),
component: EditorScene,
}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index f0319e8e8fcd..065f2ae98794 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -212,9 +212,6 @@ describe('sqlEditorLogic', () => {
sceneLogic.mount()
databaseLogic = databaseTableListLogic()
databaseLogic.mount()
- sceneLogic.actions.setTabs([
- { id: TAB_ID, title: 'SQL', pathname: '/sql', search: '', hash: '', active: true, iconType: 'blank' },
- ])
await expectLogic(teamLogic).toFinishAllListeners()
})
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index a44829b8ccfe..5975962e19c8 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -274,9 +274,6 @@ describe('insightLogic', () => {
initKeaTests(true, { ...MOCK_DEFAULT_TEAM, test_account_filters_default_checked: true })
teamLogic.mount()
sceneLogic.mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
await expectLogic(teamLogic)
.toFinishAllListeners()
.toMatchValues({ currentTeam: partial({ test_account_filters_default_checked: true }) })
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index 59eedcb5a670..6bce6337140e 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -185,13 +185,11 @@ describe('insightSceneLogic', () => {
{ logic: insightSceneLogic, component: () => null as any },
Scene.Insight,
'insightNew',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} }
)
sceneLogic.actions.setScene(
Scene.Insight,
'insightNew',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} },
false
)
@@ -298,13 +296,11 @@ describe('insightSceneLogic', () => {
{ logic: insightSceneLogic, component: () => null as any },
Scene.Insight,
'insightView',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} }
)
sceneLogic.actions.setScene(
Scene.Insight,
'insightView',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} },
false
)
@@ -340,13 +336,11 @@ describe('insightSceneLogic', () => {
{ logic: insightSceneLogic, component: () => null as any },
Scene.Insight,
'insightSubcriptions',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} }
)
sceneLogic.actions.setScene(
Scene.Insight,
'insightSubcriptions',
- sceneLogic.values.activeTabId || '',
{ params: {}, searchParams: {}, hashParams: {} },
false
)
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 7ed226b261b6..7e3291066629 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -468,7 +468,7 @@ const Message = React.memo(function Message({
isSlashCommandResponse,
}: MessageProps): JSX.Element | null {
const { editInsightToolRegistered, registeredToolMap } = useValues(maxGlobalLogic)
- const { activeTabId, activeSceneId } = useValues(sceneLogic)
+ const { activeSceneId } = useValues(sceneLogic)
const { threadLoading, isSharedThread, pendingApprovalsData, resolvedApprovalStatuses } = useValues(maxThreadLogic)
const { conversationId } = useValues(maxLogic)
@@ -757,7 +757,6 @@ const Message = React.memo(function Message({
content={message.content}
status={message.status}
isEditingInsight={editInsightToolRegistered}
- activeTabId={activeTabId}
activeSceneId={activeSceneId}
/>
)
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index 297dd8616c51..d6306051c5c8 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -1,6 +1,5 @@
import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
-import { subscriptions } from 'kea-subscriptions'
import { IconBook } from '@posthog/icons'
@@ -11,8 +10,7 @@ import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
import { uuid } from 'lib/utils/dom'
import { objectsEqual } from 'lib/utils/objects'
-import { sceneLogic } from 'scenes/sceneLogic'
-import { Scene, SceneTab } from 'scenes/sceneTypes'
+import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
@@ -129,18 +127,6 @@ function handleCommandString(options: string, actions: maxLogicType['actions']):
const CHAT_TITLE_NEW = 'New chat'
const CHAT_TITLE_HISTORY = 'Chat history'
-function updateInactiveTab(tabId: string, props: Partial<SceneTab>): void {
- const scene = sceneLogic.findMounted()
- if (!scene) {
- return
- }
- const { tabs } = scene.values
- const tab = tabs.find((t) => t.id === tabId)
- if (tab && !tab.active) {
- scene.actions.setTabs(tabs.map((t) => (t.id === tabId ? { ...t, ...props } : t)))
- }
-}
-
// Fixed panelId for the floating side panel chat, which is not a scene tab.
export const SIDE_PANEL_PANEL_ID = 'sidepanel'
@@ -470,23 +456,6 @@ export const maxLogic = kea<maxLogicType>([
actions.setChatDraftForTab(tabId, question)
}
},
- incrActiveStreamingThreads: () => {
- const tabId = sceneTabId(props.panelId, props.syncUrl)
- if (tabId) {
- updateInactiveTab(tabId, { iconType: 'loading', badge: false })
- }
- },
- decrActiveStreamingThreads: () => {
- // Reducer runs before listener, so activeStreamingThreads is already decremented.
- // If still > 0, other streams are active — don't show badge yet.
- if (values.activeStreamingThreads > 0) {
- return
- }
- const tabId = sceneTabId(props.panelId, props.syncUrl)
- if (tabId) {
- updateInactiveTab(tabId, { iconType: 'chat', badge: true })
- }
- },
// Listen for when the side panel state changes and check for initial prompt
[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {
if (tab === SidePanelTab.Max && options && typeof options === 'string') {
@@ -614,17 +583,6 @@ export const maxLogic = kea<maxLogicType>([
},
})),
- // Active tab titles are updated by sceneLogic's titleAndIcon subscription (reads breadcrumbs).
- // This subscription covers inactive tabs, which titleAndIcon doesn't reach.
- subscriptions(({ props }) => ({
- chatTitle: (title: string | null) => {
- const tabId = sceneTabId(props.panelId, props.syncUrl)
- if (title && title !== CHAT_TITLE_NEW && title !== CHAT_TITLE_HISTORY && tabId) {
- updateInactiveTab(tabId, { title })
- }
- },
- })),
-
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.
diff --git a/frontend/src/scenes/max/messages/VisualizationArtifact.tsx b/frontend/src/scenes/max/messages/VisualizationArtifact.tsx
index 7c7c11e649cc..4279e6c0b0a1 100644
--- a/frontend/src/scenes/max/messages/VisualizationArtifact.tsx
+++ b/frontend/src/scenes/max/messages/VisualizationArtifact.tsx
@@ -18,7 +18,6 @@ interface VisualizationArtifactProps {
content: VisualizationArtifactContent
status?: MessageStatus
isEditingInsight: boolean
- activeTabId?: string | null
activeSceneId?: string | null
}
@@ -58,7 +57,6 @@ export const VisualizationArtifact = React.memo(function VisualizationArtifact({
content,
status,
isEditingInsight,
- activeTabId,
activeSceneId,
}: VisualizationArtifactProps): JSX.Element | null {
// Controlled collapse synced to edit mode — a key-remount would refetch the query instead.
@@ -73,7 +71,7 @@ export const VisualizationArtifact = React.memo(function VisualizationArtifact({
}
const target = getArtifactOpenTarget(message, content)
- const showSuggestionButton = isEditingInsight && !!activeTabId && activeSceneId === Scene.Insight
+ const showSuggestionButton = isEditingInsight && activeSceneId === Scene.Insight
return (
<VisualizationWidget
diff --git a/frontend/src/scenes/persons/personsSceneLogic.test.ts b/frontend/src/scenes/persons/personsSceneLogic.test.ts
index 783bcaa9c8ea..e5e68d913522 100644
--- a/frontend/src/scenes/persons/personsSceneLogic.test.ts
+++ b/frontend/src/scenes/persons/personsSceneLogic.test.ts
@@ -24,9 +24,6 @@ describe('personsSceneLogic', () => {
})
initKeaTests()
sceneLogic({ scenes }).mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
logic = personsSceneLogic()
logic.mount()
})
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
index ac3744a4649c..196447b90eb8 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
@@ -73,9 +73,6 @@ describe('savedInsightsLogic', () => {
})
initKeaTests()
sceneLogic({ scenes }).mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
router.actions.push(urls.project(MOCK_TEAM_ID, urls.savedInsights()))
logic = savedInsightsLogic({ tabId: '1' })
logic.mount()
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsx
index 0b14d3f94088..c36d85a43ee2 100644
--- a/frontend/src/scenes/sceneLogic.test.tsx
+++ b/frontend/src/scenes/sceneLogic.test.tsx
@@ -46,8 +46,6 @@ describe('sceneLogic', () => {
featureFlagLogic.mount()
router.actions.push(urls.eventDefinitions())
logic = sceneLogic.build({ scenes: testScenes })
- // Simulate a fresh mount so that stored tabs are read from localStorage.
- logic.cache.tabsLoaded = false
logic.mount()
await expectLogic(logic).delay(1)
})
@@ -143,8 +141,6 @@ describe('sceneLogic', () => {
featureFlagLogic.mount()
router.actions.push(urls.eventDefinitions())
const bootstrappedLogic = sceneLogic.build({ scenes: testScenes })
- // Simulate a fresh mount the same way the suite's beforeEach does.
- bootstrappedLogic.cache.tabsLoaded = false
bootstrappedLogic.mount()
// homepage is populated synchronously from APP_CONTEXT — no setHomepage / API round-trip needed.
bootstrappedHomepagePathname = removeProjectIdIfPresent(
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index e054f8e6ce29..33a235cdef99 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -1,7 +1,6 @@
import equal from 'fast-deep-equal'
import { BuiltLogic, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
-import { combineUrl, router, urlToAction } from 'kea-router'
-import { subscriptions } from 'kea-subscriptions'
+import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { useEffect, useState } from 'react'
@@ -50,7 +49,7 @@ import { inviteLogic } from './settings/organization/inviteLogic'
import { teamLogic } from './teamLogic'
import { userLogic } from './userLogic'
-interface MountedTabLogic {
+interface MountedSceneLogic {
logic: SceneExport['logic']
logicProps: Record<string, any>
sceneId: string
@@ -61,58 +60,25 @@ interface MountedTabLogic {
const generateTabId = (): string => crypto?.randomUUID?.()?.split('-')?.pop() || `${Date.now()}-${Math.random()}`
/**
- * Snapshot for JSON / structuredClone. Strips only `sceneParams` (deep/cyclic routing state); everything
- * else on `SceneTab` is kept so new fields are not forgotten. If a future field holds non-plain data,
- * omit it here explicitly.
+ * Homepage tab snapshot for JSON persistence: strips `sceneParams` (deep/cyclic routing state),
+ * ensures an id, and marks it pinned + inactive. Every other `SceneTab` field is kept so new fields
+ * aren't forgotten; if a future field holds non-plain data, omit it here explicitly.
*/
-const tabToPersistableSnapshot = (tab: SceneTab, overrides: Partial<SceneTab> = {}): SceneTab => {
+const tabToPersistableSnapshot = (tab: SceneTab): SceneTab => {
const { sceneParams: _omitSceneParams, ...rest } = tab
return {
...rest,
id: tab.id || generateTabId(),
- ...overrides,
+ pinned: true,
+ active: false,
}
}
-/** Plain tab snapshots for browser history (`structuredClone` in initKea); excludes `sceneParams`. */
-export const getTabsSnapshotForHistory = (tabs: SceneTab[]): SceneTab[] => tabs.map((t) => tabToPersistableSnapshot(t))
-
-const sanitizeTabForPersistence = (tab: SceneTab): SceneTab => {
- return tabToPersistableSnapshot(tab, { pinned: true, active: false })
-}
-
// Bootstrapped by Django into APP_CONTEXT so the configured homepage is known on first paint,
// before any async fetch — otherwise urlToAction runs with a null homepage and /home can't redirect.
const getBootstrappedHomepage = (): SceneTab | null => {
const homepage = getAppContext()?.homepage
- return homepage ? sanitizeTabForPersistence(homepage) : null
-}
-
-const partitionTabs = (tabs: SceneTab[]): { pinned: SceneTab[]; unpinned: SceneTab[] } => {
- const pinned: SceneTab[] = []
- const unpinned: SceneTab[] = []
- for (const tab of tabs) {
- if (tab.pinned) {
- pinned.push({ ...tab, pinned: true })
- } else {
- unpinned.push({ ...tab, pinned: false })
- }
- }
- return { pinned, unpinned }
-}
-
-const sortTabsPinnedFirst = (tabs: SceneTab[]): SceneTab[] => {
- const { pinned, unpinned } = partitionTabs(tabs)
- return [...pinned, ...unpinned]
-}
-
-const ensureActiveTab = (tabs: SceneTab[]): SceneTab[] => {
- if (!tabs.some((tab) => tab.active)) {
- if (tabs.length > 0) {
- tabs = tabs.map((tab, index) => ({ ...tab, active: index === 0 }))
- }
- }
- return tabs
+ return homepage ? tabToPersistableSnapshot(homepage) : null
}
const pathPrefixesOnboardingNotRequiredFor = [
@@ -155,17 +121,13 @@ const DelayedLoadingSpinner = (): JSX.Element => {
return <>{show ? <Spinner /> : null}</>
}
-const getMainContentElement = (): HTMLElement | null => document.getElementById('main-content')
-const restoreMainContentScrollTop = (scrollTop: number, onlyIfTabId?: string): void => {
- const element = getMainContentElement()
+const scrollMainContentToTop = (): void => {
+ const element = document.getElementById('main-content')
if (!element) {
return
}
- if (onlyIfTabId && sceneLogic.findMounted()?.values.activeTabId !== onlyIfTabId) {
- return
- }
window.requestAnimationFrame(() => {
- element.scrollTo({ top: scrollTop })
+ element.scrollTo({ top: 0 })
})
}
@@ -217,56 +179,39 @@ export const sceneLogic = kea<sceneLogicType>([
connect(() => ({
logic: [router, userLogic, preflightLogic],
- actions: [router, ['locationChanged', 'push'], inviteLogic, ['hideInviteModal']],
+ actions: [router, ['locationChanged'], inviteLogic, ['hideInviteModal']],
values: [billingLogic, ['billing'], organizationLogic, ['organizationBeingDeleted']],
})),
afterMount(({ cache }) => {
- cache.mountedTabLogic = {} as Record<string, MountedTabLogic>
- cache.lastTrackedSceneByTab = {} as Record<string, { sceneId?: string; sceneKey?: string }>
- cache.initialNavigationTabCreated = false
+ cache.mountedSceneLogic = null as MountedSceneLogic | null
+ cache.lastTrackedScene = null as { sceneId?: string; sceneKey?: string } | null
}),
actions({
/* 1. Prepares to open the scene, as the listener may override and do something
else (e.g. redirecting if unauthenticated), then calls (2) `loadScene`*/
- openScene: (
- sceneId: string,
- sceneKey: string | undefined,
- tabId: string,
- params: SceneParams,
- method: string
- ) => ({
+ openScene: (sceneId: string, sceneKey: string | undefined, params: SceneParams, method: string) => ({
sceneId,
sceneKey,
params,
method,
- tabId,
}),
// 2. Start loading the scene's Javascript and mount any logic, then calls (3) `setScene`
- loadScene: (
- sceneId: string,
- sceneKey: string | undefined,
- tabId: string,
- params: SceneParams,
- method: string
- ) => ({
+ loadScene: (sceneId: string, sceneKey: string | undefined, params: SceneParams, method: string) => ({
sceneId,
sceneKey,
params,
method,
- tabId,
}),
// 3. Set the `scene` reducer
setScene: (
sceneId: string,
sceneKey: string | undefined,
- tabId: string,
params: SceneParams,
scrollToTop: boolean = false,
exportedScene?: SceneExport
) => ({
sceneId,
sceneKey,
- tabId,
params,
scrollToTop,
exportedScene,
@@ -275,81 +220,37 @@ export const sceneLogic = kea<sceneLogicType>([
exportedScene: SceneExport,
sceneId: string,
sceneKey: string | undefined,
- tabId: string,
params: SceneParams
) => ({
exportedScene,
sceneId,
sceneKey,
- tabId,
params,
}),
reloadBrowserDueToImportError: true,
- newTab: (href?: string | null, options?: { activate?: boolean; skipNavigate?: boolean; id?: string }) => {
- const tabId = options?.id ?? generateTabId()
- return {
- href,
- options,
- tabId,
- }
- },
- setTabs: (tabs: SceneTab[]) => ({ tabs }),
- applyTitleAndIcon: (title: string, iconType: FileSystemIconType | 'loading' | 'blank') => ({
- title,
- iconType,
- }),
setHomepage: (tab: SceneTab | null) => ({ tab }),
- setTabScrollDepth: (tabId: string, scrollTop: number) => ({ tabId, scrollTop }),
}),
reducers({
- // We store all state in "tabs". This allows us to have multiple tabs open, each with its own scene and parameters.
- tabs: [
- [] as SceneTab[],
+ sceneId: [
+ null as string | null,
{
- setTabs: (_, { tabs }) => ensureActiveTab(sortTabsPinnedFirst(tabs)),
- newTab: (state, { href, options, tabId }) => {
- const activate = options?.activate ?? true
- const { pathname, search, hash } = combineUrl(href || '/new')
- const baseTabs = activate
- ? state.map((tab) => (tab.active ? { ...tab, active: false } : tab))
- : state
- const newTab: SceneTab = {
- id: tabId,
- active: activate,
- pathname: addProjectIdIfMissing(pathname),
- search,
- hash,
- title: 'Search',
- iconType: 'search',
- pinned: false,
- }
- return sortTabsPinnedFirst([...baseTabs, newTab])
- },
- setScene: (state, { sceneId, sceneKey, tabId, params }) => {
- return state.map((tab) =>
- tab.id === tabId
- ? {
- ...tab,
- sceneId: sceneId,
- sceneKey: sceneKey ?? undefined,
- sceneParams: params,
- }
- : tab
- )
- },
- setExportedScene: (state, { sceneId, sceneKey, tabId, params }) => {
- return state.map((tab) =>
- tab.id === tabId
- ? {
- ...tab,
- sceneId: sceneId,
- sceneKey: sceneKey,
- sceneParams: params,
- }
- : tab
- )
- },
+ setScene: (_, { sceneId }) => sceneId,
+ setExportedScene: (_, { sceneId }) => sceneId,
+ },
+ ],
+ sceneKey: [
+ null as string | null,
+ {
+ setScene: (_, { sceneKey }) => sceneKey ?? null,
+ setExportedScene: (_, { sceneKey }) => sceneKey ?? null,
+ },
+ ],
+ sceneParams: [
+ emptySceneParams as SceneParams,
+ {
+ setScene: (_, { params }) => params,
+ setExportedScene: (_, { params }) => params,
},
],
exportedScenes: [
@@ -378,35 +279,13 @@ export const sceneLogic = kea<sceneLogicType>([
lastSetScenePayload: [
{} as Record<string, any>,
{
- setScene: (_, { sceneId, sceneKey, tabId, params }) => ({
+ setScene: (_, { sceneId, sceneKey, params }) => ({
sceneId,
sceneKey,
- tabId,
params,
}),
},
],
- tabScrollDepths: [
- {} as Record<string, number>,
- {
- setTabScrollDepth: (state, { tabId, scrollTop }) => ({
- ...state,
- [tabId]: scrollTop,
- }),
- setTabs: (state, { tabs }) => {
- // remove those no longer present
- return tabs.reduce(
- (acc, tab) => {
- if (state[tab.id] !== undefined) {
- acc[tab.id] = state[tab.id]
- }
- return acc
- },
- {} as Record<string, number>
- )
- },
- },
- ],
}),
// Function form so the bootstrapped default is read at build time (per kea context),
// not once at module import — production sets APP_CONTEXT before the bundle loads either way.
@@ -414,23 +293,11 @@ export const sceneLogic = kea<sceneLogicType>([
homepage: [
getBootstrappedHomepage(),
{
- setHomepage: (_, { tab }) => (tab ? sanitizeTabForPersistence(tab) : null),
+ setHomepage: (_, { tab }) => (tab ? tabToPersistableSnapshot(tab) : null),
},
],
})),
selectors({
- activeTab: [
- (s) => [s.tabs],
- (tabs: SceneTab[]): SceneTab | null => {
- return tabs.find((tab) => tab.active) || tabs[0] || null
- },
- ],
- activeTabId: [
- (s) => [s.activeTab],
- (activeTab: SceneTab | null): string | null => (activeTab ? activeTab.id : null),
- ],
- sceneId: [(s) => [s.activeTab], (activeTab) => activeTab?.sceneId],
- sceneKey: [(s) => [s.activeTab], (activeTab) => activeTab?.sceneKey],
sceneConfig: [
(s) => [s.sceneId],
(sceneId: Scene): SceneConfig | null => {
@@ -439,12 +306,6 @@ export const sceneLogic = kea<sceneLogicType>([
},
{ resultEqualityCheck: equal },
],
- sceneParams: [
- (s) => [s.activeTab],
- (activeTab): SceneParams => {
- return activeTab?.sceneParams || { params: {}, searchParams: {}, hashParams: {} }
- },
- ],
activeSceneId: [
(s) => [s.sceneId, teamLogic.selectors.isCurrentTeamUnavailable],
(sceneId, isCurrentTeamUnavailable) => {
@@ -484,42 +345,39 @@ export const sceneLogic = kea<sceneLogicType>([
{ resultEqualityCheck: (a, b) => a === b },
],
activeLoadedScene: [
- (s) => [s.activeSceneId, s.activeExportedScene, s.sceneParams, s.activeTabId],
- (activeSceneId, activeExportedScene, sceneParams, activeTabId): LoadedScene | null => {
+ (s) => [s.activeSceneId, s.activeExportedScene, s.sceneParams],
+ (activeSceneId, activeExportedScene, sceneParams): LoadedScene | null => {
return {
...(activeExportedScene ?? { component: DelayedLoadingSpinner }),
id: activeSceneId ?? Scene.Error404,
- tabId: activeTabId ?? undefined,
sceneParams: sceneParams,
}
},
],
- activeSceneComponentParamsWithTabId: [
- (s) => [s.sceneParams, s.activeTabId],
- (sceneParams, activeTabId): Record<string, any> => {
+ activeSceneComponentParams: [
+ (s) => [s.sceneParams],
+ (sceneParams): Record<string, any> => {
return {
...sceneParams.params,
- tabId: activeTabId,
}
},
{ resultEqualityCheck: equal },
],
- activeSceneLogicPropsWithTabId: [
- (s) => [s.activeExportedScene, s.sceneParams, s.activeTabId],
- (activeExportedScene, sceneParams, activeTabId): Record<string, any> => {
+ activeSceneLogicProps: [
+ (s) => [s.activeExportedScene, s.sceneParams],
+ (activeExportedScene, sceneParams): Record<string, any> => {
return {
...activeExportedScene?.paramsToProps?.(sceneParams),
- tabId: activeTabId,
}
},
{ resultEqualityCheck: equal },
],
activeSceneLogic: [
- (s) => [s.activeExportedScene, s.activeSceneLogicPropsWithTabId],
- (activeExportedScene, activeSceneLogicPropsWithTabId): BuiltLogic | null => {
+ (s) => [s.activeExportedScene, s.activeSceneLogicProps],
+ (activeExportedScene, activeSceneLogicProps): BuiltLogic | null => {
if (activeExportedScene?.logic) {
try {
- return activeExportedScene.logic.build(activeSceneLogicPropsWithTabId)
+ return activeExportedScene.logic.build(activeSceneLogicProps)
} catch (e) {
// Building a keyed logic with undefined key (e.g. during a scene
// transition before paramsToProps has resolved) throws
@@ -541,19 +399,6 @@ export const sceneLogic = kea<sceneLogicType>([
searchParams: [(s) => [s.sceneParams], (sceneParams): Record<string, any> => sceneParams.searchParams || {}],
hashParams: [(s) => [s.sceneParams], (sceneParams): Record<string, any> => sceneParams.hashParams || {}],
- tabIds: [
- (s) => [s.tabs],
- (tabs: SceneTab[]): Record<string, boolean> => {
- return tabs.reduce(
- (acc, tab) => {
- acc[tab.id] = true
- return acc
- },
- {} as Record<string, boolean>
- )
- },
- ],
-
titleAndIcon: [
(s) => [
// We're effectively passing the selector through to the scene logic, and "recalculating"
@@ -591,12 +436,6 @@ export const sceneLogic = kea<sceneLogicType>([
(titleAndIcon) => titleAndIcon as { title: string; iconType: FileSystemIconType | 'loading' | 'blank' },
{ resultEqualityCheck: equal },
],
- firstTabIsActive: [
- (s) => [s.activeTabId, s.tabs],
- (activeTabId, tabs): boolean => {
- return activeTabId === tabs[0]?.id
- },
- ],
activeSceneProductKey: [
(s) => [s.activeExportedScene],
(activeExportedScene: SceneExport | null): ProductKey | null => {
@@ -605,108 +444,19 @@ export const sceneLogic = kea<sceneLogicType>([
],
}),
listeners(({ values, actions, cache, props, selectors }) => ({
- applyTitleAndIcon: ({ title, iconType }) => {
- if (!title || title === '...' || title === 'Loading...') {
- // When the tab is loading, don't flicker between the loaded title and the new one
- return
- }
- const activeIndex = values.tabs.findIndex((t) => t.active)
- if (activeIndex !== -1) {
- actions.setTabs(
- values.tabs.map((tab, i) => (i === activeIndex ? { ...tab, title, iconType, badge: false } : tab))
- )
- }
- if (!process?.env?.STORYBOOK) {
- // Persists the changed tab titles in location.history without a replace/push action.
- // Outside the action's event loop to avoid race conditions with subscribing.
- // Somehow it messes up Storybook, so disabled for it.
- window.setTimeout(() => router.actions.refreshRouterState(), 1)
- }
- },
- newTab: ({ href, options }) => {
- if (!(options?.skipNavigate ?? false)) {
- router.actions.push(href || urls.newTab())
- }
- },
setHomepage: ({ tab }) => {
if (isSharedView()) {
return
}
api.update('api/user_home_settings/@me/', {
- homepage: tab ? sanitizeTabForPersistence(tab) : null,
+ homepage: tab ? tabToPersistableSnapshot(tab) : null,
}).catch((error) => {
console.error('Failed to persist homepage', error)
})
},
- push: ({ url, hashInput, searchInput }) => {
- let { pathname, search, hash } = combineUrl(url, searchInput, hashInput)
+ locationChanged: ({ pathname, search, hash }) => {
pathname = addProjectIdIfMissing(pathname)
- const activeTabIndex = values.tabs.findIndex((tab) => tab.active)
- if (activeTabIndex !== -1) {
- const newTabs = values.tabs.map((tab, i) =>
- i === activeTabIndex
- ? { ...tab, active: true, pathname, search, hash }
- : tab.active
- ? {
- ...tab,
- active: false,
- }
- : tab
- )
- actions.setTabs(newTabs)
- } else {
- actions.setTabs([
- ...values.tabs,
- {
- id: generateTabId(),
- active: true,
- pathname,
- search,
- hash,
- title: 'Loading...',
- iconType: 'loading',
- pinned: false,
- },
- ])
- }
- },
- locationChanged: ({ pathname, search, hash, routerState, method }) => {
- pathname = addProjectIdIfMissing(pathname)
- if (routerState?.tabs && method === 'POP') {
- actions.setTabs(routerState.tabs)
- return
- }
- const activeTabIndex = values.tabs.findIndex((tab) => tab.active)
- if (activeTabIndex !== -1) {
- actions.setTabs(
- values.tabs.map((tab, i) =>
- i === activeTabIndex
- ? { ...tab, active: true, pathname, search, hash }
- : tab.active
- ? {
- ...tab,
- active: false,
- }
- : tab
- )
- )
- } else {
- actions.setTabs([
- ...values.tabs,
- {
- id: generateTabId(),
- active: true,
- pathname,
- search,
- hash,
- title: 'Loading...',
- iconType: 'loading',
- pinned: false,
- },
- ])
- }
-
// Remove trailing slash from the address bar. Route matching itself is handled
// upstream via `pathFromWindowToRoutes` in initKea.ts so the scene loads even
// before this replace runs.
@@ -715,11 +465,10 @@ export const sceneLogic = kea<sceneLogicType>([
router.actions.replace(stripped, search, hash)
}
},
- setScene: ({ tabId, sceneKey, sceneId, exportedScene, params, scrollToTop }, _, __, previousState) => {
+ setScene: ({ sceneKey, sceneId, exportedScene, params, scrollToTop }, _, __, previousState) => {
const {
sceneId: lastSceneId,
sceneKey: lastSceneKey,
- tabId: lastTabId,
params: lastParams,
} = selectors.lastSetScenePayload(previousState)
@@ -727,7 +476,6 @@ export const sceneLogic = kea<sceneLogicType>([
if (
lastSceneId !== sceneId ||
lastSceneKey !== sceneKey ||
- lastTabId !== tabId ||
!equal(lastParams.params, params.params) ||
JSON.stringify(lastParams.searchParams) !== JSON.stringify(params.searchParams) // `equal` crashes here
) {
@@ -735,27 +483,20 @@ export const sceneLogic = kea<sceneLogicType>([
posthog.capture('$pageview', productKey ? { product_key: productKey } : undefined)
}
- if (tabId !== lastTabId) {
- const scrollTop = values.tabScrollDepths[tabId] ?? 0
- window.setTimeout(() => restoreMainContentScrollTop(scrollTop, tabId), 1)
- window.setTimeout(() => restoreMainContentScrollTop(scrollTop, tabId), 10)
- window.setTimeout(() => restoreMainContentScrollTop(scrollTop, tabId), 100)
- window.setTimeout(() => restoreMainContentScrollTop(scrollTop, tabId), 300)
- } else {
- // if we clicked on a link, scroll to top
- const previousScene = selectors.sceneId(previousState)
- if (scrollToTop && sceneId !== previousScene) {
- restoreMainContentScrollTop(0)
- }
+ const previousScene = selectors.sceneId(previousState)
+ if (scrollToTop && sceneId !== previousScene) {
+ // Forward navigation (link click) scrolls to top. There is no back/forward scroll
+ // restoration: #main-content is an inner scroll container the browser won't restore.
+ scrollMainContentToTop()
}
let newLogicErrored = false
if (exportedScene?.logic) {
try {
- const builtLogicProps = { tabId, ...exportedScene?.paramsToProps?.(params) }
- const mountedLogic = cache.mountedTabLogic[tabId]
- // Re-activating an existing internal tab should not remount its scene logic.
- // Child logics attach to this scene root to keep draft state alive while inactive.
+ const builtLogicProps = { ...exportedScene?.paramsToProps?.(params) }
+ const mountedLogic = cache.mountedSceneLogic
+ // Re-applying the same scene should not remount its logic.
+ // Child logics attach to this scene root to keep draft state alive.
const canKeepMountedLogic =
mountedLogic?.logic === exportedScene.logic &&
mountedLogic?.sceneId === sceneId &&
@@ -769,12 +510,11 @@ export const sceneLogic = kea<sceneLogicType>([
try {
mountedLogic.unmount()
} catch (error) {
- console.error('Error unmounting previous tab logic:', error)
+ console.error('Error unmounting previous scene logic:', error)
}
- delete cache.mountedTabLogic[tabId]
}
- cache.mountedTabLogic[tabId] = {
+ cache.mountedSceneLogic = {
logic: exportedScene.logic,
logicProps: builtLogicProps,
sceneId,
@@ -786,34 +526,33 @@ export const sceneLogic = kea<sceneLogicType>([
// Scene logic builders (e.g. dashboardLogic.key()) can throw on malformed
// route params like `/dashboard/abc`. Capture so regressions surface, then
// route to Error404 so the user sees a proper 404 instead of a blank crash.
- posthog.captureException(error, { extra: { sceneId, sceneKey, tabId } })
+ posthog.captureException(error, { extra: { sceneId, sceneKey } })
newLogicErrored = true
}
} else {
- const mountedLogic = cache.mountedTabLogic[tabId]
+ const mountedLogic = cache.mountedSceneLogic
if (mountedLogic) {
try {
mountedLogic.unmount()
} catch (error) {
- console.error('Error unmounting previous tab logic:', error)
+ console.error('Error unmounting previous scene logic:', error)
}
- delete cache.mountedTabLogic[tabId]
+ cache.mountedSceneLogic = null
}
}
if (newLogicErrored) {
- actions.loadScene(Scene.Error404, undefined, tabId, emptySceneParams, 'REPLACE')
+ actions.loadScene(Scene.Error404, undefined, emptySceneParams, 'REPLACE')
return
}
- const trackingKey = tabId || '__default__'
- const lastTracked = cache.lastTrackedSceneByTab?.[trackingKey]
+ const lastTracked = cache.lastTrackedScene
if (!lastTracked || lastTracked.sceneId !== sceneId || lastTracked.sceneKey !== sceneKey) {
trackFileSystemLogView({ type: 'scene', ref: sceneId })
- cache.lastTrackedSceneByTab[trackingKey] = { sceneId, sceneKey }
+ cache.lastTrackedScene = { sceneId, sceneKey }
}
},
- openScene: ({ tabId, sceneId, sceneKey, params, method }) => {
+ openScene: ({ sceneId, sceneKey, params, method }) => {
const sceneConfig = sceneConfigurations[sceneId] || {}
const { user } = userLogic.values
const { preflight } = preflightLogic.values
@@ -909,12 +648,12 @@ export const sceneLogic = kea<sceneLogicType>([
}
}
- actions.loadScene(sceneId, sceneKey, tabId, params, method)
+ actions.loadScene(sceneId, sceneKey, params, method)
},
- loadScene: async ({ sceneId, sceneKey, tabId, params, method }, breakpoint) => {
+ loadScene: async ({ sceneId, sceneKey, params, method }, breakpoint) => {
const clickedLink = method === 'PUSH'
if (values.sceneId === sceneId && values.exportedScenes[sceneId]) {
- actions.setScene(sceneId, sceneKey, tabId, params, clickedLink, values.exportedScenes[sceneId])
+ actions.setScene(sceneId, sceneKey, params, clickedLink, values.exportedScenes[sceneId])
return
}
@@ -922,7 +661,6 @@ export const sceneLogic = kea<sceneLogicType>([
actions.setScene(
Scene.Error404,
undefined,
- tabId,
emptySceneParams,
clickedLink,
values.exportedScenes[sceneId]
@@ -935,7 +673,7 @@ export const sceneLogic = kea<sceneLogicType>([
if (!exportedScene) {
// if we can't load the scene in a second, show a spinner
- const timeout = window.setTimeout(() => actions.setScene(sceneId, sceneKey, tabId, params, true), 500)
+ const timeout = window.setTimeout(() => actions.setScene(sceneId, sceneKey, params, true), 500)
let importedScene
try {
window.ESBUILD_LOAD_CHUNKS?.(sceneId)
@@ -948,7 +686,7 @@ export const sceneLogic = kea<sceneLogicType>([
parseInt(String(values.lastReloadAt)) > new Date().valueOf() - 20000
) {
console.error('App assets regenerated. Showing error page.')
- actions.setScene(Scene.ErrorNetwork, undefined, tabId, emptySceneParams, clickedLink)
+ actions.setScene(Scene.ErrorNetwork, undefined, emptySceneParams, clickedLink)
} else {
console.error('App assets regenerated. Reloading this page.')
actions.reloadBrowserDueToImportError()
@@ -985,67 +723,16 @@ export const sceneLogic = kea<sceneLogicType>([
console.error('There are multiple exports for this scene. Showing 404 instead.')
}
}
- actions.setExportedScene(exportedScene, sceneId, sceneKey, tabId, params)
+ actions.setExportedScene(exportedScene, sceneId, sceneKey, params)
}
- actions.setScene(sceneId, sceneKey, tabId, params, clickedLink || wasNotLoaded, exportedScene)
+ actions.setScene(sceneId, sceneKey, params, clickedLink || wasNotLoaded, exportedScene)
},
reloadBrowserDueToImportError: () => {
window.location.reload()
},
})),
- // keep this above subscriptions
- afterMount(({ actions, cache, values }) => {
- // PostHog tabs were removed. Always start with a single fresh tab —
- // persisted tabs are surfaced once in the farewell modal and then cleared.
- cache.tabsLoaded = true
- if (values.tabs.length === 0) {
- const { currentLocation } = router.values
- actions.setTabs([
- {
- id: generateTabId(),
- active: true,
- pathname: currentLocation.pathname,
- search: currentLocation.search,
- hash: currentLocation.hash,
- title: 'Loading...',
- iconType: 'loading',
- pinned: false,
- },
- ])
- cache.initialNavigationTabCreated = true
- }
- }),
-
- urlToAction(({ actions, values, cache }) => {
- const ensureNavigationTabId = (): string => {
- const activeTab = values.activeTab
- const location = router.values.currentLocation
- const hrefString = location ? `${location.pathname}${location.search ?? ''}${location.hash ?? ''}` : ''
- const href = hrefString || undefined
-
- const createNavigationTab = (): string => {
- const tabId = generateTabId()
- actions.newTab(href, { id: tabId, skipNavigate: true, activate: true })
- cache.initialNavigationTabCreated = true
- return tabId
- }
-
- if (values.tabs.length === 0) {
- return createNavigationTab()
- }
-
- if (activeTab?.pinned && !cache.initialNavigationTabCreated) {
- return createNavigationTab()
- }
-
- if (!activeTab?.id) {
- return createNavigationTab()
- }
-
- return activeTab.id
- }
-
+ urlToAction(({ actions, values }) => {
const mapping: Record<
string,
(
@@ -1112,11 +799,9 @@ export const sceneLogic = kea<sceneLogicType>([
if (path === projectHomepagePath && redirectToConfiguredHomepage(searchParams)) {
return
}
- const tabId = ensureNavigationTabId()
actions.openScene(
scene,
sceneKey,
- tabId,
{
params,
searchParams,
@@ -1128,81 +813,9 @@ export const sceneLogic = kea<sceneLogicType>([
}
mapping['/*'] = (_, __, { method }) => {
- const tabId = ensureNavigationTabId()
- return actions.loadScene(Scene.Error404, undefined, tabId, emptySceneParams, method)
+ return actions.loadScene(Scene.Error404, undefined, emptySceneParams, method)
}
return mapping
}),
-
- subscriptions(({ actions, values, cache }) => {
- return {
- titleAndIcon: ({ title, iconType }) => {
- const activeIndex = values.tabs.findIndex((t) => t.active)
- if (activeIndex === -1) {
- const { currentLocation } = router.values
- actions.setTabs([
- {
- id: generateTabId(),
- active: true,
- pathname: currentLocation.pathname,
- search: currentLocation.search,
- hash: currentLocation.hash,
- title: title || 'Loading...',
- iconType,
- },
- ])
- if (!process?.env?.STORYBOOK) {
- window.setTimeout(() => router.actions.refreshRouterState(), 1)
- }
- } else {
- if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
- cache.pendingTitleAndIcon = { title, iconType }
- return
- }
- cache.pendingTitleAndIcon = null
- actions.applyTitleAndIcon(title, iconType)
- }
- },
- tabs: () => {
- cache.initialNavigationTabCreated =
- cache.initialNavigationTabCreated || values.tabs.some((tab) => !tab.pinned)
- const { tabIds } = values
- for (const id of Object.keys(cache.mountedTabLogic)) {
- if (!tabIds[id]) {
- const mountedLogic = cache.mountedTabLogic[id]
- if (mountedLogic) {
- try {
- mountedLogic.unmount()
- } catch (error) {
- console.error('Error unmounting tab logic:', error)
- }
- }
- delete cache.mountedTabLogic[id]
- if (cache.lastTrackedSceneByTab) {
- delete cache.lastTrackedSceneByTab[id]
- }
- }
- }
- },
- }
- }),
-
- afterMount(({ actions, cache }) => {
- cache.disposables.add(
- () => {
- const onVisibilityChange = (): void => {
- if (document.visibilityState === 'visible' && cache.pendingTitleAndIcon) {
- const { title, iconType } = cache.pendingTitleAndIcon
- cache.pendingTitleAndIcon = null
- actions.applyTitleAndIcon(title, iconType)
- }
- }
- document.addEventListener('visibilitychange', onVisibilityChange)
- return () => document.removeEventListener('visibilitychange', onVisibilityChange)
- },
- 'titleAndIconVisibilitySync',
- { pauseOnPageHidden: false }
- )
- }),
])
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 5de7e8d15be5..4f860095cca4 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -236,7 +236,6 @@ export interface SceneExport<T = SceneProps> {
// we use an untyped SceneProps to satisfy the types
export interface LoadedScene extends SceneExport<SceneProps> {
id: string
- tabId?: string
sceneParams: SceneParams
}
diff --git a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
index 5a49188c0c24..8d8e737f5bdf 100644
--- a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
+++ b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
@@ -40,9 +40,6 @@ describe('subscriptionsSceneLogic', () => {
})
initKeaTests()
sceneLogic({ scenes }).mount()
- sceneLogic.actions.setTabs([
- { id: '1', title: '...', pathname: '/', search: '', hash: '', active: true, iconType: 'blank' },
- ])
userLogic.mount()
userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
router.actions.push(urls.subscriptions())
diff --git a/products/endpoints/frontend/endpointSceneLogic.test.ts b/products/endpoints/frontend/endpointSceneLogic.test.ts
index 914ec16bd0eb..47f2e98cd264 100644
--- a/products/endpoints/frontend/endpointSceneLogic.test.ts
+++ b/products/endpoints/frontend/endpointSceneLogic.test.ts
@@ -45,7 +45,6 @@ jest.mock('scenes/sceneLogic', () => ({
isMounted: jest.fn(() => false),
findMounted: jest.fn(() => null),
},
- getTabsSnapshotForHistory: (tabs: any[]) => tabs.map(({ sceneParams: _omit, ...rest }) => ({ ...rest })),
}))
describe('endpointSceneLogic', () => {