Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(sql-editor): preserve undo history when applying AI SQL suggestions (#61476)

George Munyoro9de8bb2f1e50
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index a5348a128d72..4f95d62736a9 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -33,7 +33,7 @@ import { OutputPane } from './OutputPane'
import { QueryFiltersMenu } from './QueryFiltersMenu'
import { QueryPane } from './QueryPane'
import { QueryVariablesMenu } from './QueryVariablesMenu'
-import { sqlEditorLogic } from './sqlEditorLogic'
+import { sqlEditorLogic, tabModelPath } from './sqlEditorLogic'
interface QueryWindowProps {
onSetMonacoAndEditor: (monaco: Monaco, editor: importedEditor.IStandaloneCodeEditor) => void
@@ -253,6 +253,11 @@ export function QueryWindow({
constrainHeight={showOutputPanel}
codeEditorProps={{
queryKey: codeEditorKey,
+ // Bind the editor to the tab's persistent Monaco model and keep it
+ // alive across the diff <-> editor swap, so undo history survives an
+ // accepted AI suggestion. Shares the URI with the model createTab makes.
+ path: tabModelPath(tabId),
+ keepCurrentModel: true,
metadataQuery: activeQueryText ?? undefined,
metadataQueryOffset: activeQueryOffset,
onChange: (v) => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 8f202545d38e..87f0caccce5f 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1358,4 +1358,107 @@ describe('sqlEditorLogic', () => {
performQuerySpy.mockRestore()
})
})
+
+ describe('AI suggestion undo', () => {
+ const ORIGINAL = 'SELECT 1'
+ const ACCEPTED = 'SELECT 2 FROM events'
+
+ // A Monaco model that records pushEditOperations as if it had a real undo stack,
+ // so we can assert the accepted query is applied as an undoable edit rather than a
+ // model.setValue (which would wipe history).
+ function createUndoTrackingModel(initialValue: string): any {
+ let value = initialValue
+ return {
+ getValue: () => value,
+ getFullModelRange: () => ({
+ startLineNumber: 1,
+ startColumn: 1,
+ endLineNumber: 1,
+ endColumn: value.length + 1,
+ }),
+ pushStackElement: jest.fn(),
+ pushEditOperations: jest.fn((_before: any, ops: any[]) => {
+ value = ops[0].text
+ return null
+ }),
+ setValue: jest.fn((next: string) => {
+ value = next
+ }),
+ onDidChangeContent: jest.fn(() => ({ dispose: jest.fn() })),
+ dispose: jest.fn(),
+ }
+ }
+
+ function createMonacoWithModel(model: any): any {
+ const monaco = createMockMonaco()
+ monaco.editor.getModel = () => model
+ monaco.editor.createModel = () => model
+ return monaco
+ }
+
+ function mountWithModel(model: any): any {
+ const monaco = createMonacoWithModel(model)
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco, editor: createMockEditor() })
+ logic.mount()
+ // Establish an active tab so accept/reject can resolve the model URI.
+ logic.actions.updateTab({ uri: monaco.Uri.parse(`tab-${TAB_ID}`), name: 'SQL' } as any)
+ return monaco
+ }
+
+ it('applies an accepted suggestion to the persistent model as an undoable edit', () => {
+ const model = createUndoTrackingModel(ORIGINAL)
+ mountWithModel(model)
+
+ logic.actions.setQueryInput(ORIGINAL)
+ logic.actions._setSuggestionPayload({
+ suggestedValue: ACCEPTED,
+ originalValue: ORIGINAL,
+ source: 'max_ai',
+ onAccept: (_shouldRun, actions) => actions.setQueryInput(ACCEPTED),
+ onReject: () => {},
+ })
+ logic.actions.onAcceptSuggestedQueryInput()
+
+ // Undoable edit, not setValue — preserves the existing undo history.
+ expect(model.pushEditOperations).toHaveBeenCalledWith(
+ [],
+ [expect.objectContaining({ text: ACCEPTED })],
+ expect.any(Function)
+ )
+ expect(model.setValue).not.toHaveBeenCalled()
+ expect(model.getValue()).toEqual(ACCEPTED)
+ })
+
+ // Both cases leave the model already holding the target query, so no undoable edit
+ // should be pushed (the no-op guard in applyUndoableModelEdit).
+ it.each([
+ {
+ name: 'the accepted query already matches the model',
+ payload: {
+ suggestedValue: ORIGINAL,
+ onAccept: (_shouldRun: boolean, actions: any) => actions.setQueryInput(ORIGINAL),
+ onReject: () => {},
+ },
+ act: () => logic.actions.onAcceptSuggestedQueryInput(),
+ },
+ {
+ name: 'a suggestion is rejected',
+ payload: {
+ suggestedValue: ACCEPTED,
+ onAccept: () => {},
+ onReject: (actions: any) => actions.setQueryInput(ORIGINAL),
+ },
+ act: () => logic.actions.onRejectSuggestedQueryInput(),
+ },
+ ])('does not push an undoable edit when $name', ({ payload, act }) => {
+ const model = createUndoTrackingModel(ORIGINAL)
+ mountWithModel(model)
+
+ logic.actions.setQueryInput(ORIGINAL)
+ logic.actions._setSuggestionPayload({ originalValue: ORIGINAL, source: 'max_ai', ...payload })
+ act()
+
+ expect(model.pushEditOperations).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index c371f9a7abe8..39fba464da4d 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -367,6 +367,32 @@ export function activeTabMatchesUrlTarget(
return !activeTab?.draft && !activeTab?.view && !activeTab?.insight
}
+// The Monaco model URI string for a tab's editor content. QueryWindow binds the editor to
+// this `path` and createTab creates the model at it — they must agree, so both derive it here.
+export function tabModelPath(tabId: string): string {
+ return `tab-${tabId}`
+}
+
+// Apply `text` to the tab's persistent Monaco model as a single undoable edit. The model is
+// kept alive across the diff <-> editor swap by `keepCurrentModel` (see QueryWindow), so its
+// full undo history survives — pushEditOperations adds one more undoable step rather than
+// wiping the stack. This also keeps the editor content in sync after accepting/rejecting a
+// suggestion: @monaco-editor/react reuses the existing model on remount without re-applying
+// the `value` prop, so the content has to be written onto the model directly. No-ops when the
+// editor isn't mounted yet or the content already matches.
+function applyUndoableModelEdit(monaco: Monaco | null | undefined, uri: Uri | undefined, text: string): void {
+ if (!monaco || !uri) {
+ return
+ }
+ const model = monaco.editor.getModel(uri)
+ if (!model || model.getValue() === text) {
+ return
+ }
+ model.pushStackElement()
+ model.pushEditOperations([], [{ range: model.getFullModelRange(), text }], () => null)
+ model.pushStackElement()
+}
+
export const sqlEditorLogic = kea<sqlEditorLogicType>([
path(['data-warehouse', 'editor', 'sqlEditorLogic']),
props({ mode: SQLEditorMode.FullScene } as SqlEditorLogicProps),
@@ -912,48 +938,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
onAcceptSuggestedQueryInput: ({ shouldRunQuery }) => {
values.suggestionPayload?.onAccept(!!shouldRunQuery, actions, values, props)
- // Re-create the model to prevent it from being purged
- if (props.monaco && values.activeTab) {
- const existingModel = props.monaco.editor.getModel(values.activeTab.uri)
- if (!existingModel) {
- const newModel = props.monaco.editor.createModel(
- values.suggestedQueryInput,
- 'hogQL',
- values.activeTab.uri
- )
- cache.createdModels = cache.createdModels || []
- cache.createdModels.push(newModel)
-
- initModel(
- newModel,
- codeEditorLogic({
- key: `hogql-editor-${props.tabId}`,
- query: values.suggestedQueryInput,
- language: 'hogQL',
- })
- )
+ // Write the accepted query onto the tab's persistent model as one undoable
+ // edit. The model survives the diff <-> editor swap (keepCurrentModel), so its
+ // existing undo history is preserved and cmd+z walks back through the accepted
+ // query to the pre-AI query and the rest of the edit history.
+ applyUndoableModelEdit(props.monaco, values.activeTab?.uri, values.queryInput ?? '')
- // Handle both diff editor and regular editor
- if (props.editor && 'getModifiedEditor' in props.editor) {
- // It's a diff editor, set model on the modified editor
- const modifiedEditor = (props.editor as any).getModifiedEditor()
- modifiedEditor.setModel(newModel)
- } else {
- // Regular editor
- props.editor?.setModel(newModel)
- }
- } else {
- // Handle both diff editor and regular editor
- if (props.editor && 'getModifiedEditor' in props.editor) {
- // It's a diff editor, set model on the modified editor
- const modifiedEditor = (props.editor as any).getModifiedEditor()
- modifiedEditor.setModel(existingModel)
- } else {
- // Regular editor
- props.editor?.setModel(existingModel)
- }
- }
- }
posthog.capture('sql-editor-accepted-suggestion', {
source: values.suggestedSource,
})
@@ -962,47 +952,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
onRejectSuggestedQueryInput: () => {
values.suggestionPayload?.onReject(actions, values, props)
- // Re-create the model to prevent it from being purged
- if (props.monaco && values.activeTab) {
- const existingModel = props.monaco.editor.getModel(values.activeTab.uri)
- if (!existingModel) {
- const newModel = props.monaco.editor.createModel(
- values.queryInput ?? '',
- 'hogQL',
- values.activeTab.uri
- )
- cache.createdModels = cache.createdModels || []
- cache.createdModels.push(newModel)
- initModel(
- newModel,
- codeEditorLogic({
- key: `hogql-editor-${props.tabId}`,
- query: values.queryInput ?? '',
- language: 'hogQL',
- })
- )
+ // Keep the persistent model's content in sync with the reverted query (the
+ // suggestion was shown in a throwaway diff model, not this one). This is a
+ // no-op when the model already matches, so rejecting adds no undo step.
+ applyUndoableModelEdit(props.monaco, values.activeTab?.uri, values.queryInput ?? '')
- // Handle both diff editor and regular editor
- if (props.editor && 'getModifiedEditor' in props.editor) {
- // It's a diff editor, set model on the modified editor
- const modifiedEditor = (props.editor as any).getModifiedEditor()
- modifiedEditor.setModel(newModel)
- } else {
- // Regular editor
- props.editor?.setModel(newModel)
- }
- } else {
- // Handle both diff editor and regular editor
- if (props.editor && 'getModifiedEditor' in props.editor) {
- // It's a diff editor, set model on the modified editor
- const modifiedEditor = (props.editor as any).getModifiedEditor()
- modifiedEditor.setModel(existingModel)
- } else {
- // Regular editor
- props.editor?.setModel(existingModel)
- }
- }
- }
posthog.capture('sql-editor-rejected-suggestion', {
source: values.suggestedSource,
})
@@ -1024,7 +978,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
: undefined
if (props.monaco) {
- const uri = props.monaco.Uri.parse(`tab-${props.tabId}`)
+ const uri = props.monaco.Uri.parse(tabModelPath(props.tabId))
let model = props.monaco.editor.getModel(uri)
if (!model) {
model = props.monaco.editor.createModel(query, 'hogQL', uri)