:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): show a not-found screen when a saved insight is missing (#86890)
posthog[bot]ac37c30eba73
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dbdef3e05091..d4e535bf25a5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7317,9 +7317,9 @@ snapshots:scenes-app-notebooks-widget-views--group-views--light:hash: v1.k794b7964.a622eda529140b0da26febf0295d5afe02224a095b690d699c90d37d189fd615.2nmLTPSj2A2MQ3TYzkrkcCOHhvvB3-4GiRvFJN_9tXIscenes-app-notebooks-widget-views--insight-views--dark:- hash: v1.k794b7964.2f40e816554706d5dae9c0ff7db3b60f92d8c71d2265fa8bebeb302dd6540aaf.gpycsrw2HtMpduduhLjSrjC4JRb2P4ZoyO13tZRRj6I+ hash: v1.k794b7964.e244662a3673ec7ba165c44cf182061da92bf464f4dd906d4a14a21097fd642a.FIzEr05lCLHYNsnjsOKAPba8sOdGAhy0to264af4mi0scenes-app-notebooks-widget-views--insight-views--light:- hash: v1.k794b7964.597a6894eaa2e15be37d9c5131aa8a648a35b3b4415e6f8bf60d25d0326be57f.64f4C1oslCdLwXhLDCTVkocQjya4p0DH16mBBflRYHs+ hash: v1.k794b7964.453689f7cbcada239210a4e86acbb1bf636b42dd8a221ebec99a697e095b4ccc.8rMJvAEuKIZteiL98EOHI4399p25PSlnJCbjkLZTXZUscenes-app-notebooks-widget-views--llm-trace-views--dark:hash: v1.k794b7964.4e1ab634bae8a93e4e3c6fed3c379cd10791a8cdfaa37c551ffc10cbb5c2d738.zBi7T4pmBEu1EV1ID04nuFxNs7iSFBMDc-tCKVEmy70scenes-app-notebooks-widget-views--llm-trace-views--light:diff --git a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsxindex 97b613507192..9dcbea3a7353 100644--- a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx+++ b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx@@ -1,5 +1,6 @@import { BuiltLogic, LogicWrapper, useValues } from 'kea'+import { NotFound } from 'lib/components/NotFound'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'@@ -29,7 +30,7 @@ export function SavedInsight({editMode,}: InsightProps): JSX.Element {const insightProps: InsightLogicProps = { dashboardItemId: propsQuery.shortId }- const { insight, insightLoading } = useValues(insightLogic(insightProps))+ const { insight, insightLoading, insightMissing } = useValues(insightLogic(insightProps))const { query: dataQuery } = useValues(insightDataLogic(insightProps))useAttachedLogic(insightLogic(insightProps), attachTo)@@ -43,6 +44,10 @@ export function SavedInsight({)}+ if (insightMissing) {+ return <NotFound object="insight" />+ }+// `showResults` is reapplied only when the caller set it: a stored query carrying an explicit// `false` would otherwise override an embed that asked for the result body and draw a card with// nothing in it, while callers that say nothing keep deferring to what the insight stored.diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex c3398adda270..aab94d0be550 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -1133,6 +1133,24 @@ describe('insightLogic', () => {})})+ describe('insightMissing', () => {+ // A notebook cell binds a saved insight by short id. When that insight is gone, the API+ // returns no results and the loader throws — the cell needs a flag it can turn into a+ // "not found" screen instead of silently rendering a blank default query.+ it('is set when the insight cannot be found', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/insights/': () => [200, { results: [] }],+ },+ })+ logic = insightLogic({ dashboardItemId: Insight42 })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadInsightFailure'])++ expect(logic.values.insightMissing).toBe(true)+ })+ })+describe('editingDisabledReason', () => {it.each([['overrides present', { filtersOverride: { date_from: '-7d' } }, 'Discard overrides to edit the insight.'],diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex fe0817ee4af8..c380380b3ec0 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -123,6 +123,7 @@ export interface insightLogicValues {insightFeedback: 'disliked' | 'liked' | nullinsightId: number | nullinsightLoading: boolean+ insightMissing: booleaninsightName: stringinsightProps: InsightLogicPropsinsightSaving: boolean@@ -431,6 +432,9 @@ export interface insightLogicActions {>}}+ setInsightMissing: () => {+ value: true+ }setPreviousQuery: (previousQuery: Node | null) => {previousQuery: Node<Record<string, any>> | null}@@ -599,6 +603,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType}),highlightSeries: (series: IndexedTrendResult | null) => ({ series }),setAccessDeniedToInsight: true,+ setInsightMissing: true,handleInsightSuggested: (suggestedInsight: Node | null) => ({ suggestedInsight }),onRejectSuggestedInsight: true,onReapplySuggestedInsight: true,@@ -644,6 +649,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType)if (!insight) {+ actions.setInsightMissing()throw new Error(`Insight with shortId ${shortId} not found`)}@@ -836,6 +842,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType},},accessDeniedToInsight: [false, { setAccessDeniedToInsight: () => true }],+ insightMissing: [false, { setInsightMissing: () => true, loadInsight: () => false }],/** The insight's state as it is in the database. */savedInsight: [() => props.cachedInsight || ({} as Partial<QueryBasedInsightModel>),diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex 7041b6a055b6..9470490e6c25 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -1,6 +1,7 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -9,7 +10,12 @@ import { initKeaTests } from '~/test/init'import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'import { notebookSettingsLogic } from '../Notebook/notebookSettingsLogic'import { NotebookNodeType } from '../types'-import { collectSqlV2Refs, notebookNodeSQLV2Logic, pollIntervalMs } from './notebookNodeSQLV2Logic'+import {+ collectSqlV2Refs,+ notebookNodeSQLV2Logic,+ pollIntervalMs,+ sqlV2RunErrorMessage,+} from './notebookNodeSQLV2Logic'describe('notebookNodeSQLV2Logic', () => {let logic: ReturnType<typeof notebookNodeSQLV2Logic.build>@@ -37,6 +43,30 @@ describe('notebookNodeSQLV2Logic', () => {jest.restoreAllMocks()})+ describe('sqlV2RunErrorMessage', () => {+ // The browser endpoints render every 404 as DRF's generic {"detail": "Not found."}, so the+ // message must come from the caller's notFoundKind, not from matching the backend string.+ const notFound = new ApiError(undefined, 404, undefined, { detail: 'Not found.' })++ it('names the notebook for a 404 on a notebook-addressed request', () => {+ expect(sqlV2RunErrorMessage(notFound, 'fallback', 'notebook')).toBe(+ 'This notebook could not be found. It may have been deleted.'+ )+ })++ it('points at a rerun for a 404 on a result-addressed request', () => {+ // The result/page call sites rely on the default kind.+ expect(sqlV2RunErrorMessage(notFound, 'fallback')).toBe(+ 'This query result is no longer available. Run the cell again.'+ )+ })++ it('keeps the original message for non-404 failures', () => {+ // A syntax error carries the detail the user needs; the not-found mapping must not swallow it.+ expect(sqlV2RunErrorMessage(new ApiError('Unexpected token', 400), 'fallback')).toBe('Unexpected token')+ })+ })+describe('collectSqlV2Refs', () => {const sqlNode = (nodeId: string, returnVariable: string): JSONContent => ({type: NotebookNodeType.SQLV2,@@ -225,6 +255,18 @@ describe('notebookNodeSQLV2Logic', () => {expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null, runStatus: null })})+ it('shows the notebook-gone message when the run dispatch 404s', async () => {+ // A deleted or inaccessible notebook 404s the dispatch as a generic "Not found."; the cell+ // must say the notebook is gone, not send the user into a rerun loop for a result that+ // never existed.+ runSpy.mockRejectedValue(new ApiError(undefined, 404, undefined, { detail: 'Not found.' }))+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.runError).toBe('This notebook could not be found. It may have been deleted.')+ expect(logic.values.isRunning).toBe(false)+ })+it('dispatches a run against the cell’s connection', async () => {// Without this the run reaches the backend with no connection and executes on ClickHouse,// which is what made warehouse queries fail with "Unknown table".diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex b010c3a77c76..9020762e5264 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -14,6 +14,7 @@ import {} from 'kea'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -38,6 +39,24 @@ export type SqlV2RunRef = {kind: 'hogql' | 'local'}+// Turn a run/result request failure into a message the user can act on. The browser endpoints+// render every 404 as DRF's generic {"detail": "Not found."}, so the response can't say what is+// gone — the caller does, via notFoundKind: a run dispatch that 404s means the notebook itself is+// gone, while a result poll or page fetch that 404s means that run's result is gone. Every other+// failure keeps its original message.+export function sqlV2RunErrorMessage(+ error: unknown,+ fallback: string,+ notFoundKind: 'notebook' | 'result' = 'result'+): string {+ if (error instanceof ApiError && error.status === 404) {+ return notFoundKind === 'notebook'+ ? 'This notebook could not be found. It may have been deleted.'+ : 'This query result is no longer available. Run the cell again.'+ }+ return error instanceof Error ? error.message : fallback+}+// Map every sibling cell's dataframe name -> {node id, kind}, excluding the running node itself.// SQLV2 siblings delegate to collectSqlV2Nodes so duplicate names get the same disambiguated// form the dependency graph shows (sql_df, sql_df_2, …) — raw attributes would let a later@@ -474,7 +493,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([if (error?.status === 409) {lemonToast.info('This result was replaced by a newer run — showing the latest first page.')} else {- lemonToast.error(error?.detail || error?.message || 'Failed to fetch page')+ lemonToast.error(sqlV2RunErrorMessage(error, 'Failed to fetch page'))}// Either way the requested page never arrived — fall back to the envelope's// first page rather than showing old rows under a new page number.@@ -554,7 +573,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([})actions.startPolling(run_id)} catch (error) {- actions.setRunError(error instanceof Error ? error.message : 'Failed to run query')+ actions.setRunError(sqlV2RunErrorMessage(error, 'Failed to run query', 'notebook'))actions.setIsRunning(false)actions.finishOperation(runOperation.id)actions.nodeRunFinished(props.nodeId, 'failed', null)@@ -706,7 +725,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([if (runId !== cache.activeRunId) {return}- actions.setRunError(error instanceof Error ? error.message : 'Failed to fetch result')+ actions.setRunError(sqlV2RunErrorMessage(error, 'Failed to fetch result'))actions.stopPolling()actions.nodeRunFinished(props.nodeId, 'failed', null)} finally {