: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
refactor(insights): read an insight's dashboards from its tiles (#116803)
Thomas Obermüllerc5efbdcfeda0
diff --git a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsxindex 394059ab62a8..7b17a960e1e3 100644--- a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx+++ b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx@@ -15,7 +15,6 @@ import { dataThemeLogic } from 'scenes/dataThemeLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { DISPLAYS_WITH_IN_CHART_LEGEND } from 'scenes/insights/insightVizDataLogic'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { Query } from '~/queries/Query/Query'import { SharingConfigurationSettings } from '~/queries/schema/schema-general'import { getDisplay, isDataTableNode, isInsightVizNode, isMetricInsightQuery, isTrendsQuery } from '~/queries/utils'@@ -25,7 +24,7 @@ import { InsightsTable } from 'products/product_analytics/frontend/insights/sharimport { BoxPlotLegend } from 'products/product_analytics/frontend/insights/trends/BoxPlot/BoxPlotLegend'export function ExportedInsight({- insight: legacyInsight,+ insight: exportedInsight,themes,exportOptions: { whitelabel, noHeader, legend, detailed: detailedResults },}: {@@ -35,10 +34,12 @@ export function ExportedInsight({}): JSX.Element {useMountedLogic(dataThemeLogic({ themes }))- const insight = getQueryBasedInsightModel(legacyInsight)- // getQueryBasedInsightModel returns the caller's query object by reference — clone it so the- // export-only tweaks below (legend settings, table editing controls) can't leak into a shared model.- insight.query = insight.query ? structuredClone(insight.query) : insight.query+ // Copy the insight and clone its query, because the export-only tweaks below (legend settings,+ // table editing controls) write to them and must not leak into the caller's insight.+ const insight: InsightModel = {+ ...exportedInsight,+ query: exportedInsight.query ? structuredClone(exportedInsight.query) : exportedInsight.query,+ }if (isDataTableNode(insight.query)) {// don't show editing controls when exporting/sharingdiff --git a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx b/frontend/src/exporter/scenes/ExporterDashboardScene.tsxindex 64b5a5af8f4f..ab18f68fc7ad 100644--- a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx+++ b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx@@ -1,12 +1,11 @@import { useActions } from 'kea'-import { useCallback, useEffect, useMemo } from 'react'+import { useCallback, useEffect } from 'react'import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'import { Dashboard } from 'scenes/dashboard/Dashboard'import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'import { DashboardPlacement, DashboardType } from '~/types'import { ExportType, ExportedData } from '../types'@@ -59,15 +58,14 @@ export default function ExporterDashboardScene({type: ExportedData['type']themes: ExportedData['themes']}): JSX.Element {- const queryBasedDashboard = useMemo(() => getQueryBasedDashboard(dashboard)!, [dashboard])return (<>{type !== ExportType.Image && (- <SharedDashboardAutoRefresh dashboardId={dashboard.id} dashboard={queryBasedDashboard} />+ <SharedDashboardAutoRefresh dashboardId={dashboard.id} dashboard={dashboard} />)}<Dashboardid={String(dashboard.id)}- dashboard={queryBasedDashboard}+ dashboard={dashboard}placement={type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public}themes={themes}/>diff --git a/frontend/src/lib/components/AddToDashboard/AddToDashboard.tsx b/frontend/src/lib/components/AddToDashboard/AddToDashboard.tsxindex abe1bf45950f..0bde192cd12a 100644--- a/frontend/src/lib/components/AddToDashboard/AddToDashboard.tsx+++ b/frontend/src/lib/components/AddToDashboard/AddToDashboard.tsx@@ -4,6 +4,7 @@ import { IconDashboard } from '@posthog/icons'import { IconWithCount } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { dashboardsModel } from '~/models/dashboardsModel'import { InsightModel } from '~/types'@@ -15,7 +16,9 @@ interface SaveToDashboardProps {export function AddToDashboard({ insight, setOpenModal }: SaveToDashboardProps): JSX.Element | null {const { rawDashboards } = useValues(dashboardsModel)- const dashboards = insight.dashboard_tiles?.map((tile) => rawDashboards[tile.dashboard_id]).filter((d) => !!d) || []+ const dashboards = liveDashboardIds(insight.dashboard_tiles)+ .map((dashboardId) => rawDashboards[dashboardId])+ .filter((d) => !!d)return (<span className="save-to-dashboard" data-attr="save-to-dashboard-button">diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.tsindex d973d8aad620..8c0e2fae7fb2 100644--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts@@ -2,6 +2,7 @@ import { MOCK_USER_UUID } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import api from 'lib/api'import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'import { insightLogic } from 'scenes/insights/insightLogic'@@ -34,7 +35,6 @@ const MOCK_INSIGHT: InsightModel = {series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: 'total' }],},},- dashboards: [1, 2],dashboard_tiles: [{ dashboard_id: 1 }, { dashboard_id: 2 }] as any,result: ['result'],saved: true,@@ -143,10 +143,42 @@ describe('addToDashboardModalLogic', () => {.toFinishAllListeners()})+ it.each([+ {+ name: 'adding keeps the dashboards the insight already sits on',+ change: (modal: ReturnType<typeof addToDashboardModalLogic.build>) => modal.actions.addToDashboard(4),+ expectedDashboards: [1, 2, 4],+ },+ {+ name: 'removing keeps the other dashboards',+ change: (modal: ReturnType<typeof addToDashboardModalLogic.build>) => modal.actions.removeFromDashboard(2),+ expectedDashboards: [1],+ },+ ])('$name', async ({ change, expectedDashboards }) => {+ const updateSpy = jest.spyOn(api.insights, 'update')+ const insightProps = { dashboardItemId: Insight1 }+ const insightLog = insightLogic(insightProps)+ insightLog.mount()+ insightLog.actions.loadInsightSuccess({+ ...MOCK_INSIGHT,+ dashboard_tiles: [+ { id: 11, dashboard_id: 1 },+ { id: 12, dashboard_id: 2 },+ { id: 13, dashboard_id: 3, deleted: true },+ ],+ })++ logic = addToDashboardModalLogic(insightProps)+ logic.mount()++ await expectLogic(logic, () => change(logic)).toFinishAllListeners()++ expect(updateSpy.mock.calls[0][1].dashboards).toEqual(expectedDashboards)+ })+it('orders dashboards: on insight first, then mine, then others pinned, then the rest', async () => {const insightOnlyOnDash2: InsightModel = {...MOCK_INSIGHT,- dashboards: [2],dashboard_tiles: [{ dashboard_id: 2 }] as any,}useMocks({@@ -200,7 +232,6 @@ describe('addToDashboardModalLogic', () => {window.POSTHOG_APP_CONTEXT = { current_user: null } as unknown as AppContextconst insightOnlyOnDash2: InsightModel = {...MOCK_INSIGHT,- dashboards: [2],dashboard_tiles: [{ dashboard_id: 2 }] as any,}useMocks({@@ -251,7 +282,6 @@ describe('addToDashboardModalLogic', () => {it('places mine pinned in the mine bucket before others pinned', async () => {const insightOnlyOnDash2: InsightModel = {...MOCK_INSIGHT,- dashboards: [2],dashboard_tiles: [{ dashboard_id: 2 }] as any,}useMocks({diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.tsindex a329b19ade8f..da1ad146fefb 100644--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts@@ -5,6 +5,7 @@ import { router } from 'kea-router'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { createFuse } from 'lib/utils/fuseSearch'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'@@ -209,7 +210,7 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([import('~/types').InsightModel<import('../../../queries/schema').Node<Record<string, any>>>>): DashboardBasicType[] =>- filteredDashboards.filter((d) => insight.dashboard_tiles?.map((dt) => dt.dashboard_id)?.includes(d.id)),+ filteredDashboards.filter((d) => liveDashboardIds(insight.dashboard_tiles).includes(d.id)),],availableDashboards: [(s) => [s.filteredDashboards, s.currentDashboards],@@ -261,7 +262,7 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([// either patch dashboard_tiles on the insight or add a dashboard_tiles APIactions.updateInsight({- dashboards: [...(values.insight.dashboards || []), dashboardId],+ dashboards: [...liveDashboardIds(values.insight.dashboard_tiles), dashboardId],},() => {actions.reportSavedInsightToDashboard(values.insight, dashboardId)@@ -283,7 +284,7 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([removeFromDashboard: async ({ dashboardId }): Promise<void> => {actions.updateInsight({- dashboards: (values.insight.dashboards || []).filter((d) => d !== dashboardId),+ dashboards: liveDashboardIds(values.insight.dashboard_tiles).filter((d) => d !== dashboardId),dashboard_tiles: (values.insight.dashboard_tiles || []).filter((dt) => dt.dashboard_id !== dashboardId),diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 976a44cf7be1..e7c54d969749 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -213,7 +213,6 @@ export function InsightMeta({const dashboardWidgetMenusLogicProps = {instanceKey: insight.short_id,dashboardId,- dashboards: insight.dashboards,dashboard_tiles: insight.dashboard_tiles,}const { copyToDestinations } = useValues(dashboardWidgetMenusLogic(dashboardWidgetMenusLogicProps))diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.tsindex 7feb3ca35b49..2134d9a7612d 100644--- a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts@@ -12,20 +12,20 @@ describe('dashboardWidgetMenusLogic', () => {dashboardsModel.mount()})- it('merges dashboardId, legacy dashboards ids, and dashboard_tiles into dashboardIdsWithThisWidget', async () => {+ it('merges dashboardId and live dashboard_tiles into dashboardIdsWithThisWidget, skipping soft-deleted tiles', async () => {const logic = dashboardWidgetMenusLogic({instanceKey: 'test',dashboardId: 10,- dashboards: [5, 6],dashboard_tiles: [{ id: 1, dashboard_id: 7 },{ id: 2, dashboard_id: 10 },+ { id: 3, dashboard_id: 8, deleted: true },],})logic.mount()await expectLogic(logic).toMatchValues({- dashboardIdsWithThisWidget: new Set([5, 6, 7, 10]),+ dashboardIdsWithThisWidget: new Set([7, 10]),})})@@ -44,7 +44,6 @@ describe('dashboardWidgetMenusLogic', () => {const logic = dashboardWidgetMenusLogic({instanceKey: 'test',dashboardId: 1,- dashboards: undefined,dashboard_tiles: [{ id: 10, dashboard_id: 1 }],})logic.mount()@@ -58,7 +57,7 @@ describe('dashboardWidgetMenusLogic', () => {})})- it('marks a destination disabled when the widget is already placed there (legacy dashboards list)', async () => {+ it('marks a destination disabled when the widget is already placed there', async () => {dashboardsModel.actions.addDashboardSuccess({id: 1,name: 'A',@@ -73,8 +72,7 @@ describe('dashboardWidgetMenusLogic', () => {const logic = dashboardWidgetMenusLogic({instanceKey: 'test',dashboardId: 1,- dashboards: [2],- dashboard_tiles: [],+ dashboard_tiles: [{ id: 11, dashboard_id: 2 }],})logic.mount()await expectLogic(logic).toMatchValues({diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.tsindex 81b33ff606ab..2751129e7426 100644--- a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.ts+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.ts@@ -1,6 +1,7 @@import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { dashboardsModel } from '~/models/dashboardsModel'import { AccessControlLevel, AccessControlResourceType, DashboardBasicType, DashboardTileBasicType } from '~/types'@@ -12,7 +13,6 @@ import type { DashboardWidgetPlacementDestination } from './DashboardWidgetPlaceexport interface DashboardWidgetMenusLogicProps {instanceKey: stringdashboardId: number | null | undefined- dashboards: number[] | null | undefineddashboard_tiles: DashboardTileBasicType[] | null | undefined}@@ -34,7 +34,6 @@ export interface dashboardWidgetMenusLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {dashboardIdsWithThisWidget: (- dashboards: number[] | null | undefined,dashboard_tiles: DashboardTileBasicType[] | null | undefined,dashboardId: number | null | undefined) => Set<number>@@ -64,23 +63,12 @@ export const dashboardWidgetMenusLogic = kea<dashboardWidgetMenusLogicType>([selectors(() => ({/** Dashboards where this widget (insight / text / button / …) is already placed. */dashboardIdsWithThisWidget: [- (_, p) => [p.dashboards, p.dashboard_tiles, p.dashboardId],+ (_, p) => [p.dashboard_tiles, p.dashboardId],(- dashboards: number[] | null | undefined,dashboard_tiles: DashboardTileBasicType[] | null | undefined,dashboardId: number | null | undefined): Set<number> => {- const set = new Set<number>()- for (const rawId of dashboards ?? []) {- if (rawId != null) {- set.add(Number(rawId))- }- }- for (const t of dashboard_tiles ?? []) {- if (t.dashboard_id != null) {- set.add(Number(t.dashboard_id))- }- }+ const set = new Set(liveDashboardIds(dashboard_tiles).map(Number))if (dashboardId != null) {set.add(Number(dashboardId))}diff --git a/frontend/src/lib/components/TerraformExporter/insightHclExporter.test.ts b/frontend/src/lib/components/TerraformExporter/insightHclExporter.test.tsindex 326076c967d9..ca2beb260642 100644--- a/frontend/src/lib/components/TerraformExporter/insightHclExporter.test.ts+++ b/frontend/src/lib/components/TerraformExporter/insightHclExporter.test.ts@@ -1,11 +1,13 @@import { generateInsightHCL } from 'lib/components/TerraformExporter/insightHclExporter'import { NodeKind } from '~/queries/schema/schema-general'-import { InsightModel } from '~/types'+import { DashboardTileBasicType, InsightModel } from '~/types'// Helper to create test insights without strict query typing// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst createTestInsight = (props: Record<string, any>): Partial<InsightModel> => props as Partial<InsightModel>+const tilesOn = (...dashboardIds: number[]): DashboardTileBasicType[] =>+ dashboardIds.map((dashboard_id, index) => ({ id: 100 + index, dashboard_id }))describe('insightHclExporter test', () => {describe('sanitizes correctly', () => {@@ -68,7 +70,7 @@ describe('insightHclExporter test', () => {series: [{ event: '$pageview', kind: NodeKind.EventsNode }],},tags: ['test', 'analytics'],- dashboards: [1, 2],+ dashboard_tiles: [...tilesOn(1, 2), { id: 200, dashboard_id: 3, deleted: true }],})const result = generateInsightHCL(insight)@@ -214,7 +216,7 @@ describe('insightHclExporter test', () => {const insight = createTestInsight({name: 'Test',query: { kind: NodeKind.TrendsQuery },- dashboards: [1, 2, 3],+ dashboard_tiles: tilesOn(1, 2, 3),})const result = generateInsightHCL(insight)@@ -228,7 +230,7 @@ describe('insightHclExporter test', () => {const insight = createTestInsight({name: 'Valid Insight',query: { kind: NodeKind.TrendsQuery },- dashboards: [1],+ dashboard_tiles: tilesOn(1),})const result = generateInsightHCL(insight, {@@ -244,7 +246,7 @@ describe('insightHclExporter test', () => {const insight = createTestInsight({name: 'Multi Dashboard Insight',query: { kind: NodeKind.TrendsQuery },- dashboards: [1, 2],+ dashboard_tiles: tilesOn(1, 2),})const result = generateInsightHCL(insight, {@@ -264,7 +266,7 @@ describe('insightHclExporter test', () => {const insight = createTestInsight({name: 'Multi Dashboard Insight',query: { kind: NodeKind.TrendsQuery },- dashboards: [1, 2, 3, 4],+ dashboard_tiles: tilesOn(1, 2, 3, 4),})const result = generateInsightHCL(insight, {diff --git a/frontend/src/lib/components/TerraformExporter/insightHclExporter.ts b/frontend/src/lib/components/TerraformExporter/insightHclExporter.tsindex c78fbb65a277..679e4f1a60e0 100644--- a/frontend/src/lib/components/TerraformExporter/insightHclExporter.ts+++ b/frontend/src/lib/components/TerraformExporter/insightHclExporter.ts@@ -5,8 +5,9 @@ import {formatJsonForHcl,sanitizeResourceName,} from 'lib/components/TerraformExporter/hclExporterFormattingUtils'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'-import { HogFunctionType, InsightModel } from '~/types'+import { DashboardTileBasicType, HogFunctionType, InsightModel } from '~/types'import { AlertType } from 'products/alerts/frontend/types'@@ -68,10 +69,14 @@ const INSIGHT_FIELD_MAPPINGS: FieldMapping<Partial<InsightModel>, InsightHclExposhouldInclude: (v) => !!v,},{- source: 'dashboards',+ source: 'dashboard_tiles',target: 'dashboard_ids',- shouldInclude: (v) => Array.isArray(v) && v.length > 0,- transform: (v, _, options) => formatIdsWithReplacements(v as number[], options.dashboardIdReplacements),+ shouldInclude: (v) => liveDashboardIds(v as DashboardTileBasicType[] | null | undefined).length > 0,+ transform: (v, _, options) =>+ formatIdsWithReplacements(+ liveDashboardIds(v as DashboardTileBasicType[] | null | undefined),+ options.dashboardIdReplacements+ ),},]@@ -88,8 +93,9 @@ function validateInsight(insight: Partial<InsightModel>, options?: InsightHclExp)}- if (insight.dashboards && insight.dashboards.length > 0) {- const hasUnresolvedIds = insight.dashboards.some((id) => !options?.dashboardIdReplacements?.has(id))+ const dashboardIds = liveDashboardIds(insight.dashboard_tiles)+ if (dashboardIds.length > 0) {+ const hasUnresolvedIds = dashboardIds.some((id) => !options?.dashboardIdReplacements?.has(id))if (hasUnresolvedIds) {warnings.push('Some `dashboard_ids` are hardcoded. After exporting, consider referencing the Terraform resource instead (for example, `posthog_dashboard.my_dashboard.id`) so the dashboard is managed alongside this configuration.'diff --git a/frontend/src/lib/utils/deleteWithUndo.tsx b/frontend/src/lib/utils/deleteWithUndo.tsxindex 7fe011f77e90..bb4cee657a51 100644--- a/frontend/src/lib/utils/deleteWithUndo.tsx+++ b/frontend/src/lib/utils/deleteWithUndo.tsx@@ -1,6 +1,7 @@import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { InsightModel } from '~/types'@@ -62,6 +63,11 @@ export async function deleteInsightWithUndo({// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.await api.update(`api/${props.endpoint}/${props.object[props.idField || 'id']}`, {...props.object,+ // The body is the whole insight, so it carries the insight's dashboards too. An explicit+ // `dashboards` on the object replaces the list read from the tiles.+ dashboards:+ props.object.dashboards ??+ (props.object.dashboard_tiles ? liveDashboardIds(props.object.dashboard_tiles) : undefined),deleted: !undo,})props.callback?.(undo, props.object)diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsxindex 644f8860a3f0..9314e78ce2ab 100644--- a/frontend/src/models/dashboardsModel.tsx+++ b/frontend/src/models/dashboardsModel.tsx@@ -17,7 +17,6 @@ import { urls } from 'scenes/urls'import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { parentPath, reparentPath } from '~/layout/panel-layout/ProjectTree/utils'import { tagsModel } from '~/models/tagsModel'-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'import { DashboardBasicType, DashboardTile, DashboardType, InsightShortId, InsightModel } from '~/types'import type { Node } from '../queries/schema/schema-general'@@ -181,33 +180,23 @@ export interface dashboardsModelActions {}loadDashboardsSuccess: (pagedDashboards:+ | PaginatedResponse<DashboardType>| {count: numbernext: nullprevious: nullresults: DashboardBasicType[]- }- | {- count?: undefined- next?: string | null | undefined- previous?: string | null | undefined- results: DashboardType[]},payload?: string) => {pagedDashboards:+ | PaginatedResponse<DashboardType>| {count: numbernext: nullprevious: nullresults: DashboardBasicType[]}- | {- count?: undefined- next?: string | null | undefined- previous?: string | null | undefined- results: DashboardType[]- }payload?: string}patchDashboardFolders: (paths: Record<string, string>) => {@@ -425,7 +414,7 @@ export const dashboardsModel = kea<dashboardsModelType>([count: 1,next: null,previous: null,- results: [getQueryBasedDashboard(exportedDashboard) as DashboardBasicType],+ results: [exportedDashboard as DashboardBasicType],}}@@ -444,11 +433,7 @@ export const dashboardsModel = kea<dashboardsModelType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.const dashboards: PaginatedResponse<DashboardType> = await api.get(apiUrl)-- return {- ...dashboards,- results: dashboards.results?.map((dashboard) => getQueryBasedDashboard(dashboard)!),- }+ return dashboards},},],@@ -492,7 +477,7 @@ export const dashboardsModel = kea<dashboardsModelType>([`api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,beforeChange)- actions.updateDashboardSuccess(getQueryBasedDashboard(reverted), {+ actions.updateDashboardSuccess(reverted, {layoutsPersisted: true,})lemonToast.success('Dashboard change reverted')@@ -505,41 +490,45 @@ export const dashboardsModel = kea<dashboardsModelType>([return null}- const mappedDashboard = getQueryBasedDashboard(response)- if (!mappedDashboard) {- return mappedDashboard+ if (!response) {+ return response}- return mergeTileTextUpdatesIntoDashboard(mappedDashboard, payload.tiles)+ return mergeTileTextUpdatesIntoDashboard(response, payload.tiles)},deleteDashboard: async ({ id, deleteInsights }) => {- const deleted = getQueryBasedDashboard(- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.- await api.update(`api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`, {+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.+ const deleted = await api.update<DashboardType>(+ `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,+ {deleted: true,delete_insights: deleteInsights,- })- ) as DashboardType+ }+ )deleteFromTree('dashboard', String(id))return deleted},restoreDashboard: async ({ id }) => {- const restored = getQueryBasedDashboard(- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.- await api.update(`api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`, {+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.+ const restored = await api.update<DashboardType>(+ `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,+ {deleted: false,- })- ) as DashboardType+ }+ )refreshTreeItem('dashboard', String(id))return restored},pinDashboard: async ({ id, source }) => {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.- const response = await api.update(`api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`, {- pinned: true,- })+ const response = await api.update<DashboardType>(+ `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,+ {+ pinned: true,+ }+ )reportDashboardPinToggled(id, true, source)- return getQueryBasedDashboard(response)!+ return response},unpinDashboard: async ({ id, source }) => {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.@@ -550,7 +539,7 @@ export const dashboardsModel = kea<dashboardsModelType>([})reportDashboardPinToggled(id, false, source)- return getQueryBasedDashboard(response)!+ return response},duplicateDashboard: async ({ id, name, show, duplicateTiles }) => {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsCreate() from 'products/dashboards/frontend/generated/api' instead.@@ -565,7 +554,7 @@ export const dashboardsModel = kea<dashboardsModelType>([if (show) {router.actions.push(urls.dashboard(result.id))}- return getQueryBasedDashboard(result)!+ return result},},})),diff --git a/frontend/src/models/insightsModel.tsx b/frontend/src/models/insightsModel.tsxindex cb11468ab65c..8e8fa577ccb1 100644--- a/frontend/src/models/insightsModel.tsx+++ b/frontend/src/models/insightsModel.tsx@@ -22,9 +22,21 @@ export interface insightsModelActions {insightSaved: (shortId: InsightShortId) => {shortId: InsightShortId}- insightsAddedToDashboard: ({ dashboardId, insightIds }: { dashboardId: number; insightIds: number[] }) => {+ insightsAddedToDashboard: ({+ dashboardId,+ tiles,+ }: {dashboardId: number- insightIds: number[]+ tiles: {+ id: number+ insightId: number+ }[]+ }) => {+ dashboardId: number+ tiles: {+ id: number+ insightId: number+ }[]}renameInsight: (item: InsightModel) => {item: InsightModel<Node<Record<string, any>>>@@ -57,9 +69,15 @@ export const insightsModel = kea<insightsModelType>([// TODO: this duplicates the insight but not the dashboard tile (e.g. if duplicated from dashboard you lose tile colorduplicateInsight: (item: InsightModel) => ({ item }),duplicateInsightSuccess: (item: InsightModel) => ({ item }),- insightsAddedToDashboard: ({ dashboardId, insightIds }: { dashboardId: number; insightIds: number[] }) => ({+ insightsAddedToDashboard: ({+ dashboardId,+ tiles,+ }: {+ dashboardId: number+ tiles: { id: number; insightId: number }[]+ }) => ({dashboardId,- insightIds,+ tiles,}),})),listeners(({ actions }) => ({diff --git a/frontend/src/queries/nodes/InsightViz/utils.test.ts b/frontend/src/queries/nodes/InsightViz/utils.test.tsindex f2ebb3536c19..ad3affb9234f 100644--- a/frontend/src/queries/nodes/InsightViz/utils.test.ts+++ b/frontend/src/queries/nodes/InsightViz/utils.test.ts@@ -1,7 +1,4 @@-import { Node, NodeKind } from '~/queries/schema/schema-general'-import { InsightModel } from '~/types'--import { extractValidationErrorCode, getQueryBasedInsightModel } from './utils'+import { extractValidationErrorCode } from './utils'describe('extractValidationErrorCode', () => {test.each([@@ -18,49 +15,3 @@ describe('extractValidationErrorCode', () => {expect(extractValidationErrorCode(error)).toBe(expected)})})--describe('getQueryBasedInsightModel', () => {- it.each([- [- 'derives dashboards from dashboard_tiles when the response omits the deprecated field',- {- dashboard_tiles: [- { id: 10, dashboard_id: 1 },- { id: 11, dashboard_id: 2 },- ],- },- [1, 2],- ],- [- 'keeps the server-provided dashboards value when present',- { dashboards: [3], dashboard_tiles: [{ id: 10, dashboard_id: 1 }] },- [3],- ],- ['leaves dashboards undefined when neither field is present', {}, undefined],- [- 'derives dashboards from dashboard_tiles when dashboards is null',- { dashboards: null, dashboard_tiles: [{ id: 10, dashboard_id: 1 }] },- [1],- ],- [- 'excludes soft-deleted tiles when deriving dashboards',- {- dashboard_tiles: [- { id: 10, dashboard_id: 1 },- { id: 11, dashboard_id: 2, deleted: true },- ],- },- [1],- ],- ])('%s', (_name, input, expected) => {- const result = getQueryBasedInsightModel(input as Partial<InsightModel>)- expect(result.dashboards).toEqual(expected)- })-- it('leaves the rest of the insight untouched', () => {- const query = { kind: NodeKind.TrendsQuery } as Node- const result = getQueryBasedInsightModel({ id: 7, name: 'Pageviews', query })-- expect(result).toEqual({ id: 7, name: 'Pageviews', query })- })-})diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.tsindex b6b34b6b9dff..5866a9b0dd44 100644--- a/frontend/src/queries/nodes/InsightViz/utils.ts+++ b/frontend/src/queries/nodes/InsightViz/utils.ts@@ -15,7 +15,7 @@ import {NodeKind,} from '~/queries/schema/schema-general'import { isInsightQueryWithSeries, setLatestVersionsOnQuery } from '~/queries/utils'-import { ActionType, DashboardTile, DashboardType, InsightModel, InsightType } from '~/types'+import { ActionType, InsightModel, InsightType } from '~/types'import { ProductAnalyticsInsightNodeKind, getNodeKindToDefaultQuery } from '../InsightQuery/defaults'@@ -68,19 +68,6 @@ export const getCachedResults = (return cachedInsight}-/**- * Backfill the deprecated `dashboards` field from `dashboard_tiles`.- *- * Session-authenticated callers already never receive `dashboards`, and token callers will stop- * receiving it too, so derive it here to keep the remaining readers working whether or not the- * response still carries the field.- */-export function getQueryBasedInsightModel<T extends InsightModel | Partial<InsightModel>>(insight: T): T {- const dashboards =- insight.dashboards ?? insight.dashboard_tiles?.filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)- return { ...insight, ...(dashboards ? { dashboards } : {}) }-}-export const queryFromKind = (kind: ProductAnalyticsInsightNodeKind,filterTestAccountsDefault: boolean@@ -136,24 +123,6 @@ export const getDefaultQuery = (throw new Error('encountered unexpected type for view')}-/** Backfill the deprecated `dashboards` field on each tile's insight. */-export const getQueryBasedDashboard = (dashboard: DashboardType | null): DashboardType | null => {- if (dashboard == null) {- return null- }-- return {- ...dashboard,- tiles: dashboard.tiles?.map(- (tile) =>- ({- ...tile,- ...(tile.insight != null ? { insight: getQueryBasedInsightModel(tile.insight) } : {}),- }) as DashboardTile- ),- }-}-// Statuses whose responses carry an actionable validation message: 400 (bad query), 512 (query// estimated too expensive to run), 513 (out of memory)export const VALIDATION_ERROR_STATUSES = new Set([400, 512, 513])diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.tsindex 5d1339648877..632ffc931ec4 100644--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts@@ -33,7 +33,6 @@ describe('dashboardBreakdownColors', () => {created_at: '2023-01-01T00:00:00Z',created_by: null,is_sample: false,- dashboards: null,dashboard_tiles: null,updated_at: '2023-01-01T00:00:00Z',last_modified_at: '2023-01-01T00:00:00Z',diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 22258ffbd018..575f02579d19 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -21,6 +21,7 @@ import { parseDashboardId } from 'scenes/dashboard/Dashboard'import { dashboardInsightColorsModalLogic } from 'scenes/dashboard/dashboardInsightColorsModalLogic'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'import * as dashboardUtils from 'scenes/dashboard/dashboardUtils'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import * as widgetFetchUtils from 'scenes/dashboard/widgetFetchUtils'import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'@@ -277,11 +278,10 @@ describe('dashboardLogic', () => {// update the insightconst insightId = tileToUpdate.insight.idconst insight = insights[insightId]- insight.dashboards?.splice(- insight.dashboards?.findIndex((d) => d === from.id),- 1- )- insight.dashboards?.push(toDashboard)+ insight.dashboard_tiles = [+ ...(insight.dashboard_tiles || []).filter((t) => t.dashboard_id !== from.id),+ { id: removedTile.id, dashboard_id: toDashboard },+ ]// add the tile to the target dashboardremovedTile.insight = insight@@ -299,19 +299,26 @@ describe('dashboardLogic', () => {const insightId = boxToId(params.id as string | readonly string[])const starting: InsightModel = insights[insightId]+ // like a session response, the stored insight carries its membership as tiles only+ const { dashboards: requestedDashboards, ...rest } = updates as Partial<InsightModel>+ const nextDashboards = requestedDashboards ?? liveDashboardIds(starting.dashboard_tiles)insights[insightId] = {...starting,- ...updates,+ ...rest,+ dashboard_tiles: nextDashboards.map((dashboardId) => ({+ id: insightId,+ dashboard_id: dashboardId,+ })),}- starting.dashboards?.forEach((dashboardId) => {+ liveDashboardIds(starting.dashboard_tiles).forEach((dashboardId) => {// remove this insight from any dashboard it is already ondashboards[dashboardId].tiles = dashboards[dashboardId].tiles.filter((t) => !!t.insight && t.insight.id !== starting.id)})- insights[insightId].dashboards?.forEach((dashboardId: number) => {+ nextDashboards.forEach((dashboardId: number) => {// then add it to any it new referencesdashboards[dashboardId].tiles.push(tileFromInsight(insights[insightId]))})@@ -1362,7 +1369,6 @@ describe('dashboardLogic', () => {.map((t) => t.insight!)const withBreakdowns = (insight: typeof firstInsight, breakdownValues: string[]): typeof firstInsight => ({...insight,- dashboards: [5],dashboard_tiles: [{ id: 1, dashboard_id: 5 }],result: breakdownValues.map((breakdown_value) => ({action: { order: 0 },@@ -1404,7 +1410,6 @@ describe('dashboardLogic', () => {for (const tileInsight of tileInsights) {dashboardsModel.actions.updateDashboardInsight({...tileInsight,- dashboards: [5],dashboard_tiles: [{ id: 1, dashboard_id: 5 }],result: [{ action: { order: 0 }, breakdown_value: ['Chrome'] },@@ -1439,7 +1444,6 @@ describe('dashboardLogic', () => {await expectLogic(logic, () => {dashboardsModel.actions.updateDashboardInsight({...tileInsight,- dashboards: [5],dashboard_tiles: [{ id: 1, dashboard_id: 5 }],result: [{ action: { order: 0 }, breakdown_value: ['Chrome'] }],query: {@@ -1488,7 +1492,6 @@ describe('dashboardLogic', () => {breakdownValues: string[] | null): typeof firstInsight => ({...insight,- dashboards: [5],dashboard_tiles: [{ id: 1, dashboard_id: 5 }],result: breakdownValues? breakdownValues.map((breakdown_value) => ({ action: { order: 0 }, breakdown_value }))@@ -2513,6 +2516,21 @@ describe('dashboardLogic', () => {)})+ it('records a copied insight tile on the source tile, so the copy menu treats the destination as taken', async () => {+ // insight 800 starts on dashboard 9 and 10+ await expectLogic(logic).toFinishAllListeners()+ const sourceTile = logic.values.insightTiles[0]+ jest.spyOn(api, 'create').mockResolvedValueOnce({ id: 8, tiles: [{ id: 555, insight: { id: 800 } }] })++ await expectLogic(logic, () => {+ logic.actions.copyToDashboard(sourceTile, 9, 8, 'targetDashboard')+ }).toFinishAllListeners()++ const insightTiles = logic.values.insightTiles[0].insight!.dashboard_tiles+ expect(insightTiles).toContainEqual({ id: 555, dashboard_id: 8 })+ expect(liveDashboardIds(insightTiles)).toEqual([9, 10, 8])+ })+it('adds tile on moveToDashboardSuccess', async () => {const dashboardEightlogic = dashboardLogic({ id: 8 })dashboardEightlogic.mount()@@ -4500,7 +4518,7 @@ describe('dashboardLogic', () => {expect(fiveLogic.values.insightTiles.map((t) => ({short_id: t.insight!.short_id,- dashboards: t.insight!.dashboards,+ dashboards: liveDashboardIds(t.insight!.dashboard_tiles),}))).toEqual([{ dashboards: [5, 6], short_id: '172' },@@ -4509,17 +4527,25 @@ describe('dashboardLogic', () => {expect(nineLogic.values.insightTiles.map((t) => ({short_id: t.insight!.short_id,- dashboards: t.insight!.dashboards,+ dashboards: liveDashboardIds(t.insight!.dashboard_tiles),}))).toEqual([{ dashboards: [9, 10], short_id: '800' }])- const changedInsight: InsightModel = { ...insight800(), dashboards: [10, 5] } // Moved from to 9 to 5+ // Moved from 9 to 5. The soft-deleted tile on 9 must not count as membership.+ const changedInsight: InsightModel = {+ ...insight800(),+ dashboard_tiles: [+ { id: 1, dashboard_id: 9, deleted: true },+ { id: 2, dashboard_id: 10 },+ { id: 3, dashboard_id: 5 },+ ],+ }dashboardsModel.actions.updateDashboardInsight(changedInsight, [9])expect(fiveLogic.values.insightTiles.map((t) => ({short_id: t.insight!.short_id,- dashboards: t.insight!.dashboards,+ dashboards: liveDashboardIds(t.insight!.dashboard_tiles),}))).toEqual([{ dashboards: [5, 6], short_id: '172' },@@ -4528,7 +4554,7 @@ describe('dashboardLogic', () => {expect(nineLogic.values.insightTiles.map((t) => ({short_id: t.insight!.short_id,- dashboards: t.insight!.dashboards,+ dashboards: liveDashboardIds(t.insight!.dashboard_tiles),}))).toEqual([])// Ensuring we do go back to the API for 800, which was added to dashboard 5diff --git a/frontend/src/scenes/dashboard/dashboardLogic.testHelpers.ts b/frontend/src/scenes/dashboard/dashboardLogic.testHelpers.tsindex 7eadfebc45b0..afded0504a5e 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.testHelpers.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.testHelpers.ts@@ -1,10 +1,9 @@-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'import { DashboardFilter } from '~/queries/schema/schema-general'import { DashboardTile, DashboardType, InsightModel } from '~/types'import _dashboardJson from './__mocks__/dashboard.json'-const dashboardJson = getQueryBasedDashboard(_dashboardJson as any as DashboardType)!+const dashboardJson = _dashboardJson as any as DashboardTypeexport function insightOnDashboard(insightId: number,@@ -21,7 +20,6 @@ export function insightOnDashboard(}return {...tile.insight,- dashboards: dashboardsRelation,dashboard_tiles: dashboardsRelation.map((dashboardId) => ({ id: insight.id!, dashboard_id: dashboardId })),query: { ...tile.insight.query, ...insight.query, kind: (tile.insight.query?.kind || insight.query?.kind)! },}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 14116dd0be5e..23eafc6c5f70 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -58,6 +58,7 @@ import { shouldCancelQuery } from 'lib/utils/requests'import { toParams } from 'lib/utils/url'import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'import { BREAKPOINTS, dashboardToSaveableTemplate, getDashboardTileDisplayName } from 'scenes/dashboard/dashboardUtils'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'import {chunkTileIds,@@ -82,7 +83,6 @@ import { dashboardsModel } from '~/models/dashboardsModel'import { insightsModel } from '~/models/insightsModel'import { variableDataLogic } from '~/queries/nodes/DataVisualization/Components/Variables/variableDataLogic'import { Variable } from '~/queries/nodes/DataVisualization/types'-import { getQueryBasedDashboard, getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import {BreakdownFilter,CompareFilter,@@ -272,11 +272,8 @@ const tileLayoutsFromDashboard = (return tileIdToLayouts}-function mergeUpdatedWidgetTileIntoDashboard(- dashboard: DashboardType,- updatedTile: DashboardTile-): DashboardType | null {- return getQueryBasedDashboard({+function mergeUpdatedWidgetTileIntoDashboard(dashboard: DashboardType, updatedTile: DashboardTile): DashboardType {+ return {...dashboard,tiles: dashboard.tiles.map((existingTile) => {if (existingTile.id !== updatedTile.id) {@@ -292,7 +289,7 @@ function mergeUpdatedWidgetTileIntoDashboard(: (updatedTile.widget ?? existingTile.widget),}}),- } as DashboardType)+ } as DashboardType}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -581,12 +578,12 @@ export interface dashboardLogicActions {errorObject?: any}duplicateTileSuccess: (- dashboard: DashboardType | null,+ dashboard: DashboardType,payload?: {tile: DashboardTile}) => {- dashboard: DashboardType | null+ dashboard: DashboardTypepayload?: {tile: DashboardTile}@@ -1706,7 +1703,7 @@ export const dashboardLogic = kea<dashboardLogicType>([throw new Error('Dashboard response was empty or invalid')}- return getQueryBasedDashboard(dashboard)+ return dashboard} catch (error: any) {if (error.status === 404) {return null@@ -1747,9 +1744,7 @@ export const dashboardLogic = kea<dashboardLogicType>([// Keep readable tiles until a complete replacement is available, even if retry fails.retriedDashboard = { ...data.dashboard, tiles: [...(data.dashboard.tiles ?? [])] }} else {- actions.loadDashboardMetadataSuccess(- getQueryBasedDashboard(data.dashboard as DashboardType)- )+ actions.loadDashboardMetadataSuccess(data.dashboard as DashboardType)}} else if (data.type === 'tile') {if (retriedDashboard) {@@ -1764,7 +1759,7 @@ export const dashboardLogic = kea<dashboardLogicType>([cache.dashboardStreamActive = falseif (metadataReceived) {if (retriedDashboard) {- actions.loadDashboardMetadataSuccess(getQueryBasedDashboard(retriedDashboard))+ actions.loadDashboardMetadataSuccess(retriedDashboard)}actions.tileStreamingComplete()} else {@@ -1891,7 +1886,7 @@ export const dashboardLogic = kea<dashboardLogicType>([})}cache.dashboardChangesPersisted = true- return getQueryBasedDashboard(updatedDashboard)+ return updatedDashboard} catch (e) {lemonToast.error('Could not update dashboard: ' + String(e))return values.dashboard@@ -1959,7 +1954,7 @@ export const dashboardLogic = kea<dashboardLogicType>([tiles: tilesToUpdate.length > 0 ? tilesToUpdate : undefined,})- return getQueryBasedDashboard(dashboard)+ return dashboard} catch (e) {// Re-throw so duplicateTileFailure fires. Swallowing the error resolved it as a// success, so the tile refreshed with no copy and the user kept clicking.@@ -1983,7 +1978,7 @@ export const dashboardLogic = kea<dashboardLogicType>([to_dashboard: toDashboard,})- return getQueryBasedDashboard(dashboard)+ return dashboard},copyToDashboard: async ({ tile, fromDashboard, toDashboard, toDashboardName }) => {if (!tile?.insight && !tile?.text && !tile?.button_tile && !tile?.widget) {@@ -2018,19 +2013,26 @@ export const dashboardLogic = kea<dashboardLogicType>([try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. dashboardsCopyTileCreate() from 'products/dashboards/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- await api.create(+ const destination = await api.create<DashboardType | null>(`api/projects/${teamLogic.values.currentTeamId}/dashboards/${toDashboard}/copy_tile`,{ fromDashboardId: fromDashboard, tileId: tile.id })if (tile.insight) {const insight = tile.insight- const nextDashboards = insight.dashboards?.includes(toDashboard)- ? insight.dashboards- : [...(insight.dashboards || []), toDashboard]- dashboardsModel.actions.updateDashboardInsight({ ...insight, dashboards: nextDashboards }, [- toDashboard,- ])+ // The copy is a new tile, so its id comes from the destination dashboard.+ const copiedTile = destination?.tiles?.find((t) => t.insight?.id === insight.id)+ const nextDashboardTiles =+ copiedTile && !liveDashboardIds(insight.dashboard_tiles).includes(toDashboard)+ ? [+ ...(insight.dashboard_tiles || []),+ { id: copiedTile.id, dashboard_id: toDashboard },+ ]+ : insight.dashboard_tiles+ dashboardsModel.actions.updateDashboardInsight(+ { ...insight, dashboard_tiles: nextDashboardTiles },+ [toDashboard]+ )}posthog.capture('dashboard widget copied to other dashboard', {@@ -2091,10 +2093,9 @@ export const dashboardLogic = kea<dashboardLogicType>([description,showDescription: shouldShowDescription ? true : undefined,})- const dashboard = mergeUpdatedWidgetTileIntoDashboard(values.dashboard, updatedTile)- if (dashboard) {- dashboardsModel.actions.updateDashboardSuccess(dashboard)- }+ dashboardsModel.actions.updateDashboardSuccess(+ mergeUpdatedWidgetTileIntoDashboard(values.dashboard, updatedTile)+ )if (config !== undefined) {actions.scheduleRefreshDashboardWidgets(tile.id)}@@ -2330,6 +2331,7 @@ export const dashboardLogic = kea<dashboardLogicType>([}if (state) {+ const insightIsOnThisDashboard = liveDashboardIds(insight.dashboard_tiles).includes(props.id)const tileIndex = state.tiles.findIndex((t) => !!t.insight && t.insight.short_id === insight.short_id)@@ -2337,12 +2339,12 @@ export const dashboardLogic = kea<dashboardLogicType>([const newTiles = state.tiles.slice()if (tileIndex >= 0) {- if (insight.dashboards?.includes(props.id)) {+ if (insightIsOnThisDashboard) {newTiles[tileIndex] = {...newTiles[tileIndex],insight: insight,}- } else if (!insight.dashboards?.includes(props.id)) {+ } else {newTiles.splice(tileIndex, 1)}} else {@@ -2410,16 +2412,9 @@ export const dashboardLogic = kea<dashboardLogicType>([return state}- const transformedTile = {- ...tile,- ...(tile.insight != null ? { insight: getQueryBasedInsightModel(tile.insight) } : {}),- }-- let newTiles = [...state.tiles, transformedTile]-return {...state,- tiles: newTiles,+ tiles: [...state.tiles, tile],} as DashboardType},},@@ -4028,13 +4023,7 @@ export const dashboardLogic = kea<dashboardLogicType>([const removedMessage = isWidgetTile ? 'widget removed' : 'has been removed from the dashboard'const toastId = `remove-tile-${tile.id}`const otherDashboardIds = new Set(- (- tile.insight?.dashboard_tiles- ?.filter((dashboardTile) => !dashboardTile.deleted)- .map((dashboardTile) => dashboardTile.dashboard_id) ??- tile.insight?.dashboards ??- []- ).filter((dashboardId) => dashboardId !== props.id)+ liveDashboardIds(tile.insight?.dashboard_tiles).filter((dashboardId) => dashboardId !== props.id))const canDeleteInsight =tile.insight?.user_access_level !== AccessControlLevel.Viewer &&@@ -4045,7 +4034,8 @@ export const dashboardLogic = kea<dashboardLogicType>([AccessControlLevel.Editor))const deleteInsight = (): void => {- if (!tile.insight) {+ const insight = tile.insight+ if (!insight) {return}@@ -4086,13 +4076,13 @@ export const dashboardLogic = kea<dashboardLogicType>([other_dashboard_count: otherDashboardCount,})return deleteInsightWithUndo({- object: { ...tile.insight!, dashboards: dashboardIds },+ object: { ...insight, dashboards: dashboardIds },endpoint: `projects/${values.currentTeamId}/insights`,- callback: (undo, insight) => {+ callback: (undo) => {const updatedInsight = {...insight,deleted: !undo,- dashboards: undo ? insight.dashboards : [],+ dashboard_tiles: undo ? insight.dashboard_tiles : [],}dashboardsModel.actions.updateDashboardInsight(updatedInsight, dashboardIds)if (!undo) {@@ -4114,12 +4104,13 @@ export const dashboardLogic = kea<dashboardLogicType>([if (tile.insight) {const insight = tile.insight- const nextDashboards = insight.dashboards?.includes(props.id)- ? insight.dashboards- : [...(insight.dashboards || []), props.id]- dashboardsModel.actions.updateDashboardInsight({ ...insight, dashboards: nextDashboards }, [- props.id,- ])+ const nextDashboardTiles = liveDashboardIds(insight.dashboard_tiles).includes(props.id)+ ? insight.dashboard_tiles+ : [...(insight.dashboard_tiles || []), { id: tile.id, dashboard_id: props.id }]+ dashboardsModel.actions.updateDashboardInsight(+ { ...insight, dashboard_tiles: nextDashboardTiles },+ [props.id]+ )}actions.loadDashboard({ action: DashboardLoadAction.Update })@@ -4207,12 +4198,9 @@ export const dashboardLogic = kea<dashboardLogicType>([if (updatedTile.insight) {const ins = updatedTile.insight- const nextDashboardTiles = nextTilePlacement(ins.dashboard_tiles ?? undefined)- const nextDashboards = [...(ins.dashboards?.filter((d) => d !== fromDashboard) || []), toDashboard]updatedTile.insight = {...ins,- dashboards: nextDashboards,- dashboard_tiles: nextDashboardTiles,+ dashboard_tiles: nextTilePlacement(ins.dashboard_tiles ?? undefined),}dashboardsModel.actions.updateDashboardInsight(updatedTile.insight, [toDashboard])}@@ -4291,7 +4279,7 @@ export const dashboardLogic = kea<dashboardLogicType>([values.dashboard?.customization?.layout_compaction ?? DashboardGridCompaction.Vertical,})- dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard), {+ dashboardsModel.actions.updateDashboardSuccess(dashboard, {layoutsPersisted: true,})eventUsageLogic.actions.reportDashboardTileDensityConfigured(tileSpacing)@@ -4336,7 +4324,7 @@ export const dashboardLogic = kea<dashboardLogicType>([grid_spacing: values.dashboard?.customization?.tile_spacing ?? 'standard',})- dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard), {+ dashboardsModel.actions.updateDashboardSuccess(dashboard, {layoutsPersisted: true,})} catch (error) {@@ -4712,10 +4700,10 @@ export const dashboardLogic = kea<dashboardLogicType>([)const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {- const dashboard = getQueryBasedDashboard({+ const dashboard = {...values.dashboard,tiles: [...values.dashboard.tiles, ...createdTiles],- } as DashboardType)+ } as DashboardTypeif (dashboard) {dashboardsModel.actions.updateDashboardSuccess(dashboard)@@ -4754,7 +4742,7 @@ export const dashboardLogic = kea<dashboardLogicType>([filters: settings.filters,variables: settings.variables,})- actions.saveDashboardChangesSuccess(getQueryBasedDashboard(dashboard), settings)+ actions.saveDashboardChangesSuccess(dashboard, settings)actions.clearDashboardSettingsUrlOverrides()actions.clearInitialDashboardSettingsOverride()if (!values.previewedDashboardSettings) {diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex b51dbe9bb71f..d742dfbc7d35 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -15,7 +15,6 @@ import { objectClean } from 'lib/utils/objects'import { isDeterministicClientError, shouldCancelQuery } from 'lib/utils/requests'import { toParams } from 'lib/utils/url'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { isExpiredQueryStatusError, parseErrorMessage, pollForResults } from '~/queries/query'import { DashboardFilter, HogQLVariable, QueryStatus, TileFilters } from '~/queries/schema/schema-general'import {@@ -382,8 +381,7 @@ export async function getInsightWithRetry(})}`// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.const insightResponse: Response = await api.getResponse(apiUrl, methodOptions)- const legacyInsight: InsightModel | null = await getJSONOrNull(insightResponse)- const result = legacyInsight !== null ? getQueryBasedInsightModel(legacyInsight) : null+ const result: InsightModel | null = await getJSONOrNull(insightResponse)if (result?.query_status?.error_code === RATE_LIMITED_ERROR_CODE ||@@ -421,13 +419,13 @@ export async function getInsightWithRetry(cacheUrl,methodOptions)- const legacyInsight: InsightModel | null = await getJSONOrNull(refreshedInsightResponse)- if (legacyInsight) {- const queryBasedInsight = getQueryBasedInsightModel(legacyInsight)+ const refreshedInsight: InsightModel | null =+ await getJSONOrNull(refreshedInsightResponse)+ if (refreshedInsight) {return {- ...queryBasedInsight,- query_status: queryBasedInsight.query_status?.error- ? queryBasedInsight.query_status+ ...refreshedInsight,+ query_status: refreshedInsight.query_status?.error+ ? refreshedInsight.query_status: finalStatus,}}@@ -453,7 +451,7 @@ export async function getInsightWithRetry(// nosemgrep: prefer-codegen-api -- Preserve the existing dynamic insight request and its filter overrides.const rerunResponse = await api.get(asyncApiUrl('async'), methodOptions)if (rerunResponse?.result != null && !rerunResponse.query_status?.error) {- return getQueryBasedInsightModel(rerunResponse)+ return rerunResponse}if (rerunResponse?.result == null &&@@ -467,7 +465,7 @@ export async function getInsightWithRetry(if (rerunResponse?.result == null) {throw new Error('The rerun returned no result')}- return getQueryBasedInsightModel(rerunResponse)+ return rerunResponse})if (!rerun) {throw new Error('The rerun returned no result')diff --git a/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts b/frontend/src/scenes/dashboard/duplicateDashboardLogic.tsindex 290190d339b3..e5910c54add0 100644--- a/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts+++ b/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts@@ -44,9 +44,18 @@ export interface duplicateDashboardLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface duplicateDashboardLogicActions {- insightsAddedToDashboard: (args_0: { dashboardId: number; insightIds: number[] }) => {+ insightsAddedToDashboard: (args_0: {dashboardId: number- insightIds: number[]+ tiles: {+ id: number+ insightId: number+ }[]+ }) => {+ dashboardId: number+ tiles: {+ id: number+ insightId: number+ }[]} // insightsModelhideDuplicateDashboardModal: () => {value: true@@ -157,12 +166,12 @@ export const duplicateDashboardLogic = kea<duplicateDashboardLogicType>([if (!payload?.duplicateTiles) {// any existing mounted insight will need to increment its dashboard count to update turbo mode- const insightsOnDuplicatedDashboard = dashboard.tiles- .map((t) => t.insight?.id)- .filter((id): id is number => !!id)+ const insightTilesOnDuplicatedDashboard = dashboard.tiles.flatMap((t) =>+ t.insight?.id ? [{ id: t.id, insightId: t.insight.id }] : []+ )actions.insightsAddedToDashboard({dashboardId: dashboard.id,- insightIds: insightsOnDuplicatedDashboard,+ tiles: insightTilesOnDuplicatedDashboard,})}diff --git a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsxindex 86532d3302f2..688f80ef7dad 100644--- a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx+++ b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx@@ -41,7 +41,6 @@ function DashboardButtonTileItemInternal(const dashboardWidgetMenusLogicProps = {instanceKey: buttonId != null ? `button-${buttonId}` : `button-tile-${tile.id}`,dashboardId,- dashboards: undefined,dashboard_tiles: tile.button_tile?.dashboard_tiles,}const { copyToDestinations } = useValues(dashboardWidgetMenusLogic(dashboardWidgetMenusLogicProps))diff --git a/frontend/src/scenes/dashboard/liveDashboardIds.ts b/frontend/src/scenes/dashboard/liveDashboardIds.tsnew file mode 100644index 000000000000..b6a57c52663e--- /dev/null+++ b/frontend/src/scenes/dashboard/liveDashboardIds.ts@@ -0,0 +1,10 @@+import { DashboardTileBasicType } from '~/types'++/**+ * Soft-deleted tiles do not count, because the backend does not count them either. Session responses omit+ * the deprecated insight `dashboards` field, and a PATCH of it replaces the whole membership, so a writer+ * builds the new list from this one.+ */+export function liveDashboardIds(tiles: DashboardTileBasicType[] | null | undefined): number[] {+ return (tiles || []).filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)+}diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.tsindex 2b161235c352..18b0b0058aa8 100644--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts@@ -26,7 +26,6 @@ import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { dashboardsModel } from '~/models/dashboardsModel'-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'import { NodeKind } from '~/queries/schema/schema-general'import { isInsightVizNode } from '~/queries/utils'import {@@ -391,8 +390,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([)actions.hideNewDashboardModal()actions.resetNewDashboard()- const queryBasedDashboard = getQueryBasedDashboard(result)- queryBasedDashboard && dashboardsModel.actions.addDashboardSuccess(queryBasedDashboard)+ dashboardsModel.actions.addDashboardSuccess(result)actions.submitNewDashboardSuccessWithResult(result, undefined, setAsHomeTabDashboard, openAI)if (titleMentionsMCP(result.name)) {tryShowMCPAnalyticsNudge('dashboard')@@ -497,8 +495,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([)actions.resetNewDashboard()- const queryBasedDashboard = getQueryBasedDashboard(result)- queryBasedDashboard && dashboardsModel.actions.addDashboardSuccess(queryBasedDashboard)+ dashboardsModel.actions.addDashboardSuccess(result)actions.submitNewDashboardSuccessWithResult(result, variables, setAsHomeTabDashboard)posthog.capture('dashboard created from template', {diff --git a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts b/frontend/src/scenes/data-management/events/eventInsightsLogic.tsindex 93f372550fda..0a2485d1ccea 100644--- a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts+++ b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts@@ -8,8 +8,6 @@ import { toParams } from 'lib/utils/url'import { InsightsResult, SavedInsightFilters, cleanFilters } from 'scenes/saved-insights/savedInsightsLogic'import { teamLogic } from 'scenes/teamLogic'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'-export interface EventInsightsLogicProps {event: string}@@ -118,7 +116,7 @@ export const eventInsightsLogic = kea<eventInsightsLogicType>([return {...response,filters,- results: (response?.results ?? []).map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),+ results: response?.results ?? [],} as InsightsResult},},diff --git a/frontend/src/scenes/data-management/variables/insightsLoader.ts b/frontend/src/scenes/data-management/variables/insightsLoader.tsindex c1a3c34a9b81..26f20c04e44d 100644--- a/frontend/src/scenes/data-management/variables/insightsLoader.ts+++ b/frontend/src/scenes/data-management/variables/insightsLoader.ts@@ -2,7 +2,6 @@ import { lemonToast } from '@posthog/lemon-ui'import api, { CountedPaginatedResponse } from 'lib/api'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { InsightModel } from '~/types'import { insightUsesVariable } from './utils'@@ -28,19 +27,17 @@ export async function fetchInsightsUsingVariable(teamId: number, variableId: str// Paginate through all insightswhile (true) {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use insightsList() from 'products/product_analytics/frontend/generated/api' instead.- const legacyResponse: CountedPaginatedResponse<InsightModel> = await api.get(+ const response: CountedPaginatedResponse<InsightModel> = await api.get(`api/projects/${teamId}/insights/?basic=true&limit=${limit}&offset=${offset}`)- const insights = legacyResponse.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))-// Filter insights that use this variable- const filtered = insights.filter((insight) => insightUsesVariable(insight, variableId))+ const filtered = response.results.filter((insight) => insightUsesVariable(insight, variableId))matchingInsights.push(...filtered)// Stop if we've fetched all insights- if (legacyResponse.results.length < limit || !legacyResponse.next) {+ if (response.results.length < limit || !response.next) {break}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex b73c2ec7d4cc..dfcfe16cdb22 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -79,7 +79,6 @@ const MOCK_DATA_TABLE_INSIGHT: InsightModel = {name: 'DataTable Insight',query: MOCK_DATA_TABLE_INSIGHT_QUERY,result: null,- dashboards: [],dashboard_tiles: [],saved: true,order: null,@@ -108,7 +107,6 @@ const MOCK_INSIGHT: InsightModel = {name: 'Test Insight',query: MOCK_INSIGHT_QUERY,result: null,- dashboards: [],dashboard_tiles: [],saved: true,order: null,@@ -3370,28 +3368,20 @@ describe('sqlEditorLogic', () => {}})- // The update path unions the target dashboard with the insight's existing links, read- // from both dashboard_tiles (preferred) and the legacy dashboards field, deduped.+ // The update path unions the target dashboard with the insight's existing links from+ // dashboard_tiles, deduped.it.each([- {- name: 'merges the dashboard with existing legacy dashboards links',- dashboards: [7],- dashboardTiles: [],- expected: [7, DASHBOARD_ID],- },{name: 'merges the dashboard with existing dashboard_tiles links',- dashboards: [],- dashboardTiles: [{ id: 1, dashboard_id: 7, deleted: null }],+ dashboardTiles: [{ id: 1, dashboard_id: 7 }],expected: [7, DASHBOARD_ID],},{name: 'does not duplicate a dashboard the insight is already linked to',- dashboards: [],- dashboardTiles: [{ id: 1, dashboard_id: DASHBOARD_ID, deleted: null }],+ dashboardTiles: [{ id: 1, dashboard_id: DASHBOARD_ID }],expected: [DASHBOARD_ID],},- ])('$name', async ({ dashboards, dashboardTiles, expected }) => {+ ])('$name', async ({ dashboardTiles, expected }) => {const updateSpy = jest.spyOn(insightsApi, 'update').mockResolvedValue(MOCK_INSIGHT)logic = sqlEditorLogic({@@ -3405,7 +3395,6 @@ describe('sqlEditorLogic', () => {const insightOnDashboards = {...MOCK_INSIGHT,- dashboards,dashboard_tiles: dashboardTiles,} as InsightModellogic.actions.editInsight(MOCK_INSIGHT_QUERY.source.query, insightOnDashboards)diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 3831b4f3997a..345dd27bdc07 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -50,6 +50,7 @@ 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'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import {filtersPlaceholderBindings,@@ -3149,10 +3150,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([// dropping the insight's existing dashboard links.const dashboardId = values.dashboardIdif (dashboardId) {- const existingDashboardIds = [- ...(values.editingInsight.dashboard_tiles?.map((tile) => tile.dashboard_id) ?? []),- ...(values.editingInsight.dashboards ?? []),- ]+ const existingDashboardIds = liveDashboardIds(values.editingInsight.dashboard_tiles)insightRequest.dashboards = Array.from(new Set([...existingDashboardIds, dashboardId]))}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex d5eaab31cbaf..91a01b7b4c3a 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -56,7 +56,6 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePaneimport { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { groupsModel } from '~/models/groupsModel'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import {AccessControlLevel,@@ -3546,7 +3545,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([const response = await api.get<PaginatedResponse<InsightModel>>(`api/projects/${values.currentProjectId}/insights/?feature_flag=${values.featureFlag.key}&order=-last_modified_at&limit=5`)- return response.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))+ return response.results}return []},diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex c8fedf000c54..280d69a0f8dc 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -299,7 +299,7 @@ export interface insightDataLogicActions {created_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null- dashboards: number[] | null+ dashboards?: number[] | undefineddeleted: booleanderived_name?: string | null | undefineddescription?: string | undefined@@ -356,7 +356,7 @@ export interface insightDataLogicActions {created_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null- dashboards: number[] | null+ dashboards?: number[] | undefineddeleted: booleanderived_name?: string | null | undefineddescription?: string | undefineddiff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex 7a0cffbbd636..d451c3b47516 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -9,6 +9,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { objectsEqual } from 'lib/utils/objects'import 'lib/constants'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { savedInsightsLogic } from 'scenes/saved-insights/savedInsightsLogic'import { sceneLogic } from 'scenes/sceneLogic'import { teamLogic } from 'scenes/teamLogic'@@ -88,11 +89,13 @@ const partialInsight44 = {filters: API_FILTERS,}-const patchResponseFor = (- payload: Record<string, any>,- id: string,- filters: Record<string, any>-): Record<string, any> => {+const TILES_ON_DASHBOARDS_1_2_3 = [+ { id: 11, dashboard_id: 1 },+ { id: 12, dashboard_id: 2 },+ { id: 13, dashboard_id: 3 },+]++const patchResponseFor = (id: string, filters: Record<string, any>): Record<string, any> => {return {result: id === '42' ? ['result from api'] : null,id: id === '42' ? 42 : 43,@@ -101,7 +104,6 @@ const patchResponseFor = (name: id === '42' ? undefined : 'Foobar 43',description: id === '42' ? undefined : 'Lorem ipsum.',tags: id === '42' ? undefined : ['good'],- dashboards: payload['dashboards'],dashboard_tiles: id === '43' ? [{ dashboard_id: MOCK_DASHBOARD_ID }] : undefined,}}@@ -112,7 +114,6 @@ function insightModelWith(properties: Record<string, any>): InsightModel {short_id: Insight42,result: ['result 42'],query: API_QUERY,- dashboards: [],dashboard_tiles: [],saved: true,name: 'new name',@@ -190,7 +191,7 @@ describe('insightLogic', () => {result: ['result 42'],filters: API_FILTERS,name: 'original name',- dashboards: [1, 2, 3],+ dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,},{ id: 43, short_id: Insight43, result: ['result 43'], filters: API_FILTERS },],@@ -211,7 +212,7 @@ describe('insightLogic', () => {short_id: shortId.toString(),filters: JSON.parse(url.searchParams.get('filters') || 'false') || API_FILTERS,name: 'original name',- dashboards: [1, 2, 3],+ dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,},],},@@ -263,9 +264,7 @@ describe('insightLogic', () => {},patch: {'/api/environments/:team_id/insights/:id': async ({ request, params }) => {- const payload = (await request.json()) as Record<string, any>const response = patchResponseFor(- payload,params.id as string,JSON.parse(new URL(request.url).searchParams.get('filters') || 'false'))@@ -641,6 +640,36 @@ describe('insightLogic', () => {await expectLogic(dashLogic).toDispatchActions(['loadDashboard'])})+ test.each([+ [+ 'sends the dashboards its live tiles sit on',+ [...TILES_ON_DASHBOARDS_1_2_3, { id: 14, dashboard_id: 4, deleted: true }],+ [1, 2, 3],+ ],+ ['sends no dashboards while its tiles are not loaded', undefined, undefined],+ ])('saving a saved insight %s', async (_name, dashboardTiles, expectedDashboards) => {+ const updateSpy = jest.spyOn(api.insights, 'update')+ const insightProps: InsightLogicProps = {+ dashboardItemId: Insight42,+ cachedInsight: {+ id: 42,+ short_id: Insight42,+ query: examples.FunnelsQuery,+ result: {},+ dashboard_tiles: dashboardTiles,+ },+ }+ logic = insightLogic(insightProps)+ logic.mount()+ insightDataLogic(insightProps).mount()++ await expectLogic(logic, () => {+ logic.actions.saveInsight()+ }).toFinishAllListeners()++ expect(updateSpy.mock.calls[0][1].dashboards).toEqual(expectedDashboards)+ })+test('updateInsight updates dashboards', async () => {savedInsightsLogic().mount()logic = insightLogic({@@ -792,11 +821,8 @@ describe('insightLogic', () => {tile: { insight: { id: 42 } } as DashboardTile,dashboardId: 3,})- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2] }),- })+ }).toFinishAllListeners()+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2])})it('does not reacts to removal of a different tile from dashboard', async () => {@@ -805,51 +831,51 @@ describe('insightLogic', () => {tile: { insight: { id: 12 } } as DashboardTile,dashboardId: 3,})- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2, 3] }),- })+ }).toFinishAllListeners()+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])})it('reacts to deletion of dashboard', async () => {await expectLogic(logic, () => {dashboardsModel.actions.deleteDashboardSuccess({ id: 3 } as DashboardType)- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2] }),- })+ }).toFinishAllListeners()+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2])})it('does not reacts to deletion of dashboard it is not on', async () => {await expectLogic(logic, () => {dashboardsModel.actions.deleteDashboardSuccess({ id: 1034 } as DashboardType)- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2, 3] }),- })+ }).toFinishAllListeners()+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])})it('reacts to duplication of dashboard attaching it to new dashboard', async () => {await expectLogic(logic, () => {- insightsModel.actions.insightsAddedToDashboard({ dashboardId: 1234, insightIds: [0, 1, 42] })- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2, 3, 1234] }),+ insightsModel.actions.insightsAddedToDashboard({+ dashboardId: 1234,+ tiles: [+ { id: 900, insightId: 0 },+ { id: 901, insightId: 1 },+ { id: 902, insightId: 42 },+ ],})+ }).toFinishAllListeners()+ expect(logic.values.insight.dashboard_tiles).toContainEqual({ id: 902, dashboard_id: 1234 })+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3, 1234])})it('does not react to duplication of dashboard that did not include this insight', async () => {await expectLogic(logic, () => {- insightsModel.actions.insightsAddedToDashboard({ dashboardId: 1234, insightIds: [0, 1, 2] })- })- .toFinishAllListeners()- .toMatchValues({- insight: expect.objectContaining({ dashboards: [1, 2, 3] }),+ insightsModel.actions.insightsAddedToDashboard({+ dashboardId: 1234,+ tiles: [+ { id: 900, insightId: 0 },+ { id: 901, insightId: 1 },+ { id: 902, insightId: 2 },+ ],})+ }).toFinishAllListeners()+ expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])})})@@ -1072,13 +1098,26 @@ describe('insightLogic', () => {expect(api.update).toHaveBeenCalledWith(expect.stringContaining('/insights/42'),- expect.objectContaining({ deleted: true })+ expect.objectContaining({ deleted: true, dashboards: [1, 2, 3] }))const expectedUrl = dashboardId ? urls.dashboard(dashboardId) : urls.savedInsights()await expectLogic(router).toDispatchActions([router.actionCreators.push(expectedUrl)])})+ it('keeps the remaining dashboards in the delete request after one of them is deleted', async () => {+ jest.spyOn(api, 'update')++ dashboardsModel.actions.deleteDashboardSuccess({ id: 3 } as DashboardType)+ logic.actions.confirmDeleteInsight(null)+ await expectLogic(logic).toFinishAllListeners()++ expect(api.update).toHaveBeenCalledWith(+ expect.stringContaining('/insights/42'),+ expect.objectContaining({ deleted: true, dashboards: [1, 2] })+ )+ })+it('restores insight on undo from dashboard', async () => {logic.actions.confirmDeleteInsight(5)await expectLogic(logic).toFinishAllListeners()@@ -1119,7 +1158,7 @@ describe('insightLogic', () => {// not the one passed in (which may have dashboard filter overrides)expect(api.create).toHaveBeenCalledWith(expect.stringContaining('/insights'),- expect.objectContaining({ name: 'original name (copy)' }),+ expect.objectContaining({ name: 'original name (copy)', dashboards: [1, 2, 3] }),expect.anything())})@@ -1465,7 +1504,6 @@ describe('insightLogic', () => {dashboardsModel.actions.updateDashboardInsight(insightModelWith({query: dashboardOverriddenQuery,- dashboards: [MOCK_DASHBOARD_ID],dashboard_tiles: [{ dashboard_id: MOCK_DASHBOARD_ID }],}),undefined,@@ -1479,7 +1517,7 @@ describe('insightLogic', () => {dashboardsModel.actions.updateDashboardInsight(insightModelWith({query: dashboardOverriddenQuery,- dashboards: [MOCK_DASHBOARD_ID],+ dashboard_tiles: [{ dashboard_id: MOCK_DASHBOARD_ID }],}))diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex eefe2f7b3426..0059b6cbe314 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -32,6 +32,7 @@ import { isEmptyObject, isObject } from 'lib/utils/guards'import { objectsEqual } from 'lib/utils/objects'import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { summarizeInsight } from 'scenes/insights/summarizeInsight'@@ -215,7 +216,7 @@ export interface insightLogicActions {created_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null- dashboards: number[] | null+ dashboards?: number[] | undefineddeleted: booleanderived_name?: string | null | undefineddescription?: string | undefined@@ -264,7 +265,7 @@ export interface insightLogicActions {created_at: stringcreated_by: UserBasicType | nulldashboard_tiles: DashboardTileBasicType[] | null- dashboards: number[] | null+ dashboards?: number[] | undefineddeleted: booleanderived_name?: string | null | undefineddescription?: string | undefined@@ -393,7 +394,7 @@ export interface insightLogicActions {created_at?: string | undefinedcreated_by?: UserBasicType | null | undefineddashboard_tiles?: DashboardTileBasicType[] | null | undefined- dashboards?: number[] | null | undefined+ dashboards?: number[] | undefineddeleted?: boolean | undefinedderived_name?: string | null | undefineddescription?: string | undefined@@ -441,7 +442,7 @@ export interface insightLogicActions {created_at?: string | undefinedcreated_by?: UserBasicType | null | undefineddashboard_tiles?: DashboardTileBasicType[] | null | undefined- dashboards?: number[] | null | undefined+ dashboards?: number[] | undefineddeleted?: boolean | undefinedderived_name?: string | null | undefineddescription?: string | undefined@@ -741,8 +742,9 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTyperesult: response.result || values.insight.result,}- const removedDashboards = (values.insight.dashboards || []).filter(- (d) => !updatedInsight.dashboards?.includes(d)+ const remainingDashboards = liveDashboardIds(updatedInsight.dashboard_tiles)+ const removedDashboards = liveDashboardIds(values.insight.dashboard_tiles).filter(+ (d) => !remainingDashboards.includes(d))dashboardsModel.actions.updateDashboardInsight(updatedInsight, removedDashboards)values.insight.short_id && refreshTreeItem('insight', String(values.insight.short_id))@@ -843,7 +845,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypereturn state}}- const targetDashboards = (insight?.dashboards || []).concat(extraDashboardIds || [])+ const targetDashboards = liveDashboardIds(insight?.dashboard_tiles).concat(extraDashboardIds || [])const updateIsForThisDashboard =insight?.short_id === state.short_id &&props.dashboardId &&@@ -876,10 +878,17 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType},[insightsModel.actionTypes.insightsAddedToDashboard]: (state: Partial<InsightModel>,- { dashboardId, insightIds }: { dashboardId: number; insightIds: number[] }+ { dashboardId, tiles }: { dashboardId: number; tiles: { id: number; insightId: number }[] }) => {- if (state.id != null && insightIds.includes(state.id)) {- return { ...state, dashboards: [...(state.dashboards || []), dashboardId] }+ const addedTile = state.id != null ? tiles.find((tile) => tile.insightId === state.id) : undefined+ if (addedTile) {+ return {+ ...state,+ dashboard_tiles: [+ ...(state.dashboard_tiles || []),+ { id: addedTile.id, dashboard_id: dashboardId },+ ],+ }}return state},@@ -888,7 +897,10 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType{ tile, dashboardId }: { tile?: DashboardTile; dashboardId?: number }) => {if (tile?.insight?.id === state.id) {- return { ...state, dashboards: state.dashboards?.filter((d: number) => d !== dashboardId) }+ return {+ ...state,+ dashboard_tiles: state.dashboard_tiles?.filter((t) => t.dashboard_id !== dashboardId),+ }}return state},@@ -897,7 +909,13 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType{ dashboard }: { dashboard: DashboardType }) => {const { id } = dashboard- return { ...state, dashboards: state.dashboards?.filter((d: number) => d !== id) }+ return {+ ...state,+ dashboard_tiles: state.dashboard_tiles?.filter((tile) => tile.dashboard_id !== id),+ // An unsaved insight must not ask to be placed on the deleted dashboard. A saved insight has+ // no `dashboards`, and an `undefined` one would replace the list a write builds from the tiles.+ ...(state.dashboards ? { dashboards: state.dashboards.filter((d: number) => d !== id) } : {}),+ }},},accessDeniedToInsight: [false, { setAccessDeniedToInsight: () => true }],@@ -1127,7 +1145,14 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypesaveInsight: async ({ redirectToViewMode, folder }) => {const insightNumericId =values.insight.id || (values.insight.short_id ? await getInsightId(values.insight.short_id) : undefined)- const { name, description, favorited, deleted, dashboards, tags } = values.insight+ const { name, description, favorited, deleted, tags } = values.insight+ // A new insight carries the dashboards to place it on. A saved one sends back the dashboards+ // it sits on. While its tiles are not loaded it sends nothing, because an empty list would+ // take it off every dashboard.+ const currentDashboards = values.insight.dashboard_tiles+ ? liveDashboardIds(values.insight.dashboard_tiles)+ : undefined+ const dashboards = insightNumericId ? currentDashboards : values.insight.dashboardslet savedInsight: InsightModel@@ -1413,7 +1438,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypeif (dashboardId) {router.actions.push(urls.dashboard(dashboardId))dashboardsModel.actions.updateDashboardInsight(- { ...(insight as InsightModel), deleted: true, dashboards: [] },+ { ...(insight as InsightModel), deleted: true, dashboard_tiles: [] },[dashboardId])} else {diff --git a/frontend/src/scenes/insights/utils/api.ts b/frontend/src/scenes/insights/utils/api.tsindex 45afb338416c..5622b5f8c280 100644--- a/frontend/src/scenes/insights/utils/api.ts+++ b/frontend/src/scenes/insights/utils/api.ts@@ -1,6 +1,6 @@import api, { ApiMethodOptions } from 'lib/api'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { DashboardFilter, HogQLVariable, RefreshType, TileFilters } from '~/queries/schema/schema-general'import { InsightShortId, InsightModel } from '~/types'@@ -10,9 +10,7 @@ async function _perform(id?: number,options?: ApiMethodOptions): Promise<InsightModel> {- const legacyInsight =- method === 'create' ? await api.insights[method](insight) : await api.insights[method](id!, insight, options)- return getQueryBasedInsightModel(legacyInsight)+ return method === 'create' ? api.insights[method](insight) : api.insights[method](id!, insight, options)}export const insightsApi = {@@ -36,15 +34,14 @@ export const insightsApi = {if (legacyInsights.results.length === 0) {return null}- const legacyInsight = legacyInsights.results[0]- return getQueryBasedInsightModel(legacyInsight) as InsightModel+ return legacyInsights.results[0] as InsightModel},async getByNumericId(numericId: number): Promise<InsightModel | null> {const legacyInsight = await api.insights.get(numericId)if (legacyInsight === null) {return null}- return getQueryBasedInsightModel(legacyInsight)+ return legacyInsight},async create(insight: Partial<InsightModel>): Promise<InsightModel> {return this._perform('create', insight)@@ -54,6 +51,11 @@ export const insightsApi = {},async duplicate(insight: InsightModel): Promise<InsightModel> {const { id, short_id, result, created_at, created_by, last_modified_at, last_modified_by, ...rest } = insight- return this.create({ ...rest, name: insight.name ? `${insight.name} (copy)` : insight.name })+ return this.create({+ // The copy goes on every dashboard the original sits on.+ ...(insight.dashboard_tiles ? { dashboards: liveDashboardIds(insight.dashboard_tiles) } : {}),+ ...rest,+ name: insight.name ? `${insight.name} (copy)` : insight.name,+ })},}diff --git a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsxindex c6c7bf9813f7..50fd5a21b324 100644--- a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx+++ b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx@@ -9,7 +9,6 @@ import { MaxContextInput } from 'scenes/max/maxTypes'import { projectLogic } from 'scenes/projectLogic'import { urls } from 'scenes/urls'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { Breadcrumb, InsightModel } from '~/types'import type { Node } from '../../queries/schema/schema-general'@@ -108,10 +107,9 @@ export const projectHomepageLogic = kea<projectHomepageLogicType>([{loadRecentInsights: async () => {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. insightsMyLastViewedRetrieve() from 'products/product_analytics/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- const insights = await api.get<InsightModel[]>(+ return await api.get<InsightModel[]>(`api/projects/${values.currentProjectId}/insights/my_last_viewed`)- return insights.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))},},],diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.tsindex ea8f5d74a1cf..58e38c111f6e 100644--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts@@ -12,11 +12,11 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { objectsEqual } from 'lib/utils/objects'import { toParams } from 'lib/utils/url'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import type { InsightModel } from '~/types'import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'@@ -41,15 +41,6 @@ interface InsightListParams {export const INSIGHTS_PER_PAGE = 15-/**- * The dashboards an insight currently sits on. Read off the tiles rather than off the deprecated- * `dashboards` field: a PATCH of `dashboards` replaces the whole membership, so the list has to come- * from something the API still serves the web app.- */-function currentDashboardIds(insight: InsightModel): number[] {- return (insight.dashboard_tiles || []).filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)-}-/*** Tell the user a membership update failed, and rethrow only what is worth filing. The listener has* already rolled the toggle back, and every `ApiError` is built in one place, so an issue raised@@ -273,10 +264,7 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([breakpoint()- return {- ...response,- results: response.results.map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),- }+ return response},},userInsights: {@@ -401,7 +389,7 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([try {actions.setDashboardUpdateLoading(insight.id, true)const response = await insightsApi.update(insight.id, {- dashboards: [...currentDashboardIds(insight), dashboardId],+ dashboards: [...liveDashboardIds(insight.dashboard_tiles), dashboardId],})if (response) {actions.updateInsight(response)@@ -425,7 +413,7 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([try {actions.setDashboardUpdateLoading(insight.id, true)const response = await insightsApi.update(insight.id, {- dashboards: currentDashboardIds(insight).filter((d) => d !== dashboardId),+ dashboards: liveDashboardIds(insight.dashboard_tiles).filter((d) => d !== dashboardId),})if (response) {actions.updateInsight(response)diff --git a/frontend/src/scenes/saved-insights/draftInsight.ts b/frontend/src/scenes/saved-insights/draftInsight.tsindex 40764fb9f5d4..a7d62a7fb1ef 100644--- a/frontend/src/scenes/saved-insights/draftInsight.ts+++ b/frontend/src/scenes/saved-insights/draftInsight.ts@@ -57,7 +57,6 @@ export function draftInsightListItem(draft: DraftInsightQuery, currentUser: Userdeleted: false,saved: false,is_sample: false,- dashboards: null,dashboard_tiles: null,last_refresh: null,created_at: timestamp,diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.tsindex 586dec899a73..b2d3565da041 100644--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts@@ -27,7 +27,6 @@ import { userLogic } from 'scenes/userLogic'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { dashboardsModel } from '~/models/dashboardsModel'import { insightsModel } from '~/models/insightsModel'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { Breadcrumb, InsightModel, SavedInsightsTabs, UserType } from '~/types'import {@@ -421,18 +420,13 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([}// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use insightsList() from 'products/product_analytics/frontend/generated/api' instead.- const legacyResponse: CountedPaginatedResponse<InsightModel> = await api.get(+ const response: CountedPaginatedResponse<InsightModel> = await api.get(`api/projects/${teamLogic.values.currentTeamId}/insights/?${toParams(params)}`)// Cancel if a newer request came in while this one was in flightawait breakpoint()- const response = {- ...legacyResponse,- results: legacyResponse.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight)),- }-if (filters.search && String(filters.search).match(/^[0-9]+$/)) {try {const insight = await insightsApi.getByNumericId(Number(filters.search))diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex c4e334b6d400..20fe6a978e73 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2692,8 +2692,12 @@ export interface InsightModel<R extends Node<Record<string, any>> = Node<Record<created_at: stringcreated_by: UserBasicType | nullis_sample: boolean- /** @deprecated Use `dashboard_tiles` instead */- dashboards: number[] | null+ /**+ * @deprecated Write-only. Session responses omit it, so read membership with+ * `liveDashboardIds(insight.dashboard_tiles)`. Send it to place a new insight on dashboards, or to+ * replace a saved insight's whole membership.+ */+ dashboards?: number[]dashboard_tiles: DashboardTileBasicType[] | nullupdated_at: stringtags?: string[]diff --git a/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts b/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.tsindex 5d36cc65f470..c92e0af765e2 100644--- a/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts@@ -7,7 +7,6 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { isEmptyObject } from 'lib/utils/guards'import { urls } from 'scenes/urls'-import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { InsightType, InsightModel } from '~/types'import type { AnyEntityNode, Node } from '../../../../../frontend/src/queries/schema/schema-general'@@ -126,7 +125,7 @@ export const journeyTemplatePickerLogic = kea<journeyTemplatePickerLogicType>([insight: InsightType.FUNNELS,...(values.searchTerm ? { search: values.searchTerm } : {}),})- return response.results.map((insight) => getQueryBasedInsightModel(insight))+ return response.results},},})),diff --git a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.test.tsx b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.test.tsxindex 00068022b640..6f505f4dcb1b 100644--- a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.test.tsx+++ b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.test.tsx@@ -34,7 +34,6 @@ describe('DashboardTextItem', () => {dashboardWidgetMenusLogic({instanceKey: 'text-10',dashboardId: 99,- dashboards: undefined,dashboard_tiles: [],}).mount()})@@ -44,7 +43,6 @@ describe('DashboardTextItem', () => {dashboardWidgetMenusLogic({instanceKey: 'text-10',dashboardId: 99,- dashboards: undefined,dashboard_tiles: [],}).unmount()})diff --git a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsxindex 11f45f6cced3..de3cf4229a7d 100644--- a/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx+++ b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx@@ -45,7 +45,6 @@ function DashboardTextItemInternal(dashboardWidgetMenusLogic({instanceKey: textId != null ? `text-${textId}` : `text-tile-${tile.id}`,dashboardId,- dashboards: undefined,dashboard_tiles: tile.text?.dashboard_tiles,}))diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsxindex ab0043b0ad62..de7eda744884 100644--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx@@ -128,7 +128,6 @@ describe('DashboardWidgetItem', () => {dashboardWidgetMenusLogic({instanceKey: 'widget-10',dashboardId: 99,- dashboards: undefined,dashboard_tiles: [],}).mount()})@@ -138,7 +137,6 @@ describe('DashboardWidgetItem', () => {dashboardWidgetMenusLogic({instanceKey: 'widget-10',dashboardId: 99,- dashboards: undefined,dashboard_tiles: [],}).unmount()})diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsxindex a9606c145f5e..610c1944b319 100644--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx@@ -415,7 +415,6 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWiddashboardWidgetMenusLogic({instanceKey: widget ? `widget-${widget.id}` : `widget-tile-${tile.id}`,dashboardId,- dashboards: undefined,dashboard_tiles: widget?.dashboard_tiles,}))diff --git a/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx b/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsxindex e1c92bf7684f..695fea9dfdc5 100644--- a/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx+++ b/products/product_analytics/frontend/insights/insightScene/InsightPageHeader.tsx@@ -242,7 +242,7 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: InsaveAs={() => saveAs(undefined, undefined, 'Unfiled/Insights')}saveInsight={saveInsightToFolder}isSaved={isSavedInsight}- addingToDashboard={!!insight.dashboards?.length && !insight.id}+ addingToDashboard={!insight.id && !!insight.dashboards?.length}insightSaving={insightSaving}insightChanged={insightChanged || queryChanged}// Only offered for already-saved insights: the add-to-dashboard modal is keyed by the