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.

fix(tabs): persist mounted tab logics, fix new source scene (#57485)

Marius Andraeac4c0c548a5
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsx
index 7b137327746d..9ffb5fdc8a59 100644
--- a/frontend/src/scenes/sceneLogic.test.tsx
+++ b/frontend/src/scenes/sceneLogic.test.tsx
@@ -1,4 +1,4 @@
-import { kea, path } from 'kea'
+import { afterMount, beforeUnmount, kea, key, path, props } from 'kea'
import { router } from 'kea-router'
import { expectLogic, partial, truth } from 'kea-test-utils'
@@ -11,7 +11,7 @@ import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import { mergePinnedTabs, sceneLogic } from './sceneLogic'
-import type { logicType } from './sceneLogic.testType'
+import type { testLogicType, tabAwareTestLogicType } from './sceneLogic.testType'
jest.mock('lib/api', () => ({
__esModule: true,
@@ -22,8 +22,21 @@ jest.mock('lib/api', () => ({
}))
const Component = (): JSX.Element => <div />
-const logic = kea<logicType>([path(['scenes', 'sceneLogic', 'test'])])
-const sceneImport = (): any => ({ scene: { component: Component, logic: logic } })
+const testLogic = kea<testLogicType>([path(['scenes', 'sceneLogic', 'test'])])
+const sceneImport = (): any => ({ scene: { component: Component, logic: testLogic } })
+let mountedTabIds: (string | undefined)[] = []
+let unmountedTabIds: (string | undefined)[] = []
+const tabAwareTestLogic = kea<tabAwareTestLogicType>([
+ path(['scenes', 'sceneLogic', 'tabAwareTestLogic']),
+ props({} as { tabId?: string }),
+ key(({ tabId }) => tabId ?? 'missing'),
+ afterMount(({ props }) => {
+ mountedTabIds.push(props.tabId)
+ }),
+ beforeUnmount(({ props }) => {
+ unmountedTabIds.push(props.tabId)
+ }),
+])
const testScenes: Record<string, () => any> = {
[Scene.DataManagement]: sceneImport,
@@ -43,6 +56,8 @@ describe('sceneLogic', () => {
await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeamSuccess'])
featureFlagLogic.mount()
router.actions.push(urls.eventDefinitions())
+ mountedTabIds = []
+ unmountedTabIds = []
logic = sceneLogic.build({ scenes: testScenes })
// Simulate a fresh mount so that stored tabs are read from localStorage.
logic.cache.tabsLoaded = false
@@ -95,6 +110,48 @@ describe('sceneLogic', () => {
})
})
+ it('keeps tab scene logic mounted when switching away and back to the same tab', async () => {
+ const sceneParams = { params: {}, searchParams: {}, hashParams: {} }
+ const dataManagementScene = { component: Component, logic: tabAwareTestLogic }
+ const settingsScene = { component: Component, logic: testLogic }
+
+ logic.actions.setTabs([
+ {
+ id: 'tab-1',
+ active: true,
+ pathname: '/data-management/events',
+ search: '',
+ hash: '',
+ title: 'Data management',
+ iconType: 'blank',
+ sceneId: Scene.DataManagement,
+ },
+ {
+ id: 'tab-2',
+ active: false,
+ pathname: '/settings/user',
+ search: '',
+ hash: '',
+ title: 'Settings',
+ iconType: 'blank',
+ sceneId: Scene.Settings,
+ },
+ ])
+
+ logic.actions.setScene(Scene.DataManagement, undefined, 'tab-1', sceneParams, false, dataManagementScene)
+ expect(mountedTabIds.filter((tabId) => tabId === 'tab-1')).toHaveLength(1)
+
+ logic.actions.activateTab(logic.values.tabs[1])
+ logic.actions.setScene(Scene.Settings, undefined, 'tab-2', sceneParams, false, settingsScene)
+ expect(unmountedTabIds).not.toContain('tab-1')
+
+ logic.actions.activateTab(logic.values.tabs[0])
+ logic.actions.setScene(Scene.DataManagement, undefined, 'tab-1', sceneParams, false, dataManagementScene)
+
+ expect(mountedTabIds.filter((tabId) => tabId === 'tab-1')).toHaveLength(1)
+ expect(unmountedTabIds).not.toContain('tab-1')
+ })
+
it('can pin and unpin tabs, syncing storage', async () => {
const teamId = teamLogic.values.currentTeamId ?? 'null'
const pinnedStorageKey = `scene-tabs-pinned-state-${teamId}`
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index a79b1fc3fe3f..75adf94d23ff 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -68,6 +68,14 @@ export interface PersistedPinnedState {
homepage: SceneTab | null
}
+interface MountedTabLogic {
+ logic: SceneExport['logic']
+ logicProps: Record<string, any>
+ sceneId: string
+ sceneKey?: string
+ unmount: () => void
+}
+
const getStorageKey = (key: string): string => {
const teamId = getCurrentTeamIdOrNone() ?? teamLogic.findMounted()?.values.currentTeamId ?? 'null'
return `${key}-${teamId}`
@@ -332,7 +340,7 @@ export const sceneLogic = kea<sceneLogicType>([
values: [billingLogic, ['billing'], organizationLogic, ['organizationBeingDeleted']],
})),
afterMount(({ cache }) => {
- cache.mountedTabLogic = {} as Record<string, () => void>
+ cache.mountedTabLogic = {} as Record<string, MountedTabLogic>
cache.lastTrackedSceneByTab = {} as Record<string, { sceneId?: string; sceneKey?: string }>
cache.initialNavigationTabCreated = false
cache.lastRegisteredTabCount = null as number | null
@@ -1135,17 +1143,39 @@ export const sceneLogic = kea<sceneLogicType>([
}
}
- // Mount the new scene logic *before* unmounting the previous one. When the new
- // mount uses the same logic key (tab switch back to the same scene with the same
- // params), kea's reference count goes 1 → 2 → 1 and reducer state is preserved.
- // Unmount-then-mount would briefly drop the count to 0 and destroy the instance.
- let newUnmount: (() => void) | undefined
let newLogicErrored = false
if (exportedScene?.logic) {
try {
const builtLogicProps = { tabId, ...exportedScene?.paramsToProps?.(params) }
- const builtLogic = exportedScene?.logic(builtLogicProps)
- newUnmount = builtLogic.mount()
+ 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 canKeepMountedLogic =
+ mountedLogic?.logic === exportedScene.logic &&
+ mountedLogic?.sceneId === sceneId &&
+ mountedLogic.sceneKey === sceneKey &&
+ equal(mountedLogic.logicProps, builtLogicProps)
+
+ if (!canKeepMountedLogic) {
+ const builtLogic = exportedScene.logic(builtLogicProps)
+
+ if (mountedLogic) {
+ try {
+ mountedLogic.unmount()
+ } catch (error) {
+ console.error('Error unmounting previous tab logic:', error)
+ }
+ delete cache.mountedTabLogic[tabId]
+ }
+
+ cache.mountedTabLogic[tabId] = {
+ logic: exportedScene.logic,
+ logicProps: builtLogicProps,
+ sceneId,
+ sceneKey,
+ unmount: builtLogic.mount(),
+ }
+ }
} catch (error) {
// Scene logic builders (e.g. dashboardLogic.key()) can throw on malformed
// route params like `/dashboard/abc`. Capture so regressions surface, then
@@ -1153,19 +1183,15 @@ export const sceneLogic = kea<sceneLogicType>([
posthog.captureException(error, { extra: { sceneId, sceneKey, tabId } })
newLogicErrored = true
}
- }
-
- const previousUnmount = cache.mountedTabLogic[tabId]
- if (newUnmount) {
- cache.mountedTabLogic[tabId] = newUnmount
} else {
- delete cache.mountedTabLogic[tabId]
- }
- if (previousUnmount) {
- try {
- previousUnmount()
- } catch (error) {
- console.error('Error unmounting previous tab logic:', error)
+ const mountedLogic = cache.mountedTabLogic[tabId]
+ if (mountedLogic) {
+ try {
+ mountedLogic.unmount()
+ } catch (error) {
+ console.error('Error unmounting previous tab logic:', error)
+ }
+ delete cache.mountedTabLogic[tabId]
}
}
@@ -1606,10 +1632,10 @@ export const sceneLogic = kea<sceneLogicType>([
const { tabIds } = values
for (const id of Object.keys(cache.mountedTabLogic)) {
if (!tabIds[id]) {
- const unmount = cache.mountedTabLogic[id]
- if (unmount) {
+ const mountedLogic = cache.mountedTabLogic[id]
+ if (mountedLogic) {
try {
- unmount()
+ mountedLogic.unmount()
} catch (error) {
console.error('Error unmounting tab logic:', error)
}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
index c7e6c11742e9..d1738b3b8f32 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx
@@ -1,4 +1,4 @@
-import { BindLogic, useActions, useValues } from 'kea'
+import { BindLogic, connect, kea, path, props, selectors, useActions, useValues } from 'kea'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { IconCopy, IconQuestion } from '@posthog/icons'
@@ -17,15 +17,18 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { useFloatingContainer } from 'lib/hooks/useFloatingContainerContext'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { nonHogFunctionTemplatesLogic } from 'scenes/data-pipelines/utils/nonHogFunctionTemplatesLogic'
import { HogFunctionTemplateList } from 'scenes/hog-functions/list/HogFunctionTemplateList'
-import { SceneExport } from 'scenes/sceneTypes'
+import { Scene, SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ExternalDataSourceType, SourceConfig } from '~/queries/schema/schema-general'
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'
import SchemaForm from '../../shared/components/forms/SchemaForm'
import SourceForm, { SourceAccessMethodSelector } from '../../shared/components/forms/SourceForm'
@@ -36,8 +39,9 @@ import { SourceIcon } from '../../shared/components/SourceIcon'
import { availableSourcesLogic } from './availableSourcesLogic'
import { BillingLimitNotice } from './components/BillingLimitNotice'
import { SelfManagedSourceForm } from './components/SelfManagedSourceForm'
+import type { newSourceSceneLogicType } from './NewSourceSceneType'
import { selfManagedSourceLogic } from './selfManagedSourceLogic'
-import { sourceWizardLogic } from './sourceWizardLogic'
+import { type SourceWizardLogicProps, sourceWizardLogic } from './sourceWizardLogic'
export const getEffectiveAccessMethod = (
currentStep: number,
@@ -50,26 +54,83 @@ export const getEffectiveAccessMethod = (
return persistedAccessMethod
}
+export interface NewSourceSceneLogicProps {
+ tabId: string
+}
+
+export const newSourceSceneLogic = kea<newSourceSceneLogicType>([
+ path(['products', 'dataWarehouse', 'newSourceSceneLogic']),
+ props({} as NewSourceSceneLogicProps),
+ tabAwareScene(),
+ connect(() => ({
+ values: [availableSourcesLogic, ['availableSources', 'availableSourcesLoading']],
+ })),
+ selectors({
+ breadcrumbs: [
+ () => [],
+ (): Breadcrumb[] => [
+ {
+ key: Scene.Sources,
+ name: 'Sources',
+ path: urls.sources(),
+ iconType: 'data_pipeline',
+ },
+ {
+ key: Scene.DataWarehouseSourceNew,
+ name: 'New data warehouse source',
+ path: urls.dataWarehouseSourceNew(),
+ iconType: 'data_pipeline',
+ },
+ ],
+ ],
+ }),
+])
+
export const scene: SceneExport = {
component: NewSourceScene,
- // logic: sourceWizardLogic, // NOTE: We can't mount it here as it needs the availableSourcesLogic to be mounted first
+ logic: newSourceSceneLogic,
}
-export function NewSourceScene(): JSX.Element {
- const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)
+export function NewSourceScene({ tabId }: { tabId?: string }): JSX.Element {
+ if (!tabId) {
+ throw new Error('NewSourceScene rendered with no tabId')
+ }
+
+ const sceneRootLogic = newSourceSceneLogic({ tabId })
+ const { availableSources, availableSourcesLoading } = useValues(sceneRootLogic)
if (availableSourcesLoading || availableSources === null) {
return <LemonSkeleton />
}
+ return <MountedNewSourceScene availableSources={availableSources} tabId={tabId} />
+}
+
+function MountedNewSourceScene({
+ availableSources,
+ tabId,
+}: {
+ availableSources: Record<string, SourceConfig>
+ tabId: string
+}): JSX.Element {
+ const sourceWizardLogicProps = useMemo(() => ({ availableSources, tabId }), [availableSources, tabId])
+ const wizardLogic = sourceWizardLogic(sourceWizardLogicProps)
+ const sceneRootLogic = newSourceSceneLogic({ tabId })
+
+ useAttachedLogic(wizardLogic, sceneRootLogic)
+
return (
- <BindLogic logic={sourceWizardLogic} props={{ availableSources }}>
- <InternalNewSourceScene />
+ <BindLogic logic={sourceWizardLogic} props={sourceWizardLogicProps}>
+ <InternalNewSourceScene sourceWizardLogicProps={sourceWizardLogicProps} />
</BindLogic>
)
}
-function InternalNewSourceScene(): JSX.Element {
+function InternalNewSourceScene({
+ sourceWizardLogicProps,
+}: {
+ sourceWizardLogicProps: SourceWizardLogicProps
+}): JSX.Element {
const { closeWizard } = useActions(sourceWizardLogic)
return (
@@ -89,7 +150,7 @@ function InternalNewSourceScene(): JSX.Element {
</LemonButton>
}
/>
- <InternalSourcesWizard />
+ <InternalSourcesWizard sourceWizardLogicProps={sourceWizardLogicProps} />
</SceneContent>
)
}
@@ -99,6 +160,7 @@ interface NewSourcesWizardProps {
allowedSources?: ExternalDataSourceType[] // Filter to only show these source types
initialSource?: ExternalDataSourceType // Pre-select this source and start on step 2
hideBackButton?: boolean
+ sourceWizardLogicProps?: SourceWizardLogicProps
}
export function NewSourcesWizard(props: NewSourcesWizardProps): JSX.Element {
@@ -108,9 +170,14 @@ export function NewSourcesWizard(props: NewSourcesWizardProps): JSX.Element {
return <LemonSkeleton />
}
+ const sourceWizardLogicProps = {
+ onComplete: props.onComplete,
+ availableSources,
+ }
+
return (
- <BindLogic logic={sourceWizardLogic} props={{ onComplete: props.onComplete, availableSources }}>
- <InternalSourcesWizard {...props} />
+ <BindLogic logic={sourceWizardLogic} props={sourceWizardLogicProps}>
+ <InternalSourcesWizard {...props} sourceWizardLogicProps={sourceWizardLogicProps} />
</BindLogic>
)
}
@@ -250,11 +317,11 @@ function InternalSourcesWizard(props: NewSourcesWizardProps): JSX.Element {
{currentStep === 1 ? (
<FirstStep allowedSources={props.allowedSources} />
) : currentStep === 2 ? (
- <SecondStep />
+ <SecondStep sourceWizardLogicProps={props.sourceWizardLogicProps} />
) : currentStep === 3 ? (
<ThirdStep />
) : currentStep === 4 ? (
- <WebhookSetupStep />
+ <WebhookSetupStep sourceWizardLogicProps={props.sourceWizardLogicProps} />
) : currentStep === 5 ? (
<ProgressStep />
) : (
@@ -420,7 +487,7 @@ function FirstStep({ allowedSources }: NewSourcesWizardProps): JSX.Element {
)
}
-function SecondStep(): JSX.Element {
+function SecondStep({ sourceWizardLogicProps }: { sourceWizardLogicProps?: SourceWizardLogicProps }): JSX.Element {
const { selectedConnector, source, sourceConnectionDetails } = useValues(sourceWizardLogic)
const selectedAccessMethod = getEffectiveAccessMethod(
2,
@@ -461,6 +528,7 @@ function SecondStep(): JSX.Element {
sourceConfig={selectedConnector}
initialAccessMethod={sourceConnectionDetails?.access_method ?? source.access_method}
showAccessMethodSelector={false}
+ sourceWizardLogicProps={sourceWizardLogicProps}
/>
</div>
) : (
@@ -474,7 +542,11 @@ function ThirdStep(): JSX.Element {
return <SchemaForm />
}
-function WebhookSetupStep(): JSX.Element {
+function WebhookSetupStep({
+ sourceWizardLogicProps,
+}: {
+ sourceWizardLogicProps?: SourceWizardLogicProps
+}): JSX.Element {
const { webhookResult, webhookCreating, selectedConnector, databaseSchema } = useValues(sourceWizardLogic)
const { createWebhook } = useActions(sourceWizardLogic)
@@ -490,7 +562,7 @@ function WebhookSetupStep(): JSX.Element {
webhookResult={webhookResult}
webhookCreating={webhookCreating}
onCreateWebhook={createWebhook}
- formLogic={sourceWizardLogic}
+ formLogic={sourceWizardLogicProps ? sourceWizardLogic(sourceWizardLogicProps) : sourceWizardLogic}
formKey="webhookFieldInputs"
/>
)
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 3ca213d8575a..da5b7cef925e 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -1,7 +1,7 @@
-import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
-import { router, urlToAction } from 'kea-router'
+import { router } from 'kea-router'
import posthog from 'posthog-js'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
@@ -9,6 +9,7 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -210,6 +211,20 @@ export function mergeRestoredSourceFormValues(
}
}
+export function shouldHydrateSourceFromUrl(
+ currentStep: number,
+ selectedConnector: SourceConfig | null,
+ source: SourceConfig,
+ currentAccessMethod: 'warehouse' | 'direct',
+ urlAccessMethod: 'warehouse' | 'direct'
+): boolean {
+ return !(selectedConnector?.name === source.name && currentAccessMethod === urlAccessMethod && currentStep > 1)
+}
+
+function webhookResultHasNoPendingInputs(webhookResult: WebhookCreateResult | null | undefined): boolean {
+ return !!webhookResult?.success && (webhookResult.pending_inputs?.length ?? 0) === 0
+}
+
const manualLinkSourceMap: Record<ManualLinkSourceType, string> = {
aws: 'S3',
'google-cloud': 'Google Cloud Storage',
@@ -276,6 +291,7 @@ function syncExpandedDirectQuerySchemaKeys(
export interface SourceWizardLogicProps {
onComplete?: () => void
availableSources: Record<string, SourceConfig>
+ tabId?: string
/** When set, only these tables will be pre-selected and they cannot be deselected */
requiredTables?: string[]
}
@@ -283,6 +299,7 @@ export interface SourceWizardLogicProps {
export const sourceWizardLogic = kea<sourceWizardLogicType>([
path(['products', 'dataWarehouse', 'sourceWizardLogic']),
props({} as SourceWizardLogicProps),
+ key((props) => props.tabId ?? 'default'),
actions({
selectConnector: (connector: SourceConfig | null, accessMethod?: 'warehouse' | 'direct') => ({
connector,
@@ -697,7 +714,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
webhookStepComplete: [
(s) => [s.webhookResult, s.selectedConnector],
(webhookResult: WebhookCreateResult | null, selectedConnector: SourceConfig | null): boolean => {
- if (webhookResult?.success && (webhookResult.pending_inputs?.length ?? 0) === 0) {
+ if (webhookResultHasNoPendingInputs(webhookResult)) {
return true
}
if (!webhookResult) {
@@ -1157,7 +1174,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
}
if (values.currentStep === 4) {
- if (values.webhookResult?.success && (values.webhookResult.pending_inputs?.length ?? 0) === 0) {
+ if (webhookResultHasNoPendingInputs(values.webhookResult)) {
actions.onNext()
} else {
// Manual mode (or auto-create with pending inputs) — submit webhook form
@@ -1419,7 +1436,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
)
},
})),
- urlToAction(({ actions, values }) => {
+ tabAwareUrlToAction(({ actions, values }) => {
const handleUrlChange = (_: Record<string, string | undefined>, searchParams: Record<string, string>): void => {
const kind = searchParams.kind?.toLowerCase()
const accessMethod = searchParams.access_method === 'direct' ? 'direct' : 'warehouse'
@@ -1436,12 +1453,27 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
const manualSource = values.manualConnectors?.find((s) => s?.type?.toLowerCase() === kind)
if (manualSource) {
+ if (values.manualLinkingProvider === manualSource.type && values.currentStep > 1) {
+ return
+ }
actions.toggleManualLinkFormVisible(true)
actions.setManualLinkingProvider(manualSource.type)
return
}
if (source) {
+ if (
+ !shouldHydrateSourceFromUrl(
+ values.currentStep,
+ values.selectedConnector,
+ source,
+ values.source.access_method,
+ accessMethod
+ )
+ ) {
+ return
+ }
+
// selectConnector forwards accessMethod to `resetSourceForm`, which seeds the
// connector's defaults and restores any OAuth-saved form state — saved
// access_method wins over the URL one (the OAuth callback URL doesn't carry it).
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index 2ae76e3fc2b9..4fd54a7085e1 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -1,11 +1,99 @@
+import type { SourceConfig } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
import {
buildKeaFormDefaultFromSourceDetails,
getDatabaseSchemaPayload,
getErrorsForFields,
mergeRestoredSourceFormValues,
+ shouldHydrateSourceFromUrl,
+ sourceWizardLogic,
} from '../sourceWizardLogic'
describe('sourceWizardLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it('keeps wizard state isolated by tab id', () => {
+ const postgresSource = {
+ name: 'Postgres',
+ iconPath: '',
+ caption: null,
+ fields: [],
+ } as SourceConfig
+ const availableSources = { Postgres: postgresSource }
+ const firstTabLogic = sourceWizardLogic({ availableSources, tabId: 'first-tab' })
+ const secondTabLogic = sourceWizardLogic({ availableSources, tabId: 'second-tab' })
+ const unmountFirstTabLogic = firstTabLogic.mount()
+ const unmountSecondTabLogic = secondTabLogic.mount()
+
+ try {
+ firstTabLogic.actions.selectConnector(postgresSource)
+ firstTabLogic.actions.setStep(2)
+ firstTabLogic.actions.setSourceConnectionDetailsValue(['payload', 'host'], 'first.example.com')
+ secondTabLogic.actions.setStep(3)
+ secondTabLogic.actions.setSourceConnectionDetailsValue(['payload', 'host'], 'second.example.com')
+
+ expect(firstTabLogic.values.selectedConnector?.name).toEqual('Postgres')
+ expect(firstTabLogic.values.currentStep).toEqual(2)
+ expect(firstTabLogic.values.sourceConnectionDetails.payload.host).toEqual('first.example.com')
+ expect(secondTabLogic.values.selectedConnector).toBeNull()
+ expect(secondTabLogic.values.currentStep).toEqual(3)
+ expect(secondTabLogic.values.sourceConnectionDetails.payload.host).toEqual('second.example.com')
+ } finally {
+ unmountFirstTabLogic()
+ unmountSecondTabLogic()
+ }
+ })
+
+ it('preserves wizard state while attached to the mounted scene tab', () => {
+ const postgresSource = {
+ name: 'Postgres',
+ iconPath: '',
+ caption: null,
+ fields: [],
+ } as SourceConfig
+ const availableSources = { Postgres: postgresSource }
+ const attachedLogic = sourceWizardLogic({ availableSources, tabId: 'remounted-tab' })
+ const unmountAttached = attachedLogic.mount()
+ const firstMount = sourceWizardLogic({ availableSources, tabId: 'remounted-tab' })
+ const unmountFirst = firstMount.mount()
+
+ try {
+ firstMount.actions.selectConnector(postgresSource)
+ firstMount.actions.setStep(2)
+ firstMount.actions.setSourceConnectionDetailsValue(['payload', 'host'], 'kept.example.com')
+ unmountFirst()
+
+ const secondMount = sourceWizardLogic({ availableSources, tabId: 'remounted-tab' })
+ const unmountSecond = secondMount.mount()
+
+ try {
+ expect(secondMount.values.selectedConnector?.name).toEqual('Postgres')
+ expect(secondMount.values.currentStep).toEqual(2)
+ expect(secondMount.values.sourceConnectionDetails.payload.host).toEqual('kept.example.com')
+ } finally {
+ unmountSecond()
+ }
+ } finally {
+ unmountAttached()
+ }
+ })
+
+ it('does not hydrate the same source URL again after the wizard has started', () => {
+ const postgresSource = {
+ name: 'Postgres',
+ iconPath: '',
+ caption: null,
+ fields: [],
+ } as SourceConfig
+
+ expect(shouldHydrateSourceFromUrl(2, postgresSource, postgresSource, 'direct', 'direct')).toBe(false)
+ expect(shouldHydrateSourceFromUrl(1, postgresSource, postgresSource, 'direct', 'direct')).toBe(true)
+ expect(shouldHydrateSourceFromUrl(2, postgresSource, postgresSource, 'warehouse', 'direct')).toBe(true)
+ })
+
describe('getDatabaseSchemaPayload', () => {
it('includes the selected access method for schema discovery', () => {
expect(
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
index dfb8a4922acd..926a4a216069 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
@@ -25,7 +25,11 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'
import { availableSourcesLogic } from '../../../scenes/NewSourceScene/availableSourcesLogic'
-import { SSH_FIELD, sourceWizardLogic } from '../../../scenes/NewSourceScene/sourceWizardLogic'
+import {
+ SSH_FIELD,
+ type SourceWizardLogicProps,
+ sourceWizardLogic,
+} from '../../../scenes/NewSourceScene/sourceWizardLogic'
import { GitHubRepositorySelector } from './GitHubRepositorySelector'
import { SourceIntegrationChoice } from './IntegrationChoice'
import { parseConnectionStringForSource } from './parsers'
@@ -38,6 +42,7 @@ export interface SourceFormProps {
jobInputs?: Record<string, any>
initialAccessMethod?: 'warehouse' | 'direct'
setSourceConfigValue?: (key: FieldName, value: any) => void
+ sourceWizardLogicProps?: SourceWizardLogicProps
}
export function SourceAccessMethodSelector({
@@ -92,7 +97,8 @@ export const sourceFieldToElement = (
field: SourceFieldConfig,
sourceConfig: SourceConfig,
lastValue?: any,
- isUpdateMode?: boolean
+ isUpdateMode?: boolean,
+ setSourceConnectionDetailsValue?: (key: FieldName, value: any) => void
): JSX.Element => {
// It doesn't make sense for this to show on an update to an existing connection since we likely just want to change
// a field or two. There is also some divergence in creates vs. updates that make this a bit more complex to handle.
@@ -119,10 +125,14 @@ export const sourceFieldToElement = (
if (isValid) {
for (const { path, value } of fields) {
- sourceWizardLogic.actions.setSourceConnectionDetailsValue(
- ['payload', ...path],
- value
- )
+ if (setSourceConnectionDetailsValue) {
+ setSourceConnectionDetailsValue(['payload', ...path], value)
+ } else {
+ sourceWizardLogic.actions.setSourceConnectionDetailsValue(
+ ['payload', ...path],
+ value
+ )
+ }
}
}
}}
@@ -147,7 +157,13 @@ export const sourceFieldToElement = (
{isEnabled && (
<Group name={field.name}>
{field.fields.map((field) =>
- sourceFieldToElement(field, sourceConfig, lastValue?.[field.name])
+ sourceFieldToElement(
+ field,
+ sourceConfig,
+ lastValue?.[field.name],
+ isUpdateMode,
+ setSourceConnectionDetailsValue
+ )
)}
</Group>
)}
@@ -165,7 +181,13 @@ export const sourceFieldToElement = (
field.options
.find((n) => n.value === (value ?? field.defaultValue))
?.fields?.map((optionField) =>
- sourceFieldToElement(optionField, sourceConfig, lastValue?.[optionField.name])
+ sourceFieldToElement(
+ optionField,
+ sourceConfig,
+ lastValue?.[optionField.name],
+ isUpdateMode,
+ setSourceConnectionDetailsValue
+ )
)
return (
@@ -247,7 +269,8 @@ export const sourceFieldToElement = (
{ ...SSH_FIELD, name: field.name, label: field.label },
sourceConfig,
lastValue,
- isUpdateMode
+ isUpdateMode,
+ setSourceConnectionDetailsValue
)
}
@@ -601,7 +624,12 @@ function CDCConfigSection(): JSX.Element {
export default function SourceFormContainer(props: SourceFormProps): JSX.Element {
return (
- <Form logic={sourceWizardLogic} formKey="sourceConnectionDetails" enableFormOnSubmit>
+ <Form
+ logic={sourceWizardLogic}
+ props={props.sourceWizardLogicProps}
+ formKey="sourceConnectionDetails"
+ enableFormOnSubmit
+ >
<SourceFormComponent {...props} />
</Form>
)
@@ -615,9 +643,13 @@ export function SourceFormComponent({
jobInputs,
initialAccessMethod,
setSourceConfigValue,
+ sourceWizardLogicProps,
}: SourceFormProps): JSX.Element {
const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)
const { featureFlags } = useValues(featureFlagLogic)
+ const setSourceConnectionDetailsValue = sourceWizardLogicProps
+ ? sourceWizardLogic(sourceWizardLogicProps).actions.setSourceConnectionDetailsValue
+ : undefined
// Default showDescription to same as showPrefix for backward compatibility
const shouldShowDescription = showDescription ?? showPrefix
@@ -713,7 +745,15 @@ export function SourceFormComponent({
<Group name="payload">
{availableSources[sourceConfig.name].fields
.filter((field) => !(isPostgresDirectQuery && field.type === 'ssh-tunnel'))
- .map((field) => sourceFieldToElement(field, sourceConfig, jobInputs?.[field.name], isUpdateMode))}
+ .map((field) =>
+ sourceFieldToElement(
+ field,
+ sourceConfig,
+ jobInputs?.[field.name],
+ isUpdateMode,
+ setSourceConnectionDetailsValue
+ )
+ )}
</Group>
{!isUpdateMode &&
sourceConfig.name === 'Postgres' &&