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(sql-editor): preserve unrun query drafts across navigation (#109995)

Marius Andra6891b8f9d621
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index f36cd3debb11..39923aab7804 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -6,6 +6,12 @@ showTitle: true
This is an internal guide to setting up and working with the data warehouse for PostHog engineers. If you're a PostHog user, check out our [data warehouse docs](https://posthog.com/docs/data-warehouse) instead.
+## SQL editor drafts
+
+The SQL editor keeps unrun edits in browser storage, scoped to the user, project, and saved query. Explicit logout clears these drafts.
+An **Edited** label marks changes to a saved view or insight. **Discard changes** restores the saved copy already loaded in memory, then refreshes it from the server. The refresh preserves edits made after discarding.
+Insights can be saved or updated before running the SQL. Updating a view still requires a successful run of the current SQL so its result types match the saved query. **Continue in a notebook** is in the update button's dropdown for saved views and insights.
+
## Apple Ads in Marketing analytics
Marketing analytics support is controlled by the boolean organization flag `marketing-analytics-apple-ads` and is off by default.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3a1e63fce72e..634a3ef53059 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9366,6 +9366,14 @@ snapshots:
hash: v1.k794b7964.22840c30d80b9e1a3bd41d5a31af2ab81a54d9f90fb82d540fb9494b44cda050.oC_UUgUXZVqKMZ6LuInaQADAzqeWAvw2dZ8T5eENhIQ
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0
+ scenes-app-data-warehouse-sql-editor--edited-insight--dark:
+ hash: v1.k794b7964.94eba9d351ec4c6b649fc4b09f5d4a69fed2995448c0cc1dac5d63d3df0ad20c.U6hnpHxuk9RKFoPU8bc536a9dTuzluwHE0pF4J0nPYc
+ scenes-app-data-warehouse-sql-editor--edited-insight--light:
+ hash: v1.k794b7964.436ab0db5bbe37772a43ac31f23e24089833a5b90524a01059ea0bd56004786c.ztvECim8t2GfzyU0YLjaBdofiHEvt_GJMLPUlzQq3sY
+ scenes-app-data-warehouse-sql-editor--edited-view--dark:
+ hash: v1.k794b7964.aa0e1284b237dcedac1fe3c970e850375b9061d0c1d5b6900f9f1d5e4ba44e19.ixiPsYdLQ_wCEBrAjs99WDvEvvFxrSkXuUch-3fGWsA
+ scenes-app-data-warehouse-sql-editor--edited-view--light:
+ hash: v1.k794b7964.bfac44e47fb689373014487971c83c5602e18d413d1d82cfb4e3816620278373.Pu-novkcDf8tMMSmGhmQOWLz1_U5Piou5PXcppc6gHQ
scenes-app-data-warehouse-sql-editor--lazy-schema--dark:
hash: v1.k794b7964.8c150639468430cd106d26a5e3dde526b0d08bde8d07f37527113386e022d97b.xTBWyA6WWMQjVdb8wJvusy7_4oieQVnkHe2FCJxpQHg
scenes-app-data-warehouse-sql-editor--lazy-schema--light:
diff --git a/frontend/src/globals.d.ts b/frontend/src/globals.d.ts
index 7e797e56ff32..5d051b17b3db 100644
--- a/frontend/src/globals.d.ts
+++ b/frontend/src/globals.d.ts
@@ -51,7 +51,7 @@ declare global {
POSTHOG_USER_IDENTITY_WITH_FLAGS?: {
distinctID?: string
isIdentifiedID?: boolean
- featureFlags: Record<string, boolean | string>
+ featureFlags?: Record<string, boolean | string> | null
}
IMPERSONATED_SESSION?: boolean
POSTHOG_JS_UUID_VERSION?: string
diff --git a/frontend/src/layout/scenes/components/SceneTitleSection.tsx b/frontend/src/layout/scenes/components/SceneTitleSection.tsx
index 0fb8f609536c..f4a51b799b06 100644
--- a/frontend/src/layout/scenes/components/SceneTitleSection.tsx
+++ b/frontend/src/layout/scenes/components/SceneTitleSection.tsx
@@ -419,6 +419,7 @@ export function SceneTitleSection({
</>
}
/>
+ {forceEdit && nameSuffix}
</>
)}
</div>
diff --git a/frontend/src/lib/oauth/oauthLogic.ts b/frontend/src/lib/oauth/oauthLogic.ts
index bc42ff7ad7ca..0baede1acb3a 100644
--- a/frontend/src/lib/oauth/oauthLogic.ts
+++ b/frontend/src/lib/oauth/oauthLogic.ts
@@ -6,6 +6,8 @@ import { getRelativeNextPath } from 'lib/utils/url'
import { Region } from '~/types'
+import { clearSQLEditorDrafts } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
+
import { buildAuthorizeUrl, clearSession, exchangeCodeForToken, OAUTH_REGIONS, PendingAuth } from './oauthClient'
import { generateCodeVerifier, generateState } from './pkce'
@@ -115,6 +117,7 @@ export const oauthLogic = kea<oauthLogicType>([
}
},
logout: () => {
+ clearSQLEditorDrafts()
clearSession()
// Back to the local instance's login.
window.location.href = '/login'
diff --git a/frontend/src/loadPostHogJS.test.ts b/frontend/src/loadPostHogJS.test.ts
index db47a793f717..0264e8c6da8a 100644
--- a/frontend/src/loadPostHogJS.test.ts
+++ b/frontend/src/loadPostHogJS.test.ts
@@ -10,8 +10,8 @@ describe('loadPostHogJS', () => {
it.each<{
case: string
lastSeen: LastSeenFeatureFlags | null
- bootstrapFlags: LastSeenFeatureFlags['featureFlags']
- expected: LastSeenFeatureFlags['featureFlags']
+ bootstrapFlags: LastSeenFeatureFlags['featureFlags'] | null | undefined
+ expected: LastSeenFeatureFlags['featureFlags'] | undefined
}>([
{
case: 'fills flags the server left out, and server values win',
@@ -31,6 +31,18 @@ describe('loadPostHogJS', () => {
bootstrapFlags: {},
expected: {},
},
+ {
+ case: 'keeps missing bootstrap flags absent when the same user has cached flags',
+ lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },
+ bootstrapFlags: undefined,
+ expected: undefined,
+ },
+ {
+ case: 'ignores null bootstrap flags when the same user has cached flags',
+ lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },
+ bootstrapFlags: null,
+ expected: undefined,
+ },
{
case: 'keeps the server flags when nothing is cached',
lastSeen: null,
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index e985c05394b0..07e5659e0ea9 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -1,4 +1,4 @@
-import posthog, { BeforeSendFn, BrowserMetricsConfig, SessionRecordingOptions } from 'posthog-js'
+import posthog, { BeforeSendFn, BrowserMetricsConfig, PostHogConfig, SessionRecordingOptions } from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { isOAuthMode } from 'lib/oauth/oauthClient'
@@ -43,7 +43,10 @@ export function withLastSeenFeatureFlags(
bootstrap: UserIdentityWithFlags,
lastSeen: LastSeenFeatureFlags | null,
distinctId: string | undefined
-): UserIdentityWithFlags {
+): NonNullable<PostHogConfig['bootstrap']> {
+ if (!bootstrap.featureFlags) {
+ return { ...bootstrap, featureFlags: undefined }
+ }
// An empty bootstrap makes posthog-js use its own persisted flags, which are already complete.
if (!lastSeen || !distinctId || lastSeen.distinctId !== distinctId || !Object.keys(bootstrap.featureFlags).length) {
return bootstrap
diff --git a/frontend/src/scenes/authentication/account/AgenticAccountMismatch.tsx b/frontend/src/scenes/authentication/account/AgenticAccountMismatch.tsx
index 5e8f4e4f5a15..61c6a1a9e9a4 100644
--- a/frontend/src/scenes/authentication/account/AgenticAccountMismatch.tsx
+++ b/frontend/src/scenes/authentication/account/AgenticAccountMismatch.tsx
@@ -1,12 +1,12 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { LemonButton } from '@posthog/lemon-ui'
-import { getCookie } from 'lib/api'
import { BridgePage } from 'lib/components/BridgePage/BridgePage'
import { IconErrorOutline } from 'lib/lemon-ui/icons'
import { SceneExport } from 'scenes/sceneTypes'
+import { userLogic } from 'scenes/userLogic'
export const scene: SceneExport = {
component: AgenticAccountMismatch,
@@ -14,6 +14,7 @@ export const scene: SceneExport = {
export function AgenticAccountMismatch(): JSX.Element {
const { searchParams } = useValues(router)
+ const { logout } = useActions(userLogic)
const expectedEmail = typeof searchParams.expected_email === 'string' ? searchParams.expected_email : ''
const currentEmail =
@@ -23,30 +24,6 @@ export function AgenticAccountMismatch(): JSX.Element {
const nextUrl = state ? `/api/agentic/authorize?state=${encodeURIComponent(state)}` : null
- const submitLogout = (): void => {
- const form = document.createElement('form')
- form.method = 'POST'
- form.action = '/logout'
- form.style.display = 'none'
-
- const csrfInput = document.createElement('input')
- csrfInput.type = 'hidden'
- csrfInput.name = 'csrfmiddlewaretoken'
- csrfInput.value = getCookie('posthog_csrftoken') || ''
- form.appendChild(csrfInput)
-
- if (nextUrl) {
- const nextInput = document.createElement('input')
- nextInput.type = 'hidden'
- nextInput.name = 'next'
- nextInput.value = nextUrl
- form.appendChild(nextInput)
- }
-
- document.body.appendChild(form)
- form.submit()
- }
-
return (
<BridgePage view="agentic-account-mismatch">
<div className="text-center mb-4">
@@ -61,7 +38,7 @@ export function AgenticAccountMismatch(): JSX.Element {
<p>To continue, log out and sign in with the correct email.</p>
</div>
<div className="flex flex-col gap-2">
- <LemonButton fullWidth type="primary" center onClick={submitLogout}>
+ <LemonButton fullWidth type="primary" center onClick={() => logout(false, nextUrl ?? undefined)}>
{expectedEmail ? `Log out and continue as ${expectedEmail}` : 'Log out and continue'}
</LemonButton>
<LemonButton fullWidth type="secondary" center to="/">
diff --git a/frontend/src/scenes/authentication/vercel/VercelLinkError.tsx b/frontend/src/scenes/authentication/vercel/VercelLinkError.tsx
index 9ba47dfaf6b4..db7ade5df5eb 100644
--- a/frontend/src/scenes/authentication/vercel/VercelLinkError.tsx
+++ b/frontend/src/scenes/authentication/vercel/VercelLinkError.tsx
@@ -1,12 +1,12 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { LemonButton } from '@posthog/lemon-ui'
-import { getCookie } from 'lib/api'
import { BridgePage } from 'lib/components/BridgePage/BridgePage'
import { IconErrorOutline } from 'lib/lemon-ui/icons'
import { SceneExport } from 'scenes/sceneTypes'
+import { userLogic } from 'scenes/userLogic'
export const scene: SceneExport = {
component: VercelLinkError,
@@ -14,6 +14,7 @@ export const scene: SceneExport = {
export function VercelLinkError(): JSX.Element {
const { searchParams } = useValues(router)
+ const { logout } = useActions(userLogic)
const expectedEmail = searchParams.expected_email
const currentEmail = searchParams.current_email || 'your current account'
@@ -24,29 +25,6 @@ export function VercelLinkError(): JSX.Element {
code && state
? `/login/vercel?mode=sso&code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`
: null
- const submitLogout = (): void => {
- const form = document.createElement('form')
- form.method = 'POST'
- form.action = '/logout'
- form.style.display = 'none'
-
- const csrfInput = document.createElement('input')
- csrfInput.type = 'hidden'
- csrfInput.name = 'csrfmiddlewaretoken'
- csrfInput.value = getCookie('posthog_csrftoken') || ''
- form.appendChild(csrfInput)
-
- if (nextUrl) {
- const nextInput = document.createElement('input')
- nextInput.type = 'hidden'
- nextInput.name = 'next'
- nextInput.value = nextUrl
- form.appendChild(nextInput)
- }
-
- document.body.appendChild(form)
- form.submit()
- }
return (
<BridgePage view="vercel-link-error">
@@ -62,7 +40,7 @@ export function VercelLinkError(): JSX.Element {
<p>To complete Vercel SSO, please log out and sign in with the correct account.</p>
</div>
<div className="flex flex-col gap-2">
- <LemonButton fullWidth type="primary" center onClick={submitLogout}>
+ <LemonButton fullWidth type="primary" center onClick={() => logout(false, nextUrl ?? undefined)}>
{expectedEmail ? `Log out and continue with ${expectedEmail}` : 'Log out and continue'}
</LemonButton>
<LemonButton fullWidth type="secondary" center to="/">
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index be8a73f269b4..a6f3d361095b 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -4,7 +4,7 @@ import type { editor as importedEditor } from 'monaco-editor'
import { useEffect, useMemo, useRef, useState } from 'react'
import { IconBook, IconChevronDown, IconDownload, IconNotebook, IconX } from '@posthog/icons'
-import { LemonModal, Spinner } from '@posthog/lemon-ui'
+import { LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
@@ -463,6 +463,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
isSourceQueryLastRun,
isMultiQuery,
selectedConnectionId,
+ hasEditorChanges,
} = useValues(sqlEditorLogic)
const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)
const {
@@ -480,6 +481,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
reportAIQueryPromptOpen,
setEditingInsightName,
setEditingInsightDescription,
+ discardChanges,
} = useActions(sqlEditorLogic)
const { editingMetricName, metricUpdating } = useValues(sqlEditorLogic)
const { response, responseError, responseLoading } = useValues(dataNodeLogic)
@@ -582,6 +584,12 @@ function SQLEditorSceneTitle(): JSX.Element | null {
saveAsInsight()
}
+ const saveAsInsightDisabledReason = insightLoading
+ ? 'Loading insight...'
+ : !queryInput?.trim()
+ ? 'Write a SQL query before saving'
+ : undefined
+
const saveAsDisabledReason = useMemo(() => {
if (insightLoading) {
return 'Loading insight...'
@@ -661,6 +669,34 @@ function SQLEditorSceneTitle(): JSX.Element | null {
Continue in a notebook
</LemonButton>
)
+ const continueInNotebookMenuItem = {
+ label: 'Continue in a notebook',
+ icon: <IconNotebook />,
+ onClick: () => convertToNotebook(),
+ disabledReason: notebooksLoading
+ ? 'Creating notebook...'
+ : queryInput?.trim()
+ ? continueInNotebookAccessDisabledReason
+ : 'Write a SQL query before continuing',
+ 'data-attr': 'sql-editor-continue-in-notebook-button',
+ }
+ const discardChangesButton = (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => discardChanges()}
+ disabledReason={
+ insightLoading || updatingDataWarehouseSavedQuery
+ ? 'Wait for the current operation to finish'
+ : !hasEditorChanges
+ ? 'No changes to discard'
+ : undefined
+ }
+ data-attr="sql-editor-discard-changes"
+ >
+ Discard changes
+ </LemonButton>
+ )
return (
<>
@@ -669,6 +705,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
noBorder
noPadding
{...titleSectionProps}
+ nameSuffix={hasEditorChanges ? <LemonTag type="warning">Edited</LemonTag> : undefined}
{...(editingInsight && {
onNameChange: setEditingInsightName,
onDescriptionChange: setEditingInsightDescription,
@@ -702,7 +739,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
},
}}
actions={
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
{editingView ? (
<>
<LemonButton
@@ -713,6 +750,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
>
History
</LemonButton>
+ {discardChangesButton}
<AccessControlAction
resourceType={AccessControlResourceType.WarehouseObjects}
minAccessLevel={AccessControlLevel.Editor}
@@ -742,9 +780,10 @@ function SQLEditorSceneTitle(): JSX.Element | null {
overlay: (
<LemonMenuOverlay
items={[
+ continueInNotebookMenuItem,
{
label: 'Save as new insight...',
- disabledReason: saveAsDisabledReason,
+ disabledReason: saveAsInsightDisabledReason,
onClick: () => saveAsInsight(),
},
{
@@ -790,14 +829,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {
>
History
</LemonButton>
- {continueInNotebookButton}
+ {discardChangesButton}
<LemonButton
disabledReason={
- !isSourceQueryLastRun
- ? 'Run latest query changes before saving'
- : !updateInsightButtonEnabled
- ? 'No updates to save'
- : undefined
+ saveAsInsightDisabledReason ??
+ (!updateInsightButtonEnabled ? 'No updates to save' : undefined)
}
loading={insightLoading}
type="primary"
@@ -811,9 +847,10 @@ function SQLEditorSceneTitle(): JSX.Element | null {
overlay: (
<LemonMenuOverlay
items={[
+ continueInNotebookMenuItem,
{
label: 'Save as new insight...',
- disabledReason: saveAsDisabledReason,
+ disabledReason: saveAsInsightDisabledReason,
onClick: () => saveAsInsight(),
},
{
@@ -864,7 +901,9 @@ function SQLEditorSceneTitle(): JSX.Element | null {
items={secondarySaveMenuItems.map((item) => ({
...item,
disabledReason:
- saveAsDisabledReason ?? item.accessDisabledReason,
+ (item.action === 'insight'
+ ? saveAsInsightDisabledReason
+ : saveAsDisabledReason) ?? item.accessDisabledReason,
}))}
/>
),
@@ -890,7 +929,9 @@ function SQLEditorSceneTitle(): JSX.Element | null {
size="small"
onClick={onPrimarySaveClick}
disabledReason={
- saveAsDisabledReason ??
+ (saveAsMenuItems.primary.action === 'insight'
+ ? saveAsInsightDisabledReason
+ : saveAsDisabledReason) ??
(saveAsMenuItems.primary.action === 'endpoint'
? saveAsEndpointDisabledReason
: saveAsMenuItems.primary.action === 'view'
@@ -907,7 +948,9 @@ function SQLEditorSceneTitle(): JSX.Element | null {
items={secondarySaveMenuItems.map((item) => ({
...item,
disabledReason:
- saveAsDisabledReason ?? item.accessDisabledReason,
+ (item.action === 'insight'
+ ? saveAsInsightDisabledReason
+ : saveAsDisabledReason) ?? item.accessDisabledReason,
}))}
/>
),
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index c73d115721de..ed0f760e59f9 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -9,6 +9,8 @@ import { mswDecorator } from '~/mocks/browser'
import type { DataWarehouseSavedQuery } from '~/types'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { expect, userEvent, waitFor, within } from 'storybook/test'
+
import { QueryInfo } from './output-pane-tabs/QueryInfo'
import { sqlEditorLogic } from './sqlEditorLogic'
@@ -166,6 +168,100 @@ export const ManagedWarehouseConnection: Story = {
},
}
+const DISCARD_VIEW = {
+ id: 'discard-view',
+ name: 'Saved query',
+ query: { kind: 'HogQLQuery', query: 'SELECT 1' },
+ columns: [],
+ is_materialized: false,
+ user_access_level: AccessControlLevel.Editor,
+}
+const DISCARD_INSIGHT = {
+ id: 42,
+ short_id: 'discard1',
+ name: 'Saved insight',
+ description: '',
+ query: { kind: 'DataVisualizationNode', source: DISCARD_VIEW.query, display: 'Auto' },
+ saved: true,
+ dashboards: [],
+ user_access_level: AccessControlLevel.Editor,
+}
+
+const discardMocks = {
+ get: {
+ '/api/projects/:team_id/warehouse_saved_queries/': [200, { results: [DISCARD_VIEW] }],
+ '/api/:scope/:team_id/warehouse_saved_queries/:id/': [200, DISCARD_VIEW],
+ '/api/environments/:team_id/insights/': [200, { results: [DISCARD_INSIGHT] }],
+ '/api/projects/:team_id/warehouse_expressions/': [200, { results: [] }],
+ '/api/projects/:team_id/data_modeling_nodes/lineage/': [200, { nodes: [], edges: [] }],
+ '/api/projects/:team_id/query_tab_state/user/': [200, { state: {} }],
+ },
+}
+
+export const EditedView: Story = {
+ parameters: {
+ pageUrl: `${urls.sqlEditor({ view_id: DISCARD_VIEW.id })}#q=SELECT%202`,
+ msw: { mocks: discardMocks },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const discard = await canvas.findByRole('button', { name: 'Discard changes' }, { timeout: 15000 })
+ await waitFor(() =>
+ expect(canvas.getByRole('button', { name: 'Discard changes' })).toHaveAttribute('aria-disabled', 'false')
+ )
+ await expect(canvas.getByText('Edited')).toBeVisible()
+ await expect(canvas.getByRole('button', { name: 'Update view' })).toHaveAttribute('aria-disabled', 'true')
+ await userEvent.click(discard)
+ await waitFor(() =>
+ expect(canvas.getByRole('button', { name: 'Discard changes' })).toHaveAttribute('aria-disabled', 'true')
+ )
+ await expect(canvas.queryByText('Edited')).not.toBeInTheDocument()
+ await expect(canvas.getByRole('button', { name: 'Update view' })).toHaveAttribute('aria-disabled', 'true')
+ sqlEditorLogic({ tabId: 'default' }).actions.setQueryInput('SELECT 2')
+ await waitFor(() =>
+ expect(canvas.getByRole('button', { name: 'Discard changes' })).toHaveAttribute('aria-disabled', 'false')
+ )
+ await userEvent.click(canvas.getByRole('button', { name: 'Run' }))
+ await waitFor(
+ () => expect(canvas.getByRole('button', { name: 'Update view' })).toHaveAttribute('aria-disabled', 'false'),
+ {
+ timeout: 15000,
+ }
+ )
+ sqlEditorLogic({ tabId: 'default' }).actions.setQueryInput('SELECT 3')
+ await waitFor(() =>
+ expect(canvas.getByRole('button', { name: 'Update view' })).toHaveAttribute('aria-disabled', 'true')
+ )
+ },
+}
+
+export const EditedInsight: Story = {
+ parameters: {
+ pageUrl: `${urls.sqlEditor({ insightShortId: DISCARD_INSIGHT.short_id })}#q=SELECT%202`,
+ msw: { mocks: discardMocks },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await canvas.findByRole('button', { name: 'Discard changes' }, { timeout: 15000 })
+ await waitFor(() =>
+ expect(canvas.getByRole('button', { name: 'Discard changes' })).toHaveAttribute('aria-disabled', 'false')
+ )
+ await expect(canvas.getByText('Edited')).toBeVisible()
+ await expect(canvas.getByRole('button', { name: 'Update insight' })).toHaveAttribute('aria-disabled', 'false')
+ await userEvent.click(canvasElement.querySelector('[data-attr="sql-editor-save-options-button"]')!)
+ const menu = within(canvasElement.ownerDocument.body)
+ await expect(await menu.findByRole('menuitem', { name: 'Save as new insight...' })).toHaveAttribute(
+ 'aria-disabled',
+ 'false'
+ )
+ await expect(menu.getByRole('menuitem', { name: 'Save as new view...' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ )
+ await userEvent.keyboard('{Escape}')
+ },
+}
+
const SETTINGS_VIEW = {
id: 'settings-view',
name: 'revenue_summary',
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
index 31e75e6ac25c..08896913b98c 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
@@ -234,7 +234,8 @@ export interface editorSceneLogicMeta {
updateInsightButtonEnabled: (
sourceQuery: DataVisualizationNode,
activeTab: QueryTab | null,
- editingInsight: InsightModel<import('~/queries/schema/schema-general').Node<Record<string, any>>> | null
+ editingInsight: InsightModel<import('~/queries/schema/schema-general').Node<Record<string, any>>> | null,
+ queryInput: string | null
) => boolean
}
}
@@ -519,11 +520,12 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
},
],
updateInsightButtonEnabled: [
- (s) => [s.sourceQuery, s.activeTab, s.editingInsight],
+ (s) => [s.sourceQuery, s.activeTab, s.editingInsight, s.queryInput],
(
sourceQuery: DataVisualizationNode,
activeTab: null | import('./sqlEditorLogic').QueryTab,
- editingInsight: null | import('~/types').InsightModel
+ editingInsight: null | import('~/types').InsightModel,
+ queryInput: string | null
) => {
if (!editingInsight?.query) {
return false
@@ -531,7 +533,10 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
const updatedName = activeTab?.name !== editingInsight.name
const updatedDescription = (activeTab?.description ?? '') !== (editingInsight.description ?? '')
- const sourceQueryWithoutUndefinedAndNullKeys = removeUndefinedAndNull(sourceQuery)
+ const sourceQueryWithoutUndefinedAndNullKeys = removeUndefinedAndNull({
+ ...sourceQuery,
+ source: { ...sourceQuery.source, query: queryInput ?? sourceQuery.source.query },
+ })
// Normalize so DataTableNode-based insights don't look "changed" immediately after load.
const editingInsightQuery = toDataVisualizationNode(editingInsight.query) ?? editingInsight.query
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 6a731247650a..2183951675e4 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1,3 +1,5 @@
+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'
+
import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -30,6 +32,7 @@ import { initKeaTests } from '~/test/init'
import { ChartDisplayType, InsightShortId, InsightModel } from '~/types'
import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
import { BI_EDITOR_EVENTS } from './bi/biEditorAnalytics'
import { biEditorLogic } from './bi/biEditorLogic'
@@ -237,9 +240,13 @@ describe('sqlEditorLogic', () => {
let materializeEndpointMock: jest.Mock
// Lets a test control the server's current activity-log head returned by the saved-query GET.
let serverViewHistoryId: string | null = null
+ let serverViewQuery: string | undefined
beforeEach(async () => {
+ localStorage.clear()
+ sessionStorage.clear()
serverViewHistoryId = null
+ serverViewQuery = undefined
queryEndpointMock = jest.fn(() => [200, { tables: {}, joins: [] }])
materializeEndpointMock = jest.fn(() => [200, {}])
useMocks({
@@ -255,11 +262,15 @@ describe('sqlEditorLogic', () => {
return [200, { results: [] }]
},
'/api/projects/:team_id/warehouse_saved_queries/': { results: [MOCK_VIEW] },
- '/api/environments/:team_id/warehouse_saved_queries/:id/': ({ params }) => {
+ '/api/:scope/:team_id/warehouse_saved_queries/:id/': ({ params }) => {
if (params.id === MOCK_VIEW.id) {
return [
200,
- { ...MOCK_VIEW, latest_history_id: serverViewHistoryId ?? MOCK_VIEW.latest_history_id },
+ {
+ ...MOCK_VIEW,
+ latest_history_id: serverViewHistoryId ?? MOCK_VIEW.latest_history_id,
+ query: { ...MOCK_VIEW.query, query: serverViewQuery ?? MOCK_VIEW.query.query },
+ },
]
}
return [404]
@@ -319,6 +330,284 @@ describe('sqlEditorLogic', () => {
databaseLogic?.unmount()
})
+ describe('local draft recovery', () => {
+ const mountEditor = (): void => {
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ logic.mount()
+ }
+
+ it.each([
+ { searchParams: { open_view: MOCK_VIEW.id }, savedQuery: MOCK_VIEW.query.query },
+ {
+ searchParams: { open_insight: MOCK_INSIGHT_SHORT_ID },
+ savedQuery: MOCK_INSIGHT_QUERY.source.query,
+ },
+ ])('discards an unrun edit and does not recover it again (%j)', async ({ searchParams, savedQuery }) => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), searchParams))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ expect(logic.values.hasEditorChanges).toBe(false)
+
+ logic.actions.setQueryInput('SELECT unfinished')
+ expect(logic.values.hasEditorChanges).toBe(true)
+ expect(logic.values.isSourceQueryLastRun).toBe(false)
+ await expectLogic(logic, () => {
+ logic.actions.discardChanges()
+ expect(logic.values.queryInput).toEqual(savedQuery)
+ expect(logic.values.hasEditorChanges).toBe(false)
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: savedQuery, hasEditorChanges: false })
+ expect(router.values.hashParams.q).toEqual(savedQuery)
+ expect(logic.values.activeTab?.view?.id ?? logic.values.activeTab?.insight?.short_id).toEqual(
+ searchParams.open_view ?? searchParams.open_insight
+ )
+
+ logic.unmount()
+ initKeaTests()
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), searchParams))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: savedQuery, hasEditorChanges: false })
+ })
+
+ it.each([false, true])('refreshes a discarded draft without overwriting new edits (%s)', async (editAgain) => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.unmount()
+ initKeaTests()
+ mountEditor()
+ serverViewQuery = 'SELECT latest_saved'
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: 'SELECT unfinished', hasEditorChanges: true })
+
+ await expectLogic(logic, () => {
+ logic.actions.discardChanges()
+ expect(logic.values.queryInput).toEqual(MOCK_VIEW.query.query)
+ if (editAgain) {
+ logic.actions.setQueryInput('SELECT new_edit')
+ }
+ })
+ .toFinishAllListeners()
+ .toMatchValues({
+ queryInput: editAgain ? 'SELECT new_edit' : 'SELECT latest_saved',
+ hasEditorChanges: editAgain,
+ })
+ })
+
+ it.each([
+ ['new query', {}, 'SELECT unfinished'],
+ ['view', { open_view: MOCK_VIEW.id }, 'SELECT unfinished'],
+ ['insight', { open_insight: MOCK_INSIGHT_SHORT_ID }, 'SELECT unfinished'],
+ ['cleared view', { open_view: MOCK_VIEW.id }, ''],
+ ])('restores a %s after leaving before the URL debounce', async (_, searchParams, editedQuery) => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), searchParams))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+
+ logic.actions.setQueryInput(editedQuery)
+ logic.unmount()
+ initKeaTests()
+ mountEditor()
+
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), searchParams))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: editedQuery })
+ .toNotHaveDispatchedActions(['runQuery'])
+ })
+
+ it.each([{}, { open_insight: MOCK_INSIGHT_SHORT_ID }])(
+ 'restores the connection with an unrun query (%j)',
+ async (searchParams) => {
+ mountEditor()
+ await expectLogic(logic, () =>
+ router.actions.push(urls.sqlEditor(), searchParams, { q: 'SELECT 1', c: 'conn-123', raw: '1' })
+ )
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.unmount()
+ initKeaTests()
+ mountEditor()
+
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), searchParams))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({
+ queryInput: 'SELECT unfinished',
+ sourceQuery: partial({ source: partial({ connectionId: 'conn-123', sendRawQuery: true }) }),
+ })
+ }
+ )
+
+ it.each(['SELECT explicit', ''])('prefers explicit SQL over a local draft (%s)', async (query) => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), {}, { q: 'SELECT 1' }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.unmount()
+ initKeaTests()
+ mountEditor()
+
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), {}, { q: query }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: query })
+ })
+
+ it.each(['q', 'open_query'])('applies an explicit empty %s to an already open editor', async (param) => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), {}, { q: 'SELECT 1' }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ await expectLogic(logic, () =>
+ router.actions.push(
+ urls.sqlEditor(),
+ param === 'open_query' ? { open_query: '' } : {},
+ param === 'q' ? { q: '' } : {}
+ )
+ )
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: '' })
+ })
+
+ it.each(['reload', 'back'])(
+ 'restores the last keystroke on %s before the URL catches up',
+ async (navigation) => {
+ mountEditor()
+ const staleHash = { q: 'SELECT 1', c: 'conn-123', raw: '1' }
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), {}, staleHash))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.actions.setSourceQuery({
+ ...logic.values.sourceQuery,
+ source: { ...logic.values.sourceQuery.source, connectionId: undefined, sendRawQuery: undefined },
+ })
+ logic.unmount()
+ initKeaTests()
+ router.actions.push(urls.sqlEditor(), {}, staleHash)
+ const getEntriesByType = window.performance.getEntriesByType
+ window.performance.getEntriesByType = () => [{ type: navigation } as PerformanceNavigationTiming]
+ if (navigation === 'back') {
+ router.actions.locationChanged({
+ ...router.values.location,
+ searchParams: {},
+ hashParams: staleHash,
+ url: urls.sqlEditor(),
+ method: 'POP',
+ })
+ }
+ try {
+ mountEditor()
+ await expectLogic(logic).toDispatchActions(['createTab', 'setQueryInput']).toFinishAllListeners()
+ expect(logic.values.queryInput).toEqual('SELECT unfinished')
+ expect(logic.values.sourceQuery.source.connectionId).toBeUndefined()
+ expect(logic.values.sourceQuery.source.sendRawQuery).toBeUndefined()
+ } finally {
+ window.performance.getEntriesByType = getEntriesByType
+ }
+ }
+ )
+
+ it('does not replace this tab with another browser tab’s draft on reload', async () => {
+ sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, MOCK_DEFAULT_TEAM.id, 'new')?.set({ q: 'SELECT other_tab' })
+ sessionStorage.clear()
+ router.actions.push(urls.sqlEditor(), {}, { q: 'SELECT this_tab' })
+ const getEntriesByType = window.performance.getEntriesByType
+ window.performance.getEntriesByType = () => [{ type: 'reload' } as PerformanceNavigationTiming]
+ try {
+ mountEditor()
+ await expectLogic(logic).toDispatchActions(['createTab', 'setQueryInput']).toFinishAllListeners()
+ expect(logic.values.queryInput).toEqual('SELECT this_tab')
+ } finally {
+ window.performance.getEntriesByType = getEntriesByType
+ }
+ })
+
+ it('preserves the view revision the recovered edits were based on', async () => {
+ serverViewHistoryId = 'original-revision'
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.unmount()
+ initKeaTests()
+ serverViewHistoryId = 'new-revision'
+ serverViewQuery = 'SELECT another_edit'
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ expect(logic.values.inProgressViewEdits[MOCK_VIEW.id]).toEqual('original-revision')
+ expect(
+ sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, MOCK_DEFAULT_TEAM.id, `view:${MOCK_VIEW.id}`)?.get()
+ ).toMatchObject({ edited_history_id: 'original-revision' })
+ await expectLogic(logic, () =>
+ logic.actions.updateView({
+ id: MOCK_VIEW.id,
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT unfinished' },
+ edited_history_id: 'original-revision',
+ types: [],
+ })
+ )
+ .toDispatchActions(['_setSuggestionPayload'])
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions([
+ 'updateViewSuccess',
+ dataWarehouseViewsLogic.actionTypes.updateDataWarehouseSavedQuery,
+ ])
+ expect(logic.values.suggestionPayload).toMatchObject({
+ originalValue: 'SELECT another_edit',
+ suggestedValue: 'SELECT unfinished',
+ })
+ })
+
+ it('clears the local draft after reverting to the saved query', async () => {
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ logic.actions.setQueryInput('SELECT unfinished')
+ logic.actions.setQueryInput(MOCK_VIEW.query.query)
+ expect(
+ sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, MOCK_DEFAULT_TEAM.id, `view:${MOCK_VIEW.id}`)?.get()
+ ).toBeNull()
+ })
+
+ it('does not save embedded editors as the standalone draft', () => {
+ logic = sqlEditorLogic({ tabId: TAB_ID, mode: SQLEditorMode.Embedded, monaco: createMockMonaco() })
+ logic.mount()
+ logic.actions.createTab('SELECT embedded')
+ logic.actions.setQueryInput('SELECT unfinished')
+ expect(sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, MOCK_DEFAULT_TEAM.id, 'new')?.get()).toBeNull()
+ })
+
+ it.each([
+ ['other user', 'other-user', MOCK_DEFAULT_TEAM.id],
+ ['other project', MOCK_DEFAULT_USER.uuid, 99],
+ ])('does not restore drafts belonging to an %s', async (_, userUuid, teamId) => {
+ sqlEditorDraftStorage(userUuid, teamId, 'new')?.set({ q: 'SELECT private_draft' })
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor()))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+ .toMatchValues({ queryInput: '' })
+ })
+ })
+
describe('index quickfix', () => {
// A Monaco model and editor that apply an edit to real text, so a test asserts the resulting
// SQL rather than the range that produced it. Offsets are UTF-16, as Monaco's are.
@@ -627,7 +916,7 @@ describe('sqlEditorLogic', () => {
logic.actions.createTab()
await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
- expect(logic.values.queryInput).toBeNull()
+ expect(logic.values.queryInput).toEqual('')
logic.actions.setSourceQuery({
...logic.values.sourceQuery,
@@ -1041,7 +1330,7 @@ describe('sqlEditorLogic', () => {
expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(true)
})
- it('enables Update insight as soon as sourceQuery diverges from the saved insight, even when dataVisualizationLogic mirror lags behind', async () => {
+ it('enables Update insight for unrun SQL edits, even when the visualization still shows the saved query', async () => {
logic = sqlEditorLogic({
tabId: TAB_ID,
monaco: createMockMonaco(),
@@ -1071,6 +1360,10 @@ describe('sqlEditorLogic', () => {
expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(false)
+ logic.actions.setQueryInput('SELECT count() FROM events WHERE event = $pageview')
+ expect(editorRootLogic.values.updateInsightButtonEnabled).toEqual(true)
+ expect(logic.values.isSourceQueryLastRun).toEqual(false)
+
// Simulate runQuery firing setSourceQuery with a different SQL string.
// dataVisualizationLogic.values.query still mirrors the OLD query at this point —
// in production it only catches up after React re-renders and propsChanged fires.
@@ -2611,16 +2904,19 @@ describe('sqlEditorLogic', () => {
})
logic = sqlEditorLogic({
tabId: TAB_ID,
- monaco: createMockMonaco(),
- editor: createMockEditor(),
})
logic.mount()
- router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', c: connection.id })
+ router.actions.push(urls.sqlEditor({ query, connectionId: connection.id }))
- await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])
await expectLogic(logic).toDispatchActions(['setSendRawQuery'])
+ // Connection options can arrive before Monaco, while the URL query is still pending.
+ expect(router.values.searchParams.open_query).toEqual(query)
+ sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab']).toFinishAllListeners()
+
+ expect(logic.values.queryInput).toEqual(query)
expect(logic.values.selectedConnectionSupportsHogQL).toEqual(true)
expect(logic.values.sourceQuery.source.sendRawQuery).toEqual(true)
expect(logic.values.sendRawQueryEnabled).toEqual(true)
@@ -3139,12 +3435,17 @@ describe('sqlEditorLogic', () => {
logic.actions.setDashboardId(dashboardId)
}
+ logic.actions.setQueryInput('SELECT 42 AS unrun_edit')
logic.actions.saveAsInsightSubmit('My SQL insight')
await expectLogic(logic).toFinishAllListeners()
expect(createSpy).toHaveBeenCalledTimes(1)
const createPayload = createSpy.mock.calls[0][0]
- expect(createPayload).toMatchObject({ name: 'My SQL insight', saved: true })
+ expect(createPayload).toMatchObject({
+ name: 'My SQL insight',
+ saved: true,
+ query: { source: { query: 'SELECT 42 AS unrun_edit' } },
+ })
if (dashboardId !== null) {
expect(createPayload.dashboards).toEqual([dashboardId])
} else {
@@ -3196,11 +3497,13 @@ describe('sqlEditorLogic', () => {
.toMatchValues({ editingInsight: partial({ short_id: MOCK_INSIGHT_SHORT_ID }) })
logic.actions.setDashboardId(DASHBOARD_ID)
+ logic.actions.setQueryInput('SELECT 42 AS unrun_edit')
logic.actions.updateInsight()
await expectLogic(logic).toFinishAllListeners()
expect(updateSpy).toHaveBeenCalledTimes(1)
const [, updatePayload] = updateSpy.mock.calls[0]
+ expect(updatePayload.query).toMatchObject({ source: { query: 'SELECT 42 AS unrun_edit' } })
// Order-independent: only the set of linked dashboards matters.
expect([...(updatePayload.dashboards ?? [])].sort()).toEqual([...expected].sort())
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 6c6dd6342877..41e11e80355b 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -45,7 +45,8 @@ import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
import { findQueryAtCursor, type QueryRange, splitQueries } from 'lib/monaco/multiQueryUtils'
import { characterOffsetToUtf16 } from 'lib/monaco/offsets'
-import { objectsEqual } from 'lib/utils/objects'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { objectsEqual, removeUndefinedAndNull } from 'lib/utils/objects'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { slugify } from 'lib/utils/strings'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -57,6 +58,7 @@ import {
} from 'scenes/data-warehouse/editor/sql-utils'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightsApi } from 'scenes/insights/utils/api'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -102,6 +104,8 @@ import {
dataCatalogMetricsRetrieve,
} from 'products/data_catalog/frontend/generated/api'
import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+import { warehouseSavedQueriesRetrieve } from 'products/data_warehouse/frontend/generated/api'
+import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
import { validateEndpointName } from 'products/endpoints/frontend/common'
import type { ExternalDataSourceConnectionOptionApi } from '../../../../../products/warehouse_sources/frontend/generated/api.schemas'
@@ -437,7 +441,8 @@ export function toDataVisualizationNode(
export function getCurrentVisualizationQuery(
dataLogicKey: string,
- fallbackQuery: DataVisualizationNode
+ fallbackQuery: DataVisualizationNode,
+ queryInput: string | null
): DataVisualizationNode {
// This reads the mounted visualization state so save/update actions can include in-flight
// axis/display edits. Those edits are also synced back through props.setQuery -> setSourceQuery,
@@ -446,7 +451,11 @@ export function getCurrentVisualizationQuery(
key: dataLogicKey,
} as any)
- return mountedVisualizationLogic?.values.query ?? fallbackQuery
+ const visualizationQuery = mountedVisualizationLogic?.values.query ?? fallbackQuery
+ return {
+ ...visualizationQuery,
+ source: { ...visualizationQuery.source, query: queryInput ?? visualizationQuery.source.query },
+ }
}
function getTabHash(values: sqlEditorLogicType['values']): Record<string, any> {
@@ -605,6 +614,7 @@ export interface sqlEditorLogicValues {
filtersPlaceholderBindings: string[] | null
finishedLoading: boolean
fixErrorsError: string | null
+ hasEditorChanges: boolean
hasFiltersPlaceholder: boolean
hasQueryInput: boolean
hoveredNode: string | null
@@ -844,6 +854,9 @@ export interface sqlEditorLogicActions {
deleteInProgressViewEdit: (viewId: string) => {
viewId: string
}
+ discardChanges: () => {
+ value: true
+ }
editInsight: (
query: string,
insight: InsightModel,
@@ -1170,6 +1183,11 @@ export interface sqlEditorLogicMeta {
editingView: (activeTab: QueryTab | null) => DataWarehouseSavedQuery | undefined
editingMetricName: (activeTab: QueryTab | null) => string | null
changesToSave: (editingView: DataWarehouseSavedQuery | undefined, queryInput: string | null) => boolean
+ hasEditorChanges: (
+ activeTab: QueryTab | null,
+ queryInput: string | null,
+ sourceQuery: DataVisualizationNode
+ ) => boolean
exportContext: (sourceQuery: DataVisualizationNode) => ExportContext
selectedConnectionId: (sourceQuery: DataVisualizationNode) => string | undefined
selectedDirectSource: (
@@ -1295,6 +1313,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
tablesAndColumns,
}),
setQueryInput: (queryInput: string | null) => ({ queryInput }),
+ discardChanges: true,
setActiveQueryText: (activeQueryText: string | null, activeQueryOffset: number) => ({
activeQueryText,
activeQueryOffset,
@@ -1775,6 +1794,40 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
],
})),
listeners(({ values, props, actions, asyncActions, cache }) => {
+ const persistEditorDraft = (): void => {
+ if (
+ values.isEmbeddedMode ||
+ values.queryInput === null ||
+ !values.activeTab ||
+ values.activeTab.metricName
+ ) {
+ return
+ }
+ const { draft, view, insight } = values.activeTab
+ const target = draft
+ ? `draft:${draft.id}`
+ : view
+ ? `view:${view.id}`
+ : insight
+ ? `insight:${insight.short_id}`
+ : 'new'
+ const storage = sqlEditorDraftStorage(values.user?.uuid, teamLogic.values.currentTeamId, target)
+ const savedQuery =
+ draft?.query.query ?? view?.query?.query ?? toDataVisualizationNode(insight?.query)?.source.query
+ if (savedQuery !== undefined && values.queryInput === savedQuery) {
+ storage?.set(null)
+ return
+ }
+ storage?.set({
+ ...getTabHash(values),
+ q: values.queryInput,
+ baseline_query: view?.query?.query,
+ edited_history_id: view
+ ? (values.inProgressViewEdits[view.id] ?? view.latest_history_id ?? undefined)
+ : undefined,
+ })
+ }
+
// Extract cursor offset and selection text from monaco and defer to the pure helper.
const resolveSaveCandidates = (): ReturnType<typeof resolveSaveCandidatesPure> => {
const fullText = values.queryInput ?? ''
@@ -1978,7 +2031,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
editInsight: ({ query, insight, biEditorState }) => {
actions.createTab(query, undefined, insight, undefined, undefined, biEditorState)
},
- createTab: async ({ query = '', view, insight, draft, metricName, biEditorState }) => {
+ createTab: async ({ query, view, insight, draft, metricName, biEditorState }) => {
// Use tabId to ensure each browser tab has its own unique Monaco model
const tabName = insight ? (insight.name ?? NEW_QUERY) : draft?.name || view?.name || NEW_QUERY
const tabDescription = insight?.description ?? ''
@@ -1991,7 +2044,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const uri = props.monaco.Uri.parse(tabModelPath(props.tabId))
let model = props.monaco.editor.getModel(uri)
if (!model) {
- model = props.monaco.editor.createModel(query, 'hogQL', uri)
+ model = props.monaco.editor.createModel(query ?? '', 'hogQL', uri)
cache.createdModels = cache.createdModels || []
cache.createdModels.push(model)
if (isEditorAlive(props.editor)) {
@@ -2023,7 +2076,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
if (insightVisualizationQuery) {
actions.setLastRunQuery(insightVisualizationQuery)
}
- if (query) {
+ if (query !== undefined) {
actions.setQueryInput(query)
} else if (draft) {
actions.setQueryInput(draft.query.query)
@@ -2055,6 +2108,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
sourceQuery: nextSourceQuery,
})
}
+ persistEditorDraft()
},
setSendRawQuery: ({ sendRawQuery }) => {
const currentSourceQuery = values.sourceQuery
@@ -2163,6 +2217,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
}
+ // Write before the debounce so navigation or reload cannot drop the last edit.
+ persistEditorDraft()
await breakpoint(500)
actions.syncUrlWithQuery()
@@ -2558,7 +2614,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
},
saveAsInsight: async () => {
- const currentVisualizationQuery = getCurrentVisualizationQuery(values.dataLogicKey, values.sourceQuery)
+ const currentVisualizationQuery = getCurrentVisualizationQuery(
+ values.dataLogicKey,
+ values.sourceQuery,
+ values.queryInput
+ )
const effectiveVisualizationType = dataVisualizationLogic.findMounted({
key: values.dataLogicKey,
query: currentVisualizationQuery,
@@ -2626,7 +2686,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
},
saveAsInsightSubmit: async ({ name, queryOverride }) => {
const biEditorState = getActiveBIEditorState()
- const currentVisualizationQuery = getCurrentVisualizationQuery(values.dataLogicKey, values.sourceQuery)
+ const currentVisualizationQuery = getCurrentVisualizationQuery(
+ values.dataLogicKey,
+ values.sourceQuery,
+ values.queryInput
+ )
const effectiveVisualizationType = dataVisualizationLogic.findMounted({
key: values.dataLogicKey,
query: currentVisualizationQuery,
@@ -2926,7 +2990,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
},
updateInsight: async () => {
- if (!values.editingInsight) {
+ if (!values.editingInsight || values.insightLoading) {
return
}
@@ -2935,7 +2999,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const insightName = values.activeTab?.name
const insightDescription = values.activeTab?.description
- const currentVisualizationQuery = getCurrentVisualizationQuery(values.dataLogicKey, values.sourceQuery)
+ const currentVisualizationQuery = getCurrentVisualizationQuery(
+ values.dataLogicKey,
+ values.sourceQuery,
+ values.queryInput
+ )
const insightRequest: Partial<InsightModel> = {
name: insightName ?? values.editingInsight.name,
@@ -2974,6 +3042,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
...values.activeTab,
insight: savedInsight,
})
+ persistEditorDraft()
}
insightsModel.findMounted()?.actions.renameInsightSuccess(savedInsight)
const loadedLogic = insightLogic.findMounted({
@@ -3007,6 +3076,71 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
router.actions.push(urls.insightView(savedInsight.short_id))
}
},
+ discardChanges: async (_, breakpoint) => {
+ const tab = values.activeTab
+ if (!tab || !values.hasEditorChanges) {
+ return
+ }
+ const restore = (view?: DataWarehouseSavedQuery, insight?: InsightModel): void => {
+ const savedQuery = view
+ ? hogQLEditorSourceQuery(view.query)
+ : toDataVisualizationNode(insight?.query)
+ if (!savedQuery) {
+ return
+ }
+ actions._setSuggestionPayload(null)
+ actions.createTab(savedQuery.source.query, view, insight)
+ actions.setSourceQuery(savedQuery)
+ applyUndoableModelEdit(props.monaco, values.activeTab?.uri, savedQuery.source.query)
+ actions.syncUrlWithQuery()
+ }
+ restore(
+ tab.view
+ ? {
+ ...tab.view,
+ latest_history_id: values.inProgressViewEdits[tab.view.id] ?? tab.view.latest_history_id,
+ }
+ : undefined,
+ tab.insight
+ )
+ const restoredTab = values.activeTab
+ const restoredQuery = values.queryInput
+ const restoredSourceQuery = values.sourceQuery
+ try {
+ const view = tab.view
+ ? await warehouseSavedQueriesRetrieve(String(teamLogic.values.currentTeamId), tab.view.id)
+ : undefined
+ const insight = tab.insight ? await insightsApi.getByShortId(tab.insight.short_id) : undefined
+ breakpoint()
+ if (
+ values.activeTab !== restoredTab ||
+ values.queryInput !== restoredQuery ||
+ values.sourceQuery !== restoredSourceQuery
+ ) {
+ return
+ }
+ restore(
+ view && tab.view
+ ? {
+ ...tab.view,
+ name: view.name,
+ query: {
+ ...view.query,
+ kind: NodeKind.HogQLQuery,
+ query: view.query.query ?? '',
+ },
+ latest_history_id: view.latest_history_id ?? undefined,
+ }
+ : undefined,
+ insight ?? undefined
+ )
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ lemonToast.error('Changes discarded. Could not refresh the saved query.')
+ }
+ },
closeEditingObject: () => {
actions.setInsightLoading(false)
actions.setViewLoading(false)
@@ -3176,6 +3310,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
...values.activeTab,
view: { ...values.activeTab.view, query: view.query },
})
+ persistEditorDraft()
// Re-read the server's activity-log head and adopt it as the new base. The concurrency
// check — both the frontend guard and the backend's edited_history_id check — keys off
// this head; without re-basing, reverting the query and saving again is misread as a
@@ -3367,6 +3502,39 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
return editingView?.query?.query !== queryInput
},
],
+ hasEditorChanges: [
+ (s) => [s.activeTab, s.queryInput, s.sourceQuery],
+ (activeTab: QueryTab | null, queryInput: string | null, sourceQuery: DataVisualizationNode): boolean => {
+ if (!activeTab || queryInput === null || activeTab.draft) {
+ return false
+ }
+ const savedQuery = activeTab.view
+ ? hogQLEditorSourceQuery(activeTab.view.query)
+ : toDataVisualizationNode(activeTab.insight?.query)
+ if (!savedQuery) {
+ return false
+ }
+ const normalize = (query: DataVisualizationNode): Record<string, unknown> =>
+ removeUndefinedAndNull({
+ ...sanitizeSourceQuery(query),
+ display: query.display ?? ChartDisplayType.Auto,
+ source: {
+ ...normalizeRawQuerySource(query.source),
+ filters: normalizeFiltersForUrl(query.source.filters),
+ },
+ })
+ const currentQuery = { ...sourceQuery, source: { ...sourceQuery.source, query: queryInput } }
+ return (
+ !equal(
+ normalize(activeTab.view ? hogQLEditorSourceQuery(currentQuery.source) : currentQuery),
+ normalize(savedQuery)
+ ) ||
+ (!!activeTab.insight &&
+ (activeTab.name !== (activeTab.insight.name ?? NEW_QUERY) ||
+ (activeTab.description ?? '') !== (activeTab.insight.description ?? '')))
+ )
+ },
+ ],
exportContext: [
(s) => [s.sourceQuery],
(sourceQuery: DataVisualizationNode) => {
@@ -3490,7 +3658,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}),
trackedActionToUrl(({ values }) => ({
syncUrlWithQuery: () => {
- if (values.isEmbeddedMode) {
+ if (
+ values.isEmbeddedMode ||
+ values.queryInput === null ||
+ removeProjectIdIfPresent(router.values.location.pathname) !== urls.sqlEditor()
+ ) {
return
}
return [urls.sqlEditor(), undefined, getTabHash(values), { replace: true }]
@@ -3509,7 +3681,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
},
})),
urlToAction(({ actions, values, props }) => ({
- [urls.sqlEditor()]: async (_, searchParams, hashParams) => {
+ [urls.sqlEditor()]: async (_, searchParams, hashParams, { initial }) => {
if (isEmbeddedSQLEditorMode(props.mode ?? SQLEditorMode.FullScene)) {
return
}
@@ -3533,6 +3705,46 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
}
+ const draftTarget = searchParams.open_draft || hashParams.draft
+ const viewTarget = searchParams.open_view || hashParams.view
+ const insightTarget = searchParams.open_insight || hashParams.insight
+ const target = draftTarget
+ ? `draft:${draftTarget}`
+ : viewTarget
+ ? `view:${viewTarget}`
+ : insightTarget
+ ? `insight:${insightTarget}`
+ : 'new'
+ const draftStorage = sqlEditorDraftStorage(values.user?.uuid, teamLogic.values.currentTeamId, target)
+ const storedDraft = draftStorage?.get()
+ const isReload =
+ initial &&
+ window.performance
+ .getEntriesByType?.('navigation')
+ .some((entry) => (entry as PerformanceNavigationTiming).type === 'reload')
+ const restoreWorkingCopy = isReload || router.values.lastMethod === 'POP'
+ const localDraft =
+ !hasOwnProperty(searchParams, 'open_query') &&
+ (!hasOwnProperty(hashParams, 'q') || restoreWorkingCopy) &&
+ !searchParams.edit_metric
+ ? restoreWorkingCopy
+ ? draftStorage?.get(true)
+ : storedDraft
+ : null
+ if (localDraft) {
+ hashParams = restoreWorkingCopy
+ ? {
+ ...hashParams,
+ c: undefined,
+ raw: undefined,
+ filters: undefined,
+ mode: undefined,
+ bi: undefined,
+ ...localDraft,
+ }
+ : { ...localDraft, ...hashParams }
+ }
+
const outputTabFromUrl = parseOutputTab(searchParams.output_tab ?? hashParams.output_tab)
const draftIdFromUrl = searchParams.open_draft || hashParams.draft
const viewIdFromUrl = searchParams.open_view || hashParams.view
@@ -3564,13 +3776,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
values.databaseConnectionId !== expectedDatabaseConnectionId || !values.database
if (
- !searchParams.open_query &&
+ !hasOwnProperty(searchParams, 'open_query') &&
!searchParams.open_view &&
!searchParams.open_insight &&
!searchParams.open_draft &&
!searchParams.edit_metric &&
!searchParams.output_tab &&
- !hashParams.q &&
+ !hasOwnProperty(hashParams, 'q') &&
!hashParams.c &&
!hashParams.raw &&
!hasFiltersHashParam &&
@@ -3651,7 +3863,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
: undefined
actions.createTab(
- draft.query.query,
+ hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : draft.query.query,
associatedView,
undefined,
draft,
@@ -3695,8 +3907,19 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
return
}
- const queryToOpen = searchParams.open_query ? searchParams.open_query : (view.query?.query ?? '')
+ const queryToOpen =
+ searchParams.open_query ??
+ (hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : (view.query?.query ?? ''))
+ if (localDraft?.baseline_query !== undefined) {
+ view = {
+ ...view,
+ query: { ...view.query, kind: NodeKind.HogQLQuery, query: localDraft.baseline_query },
+ }
+ }
+ if (localDraft?.edited_history_id) {
+ actions.setInProgressViewEdit(view.id, localDraft.edited_history_id)
+ }
if (outputTabFromUrl) {
actions.createTab(
queryToOpen,
@@ -3764,10 +3987,22 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const insightVisualizationQuery = toDataVisualizationNode(insight.query)
const query = insightVisualizationQuery?.source.query ?? ''
- const queryToOpen = searchParams.open_query ? searchParams.open_query : query
+ const queryToOpen =
+ searchParams.open_query ?? (hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : query)
if (insightVisualizationQuery) {
- actions.setSourceQuery(applyFiltersFromUrl(insightVisualizationQuery))
+ let insightSource = applyFiltersFromUrl(insightVisualizationQuery)
+ if (localDraft || hasOwnProperty(hashParams, 'c') || hasOwnProperty(hashParams, 'raw')) {
+ insightSource = {
+ ...insightSource,
+ source: {
+ ...insightSource.source,
+ connectionId: connectionIdFromHash,
+ sendRawQuery: sendRawQueryFromHash || undefined,
+ },
+ }
+ }
+ actions.setSourceQuery(insightSource)
}
actions.editInsight(queryToOpen, insight, biEditorStateFromUrl ?? undefined)
if (!outputTabFromUrl) {
@@ -3775,20 +4010,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
// Only run the query if the results aren't already cached locally and we're not using the open_query search param
- if (insightVisualizationQuery && !searchParams.open_query) {
- const mountedDataLogic = dataNodeLogic.findMounted({
- key: values.dataLogicKey,
- })
- const response = mountedDataLogic?.values.response
- const responseLoading = mountedDataLogic?.values.responseLoading ?? false
+ if (!hasOwnProperty(hashParams, 'q') || queryToOpen === query) {
+ if (insightVisualizationQuery && !searchParams.open_query) {
+ const mountedDataLogic = dataNodeLogic.findMounted({
+ key: values.dataLogicKey,
+ })
+ const response = mountedDataLogic?.values.response
+ const responseLoading = mountedDataLogic?.values.responseLoading ?? false
- if (!responseLoading && !response) {
+ if (!responseLoading && !response) {
+ actions.runQuery()
+ }
+ } else {
actions.runQuery()
}
- } else {
- actions.runQuery()
}
-
tabAdded = true
router.actions.replace(urls.sqlEditor(), undefined, getTabHash(values))
} else if (searchParams.edit_metric) {
@@ -3800,7 +4036,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// authenticated response.
actions.openMetricFromUrl(searchParams.edit_metric, biEditorStateFromUrl)
tabAdded = true
- } else if (searchParams.open_query) {
+ } else if (hasOwnProperty(searchParams, 'open_query')) {
// kea-router decodes JSON-shaped URL values to objects — a node here carries
// visualization settings (display, chartSettings) alongside the SQL
const openQueryNode =
@@ -3836,7 +4072,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
tabAdded = true
} else if (
- hashParams.q &&
+ hasOwnProperty(hashParams, 'q') &&
!draftIdFromUrl &&
!viewIdFromUrl &&
!insightShortIdFromUrl &&
diff --git a/frontend/src/scenes/userLogic.test.ts b/frontend/src/scenes/userLogic.test.ts
index baa603c289c5..002c83c6f840 100644
--- a/frontend/src/scenes/userLogic.test.ts
+++ b/frontend/src/scenes/userLogic.test.ts
@@ -9,6 +9,8 @@ import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
+
import { userLogic } from './userLogic'
describe('userLogic', () => {
@@ -29,6 +31,59 @@ describe('userLogic', () => {
userLogic.mount()
})
+ describe('SQL draft logout cleanup', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ sessionStorage.clear()
+ })
+
+ afterEach(() => {
+ localStorage.clear()
+ sessionStorage.clear()
+ jest.restoreAllMocks()
+ })
+
+ it.each([undefined, '/api/agentic/authorize?state=example-state'])(
+ 'clears drafts without removing preferences when logging out to %s',
+ (nextUrl) => {
+ let submittedNext: string | null = null
+ const submit = jest
+ .spyOn(HTMLFormElement.prototype, 'submit')
+ .mockImplementation(function (this: HTMLFormElement) {
+ submittedNext = this.querySelector<HTMLInputElement>('input[name="next"]')?.value ?? null
+ this.remove()
+ })
+ for (const teamId of [1, 2]) {
+ sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, teamId, 'new')?.set({ q: 'SELECT unfinished' })
+ }
+ localStorage.setItem('theme', 'dark')
+ sessionStorage.setItem('other-session-state', 'keep')
+
+ userLogic.actions.logout(false, nextUrl)
+
+ expect(submit).toHaveBeenCalledTimes(1)
+ expect(submittedNext).toEqual(nextUrl ?? null)
+ expect(Object.keys(localStorage)).toEqual(['theme'])
+ expect(Object.keys(sessionStorage)).toEqual(['other-session-state'])
+ }
+ )
+
+ it('clears this tab’s session copy when another tab removes the shared draft', () => {
+ const draft = sqlEditorDraftStorage(MOCK_DEFAULT_USER.uuid, 1, 'new')!
+ draft.set({ q: 'SELECT unfinished' })
+ const key = localStorage.key(0)!
+ window.dispatchEvent(new StorageEvent('storage', { key, newValue: 'null', storageArea: localStorage }))
+ expect(draft.get(true)).toEqual({ q: 'SELECT unfinished' })
+
+ localStorage.removeItem(key)
+
+ window.dispatchEvent(new StorageEvent('storage', { key, newValue: null, storageArea: localStorage }))
+
+ expect(sessionStorage.getItem(key)).toBeNull()
+ expect(draft.get(true)).toBeNull()
+ })
+ })
+
describe('optimistic theme mode', () => {
afterEach(() => {
jest.restoreAllMocks()
diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.ts
index ed357060af3d..04a45031edc3 100644
--- a/frontend/src/scenes/userLogic.ts
+++ b/frontend/src/scenes/userLogic.ts
@@ -17,6 +17,11 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePane
import { ProductKey } from '~/queries/schema/schema-general'
import { AvailableFeature, NotificationSettings, OrganizationBasicType, UserRole, UserTheme, UserType } from '~/types'
+import {
+ clearSQLEditorDraftFromStorageEvent,
+ clearSQLEditorDrafts,
+} from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
+
import type { BillingFeatureType } from '../types'
import { urls } from './urls'
@@ -161,7 +166,11 @@ export interface userLogicActions {
resetOnFailure: boolean | undefined
}
}
- logout: (preserveLocation?: any) => {
+ logout: (
+ preserveLocation?: any,
+ nextUrl?: string
+ ) => {
+ nextUrl: string | undefined
preserveLocation: any
}
resetUserDetails: (values?: Record<string, any>) => {
@@ -420,7 +429,7 @@ export const userLogic = kea<userLogicType>([
actions(() => ({
loadUser: (resetOnFailure?: boolean) => ({ resetOnFailure }),
updateCurrentOrganization: (organizationId: string, destination?: string) => ({ organizationId, destination }),
- logout: (preserveLocation = false) => ({ preserveLocation }),
+ logout: (preserveLocation = false, nextUrl?: string) => ({ preserveLocation, nextUrl }),
upgradeImpersonation: (reason: string) => ({ reason }),
updateUser: (user: Partial<UserType>, successCallback?: () => void) => ({
user,
@@ -616,7 +625,7 @@ export const userLogic = kea<userLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
- logout: ({ preserveLocation }) => {
+ logout: ({ preserveLocation, nextUrl }) => {
if (cache.loggingOut) {
return
}
@@ -624,6 +633,7 @@ export const userLogic = kea<userLogicType>([
posthog.reset()
// Drop the address a signup or login attempt stored for the verify page
clearPendingVerificationEmail()
+ clearSQLEditorDrafts()
// OAuth mode: there's no local Django session to end — just drop the stored cloud
// token and return to the local login. (A cross-origin /logout POST would do nothing.)
@@ -644,12 +654,12 @@ export const userLogic = kea<userLogicType>([
csrfInput.value = getCookie('posthog_csrftoken') || ''
form.appendChild(csrfInput)
- if (preserveLocation) {
+ if (preserveLocation || nextUrl) {
const { pathname, search, hash } = window.location
const nextInput = document.createElement('input')
nextInput.type = 'hidden'
nextInput.name = 'next'
- nextInput.value = pathname + search + hash
+ nextInput.value = nextUrl || pathname + search + hash
form.appendChild(nextInput)
}
@@ -1054,7 +1064,15 @@ export const userLogic = kea<userLogicType>([
},
],
}),
- afterMount(({ actions }) => {
+ afterMount(({ actions, cache }) => {
+ cache.disposables.add(
+ () => {
+ window.addEventListener('storage', clearSQLEditorDraftFromStorageEvent)
+ return () => window.removeEventListener('storage', clearSQLEditorDraftFromStorageEvent)
+ },
+ 'sqlEditorDraftLogout',
+ { pauseOnPageHidden: false }
+ )
const preloadedUser = getAppContext()?.current_user
if (preloadedUser) {
actions.loadUserSuccess(preloadedUser)
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 5509fc08981f..635ddd37c016 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -71,6 +71,7 @@ export default defineConfig(({ mode }) => {
public: resolve(__dirname, 'src/assets'),
// Required for production builds — @posthog/icons is in the pnpm store, not node_modules root
'@posthog/icons': resolve(__dirname, 'node_modules/@posthog/icons'),
+ '@posthog/quill-charts': resolve(__dirname, 'node_modules/@posthog/quill-charts'),
// Source-only workspace package (exports map points at src/*.ts) — Vite can't resolve
// it by default when imported from products/*/frontend, like the @posthog/icons case above.
// Alias each export explicitly, subpath first: a lone package-root alias would rewrite the
diff --git a/products/data_warehouse/frontend/sqlEditorDraftStorage.ts b/products/data_warehouse/frontend/sqlEditorDraftStorage.ts
new file mode 100644
index 000000000000..4d9405ba67b0
--- /dev/null
+++ b/products/data_warehouse/frontend/sqlEditorDraftStorage.ts
@@ -0,0 +1,80 @@
+import { z } from 'zod'
+
+import { LocalStorageSlot, localStorageSlot } from 'lib/utils/localStorageSlot'
+
+const DRAFT_KEY_PREFIX = 'sql-editor-draft:'
+
+export function clearSQLEditorDrafts(): void {
+ for (const storageName of ['localStorage', 'sessionStorage'] as const) {
+ try {
+ const storage = window[storageName]
+ for (let index = storage.length - 1; index >= 0; index--) {
+ const key = storage.key(index)
+ if (key?.startsWith(DRAFT_KEY_PREFIX)) {
+ storage.removeItem(key)
+ }
+ }
+ } catch {
+ // Disabled storage must not prevent logout or cleanup of the other store.
+ }
+ }
+}
+
+export function clearSQLEditorDraftFromStorageEvent(event: StorageEvent): void {
+ try {
+ if (event.storageArea === localStorage && event.key?.startsWith(DRAFT_KEY_PREFIX) && event.newValue === null) {
+ sessionStorage.removeItem(event.key)
+ }
+ } catch {
+ // Session storage can be disabled by the browser.
+ }
+}
+
+const draftSchema = z
+ .object({
+ q: z.string(),
+ edited_history_id: z.string().optional(),
+ baseline_query: z.string().optional(),
+ })
+ .passthrough()
+ .nullable()
+
+interface SQLEditorDraftStorage extends LocalStorageSlot<z.infer<typeof draftSchema>> {
+ get: (currentTabOnly?: boolean) => z.infer<typeof draftSchema>
+}
+
+export function sqlEditorDraftStorage(
+ userUuid: string | undefined,
+ teamId: number | null,
+ target: string
+): SQLEditorDraftStorage | null {
+ if (!userUuid || !teamId) {
+ return null
+ }
+
+ const key = `${DRAFT_KEY_PREFIX}${userUuid}:${teamId}:${target}`
+ const localDraft = localStorageSlot(key, draftSchema)
+ return {
+ get: (currentTabOnly = false) => {
+ try {
+ const raw = sessionStorage.getItem(key)
+ if (raw !== null) {
+ return draftSchema.parse(JSON.parse(raw))
+ }
+ } catch {
+ // Storage may be disabled, or contain a draft from an incompatible version.
+ }
+ return currentTabOnly ? null : localDraft.get()
+ },
+ set: (draft) => {
+ // Keep null tombstones: key removal tells other tabs to discard their working copies on logout.
+ localDraft.set(draft)
+ try {
+ // A reload must recover this tab's edits, even if another tab edits the same query.
+ sessionStorage.setItem(key, JSON.stringify(draft))
+ } catch {
+ // The local copy still supports recovery when session storage is unavailable.
+ }
+ },
+ }
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
index 99cb2d6953d6..5082652278ef 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
@@ -1,5 +1,4 @@
-import { resetContext } from 'kea'
-import { expectLogic, partial, testUtilsPlugin } from 'kea-test-utils'
+import { expectLogic, partial } from 'kea-test-utils'
import { uuid } from 'lib/utils/dom'
@@ -27,10 +26,6 @@ describe('stepDelayLogic', () => {
beforeEach(() => {
initKeaTests()
- resetContext({
- plugins: [testUtilsPlugin],
- })
-
wfLogic = workflowLogic({ id: 'new' })
wfLogic.mount()
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
index 6451386f97d8..a19f6cf98d55 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
@@ -1,5 +1,4 @@
-import { resetContext } from 'kea'
-import { expectLogic, partial, testUtilsPlugin } from 'kea-test-utils'
+import { expectLogic, partial } from 'kea-test-utils'
import { uuid } from 'lib/utils/dom'
@@ -17,10 +16,6 @@ describe('stepWaitUntilTimeWindowLogic', () => {
beforeEach(() => {
initKeaTests()
- resetContext({
- plugins: [testUtilsPlugin],
- })
-
wfLogic = workflowLogic({ id: 'new' })
wfLogic.mount()
diff --git a/products/workflows/frontend/Workflows/templates/workflowTemplateLogic.test.ts b/products/workflows/frontend/Workflows/templates/workflowTemplateLogic.test.ts
index f2f5c078625a..4c348b2190d6 100644
--- a/products/workflows/frontend/Workflows/templates/workflowTemplateLogic.test.ts
+++ b/products/workflows/frontend/Workflows/templates/workflowTemplateLogic.test.ts
@@ -1,7 +1,6 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
-import { resetContext } from 'kea'
-import { expectLogic, testUtilsPlugin } from 'kea-test-utils'
+import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
import { userLogic } from 'scenes/userLogic'
@@ -37,10 +36,6 @@ describe('workflowTemplateLogic', () => {
beforeEach(() => {
initKeaTests()
- resetContext({
- plugins: [testUtilsPlugin],
- })
-
jest.clearAllMocks()
})