: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
feat(sql-editor): add version history for saved sql insights (#68075)
Anna Szell807a32438d23
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 225d425a0296..3ddc4065fe7f 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -482,6 +482,7 @@ export const FEATURE_FLAGS = {SHOW_REPLAY_FILTERS_FEEDBACK_BUTTON: 'show-replay-filters-feedback-button', // owner: @ksvat #team-replaySIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources+ SQL_EDITOR_QUERY_HISTORY: 'sql-editor-query-history', // owner: @annaszell #team-data-toolsSQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeusSSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platformSUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptionsdiff --git a/frontend/src/scenes/data-warehouse/editor/InsightHistory.tsx b/frontend/src/scenes/data-warehouse/editor/InsightHistory.tsxnew file mode 100644index 000000000000..59ae92cfa788--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/InsightHistory.tsx@@ -0,0 +1,241 @@+import useSize from '@react-hook/size'+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { useRef, useState } from 'react'++import { IconRevert } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { SkeletonLog } from 'lib/components/ActivityLog/ActivityLog'+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'+import { TZLabel } from 'lib/components/TZLabel'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { fullName } from 'lib/utils/strings'++import { QueryBasedInsightModel } from '~/types'++import { editorSceneLogic } from './editorSceneLogic'+import { InsightQueryVersion, insightHistoryLogic } from './insightHistoryLogic'+import { sqlEditorLogic, toDataVisualizationNode } from './sqlEditorLogic'++interface VersionRowShellProps {+ createdAt: string+ authorName: string+ email?: string | null+ isSystem?: boolean+ tags?: JSX.Element+ onRestore?: () => void+ children: React.ReactNode+}++function VersionRowShell({+ createdAt,+ authorName,+ email,+ isSystem,+ tags,+ onRestore,+ children,+}: VersionRowShellProps): JSX.Element {+ const [isExpanded, setIsExpanded] = useState(false)++ return (+ <div className={clsx('flex flex-col rounded border', isExpanded ? 'border-primary' : 'border-transparent')}>+ <div+ className="flex items-center gap-3 px-2 py-2 rounded cursor-pointer hover:bg-surface-secondary group"+ onClick={() => setIsExpanded(!isExpanded)}+ >+ <div className="flex-grow min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-semibold">+ <TZLabel time={createdAt} formatDate="MMMM D" formatTime="h:mm A" />+ </span>+ {tags}+ </div>+ <div className="flex items-center gap-1.5 text-secondary text-xs mt-0.5">+ <ProfilePicture+ showName={false}+ user={{+ first_name: isSystem ? authorName : undefined,+ email: email ?? undefined,+ }}+ type={isSystem ? 'system' : 'person'}+ size="xs"+ />+ <span>{authorName}</span>+ </div>+ </div>+ {onRestore && (+ <LemonButton+ size="small"+ icon={<IconRevert />}+ className="opacity-0 group-hover:opacity-100"+ tooltip="Load this version into the editor to review and restore"+ data-attr="sql-editor-insight-history-restore"+ onClick={(e) => {+ e.stopPropagation()+ onRestore()+ }}+ >+ Restore+ </LemonButton>+ )}+ </div>+ {isExpanded && <div className="px-2 pb-2">{children}</div>}+ </div>+ )+}++function EditVersionRow({ version, isCurrent }: { version: InsightQueryVersion; isCurrent: boolean }): JSX.Element {+ const { setSuggestedQueryInput } = useActions(sqlEditorLogic)+ const { closeHistoryModal } = useActions(editorSceneLogic)++ return (+ <VersionRowShell+ createdAt={version.createdAt}+ authorName={version.authorName}+ email={version.email}+ isSystem={version.isSystem}+ tags={+ isCurrent ? (+ <LemonTag type="primary" size="small">+ Current version+ </LemonTag>+ ) : undefined+ }+ onRestore={+ isCurrent+ ? undefined+ : () => {+ setSuggestedQueryInput(version.afterSql, 'query_history')+ // Close the modal so the restore diff in the editor is visible+ closeHistoryModal()+ }+ }+ >+ <div className="text-xs text-secondary mb-1">Changes compared to the previous version</div>+ <SqlDiffViewer before={version.beforeSql} after={version.afterSql} />+ </VersionRowShell>+ )+}++function OriginalVersionRow({+ insight,+ sql,+ isCurrent,+}: {+ insight: QueryBasedInsightModel+ sql: string+ isCurrent: boolean+}): JSX.Element {+ const { setSuggestedQueryInput } = useActions(sqlEditorLogic)+ const { closeHistoryModal } = useActions(editorSceneLogic)++ return (+ <VersionRowShell+ createdAt={insight.created_at}+ authorName={insight.created_by ? fullName(insight.created_by) : 'Unknown'}+ email={insight.created_by?.email}+ tags={+ <>+ <LemonTag size="small">Original</LemonTag>+ {isCurrent && (+ <LemonTag type="primary" size="small">+ Current version+ </LemonTag>+ )}+ </>+ }+ onRestore={+ isCurrent+ ? undefined+ : () => {+ setSuggestedQueryInput(sql, 'query_history')+ closeHistoryModal()+ }+ }+ >+ <CodeSnippet language={Language.SQL} compact>+ {sql}+ </CodeSnippet>+ </VersionRowShell>+ )+}++function SqlDiffViewer({ before, after }: { before: string; after: string }): JSX.Element {+ const containerRef = useRef<HTMLDivElement>(null)+ const [width] = useSize(containerRef)+ return (+ <div ref={containerRef} className="flex flex-col w-full">+ <MonacoDiffEditor+ original={before}+ modified={after}+ language="hogQL"+ width={width}+ options={{+ renderOverviewRuler: false,+ scrollBeyondLastLine: false,+ renderGutterMenu: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ }}+ />+ </div>+ )+}++export function InsightHistory({ insight }: { insight: QueryBasedInsightModel | null }): JSX.Element {+ return insight ? (+ <InsightHistoryContent insight={insight} />+ ) : (+ // The insight itself is still loading — the tab shows immediately, the content follows+ <InsightHistorySkeleton />+ )+}++function InsightHistorySkeleton(): JSX.Element {+ return (+ <div className="deprecated-space-y-2 p-2">+ <SkeletonLog />+ <SkeletonLog />+ <SkeletonLog />+ </div>+ )+}++function InsightHistoryContent({ insight }: { insight: QueryBasedInsightModel }): JSX.Element {+ const logic = insightHistoryLogic({ insightId: insight.id })+ const { versions, activityPageLoading, historyComplete } = useValues(logic)++ if (activityPageLoading) {+ return <InsightHistorySkeleton />+ }++ // The state the insight was created with: what the oldest recorded edit started from,+ // or the current query if the SQL has never been edited. Only trustworthy when the+ // full activity log was fetched — otherwise the oldest loaded edit is not the creation state.+ const originalSql =+ historyComplete && versions.length+ ? versions[versions.length - 1].beforeSql+ : versions.length === 0+ ? (toDataVisualizationNode(insight.query)?.source.query ?? '')+ : ''++ return (+ <div className="flex flex-col gap-1 p-2 max-w-200">+ {versions.map((version, index) => (+ <EditVersionRow key={version.id ?? index} version={version} isCurrent={index === 0} />+ ))}+ {originalSql.trim() !== '' && (+ <OriginalVersionRow insight={insight} sql={originalSql} isCurrent={versions.length === 0} />+ )}+ {!historyComplete && (+ <div className="p-2 text-secondary text-xs">+ This insight has a very long history — older versions are not shown.+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsxindex 64b766815685..3de15b252d03 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx@@ -15,6 +15,7 @@ import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControlimport { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { editorSceneLogic } from './editorSceneLogic'+import { InsightHistory } from './InsightHistory'import { queryHistoryLogic } from './queryHistoryLogic'function QueryHistoryLogRow({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {@@ -138,14 +139,23 @@ function QueryHistoryLog({ id }: { id?: number | string }): JSX.Element {}export function QueryHistoryModal(): JSX.Element {- const { editingView, isHistoryModalOpen } = useValues(editorSceneLogic)+ const { editingView, editingInsight, insightLoading, isHistoryModalOpen } = useValues(editorSceneLogic)const { closeHistoryModal } = useActions(editorSceneLogic)return (- <LemonModal title="View history" isOpen={isHistoryModalOpen} onClose={closeHistoryModal} width={800}>- <div className="ActivityLog">- <QueryHistoryLog id={editingView?.id} />- </div>+ <LemonModal+ title={editingView ? 'View history' : 'Insight history'}+ isOpen={isHistoryModalOpen}+ onClose={closeHistoryModal}+ width={800}+ >+ {editingView ? (+ <div className="ActivityLog">+ <QueryHistoryLog id={editingView.id} />+ </div>+ ) : editingInsight || insightLoading ? (+ <InsightHistory insight={editingInsight ?? null} />+ ) : null}</LemonModal>)}diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex b9ddb39f584d..f1d7f274d8d6 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -634,6 +634,17 @@ function SQLEditorSceneTitle(): JSX.Element | null {</>) : editingInsight ? (<>+ {featureFlags[FEATURE_FLAGS.SQL_EDITOR_QUERY_HISTORY] && (+ <LemonButton+ onClick={() => openHistoryModal()}+ icon={<IconBook />}+ type="secondary"+ size="small"+ data-attr="sql-editor-insight-history-button"+ >+ History+ </LemonButton>+ )}<LemonButtondisabledReason={!isSourceQueryLastRundiff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsxindex 1aa350cde4b2..91ab07133500 100644--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx@@ -1,5 +1,6 @@import { deepEqual as equal } from 'fast-equals'import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -464,6 +465,11 @@ export const editorSceneLogic = kea<editorSceneLogicType>([],}),listeners(({ values }) => ({+ openHistoryModal: () => {+ posthog.capture('sql-editor-history-modal-opened', {+ object: values.editingView ? 'view' : 'insight',+ })+ },shareTab: () => {const { activeTab, queryInput, sourceQuery } = valuesif (!activeTab) {diff --git a/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.test.tsnew file mode 100644index 000000000000..0ce07fc30f97--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.test.ts@@ -0,0 +1,207 @@+import { expectLogic } from 'kea-test-utils'++import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { ActivityScope } from '~/types'++import { getChangeSql, getQueryChange, insightHistoryLogic } from './insightHistoryLogic'++const queryChangeItem = {+ id: 'activity-1',+ user: { first_name: 'Jane', last_name: 'Doe', email: '[email protected]' },+ activity: 'updated',+ scope: ActivityScope.INSIGHT,+ item_id: '42',+ detail: {+ name: 'revenue',+ changes: [+ {+ type: 'Insight',+ field: 'query',+ action: 'changed',+ before: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } },+ after: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 2' } },+ },+ ],+ },+ created_at: '2026-07-01T10:00:00Z',+} as unknown as ActivityLogItem++const nameChangeItem = {+ ...queryChangeItem,+ detail: {+ name: 'revenue',+ changes: [{ type: 'Insight', field: 'name', action: 'changed', before: 'old', after: 'revenue' }],+ },+} as unknown as ActivityLogItem++// Chart settings edits touch the query JSON but leave the SQL text untouched+const settingsOnlyChangeItem = {+ ...queryChangeItem,+ detail: {+ name: 'revenue',+ changes: [+ {+ type: 'Insight',+ field: 'query',+ action: 'changed',+ before: {+ kind: 'DataVisualizationNode',+ source: { kind: 'HogQLQuery', query: 'SELECT 2' },+ display: 'ActionsTable',+ },+ after: {+ kind: 'DataVisualizationNode',+ source: { kind: 'HogQLQuery', query: 'SELECT 2' },+ display: 'BoldNumber',+ },+ },+ ],+ },+} as unknown as ActivityLogItem++describe('insightHistoryLogic', () => {+ describe('getChangeSql', () => {+ it.each([+ [{ kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } }, 'SELECT 1'],+ [{ source: { query: ' ' } }, null],+ [{ source: {} }, null],+ [{}, null],+ [null, null],+ ['SELECT 1', null],+ ])('extracts SQL from %p as %p', (changeSide, expected) => {+ expect(getChangeSql(changeSide as any)).toEqual(expected)+ })+ })++ describe('getQueryChange', () => {+ it('finds the query change on an item and ignores non-query changes', () => {+ expect(getQueryChange(queryChangeItem)?.field).toEqual('query')+ expect(getQueryChange(nameChangeItem)).toBeNull()+ })++ it('ignores query changes where the SQL text is unchanged (settings-only edits)', () => {+ expect(getQueryChange(settingsOnlyChangeItem)).toBeNull()+ })+ })++ describe('loading', () => {+ let logic: ReturnType<typeof insightHistoryLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/activity_log/': () => [+ 200,+ { results: [settingsOnlyChangeItem, queryChangeItem, nameChangeItem], count: 3, next: null },+ ],+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads activity on mount and only surfaces query-change versions', async () => {+ logic = insightHistoryLogic({ insightId: 42 })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])++ expect(logic.values.activity).toHaveLength(3)+ expect(logic.values.historyComplete).toBe(true)+ expect(logic.values.versions).toEqual([+ {+ id: 'activity-1',+ createdAt: '2026-07-01T10:00:00Z',+ authorName: 'Jane Doe',+ email: '[email protected]',+ isSystem: false,+ beforeSql: 'SELECT 1',+ afterSql: 'SELECT 2',+ },+ ])+ })++ it('pages through the full activity log and concatenates results', async () => {+ const fullPage = Array.from({ length: 100 }, () => queryChangeItem)+ useMocks({+ get: {+ '/api/projects/:team_id/activity_log/': ({ request }) => {+ const page = Number(new URL(request.url).searchParams.get('page') || '1')+ return [+ 200,+ page === 1+ ? { results: fullPage, count: 101, next: '/api/activity_log/?page=2' }+ : { results: [nameChangeItem], count: 101, next: null },+ ]+ },+ },+ })++ logic = insightHistoryLogic({ insightId: 42 })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])++ expect(logic.values.activity).toHaveLength(101)+ expect(logic.values.historyComplete).toBe(true)+ })++ it('treats a log ending on an exactly full page as complete', async () => {+ const fullPage = Array.from({ length: 100 }, () => queryChangeItem)+ useMocks({+ get: {+ '/api/projects/:team_id/activity_log/': ({ request }) => {+ const page = Number(new URL(request.url).searchParams.get('page') || '1')+ if (page > 2) {+ // DRF's paginator 404s past the last page — a length-based+ // completeness check would request page 3 and blow up here+ return [404, { detail: 'Invalid page.' }]+ }+ return [+ 200,+ {+ results: fullPage,+ count: 200,+ next: page === 1 ? '/api/activity_log/?page=2' : null,+ },+ ]+ },+ },+ })++ logic = insightHistoryLogic({ insightId: 42 })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])++ expect(logic.values.activity).toHaveLength(200)+ expect(logic.values.historyComplete).toBe(true)+ })++ it('marks history incomplete when the page cap is hit', async () => {+ const fullPage = Array.from({ length: 100 }, () => queryChangeItem)+ useMocks({+ get: {+ '/api/projects/:team_id/activity_log/': () => [+ 200,+ { results: fullPage, count: 5000, next: '/api/activity_log/?page=next' },+ ],+ },+ })++ logic = insightHistoryLogic({ insightId: 42 })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadActivity', 'loadActivitySuccess'])++ expect(logic.values.activity).toHaveLength(1000)+ expect(logic.values.historyComplete).toBe(false)+ })+ })+})diff --git a/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.tsnew file mode 100644index 000000000000..479109c5d6b5--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts@@ -0,0 +1,186 @@+import { MakeLogicType, events, kea, key, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'+import { fullName } from 'lib/utils/strings'++import { ActivityScope } from '~/types'++export interface InsightHistoryLogicProps {+ insightId: number+}++/** One saved state of the insight's query: the result of a single edit. */+export interface InsightQueryVersion {+ id?: string+ createdAt: string+ authorName: string+ email?: string | null+ isSystem: boolean+ /** SQL before this edit — the previous version, used as the diff base */+ beforeSql: string+ /** SQL as of this edit — what "Restore" brings back */+ afterSql: string+}++/** Pull the HogQL text out of an insight `query` field activity change (a DataVisualizationNode). */+export function getChangeSql(changeSide: ActivityChange['before'] | ActivityChange['after']): string | null {+ if (!changeSide || typeof changeSide !== 'object' || Array.isArray(changeSide)) {+ return null+ }+ const source = (changeSide as { source?: unknown }).source+ if (!source || typeof source !== 'object') {+ return null+ }+ const query = (source as { query?: unknown }).query+ return typeof query === 'string' && query.trim() !== '' ? query : null+}++export function getQueryChange(logItem: ActivityLogItem): ActivityChange | null {+ return (+ logItem.detail?.changes?.find(+ (change) =>+ change.field === 'query' &&+ getChangeSql(change.after) !== null &&+ // Settings-only edits (chart type, axis config) also touch the query JSON —+ // only SQL text changes count as versions, otherwise the diff has nothing to show+ getChangeSql(change.after) !== getChangeSql(change.before)+ ) ?? null+ )+}++const ACTIVITY_PAGE_SIZE = 100+// Safety cap: 10 pages = 1000 activity entries. Beyond that we stop and admit the history is partial.+const ACTIVITY_MAX_PAGES = 10++export interface InsightActivityPage {+ items: ActivityLogItem[]+ /** False when the log was too long to fetch fully — the oldest loaded entry is NOT the creation state */+ complete: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface insightHistoryLogicValues {+ activity: ActivityLogItem[]+ activityPage: InsightActivityPage+ activityPageLoading: boolean+ historyComplete: boolean+ versions: InsightQueryVersion[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface insightHistoryLogicActions {+ loadActivity: () => any+ loadActivityFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadActivitySuccess: (+ activityPage:+ | {+ complete: false+ items: ActivityLogItem[]+ }+ | {+ complete: true+ items: ActivityLogItem[]+ },+ payload?: any+ ) => {+ activityPage:+ | {+ complete: false+ items: ActivityLogItem[]+ }+ | {+ complete: true+ items: ActivityLogItem[]+ }+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface insightHistoryLogicMeta {+ key: number+ __keaTypeGenInternalSelectorTypes: {+ activity: (activityPage: InsightActivityPage) => ActivityLogItem[]+ historyComplete: (activityPage: InsightActivityPage) => boolean+ versions: (activity: ActivityLogItem[]) => InsightQueryVersion[]+ }+}++export type insightHistoryLogicType = MakeLogicType<+ insightHistoryLogicValues,+ insightHistoryLogicActions,+ InsightHistoryLogicProps,+ insightHistoryLogicMeta+>++export const insightHistoryLogic = kea<insightHistoryLogicType>([+ path(['data-warehouse', 'editor', 'insightHistoryLogic']),+ props({} as InsightHistoryLogicProps),+ key((props) => props.insightId),+ loaders(({ props }) => ({+ activityPage: [+ { items: [], complete: true } as InsightActivityPage,+ {+ loadActivity: async () => {+ const items: ActivityLogItem[] = []+ for (let page = 1; page <= ACTIVITY_MAX_PAGES; page++) {+ const response = await api.activity+ .listRequest({+ scope: ActivityScope.INSIGHT,+ item_id: props.insightId,+ page,+ page_size: ACTIVITY_PAGE_SIZE,+ })+ .get()+ items.push(...(response.results ?? []))+ // `next` is null on the last page — unlike a results-length check, this stays+ // correct when the total is an exact multiple of the page size+ if (!response.next) {+ return { items, complete: true }+ }+ }+ return { items, complete: false }+ },+ },+ ],+ })),+ selectors({+ activity: [(s) => [s.activityPage], (activityPage: InsightActivityPage) => activityPage.items],+ historyComplete: [(s) => [s.activityPage], (activityPage: InsightActivityPage) => activityPage.complete],+ // Newest first, only edits that changed the SQL — each one is a "version"+ versions: [+ (s) => [s.activity],+ (activity: ActivityLogItem[]): InsightQueryVersion[] =>+ activity+ .map((logItem): InsightQueryVersion | null => {+ const queryChange = getQueryChange(logItem)+ if (!queryChange) {+ return null+ }+ return {+ id: logItem.id,+ createdAt: logItem.created_at,+ authorName: logItem.is_system ? 'PostHog' : fullName(logItem.user),+ email: logItem.user?.email,+ isSystem: !!logItem.is_system,+ beforeSql: getChangeSql(queryChange.before) ?? '',+ afterSql: getChangeSql(queryChange.after) ?? '',+ }+ })+ .filter((version): version is InsightQueryVersion => version !== null),+ ],+ }),+ events(({ actions }) => ({+ afterMount: () => {+ actions.loadActivity()+ },+ })),+])diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex d2cfa076a294..9c6c80ad5f33 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -1865,4 +1865,61 @@ describe('sqlEditorLogic', () => {viewsLogic.unmount()})})++ describe('query history', () => {+ it('tags SQL editor runs with the sql_editor product key', async () => {+ const performQuerySpy = jest+ .spyOn(queryRunner, 'performQuery')+ .mockResolvedValue({ results: [], columns: [], types: [] } as never)++ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1' })+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])+ await new Promise((resolve) => setTimeout(resolve, 0))++ performQuerySpy.mockClear()+ logic.actions.runQuery()+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(performQuerySpy).toHaveBeenCalled()+ expect(performQuerySpy.mock.calls[0][0]).toMatchObject({+ kind: NodeKind.HogQLQuery,+ query: 'SELECT 1',+ tags: { productKey: 'sql_editor' },+ })++ performQuerySpy.mockRestore()+ })++ it.each([+ ['query_history' as const, 'Restore', 'Cancel'],+ ['max_ai' as const, 'Accept', 'Reject'],+ ])('suggestions from %s use the %s/%s handlers', async (source, acceptText, rejectText) => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ logic.actions.createTab('SELECT 1')+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ logic.actions.setSuggestedQueryInput('SELECT 2', source)+ await expectLogic(logic).toDispatchActions(['setSuggestedQueryInput'])++ expect(logic.values.suggestionPayload).toMatchObject({+ suggestedValue: 'SELECT 2',+ acceptText,+ rejectText,+ source,+ })+ })+ })})diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 89eeb82b83ff..1643a4496d9e 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -106,6 +106,12 @@ import {aiSuggestionOnReject,aiSuggestionOnRejectText,} from './suggestions/aiSuggestion'+import {+ queryHistorySuggestionOnAccept,+ queryHistorySuggestionOnAcceptText,+ queryHistorySuggestionOnReject,+ queryHistorySuggestionOnRejectText,+} from './suggestions/queryHistorySuggestion'import { ViewEmptyState } from './ViewLoadingState'export interface SqlEditorLogicProps {@@ -246,7 +252,7 @@ export interface SuggestionPayload {acceptText?: stringrejectText?: stringdiffShowRunButton?: boolean- source?: 'max_ai' | 'hogql_fixer' | 'materialization_fix'+ source?: 'max_ai' | 'hogql_fixer' | 'query_history' | 'materialization_fix'onAccept: (shouldRunQuery: boolean,actions: sqlEditorLogicType['actions'],@@ -523,7 +529,7 @@ export interface sqlEditorLogicValues {sourceQuery: DataVisualizationNodesplitQueryRanges: QueryRange[]suggestedQueryInput: string- suggestedSource: 'hogql_fixer' | 'materialization_fix' | 'max_ai' | null+ suggestedSource: 'hogql_fixer' | 'materialization_fix' | 'max_ai' | 'query_history' | nullsuggestionPayload: SuggestionPayload | nullupstream: {edges: DataModelingEdge[]@@ -969,7 +975,7 @@ export interface sqlEditorLogicActions {suggestedQueryInput: string,source?: SuggestionPayload['source']) => {- source: 'hogql_fixer' | 'materialization_fix' | 'max_ai' | undefined+ source: 'hogql_fixer' | 'materialization_fix' | 'max_ai' | 'query_history' | undefinedsuggestedQueryInput: string}setUpstreamViewMode: (mode: 'graph' | 'table') => {@@ -1012,7 +1018,7 @@ export interface sqlEditorLogicMeta {__keaTypeGenInternalSelectorTypes: {suggestedSource: (suggestionPayload: SuggestionPayload | null- ) => 'hogql_fixer' | 'materialization_fix' | 'max_ai' | null+ ) => 'hogql_fixer' | 'materialization_fix' | 'max_ai' | 'query_history' | nulldiffShowRunButton: (suggestionPayload: SuggestionPayload | null) => boolean | undefinedacceptText: (suggestionPayload: SuggestionPayload | null) => stringrejectText: (suggestionPayload: SuggestionPayload | null) => string@@ -1626,16 +1632,22 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return}+ const isQueryHistory = source === 'query_history'+ if (isQueryHistory) {+ // Accept/cancel of the restore is captured via sql-editor-accepted/rejected-suggestion+ posthog.capture('sql-editor-history-restore-initiated')+ }+// Always create suggestion payload when a new suggestion comes in, even for consecutive suggestions// Only skip diff mode if the editor is completely emptyif (values.queryInput && values.queryInput.trim() !== '') {actions._setSuggestionPayload({suggestedValue: suggestedQueryInput,originalValue: values.queryInput, // Store the current content as original for diff mode- acceptText: aiSuggestionOnAcceptText,- rejectText: aiSuggestionOnRejectText,- onAccept: aiSuggestionOnAccept,- onReject: aiSuggestionOnReject,+ acceptText: isQueryHistory ? queryHistorySuggestionOnAcceptText : aiSuggestionOnAcceptText,+ rejectText: isQueryHistory ? queryHistorySuggestionOnRejectText : aiSuggestionOnRejectText,+ onAccept: isQueryHistory ? queryHistorySuggestionOnAccept : aiSuggestionOnAccept,+ onReject: isQueryHistory ? queryHistorySuggestionOnReject : aiSuggestionOnReject,source,diffShowRunButton: true,})@@ -1893,6 +1905,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([query,})+ // Tag only the executed query — keeping tags out of sourceQuery so saved+ // insights/views and change detection never pick them up+ const executedSource: HogQLQuery = {+ ...newSource,+ tags: { ...newSource.tags, productKey: 'sql_editor' },+ }+actions.setSourceQuery({...values.sourceQuery,source: newSource,@@ -1904,14 +1923,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([if (!cache.umountDataNode) {cache.umountDataNode = dataNodeLogic({key: values.dataLogicKey,- query: newSource,+ query: executedSource,}).mount()}dataNodeLogic({key: values.dataLogicKey,- query: newSource,- }).actions.loadData(!switchTab ? 'force_async' : 'async', undefined, newSource)+ query: executedSource,+ }).actions.loadData(!switchTab ? 'force_async' : 'async', undefined, executedSource)// Mark the first query task as complete when the query is runglobalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.RunFirstQuery)diff --git a/frontend/src/scenes/data-warehouse/editor/suggestions/queryHistorySuggestion.ts b/frontend/src/scenes/data-warehouse/editor/suggestions/queryHistorySuggestion.tsnew file mode 100644index 000000000000..c5fe013fa1bf--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/suggestions/queryHistorySuggestion.ts@@ -0,0 +1,43 @@+import type { sqlEditorLogicType } from '../sqlEditorLogic'++// Handlers for restoring a previous version of a saved query from the history modal.+// Restoring only updates the editor content — the user persists it through the normal+// "Update view" flow, which keeps conflict detection and writes a new activity log entry.++export const queryHistorySuggestionOnAcceptText = 'Restore'+export const queryHistorySuggestionOnRejectText = 'Cancel'++export const queryHistorySuggestionOnAccept = (+ shouldRunQuery: boolean,+ actions: sqlEditorLogicType['actions'],+ values: sqlEditorLogicType['values'],+ props: sqlEditorLogicType['props']+): void => {+ // Get the current editor content (which includes any user edits to the restored version)+ let currentEditorContent = values.suggestedQueryInput++ if (props.editor) {+ // If we're in diff mode, get the current content from the modified editor+ if ('getModifiedEditor' in props.editor) {+ const modifiedEditor = (props.editor as any).getModifiedEditor()+ currentEditorContent = modifiedEditor.getValue()+ } else {+ currentEditorContent = props.editor.getValue()+ }+ }++ actions.setQueryInput(currentEditorContent)++ if (shouldRunQuery) {+ actions.runQuery(currentEditorContent)+ }+}++export const queryHistorySuggestionOnReject = (+ actions: sqlEditorLogicType['actions'],+ values: sqlEditorLogicType['values']+): void => {+ // Revert to the content from before the restore was initiated+ const originalContent = values.suggestionPayload?.originalValue || values.queryInput+ actions.setQueryInput(originalContent)+}diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex eae94fc4313c..f94f3f56f202 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -82,6 +82,7 @@ class Product(StrEnum):SDK_HEALTH = "sdk_health"SESSION_SUMMARY = "session_summary"SIGNALS = "signals"+ SQL_EDITOR = "sql_editor"SURVEYS = "surveys"USER_INTERVIEWS = "user_interviews"WAREHOUSE = "warehouse"diff --git a/posthog/hogql/database/schema/query_log_archive.py b/posthog/hogql/database/schema/query_log_archive.pyindex 6c028e705dfd..ab4c57eca1e2 100644--- a/posthog/hogql/database/schema/query_log_archive.py+++ b/posthog/hogql/database/schema/query_log_archive.py@@ -40,6 +40,9 @@ QUERY_LOG_ARCHIVE_FIELDS: dict[str, FieldOrTable] = {"created_by": IntegerDatabaseField(name="lc_user_id", nullable=False, description="ID of the PostHog user who triggered the query."),+ "product": StringDatabaseField(+ name="lc_product", nullable=False, description="PostHog product that issued the query, e.g. 'sql_editor'."+ ),"read_rows": IntegerDatabaseField(name="read_rows", nullable=False, description="Number of rows ClickHouse read while executing the query."),@@ -204,6 +207,9 @@ class RawQueryLogArchiveTable(Table):"lc_user_id": IntegerDatabaseField(name="lc_user_id", nullable=False, description="ID of the PostHog user who triggered the query."),+ "lc_product": StringDatabaseField(+ name="lc_product", nullable=False, description="PostHog product that issued the query, e.g. 'sql_editor'."+ ),"read_rows": IntegerDatabaseField(name="read_rows", nullable=False),"read_bytes": IntegerDatabaseField(name="read_bytes", nullable=False),"result_rows": IntegerDatabaseField(name="result_rows", nullable=False),diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 73cd6d72ece0..a645e4ccd460 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -2407,6 +2407,16 @@"table": null,"type": "integer"},+ "product": {+ "chain": null,+ "fields": null,+ "hogql_value": "product",+ "id": null,+ "name": "product",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },"read_rows": {"chain": null,"fields": null,@@ -11172,6 +11182,16 @@"table": null,"type": "integer"},+ "product": {+ "chain": null,+ "fields": null,+ "hogql_value": "product",+ "id": null,+ "name": "product",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },"read_rows": {"chain": null,"fields": null,