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.

feat(sql-editor): save vim mode to the account and add a vimrc (#109808)

Luke Belton3eabd8057fd6
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f69d29ff5630..af237b963fe5 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -5022,7 +5022,7 @@ export interface UserApi {
passkeys_enabled_for_2fa?: boolean | null
/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */
hide_mcp_hints?: boolean
- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
ui_configuration?: unknown
/** @nullable */
readonly onboarding_skipped_at: string | null
@@ -5138,7 +5138,7 @@ export interface PatchedUserApi {
passkeys_enabled_for_2fa?: boolean | null
/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */
hide_mcp_hints?: boolean
- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
ui_configuration?: unknown
/** @nullable */
readonly onboarding_skipped_at?: string | null
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index b3fd3c6d9405..940c19a7f180 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1369,7 +1369,7 @@ export const UsersUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -1460,7 +1460,7 @@ export const UsersPartialUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -1548,7 +1548,7 @@ export const UsersHedgehogConfigPartialUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -1824,7 +1824,7 @@ export const UsersScenePersonalisationCreateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -1915,7 +1915,7 @@ export const UsersTwoFactorBackupCodesCreateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -2006,7 +2006,7 @@ export const UsersTwoFactorDisableCreateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -2094,7 +2094,7 @@ export const UsersTwoFactorValidateCreateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -2182,7 +2182,7 @@ export const UsersValidate2faCreateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -2270,7 +2270,7 @@ export const UsersCancelEmailChangeRequestPartialUpdateBody = /* @__PURE__ */ zo
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
@@ -2358,7 +2358,7 @@ export const UsersRequestEmailVerificationCreateBody = /* @__PURE__ */ zod.objec
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
diff --git a/frontend/src/layout/uiCustomizationLogic.ts b/frontend/src/layout/uiCustomizationLogic.ts
index d5baa93480e7..3923d0a906da 100644
--- a/frontend/src/layout/uiCustomizationLogic.ts
+++ b/frontend/src/layout/uiCustomizationLogic.ts
@@ -85,33 +85,33 @@ export interface uiCustomizationLogicValues {
export interface uiCustomizationLogicActions {
updateUser: (
user: Partial<UserType>,
- successCallback?: (() => void) | undefined
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
) => {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
} // userLogic
- updateUserFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- } // userLogic
updateUserSuccess: (
user: UserType,
payload?:
| {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
| undefined
) => {
payload?: {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
user: UserType
} // userLogic
+ clearPendingUiConfiguration: (configuration: UserUIConfiguration) => {
+ configuration: UserUIConfiguration
+ }
completeStarredProductsSetup: () => {
value: true
}
@@ -135,6 +135,15 @@ export interface uiCustomizationLogicActions {
section: keyof SidebarSectionsConfiguration
shown: boolean
}
+ updateUiConfiguration: (
+ configuration: UserUIConfiguration,
+ successCallback?: () => void,
+ failureCallback?: () => void
+ ) => {
+ configuration: UserUIConfiguration
+ failureCallback: (() => void) | undefined
+ successCallback: (() => void) | undefined
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -174,13 +183,19 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
path(['layout', 'uiCustomizationLogic']),
connect(() => ({
values: [userLogic, ['user', 'userLoading'], featureFlagLogic, ['featureFlags']],
- actions: [userLogic, ['updateUser', 'updateUserSuccess', 'updateUserFailure']],
+ actions: [userLogic, ['updateUser', 'updateUserSuccess']],
})),
actions({
setSidebarSectionShown: (section: SidebarSectionKey, shown: boolean) => ({ section, shown }),
setSidebarDensity: (density: SidebarDensity) => ({ density }),
setSidebarItemShown: (item: SidebarItemKey, shown: boolean) => ({ item, shown }),
setPendingUiConfiguration: (configuration: UserUIConfiguration | null) => ({ configuration }),
+ clearPendingUiConfiguration: (configuration: UserUIConfiguration) => ({ configuration }),
+ updateUiConfiguration: (
+ configuration: UserUIConfiguration,
+ successCallback?: () => void,
+ failureCallback?: () => void
+ ) => ({ configuration, successCallback, failureCallback }),
completeStarredProductsSetup: true,
}),
reducers({
@@ -189,6 +204,8 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
null as UserUIConfiguration | null,
{
setPendingUiConfiguration: (_, { configuration }) => configuration,
+ clearPendingUiConfiguration: (state, { configuration }) => (state === configuration ? null : state),
+ updateUserSuccess: (state, { payload }) => (payload?.user.ui_configuration === state ? null : state),
},
],
}),
@@ -228,10 +245,16 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ updateUiConfiguration: ({ configuration, successCallback, failureCallback }) => {
+ actions.setPendingUiConfiguration(configuration)
+ actions.updateUser({ ui_configuration: configuration }, successCallback, () => {
+ actions.clearPendingUiConfiguration(configuration)
+ failureCallback?.()
+ })
+ },
setSidebarSectionShown: ({ section, shown }) => {
const configuration = withSidebarSectionVisibility(values.uiConfiguration, section, shown)
- actions.setPendingUiConfiguration(configuration)
- actions.updateUser({ ui_configuration: configuration })
+ actions.updateUiConfiguration(configuration)
posthog.capture('sidebar customization changed', {
element_kind: 'section',
element_key: section,
@@ -240,8 +263,7 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
},
setSidebarItemShown: ({ item, shown }) => {
const configuration = withSidebarItemVisibility(values.uiConfiguration, item, shown)
- actions.setPendingUiConfiguration(configuration)
- actions.updateUser({ ui_configuration: configuration })
+ actions.updateUiConfiguration(configuration)
posthog.capture('sidebar customization changed', {
element_kind: 'item',
element_key: item,
@@ -250,8 +272,7 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
},
setSidebarDensity: ({ density }) => {
const configuration = withSidebarPatch(values.uiConfiguration, { density })
- actions.setPendingUiConfiguration(configuration)
- actions.updateUser({ ui_configuration: configuration })
+ actions.updateUiConfiguration(configuration)
posthog.capture('sidebar customization changed', {
element_kind: 'density',
element_key: density,
@@ -259,14 +280,7 @@ export const uiCustomizationLogic = kea<uiCustomizationLogicType>([
},
completeStarredProductsSetup: () => {
const configuration = withSidebarPatch(values.uiConfiguration, { starred_products_setup_completed: true })
- actions.setPendingUiConfiguration(configuration)
- actions.updateUser({ ui_configuration: configuration })
- },
- updateUserSuccess: () => {
- actions.setPendingUiConfiguration(null)
- },
- updateUserFailure: () => {
- actions.setPendingUiConfiguration(null)
+ actions.updateUiConfiguration(configuration)
},
})),
])
diff --git a/frontend/src/lib/components/MCPHint/mcpHintLogic.tsx b/frontend/src/lib/components/MCPHint/mcpHintLogic.tsx
index 0f4192e8f9d7..e22616e137f9 100644
--- a/frontend/src/lib/components/MCPHint/mcpHintLogic.tsx
+++ b/frontend/src/lib/components/MCPHint/mcpHintLogic.tsx
@@ -70,8 +70,10 @@ export interface mcpHintLogicActions {
} // eventUsageLogic
updateUser: (
user: Partial<UserType>,
- successCallback?: (() => void) | undefined
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
) => {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
} // userLogic
diff --git a/frontend/src/lib/logic/themeLogic.ts b/frontend/src/lib/logic/themeLogic.ts
index ca6efe7d743f..4f63c924c2d1 100644
--- a/frontend/src/lib/logic/themeLogic.ts
+++ b/frontend/src/lib/logic/themeLogic.ts
@@ -27,8 +27,10 @@ export interface themeLogicValues {
export interface themeLogicActions {
updateUser: (
user: Partial<UserType>,
- successCallback?: (() => void) | undefined
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
) => {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
} // userLogic
diff --git a/frontend/src/lib/logic/userPreferencesLogic.ts b/frontend/src/lib/logic/userPreferencesLogic.ts
index db73d6833f9c..9923cd3b1174 100644
--- a/frontend/src/lib/logic/userPreferencesLogic.ts
+++ b/frontend/src/lib/logic/userPreferencesLogic.ts
@@ -23,9 +23,6 @@ export interface userPreferencesLogicActions {
pinPersonProperty: (prop: string) => {
prop: string
}
- setEditorVimModeEnabled: (enabled: boolean) => {
- enabled: boolean
- }
setHideNullValues: (enabled: boolean) => {
enabled: boolean
}
@@ -52,7 +49,6 @@ export const userPreferencesLogic = kea<userPreferencesLogicType>([
unpinPersonProperty: (prop: string) => ({ prop }),
pinGroupProperty: (prop: string) => ({ prop }),
unpinGroupProperty: (prop: string) => ({ prop }),
- setEditorVimModeEnabled: (enabled: boolean) => ({ enabled }),
}),
connect(() => ({
values: [teamLogic, ['currentTeam']],
@@ -86,12 +82,8 @@ export const userPreferencesLogic = kea<userPreferencesLogicType>([
unpinGroupProperty: (state, { prop }) => state.filter((p) => p !== prop),
},
],
- editorVimModeEnabled: [
- false,
- { persist: true },
- {
- setEditorVimModeEnabled: (_, { enabled }) => enabled,
- },
- ],
+ // Read-only fallback for users who turned Vim mode on before sqlEditorVimLogic saved it to their account.
+ // pinned: the persisted localStorage key comes from this reducer name, so renaming it drops their setting.
+ editorVimModeEnabled: [false, { persist: true }, {}],
})),
])
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsx
index eefd56e91d87..caa37e8729e7 100644
--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx
+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx
@@ -55,6 +55,8 @@ export interface CodeEditorProps extends Omit<EditorProps, 'loading' | 'theme'>
originalValue?: string
/** Enable vim keybindings */
enableVimMode?: boolean
+ /** Vim commands to run when vim mode starts, one per line */
+ vimrc?: string
}
let codeEditorIndex = 0
@@ -177,6 +179,7 @@ export function CodeEditor({
metadataQueryOffset,
originalValue,
enableVimMode,
+ vimrc,
...editorProps
}: CodeEditorProps): JSX.Element {
const isDarkModeOn = useBodyIsDark()
@@ -224,6 +227,10 @@ export function CodeEditor({
const { vimCommandHistory } = useValues(builtCodeEditorLogic)
const { appendVimCommand } = useActions(builtCodeEditorLogic)
+ // Vim mode reads the history only when it starts. Each ex command appends to the history, so a dependency
+ // on it would restart Vim mode after every command and undo `:set` and `:map` changes made in the editor.
+ const vimCommandHistoryRef = useRef(vimCommandHistory)
+ vimCommandHistoryRef.current = vimCommandHistory
const { isVisible } = usePageVisibility()
@@ -416,8 +423,9 @@ export function CodeEditor({
return
}
vimModeRef.current = setupVimMode(editor, statusBar, {
- initialHistory: vimCommandHistory,
+ initialHistory: vimCommandHistoryRef.current,
onCommandExecuted: appendVimCommand,
+ vimrc,
})
})
} else if (vimModeRef.current) {
@@ -432,7 +440,7 @@ export function CodeEditor({
vimModeRef.current = null
}
}
- }, [editor, enableVimMode, vimCommandHistory, appendVimCommand])
+ }, [editor, enableVimMode, vimrc, appendVimCommand])
// The wrapper calls `editor.updateOptions` whenever this object's identity changes, and
// Monaco revalidates every option on each call, so only rebuild it when an input changes.
diff --git a/frontend/src/lib/monaco/vimMode.ts b/frontend/src/lib/monaco/vimMode.ts
index c8471e62d200..ebcbbf5f0fcf 100644
--- a/frontend/src/lib/monaco/vimMode.ts
+++ b/frontend/src/lib/monaco/vimMode.ts
@@ -1,6 +1,9 @@
import { editor as monacoEditor } from 'monaco-editor'
import { VimMode, initVimMode } from 'monaco-vim'
+import { VimrcError, parseVimrc } from './vimrc'
+import { VimMappingContext, VimrcMappingSession, createNonrecursiveVimMapping } from './vimrcMappings'
+
export interface VimModeHandle {
vimMode: VimMode
dispose: () => void
@@ -9,6 +12,128 @@ export interface VimModeHandle {
export interface VimModeProps {
initialHistory?: string[]
onCommandExecuted?: (command: string) => void
+ vimrc?: string
+}
+
+interface VimrcEditorState {
+ cursorBlink: boolean
+ defaultLineNumbers: monacoEditor.LineNumbersType
+}
+
+const vimrcEditorStates = new WeakMap<object, VimrcEditorState>()
+const vimrcMappingSession = new VimrcMappingSession()
+let vimrcSupportRegistered = false
+
+// Options and ex commands live on monaco-vim's global Vim object, which all editors share, so register them once.
+function registerVimrcSupport(): void {
+ if (vimrcSupportRegistered) {
+ return
+ }
+ const Vim = (VimMode as any).Vim
+
+ const noremapContexts: [string, VimMappingContext | undefined][] = [
+ ['noremap', undefined],
+ ['nnoremap', 'normal'],
+ ['inoremap', 'insert'],
+ ['vnoremap', 'visual'],
+ ]
+ for (const [name, context] of noremapContexts) {
+ Vim.defineEx(name, name, (_cm: any, params: { args?: string[]; input: string }): void => {
+ if (!params.args || params.args.length < 2) {
+ throw new Error(`Invalid mapping: ${params.input}`)
+ }
+ createNonrecursiveVimMapping(params.args[0], params.args[1], context)
+ })
+ }
+
+ // monaco-vim forces a solid cursor each time the editor enters normal mode. patchCursorBlink re-applies this option after that.
+ Vim.defineOption('cursorblink', false, 'boolean', [], (value: boolean | undefined, cm?: any): boolean | void => {
+ const state = cm && vimrcEditorStates.get(cm)
+ if (!state) {
+ return
+ }
+ if (value === undefined) {
+ return state.cursorBlink
+ }
+ state.cursorBlink = value
+ if (!cm.state.vim?.insertMode) {
+ cm.editor.updateOptions({ cursorBlinking: value ? 'blink' : 'solid' })
+ }
+ })
+
+ Vim.defineOption(
+ 'relativenumber',
+ false,
+ 'boolean',
+ ['rnu'],
+ (value: boolean | undefined, cm?: any): boolean | void => {
+ const state = cm && vimrcEditorStates.get(cm)
+ if (!state) {
+ return
+ }
+ if (value === undefined) {
+ return cm.editor.getRawOptions().lineNumbers === 'relative'
+ }
+ cm.editor.updateOptions({ lineNumbers: value ? 'relative' : state.defaultLineNumbers })
+ }
+ )
+
+ vimrcSupportRegistered = true
+}
+
+function patchCursorBlink(cmAdapter: any): () => void {
+ const originalEnterVimMode = cmAdapter.enterVimMode
+
+ cmAdapter.enterVimMode = function (...args: unknown[]): void {
+ originalEnterVimMode.apply(this, args)
+ if (vimrcEditorStates.get(cmAdapter)?.cursorBlink) {
+ this.editor.updateOptions({ cursorBlinking: 'blink' })
+ }
+ }
+
+ return () => {
+ cmAdapter.enterVimMode = originalEnterVimMode
+ }
+}
+
+// Runs each vimrc line as an ex command and returns an error for each line that failed. monaco-vim reports
+// most failures through openNotification instead of throwing, so the notifications are captured while the lines run.
+function applyVimrc(cmAdapter: any, vimrc: string): VimrcError[] {
+ const Vim = (VimMode as any).Vim
+
+ Vim.setOption('cursorblink', false, cmAdapter)
+ Vim.setOption('relativenumber', false, cmAdapter)
+
+ const { commands, errors } = parseVimrc(vimrc)
+ const failures = [...errors]
+
+ // Running a command overwrites the ":" register, which holds the last command the user typed.
+ const lastCommandRegister = Vim.getRegisterController().getRegister(':')
+ const lastCommand = lastCommandRegister.toString()
+ const originalOpenNotification = cmAdapter.openNotification
+ const captured: { notification: string | null } = { notification: null }
+ cmAdapter.openNotification = (html: string | Node): void => {
+ captured.notification = typeof html === 'string' ? html : html.textContent
+ }
+
+ try {
+ for (const { lineNumber, command } of vimrcMappingSession.getCommandsToApply(commands)) {
+ captured.notification = null
+ try {
+ Vim.handleEx(cmAdapter, command)
+ } catch {
+ // monaco-vim sends the error to openNotification before it rethrows, so the failure is already recorded.
+ }
+ if (captured.notification) {
+ failures.push({ lineNumber, message: captured.notification })
+ }
+ }
+ } finally {
+ cmAdapter.openNotification = originalOpenNotification
+ lastCommandRegister.setText(lastCommand)
+ }
+
+ return failures
}
function extractPatternBeforeSeparator(str: string, separator: string): string | null {
@@ -244,15 +369,27 @@ export function setupVimMode(
statusBarEl: HTMLElement,
options?: VimModeProps
): VimModeHandle {
+ registerVimrcSupport()
+ const defaultLineNumbers = editor.getRawOptions().lineNumbers ?? 'on'
const vimMode = initVimMode(editor, statusBarEl)
const cmAdapter = vimMode as any
+ vimrcEditorStates.set(cmAdapter, { cursorBlink: false, defaultLineNumbers })
const restoreAddOverlay = patchAddOverlay(cmAdapter)
const restoreCloseInput = patchCloseInput(cmAdapter.statusBar)
const restoreArrowKeys = patchStatusBarArrowKeys(statusBarEl)
const restoreSetSec = patchSubstituteHighlight(cmAdapter, cmAdapter.statusBar)
+ const restoreCursorBlink = patchCursorBlink(cmAdapter)
const cleanupClipboard = setupClipboardSync(editor, statusBarEl)
+ const releaseVimrcMappings = vimrcMappingSession.retainEditor()
+ const vimrcFailures = applyVimrc(cmAdapter, options?.vimrc ?? '')
+ if (vimrcFailures.length) {
+ const [{ lineNumber, message }] = vimrcFailures
+ const more = vimrcFailures.length > 1 ? ` (and ${vimrcFailures.length - 1} more)` : ''
+ cmAdapter.openNotification(`Couldn't apply vimrc line ${lineNumber}: ${message}${more}`)
+ }
+
let cleanupHistoryPersistence: (() => void) | undefined
if (options?.onCommandExecuted) {
cleanupHistoryPersistence = setupCommandHistoryPersistence(
@@ -265,12 +402,15 @@ export function setupVimMode(
vimMode,
dispose: () => {
cleanupHistoryPersistence?.()
+ releaseVimrcMappings()
cleanupClipboard()
+ restoreCursorBlink()
restoreSetSec()
restoreArrowKeys()
restoreCloseInput()
restoreAddOverlay()
vimMode.dispose()
+ editor.updateOptions({ lineNumbers: defaultLineNumbers })
},
}
}
diff --git a/frontend/src/lib/monaco/vimrc.test.ts b/frontend/src/lib/monaco/vimrc.test.ts
new file mode 100644
index 000000000000..25b3e131f8fa
--- /dev/null
+++ b/frontend/src/lib/monaco/vimrc.test.ts
@@ -0,0 +1,43 @@
+import { parseVimrc } from './vimrc'
+
+describe('parseVimrc', () => {
+ it('keeps mapping and set commands with their line numbers and skips blanks and comments', () => {
+ const vimrc = ['" my settings', '', 'inoremap jj <Esc>', ' :set cursorblink ', 'nmap H ^'].join('\n')
+
+ expect(parseVimrc(vimrc)).toEqual({
+ commands: [
+ { lineNumber: 3, command: 'inoremap jj <Esc>' },
+ { lineNumber: 4, command: 'set cursorblink' },
+ { lineNumber: 5, command: 'nmap H ^' },
+ ],
+ errors: [],
+ })
+ })
+
+ it('allows mappings from the colon key and keys that run an ex command', () => {
+ expect(parseVimrc('map : <Esc>\nnmap S :sort')).toEqual({
+ commands: [
+ { lineNumber: 1, command: 'map : <Esc>' },
+ { lineNumber: 2, command: 'nmap S :sort' },
+ ],
+ errors: [],
+ })
+ })
+
+ it.each([
+ ['deletes every line', '%d'],
+ ['deletes matching lines', 'g/select/d'],
+ ['substitutes text', 's/select/SELECT/'],
+ ['sorts lines', 'sort'],
+ ['shares a prefix with an allowed command', 'setfoo'],
+ ['adds a suffix to an allowed command', 'set123'],
+ ['overrides an option command', 'map :set :sort'],
+ ['overrides a mapping command', 'noremap :map :sort'],
+ ['removes an ex-command mapping', 'unmap :set'],
+ ])('rejects a command that %s', (_description, command) => {
+ const { commands, errors } = parseVimrc(`set relativenumber\n${command}`)
+
+ expect(commands).toEqual([{ lineNumber: 1, command: 'set relativenumber' }])
+ expect(errors).toEqual([{ lineNumber: 2, message: expect.stringContaining(command) }])
+ })
+})
diff --git a/frontend/src/lib/monaco/vimrc.ts b/frontend/src/lib/monaco/vimrc.ts
new file mode 100644
index 000000000000..925996cabef6
--- /dev/null
+++ b/frontend/src/lib/monaco/vimrc.ts
@@ -0,0 +1,54 @@
+// The vimrc runs as ex commands against the live editor each time Vim mode starts. Only commands that
+// configure Vim are allowed, because a command like `%d` or `g/x/d` would edit the user's query on every load.
+const MAPPING_COMMANDS = ['map', 'nmap', 'imap', 'vmap', 'noremap', 'nnoremap', 'inoremap', 'vnoremap', 'unmap']
+const OPTION_COMMANDS = ['set', 'setlocal', 'setglobal']
+export const VIMRC_ALLOWED_COMMANDS: readonly string[] = [...MAPPING_COMMANDS, ...OPTION_COMMANDS]
+
+export const VIMRC_MAX_LENGTH = 10000
+
+export interface VimrcCommand {
+ lineNumber: number
+ command: string
+}
+
+export interface VimrcError {
+ lineNumber: number
+ message: string
+}
+
+export interface ParsedVimrc {
+ commands: VimrcCommand[]
+ errors: VimrcError[]
+}
+
+export function parseVimrc(vimrc: string): ParsedVimrc {
+ const commands: VimrcCommand[] = []
+ const errors: VimrcError[] = []
+
+ vimrc.split('\n').forEach((rawLine, index) => {
+ const lineNumber = index + 1
+ const command = rawLine.trim().replace(/^:+/, '')
+ if (!command || command.startsWith('"')) {
+ return
+ }
+ const commandName = command.match(/^[a-z]+(?=\s|$)/i)?.[0]
+ if (!commandName || !VIMRC_ALLOWED_COMMANDS.includes(commandName)) {
+ errors.push({
+ lineNumber,
+ message: `"${command}" isn't supported. Use one of: ${VIMRC_ALLOWED_COMMANDS.join(', ')}.`,
+ })
+ return
+ }
+ const lhs = command.split(/\s+/)[1]
+ if (MAPPING_COMMANDS.includes(commandName) && lhs?.startsWith(':') && lhs !== ':') {
+ errors.push({
+ lineNumber,
+ message: `"${command}" maps an ex command. Map a key instead.`,
+ })
+ return
+ }
+ commands.push({ lineNumber, command })
+ })
+
+ return { commands, errors }
+}
diff --git a/frontend/src/lib/monaco/vimrcMappings.test.ts b/frontend/src/lib/monaco/vimrcMappings.test.ts
new file mode 100644
index 000000000000..13965bfe7484
--- /dev/null
+++ b/frontend/src/lib/monaco/vimrcMappings.test.ts
@@ -0,0 +1,140 @@
+import { VimMode } from 'monaco-vim'
+
+import { parseVimrc } from './vimrc'
+import { VimrcMappingSession, createNonrecursiveVimMapping } from './vimrcMappings'
+
+jest.mock('monaco-editor', () => ({ KeyCode: {}, editor: {}, SelectionDirection: {} }))
+
+interface Cursor {
+ line: number
+ ch: number
+}
+
+const Vim = (
+ VimMode as unknown as {
+ Vim: {
+ mapclear: () => void
+ handleKey: (cm: unknown, key: string) => void
+ handleEx: (cm: unknown, input: string) => void
+ maybeInitVimState_: (cm: unknown) => void
+ }
+ }
+).Vim
+
+function createAdapter(): {
+ state: { vim: { insertMode: boolean } | undefined }
+ curOp: Record<string, unknown>
+ operation: (callback: () => unknown) => unknown
+ dispatch: () => void
+ getCursor: () => Cursor
+ setCursor: (line: number, ch: number) => void
+ firstLine: () => number
+ lastLine: () => number
+ getLine: () => string
+ findPosV: (position: Cursor, amount: number) => Cursor
+ charCoords: () => { left: number }
+ listSelections: () => { head: Cursor; anchor: Cursor }[]
+ replaceRange: () => void
+ getInputField: () => HTMLInputElement
+ off: () => void
+ setOption: () => void
+ toggleOverwrite: () => void
+ enterVimMode: () => void
+} {
+ let cursor = { line: 1, ch: 2 }
+ const input = document.createElement('input')
+ const cm = {
+ state: { vim: undefined as { insertMode: boolean } | undefined },
+ curOp: {},
+ operation: (callback: () => unknown): unknown => callback(),
+ dispatch: (): void => {},
+ getCursor: (): Cursor => cursor,
+ setCursor: (line: number, ch: number): void => {
+ cursor = { line, ch }
+ },
+ firstLine: (): number => 0,
+ lastLine: (): number => 2,
+ getLine: (): string => 'SELECT 1',
+ findPosV: (position: Cursor, amount: number): Cursor => ({ ...position, line: position.line + amount }),
+ charCoords: (): { left: number } => ({ left: 0 }),
+ listSelections: (): { head: Cursor; anchor: Cursor }[] => [{ head: cursor, anchor: cursor }],
+ replaceRange: (): void => {},
+ getInputField: (): HTMLInputElement => input,
+ off: (): void => {},
+ setOption: (): void => {},
+ toggleOverwrite: (): void => {},
+ enterVimMode: (): void => {},
+ }
+ Vim.maybeInitVimState_(cm)
+ return cm
+}
+
+describe('createNonrecursiveVimMapping', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ Vim.mapclear()
+ })
+
+ afterEach(() => {
+ Vim.mapclear()
+ jest.useRealTimers()
+ })
+
+ it('swaps movement keys without recursively applying the other mapping', () => {
+ const cm = createAdapter()
+ createNonrecursiveVimMapping('j', 'k', 'normal')
+ createNonrecursiveVimMapping('k', 'j', 'normal')
+
+ Vim.handleKey(cm, 'j')
+ expect(cm.getCursor().line).toBe(0)
+
+ Vim.handleKey(cm, 'k')
+ expect(cm.getCursor().line).toBe(1)
+ })
+
+ it('keeps the insert-mode escape mapping', () => {
+ const cm = createAdapter()
+ cm.state.vim!.insertMode = true
+ createNonrecursiveVimMapping('jj', '<Esc>', 'insert')
+
+ Vim.handleKey(cm, 'j')
+ Vim.handleKey(cm, 'j')
+
+ expect(cm.state.vim!.insertMode).toBe(false)
+ })
+
+ it('preserves typed mappings when another editor opens and resets them after the last editor closes', () => {
+ const session = new VimrcMappingSession()
+ const commands = parseVimrc('nmap H j\nset pcre').commands
+ const firstEditor = createAdapter()
+ const releaseFirst = session.retainEditor()
+ session.getCommandsToApply(commands).forEach(({ command }) => Vim.handleEx(firstEditor, command))
+ Vim.handleEx(firstEditor, 'nmap H k')
+
+ const secondEditor = createAdapter()
+ const releaseSecond = session.retainEditor()
+ const secondCommands = session.getCommandsToApply(commands)
+ expect(secondCommands.map(({ command }) => command)).toEqual(['set pcre'])
+ secondCommands.forEach(({ command }) => Vim.handleEx(secondEditor, command))
+
+ Vim.handleKey(firstEditor, 'H')
+ expect(firstEditor.getCursor().line).toBe(0)
+
+ releaseFirst()
+ releaseSecond()
+ const nextEditor = createAdapter()
+ session.retainEditor()
+ session.getCommandsToApply(commands).forEach(({ command }) => Vim.handleEx(nextEditor, command))
+ Vim.handleKey(nextEditor, 'H')
+ expect(nextEditor.getCursor().line).toBe(2)
+ })
+
+ it('rejects unsupported key sequences instead of making them recursive', () => {
+ const cm = createAdapter()
+
+ expect(() => createNonrecursiveVimMapping('j', 'kk', 'normal')).toThrow("isn't supported by noremap")
+
+ Vim.handleKey(cm, 'j')
+ expect(cm.getCursor().line).toBe(2)
+ })
+})
diff --git a/frontend/src/lib/monaco/vimrcMappings.ts b/frontend/src/lib/monaco/vimrcMappings.ts
new file mode 100644
index 000000000000..099c3f886985
--- /dev/null
+++ b/frontend/src/lib/monaco/vimrcMappings.ts
@@ -0,0 +1,85 @@
+import { VimMode } from 'monaco-vim'
+
+import { VimrcCommand } from './vimrc'
+
+export type VimMappingContext = 'normal' | 'insert' | 'visual'
+
+interface VimKeyMapping {
+ keys: string
+ type: string
+ [key: string]: unknown
+}
+
+interface VimMappingApi {
+ noremap: (
+ this: { _mapCommand: (mapping: VimKeyMapping) => void },
+ lhs: string,
+ rhs: string,
+ context?: VimMappingContext
+ ) => void
+ _mapCommand: (mapping: VimKeyMapping) => void
+ mapclear: () => void
+ mapCommand: (
+ keys: string,
+ type: string,
+ name: string,
+ args: Record<string, unknown>,
+ extra: { context: VimMappingContext }
+ ) => void
+}
+
+function isMappingCommand({ command }: VimrcCommand): boolean {
+ return command.split(/\s+/, 1)[0].endsWith('map')
+}
+
+export class VimrcMappingSession {
+ private mappingCommands: string | null = null
+ private editorCount = 0
+
+ retainEditor(): () => void {
+ this.editorCount++
+ let released = false
+ return () => {
+ if (released) {
+ return
+ }
+ released = true
+ this.editorCount--
+ if (!this.editorCount) {
+ this.mappingCommands = null
+ }
+ }
+ }
+
+ getCommandsToApply(commands: VimrcCommand[]): VimrcCommand[] {
+ const mappingCommands = commands
+ .filter(isMappingCommand)
+ .map(({ command }) => command)
+ .join('\n')
+ // Replaying the same profile would erase mappings typed in another active editor.
+ if (mappingCommands === this.mappingCommands) {
+ return commands.filter((command) => !isMappingCommand(command))
+ }
+ const Vim = (VimMode as unknown as { Vim: VimMappingApi }).Vim
+ Vim.mapclear()
+ this.mappingCommands = mappingCommands
+ return commands
+ }
+}
+
+export function createNonrecursiveVimMapping(lhs: string, rhs: string, context?: VimMappingContext): void {
+ const Vim = (VimMode as unknown as { Vim: VimMappingApi }).Vim
+
+ // Escape is handled before keymap lookup, so noremap cannot resolve it from the default keymap.
+ if (context === 'insert' && rhs === '<Esc>') {
+ Vim.mapCommand(lhs, 'action', 'exitInsertMode', {}, { context })
+ return
+ }
+
+ const mappings: VimKeyMapping[] = []
+ Vim.noremap.call({ _mapCommand: (mapping) => mappings.push(mapping) }, lhs, rhs, context)
+ if (!mappings.length) {
+ throw new Error(`Mapping "${lhs} ${rhs}" isn't supported by noremap. Use a map command for key sequences.`)
+ }
+ mappings.forEach((mapping) => Vim._mapCommand(mapping))
+}
diff --git a/frontend/src/models/groupsModel.ts b/frontend/src/models/groupsModel.ts
index 6dc06a3142a7..aff68485622c 100644
--- a/frontend/src/models/groupsModel.ts
+++ b/frontend/src/models/groupsModel.ts
@@ -49,12 +49,14 @@ export interface groupsModelActions {
user: UserType,
payload?:
| {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
| undefined
) => {
payload?: {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 39db5638ba80..de8f2992699a 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -51585,6 +51585,22 @@
}
]
},
+ "SQLEditorConfiguration": {
+ "additionalProperties": {},
+ "description": "Customization of the SQL editor. Extra keys are tolerated so older servers accept configs written by newer clients.",
+ "properties": {
+ "vim_mode_enabled": {
+ "description": "Whether the SQL editor uses Vim keybindings. An absent value falls back to the legacy browser preference.",
+ "type": "boolean"
+ },
+ "vimrc": {
+ "description": "Vim commands to run when Vim mode starts, one per line, such as `imap jj <Esc>` or `set cursorblink`.",
+ "maxLength": 10000,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
"SampleRatioMismatch": {
"additionalProperties": false,
"properties": {
@@ -56553,6 +56569,9 @@
"sidebar": {
"$ref": "#/definitions/SidebarConfiguration"
},
+ "sql_editor": {
+ "$ref": "#/definitions/SQLEditorConfiguration"
+ },
"version": {
"description": "Schema version of this configuration blob, for future format migrations.",
"type": "integer"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a463aa4cbec2..6cf29ee4aaaf 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -9093,6 +9093,18 @@ export interface SidebarConfiguration {
[key: string]: unknown
}
+/** Customization of the SQL editor. Extra keys are tolerated so older servers accept configs written by newer clients. */
+export interface SQLEditorConfiguration {
+ /** Whether the SQL editor uses Vim keybindings. An absent value falls back to the legacy browser preference. */
+ vim_mode_enabled?: boolean
+ /**
+ * Vim commands to run when Vim mode starts, one per line, such as `imap jj <Esc>` or `set cursorblink`.
+ * @maxLength 10000
+ */
+ vimrc?: string
+ [key: string]: unknown
+}
+
/**
* Per-user UI customization, persisted on the User model as a single JSONB blob.
* A null configuration and any absent key mean "default", which for visibility is "shown",
@@ -9106,6 +9118,7 @@ export interface UserUIConfiguration {
*/
version: number
sidebar?: SidebarConfiguration
+ sql_editor?: SQLEditorConfiguration
[key: string]: unknown
}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx b/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx
index e9eea36fd0d6..864cbb421345 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx
@@ -23,6 +23,7 @@ interface QueryPaneProps {
originalValue?: string
onRun?: () => void
editorVimModeEnabled?: boolean
+ editorVimrc?: string
constrainHeight?: boolean
}
@@ -90,6 +91,7 @@ export function QueryPane(props: QueryPaneProps): JSX.Element {
width={width}
originalValue={props.originalValue}
enableVimMode={props.editorVimModeEnabled}
+ vimrc={props.editorVimrc}
{...props.codeEditorProps}
autoFocus={!queryLoading && (props.codeEditorProps.autoFocus ?? true)}
options={editorOptions}
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index cca88ca3506e..115f0547176c 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -18,7 +18,6 @@ import { LemonMenu } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { userPreferencesLogic } from 'lib/logic/userPreferencesLogic'
import { cn } from 'lib/utils/css-classes'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { Scene } from 'scenes/sceneTypes'
@@ -29,6 +28,8 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { VimrcModal } from 'products/data_warehouse/frontend/shared/components/VimrcModal'
+import { sqlEditorVimLogic } from 'products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic'
import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
import { BIEditor } from './bi/BIEditor'
@@ -124,8 +125,8 @@ export function QueryWindow({
const { setSuggestedQueryInput, reportAIQueryPromptOpen, fixIndexUsageWithAI } = useActions(logic)
const biModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_BI_MODE')
const vimModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_VIM_MODE')
- const { editorVimModeEnabled } = useValues(userPreferencesLogic)
- const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)
+ const { vimModeEnabled, vimrc, editorSettingsMenuKey } = useValues(sqlEditorVimLogic)
+ const { setVimModeEnabled, openVimrcModal, setEditorSettingsMenuOpen } = useActions(sqlEditorVimLogic)
const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)
const { setDatabaseTreeCollapsed } = useActions(editorSizingLogic)
// Raw-only connections are forced to raw SQL mode — no toggle to show.
@@ -232,8 +233,8 @@ export function QueryWindow({
custom: true,
label: () => (
<LemonSwitch
- checked={editorVimModeEnabled}
- onChange={setEditorVimModeEnabled}
+ checked={vimModeEnabled}
+ onChange={setVimModeEnabled}
label="Vim mode"
size="small"
fullWidth
@@ -241,6 +242,16 @@ export function QueryWindow({
/>
),
},
+ ...(vimModeEnabled
+ ? [
+ {
+ label: 'Edit vimrc',
+ onClick: () => openVimrcModal(codeEditorKey),
+ size: 'small' as const,
+ 'data-attr': 'sql-editor-vimrc-edit',
+ },
+ ]
+ : []),
]
: []),
...(canSendRawQuery
@@ -336,7 +347,13 @@ export function QueryWindow({
<div className="ml-auto flex items-center gap-2">
<FixErrorButton type="secondary" size="small" source="action-bar" />
{editorSettingsItems.length > 0 ? (
- <LemonMenu items={editorSettingsItems} closeOnClickInside={false} placement="bottom-end">
+ <LemonMenu
+ items={editorSettingsItems}
+ closeOnClickInside={false}
+ placement="bottom-end"
+ visible={editorSettingsMenuKey === codeEditorKey}
+ onVisibilityChange={(open) => setEditorSettingsMenuOpen(codeEditorKey, open)}
+ >
<LemonButton
icon={<IconGear />}
type="secondary"
@@ -346,6 +363,7 @@ export function QueryWindow({
/>
</LemonMenu>
) : null}
+ {vimModeFeatureEnabled ? <VimrcModal editorKey={codeEditorKey} /> : null}
{mode === SQLEditorMode.Embedded && (
<SceneTitlePanelButton
buttonClassName="size-[26px]"
@@ -369,7 +387,8 @@ export function QueryWindow({
sourceQuery={sourceQuery.source}
promptError={null}
onRun={runQuery}
- editorVimModeEnabled={vimModeFeatureEnabled && editorVimModeEnabled}
+ editorVimModeEnabled={vimModeFeatureEnabled && vimModeEnabled}
+ editorVimrc={vimrc}
constrainHeight={showOutputPanel}
codeEditorProps={{
queryKey: codeEditorKey,
diff --git a/frontend/src/scenes/settings/user/profilePictureLogic.ts b/frontend/src/scenes/settings/user/profilePictureLogic.ts
index cd4a44bdd37d..b087a94513a4 100644
--- a/frontend/src/scenes/settings/user/profilePictureLogic.ts
+++ b/frontend/src/scenes/settings/user/profilePictureLogic.ts
@@ -48,12 +48,14 @@ export interface profilePictureLogicActions {
user: UserType,
payload?:
| {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
| undefined
) => {
payload?: {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
diff --git a/frontend/src/scenes/userLogic.test.ts b/frontend/src/scenes/userLogic.test.ts
index 002c83c6f840..4c22aa37099c 100644
--- a/frontend/src/scenes/userLogic.test.ts
+++ b/frontend/src/scenes/userLogic.test.ts
@@ -8,6 +8,7 @@ import api from 'lib/api'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { UserType } from '~/types'
import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
@@ -293,6 +294,48 @@ describe('userLogic', () => {
}
)
+ it.each([false, true])('serializes subsequent updates when the first request fails: %s', async (firstFails) => {
+ let releaseFirst: (user: UserType) => void = () => {}
+ let rejectFirst: (error: unknown) => void = () => {}
+ let reportFirstStarted: () => void = () => {}
+ const firstStarted = new Promise<void>((resolve) => {
+ reportFirstStarted = resolve
+ })
+ const firstHeld = new Promise<UserType>((resolve, reject) => {
+ releaseFirst = resolve
+ rejectFirst = reject
+ })
+ const latestUser = { ...userWithLightTheme, first_name: 'Latest' }
+ const update = jest
+ .spyOn(api, 'update')
+ .mockImplementationOnce(async () => {
+ reportFirstStarted()
+ return await firstHeld
+ })
+ .mockResolvedValueOnce(latestUser)
+ const firstSuccess = jest.fn()
+ const firstFailure = jest.fn()
+
+ userLogic.actions.updateUser({ first_name: 'First' }, firstSuccess, firstFailure)
+ await firstStarted
+ userLogic.actions.updateUser({ first_name: 'Latest' })
+ const requestsBeforeRelease = update.mock.calls.length
+
+ await expectLogic(userLogic, () => {
+ if (firstFails) {
+ rejectFirst({ status: 400, detail: 'Update rejected by server.' })
+ } else {
+ releaseFirst({ ...userWithLightTheme, first_name: 'First' })
+ }
+ }).toFinishAllListeners()
+
+ expect(requestsBeforeRelease).toBe(1)
+ expect(update).toHaveBeenCalledTimes(2)
+ expect(userLogic.values.user?.first_name).toBe('Latest')
+ expect(firstSuccess).toHaveBeenCalledTimes(firstFails ? 0 : 1)
+ expect(firstFailure).toHaveBeenCalledTimes(firstFails ? 1 : 0)
+ })
+
it('reports a genuine backend error (500) to error tracking', async () => {
const captureSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
jest.spyOn(api, 'update').mockRejectedValue({ status: 500, statusText: 'Internal Server Error' })
diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.ts
index 04a45031edc3..e51036d5afdf 100644
--- a/frontend/src/scenes/userLogic.ts
+++ b/frontend/src/scenes/userLogic.ts
@@ -330,8 +330,10 @@ export interface userLogicActions {
}
updateUser: (
user: Partial<UserType>,
- successCallback?: () => void
+ successCallback?: () => void,
+ failureCallback?: () => void
) => {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
@@ -345,12 +347,14 @@ export interface userLogicActions {
updateUserSuccess: (
user: UserType,
payload?: {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
) => {
user: UserType
payload?: {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
}
@@ -431,9 +435,10 @@ export const userLogic = kea<userLogicType>([
updateCurrentOrganization: (organizationId: string, destination?: string) => ({ organizationId, destination }),
logout: (preserveLocation = false, nextUrl?: string) => ({ preserveLocation, nextUrl }),
upgradeImpersonation: (reason: string) => ({ reason }),
- updateUser: (user: Partial<UserType>, successCallback?: () => void) => ({
+ updateUser: (user: Partial<UserType>, successCallback?: () => void, failureCallback?: () => void) => ({
user,
successCallback,
+ failureCallback,
}),
cancelEmailChangeRequest: true,
setUserScenePersonalisation: (scene: DashboardCompatibleScenes, dashboard: number) => ({ scene, dashboard }),
@@ -498,7 +503,7 @@ export const userLogic = kea<userLogicType>([
},
},
})),
- loaders(({ values, actions }) => ({
+ loaders(({ values, actions, cache }) => ({
user: [
// TODO: Because we don't actually load the app until this request completes, `user` is never `null` (will help simplify checks across the app)
null as UserType | null,
@@ -513,16 +518,34 @@ export const userLogic = kea<userLogicType>([
}
return null
},
- updateUser: async ({ user, successCallback }) => {
- if (!values.user) {
- throw new Error('Current user has not been loaded yet, so it cannot be updated!')
+ updateUser: async ({ user, successCallback, failureCallback }): Promise<UserType> => {
+ const previousUpdate = cache.pendingUserUpdate as Promise<void> | undefined
+ let completeUpdate: () => void = () => {}
+ const pendingUpdate = new Promise<void>((resolve) => {
+ completeUpdate = resolve
+ })
+ cache.pendingUserUpdate = pendingUpdate
+ await previousUpdate
+
+ try {
+ if (!values.user) {
+ throw new Error('Current user has not been loaded yet, so it cannot be updated!')
+ }
+ // Full user responses can replace newer state, so account writes finish in submission order.
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersPartialUpdate() from '~/generated/core/api' instead.
+ const response = await api.update<UserType>('api/users/@me/', user)
+ successCallback?.()
+ return response
+ } catch (error) {
+ failureCallback?.()
+ // Returning the old user would make kea-loaders report a failed write as a success.
+ throw error
+ } finally {
+ completeUpdate()
+ if (cache.pendingUserUpdate === pendingUpdate) {
+ cache.pendingUserUpdate = undefined
+ }
}
- // Let failures throw so kea-loaders dispatches `updateUserFailure` — returning the old
- // user here would be treated as a success, silently masking backend errors.
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersPartialUpdate() from '~/generated/core/api' instead.
- const response = await api.update<UserType>('api/users/@me/', user)
- successCallback?.()
- return response
},
cancelEmailChangeRequest: async () => {
if (!values.user) {
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 10734e371653..55cc107730fc 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -283,8 +283,10 @@ export interface webAnalyticsLogicActions {
cancelAllLoading: () => {} // dataNodeCollectionLogic
updateUser: (
user: Partial<UserType>,
- successCallback?: (() => void) | undefined
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
) => {
+ failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
} // userLogic
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 092d6e0eefb0..e0f4a621ac96 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -2808,6 +2808,9 @@ class TestUserUIConfigurationValidation(SimpleTestCase):
("activity_not_customizable", {"version": 1, "sidebar": {"items": {"activity": {"visible": False}}}}),
("non_boolean_visible", {"version": 1, "sidebar": {"items": {"home": {"visible": "nope"}}}}),
("unknown_node_key", {"version": 1, "sidebar": {"items": {"home": {"visible": False, "size": 1}}}}),
+ ("non_boolean_vim_mode", {"version": 1, "sql_editor": {"vim_mode_enabled": "nope"}}),
+ ("non_string_vimrc", {"version": 1, "sql_editor": {"vimrc": ["imap jj <Esc>"]}}),
+ ("vimrc_too_long", {"version": 1, "sql_editor": {"vimrc": "x" * 10001}}),
]
)
def test_invalid_ui_configuration_is_rejected(self, _name, value):
@@ -2842,6 +2845,13 @@ class TestUserUIConfigurationValidation(SimpleTestCase):
},
),
("new_user_default", default_ui_configuration_for_new_users()),
+ (
+ "sql_editor",
+ {
+ "version": 1,
+ "sql_editor": {"vim_mode_enabled": True, "vimrc": "imap jj <Esc>\nset cursorblink"},
+ },
+ ),
]
)
def test_valid_ui_configuration_is_accepted(self, _name, value):
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 58a37194efe0..37cb0b30a3fc 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -284,8 +284,9 @@ class UserSerializer(serializers.ModelSerializer):
required=False,
allow_null=True,
help_text=(
- "Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers "
- "sidebar section and item visibility. Send the complete object: it replaces the stored value "
+ "Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar "
+ "section and item visibility, and SQL editor settings such as Vim mode and the vimrc. "
+ "Send the complete object: it replaces the stored value "
"wholesale. Null means no customization; absent keys mean the element is shown. Once "
"`sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true."
),
diff --git a/posthog/schema.py b/posthog/schema.py
index b11abc2a3d89..fdd075cc290d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2991,6 +2991,21 @@ class RevenueCurrencyPropertyConfig(BaseModel):
static: CurrencyCode | None = None
+class SQLEditorConfiguration(BaseModel):
+ vim_mode_enabled: bool | None = Field(
+ default=None,
+ description=(
+ "Whether the SQL editor uses Vim keybindings. An absent value falls back to the legacy browser preference."
+ ),
+ )
+ vimrc: constr(max_length=10000) | None = Field(
+ default=None,
+ description=(
+ "Vim commands to run when Vim mode starts, one per line, such as `imap jj <Esc>` or `set cursorblink`."
+ ),
+ )
+
+
class SampleRatioMismatch(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -25540,6 +25555,7 @@ class UsageMetricsQuery(BaseModel):
class UserUIConfiguration(BaseModel):
sidebar: SidebarConfiguration | None = None
+ sql_editor: SQLEditorConfiguration | None = None
version: int = Field(
...,
description=("Schema version of this configuration blob, for future format migrations."),
diff --git a/products/data_warehouse/frontend/shared/components/VimrcModal.tsx b/products/data_warehouse/frontend/shared/components/VimrcModal.tsx
new file mode 100644
index 000000000000..07cdff9627b7
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/VimrcModal.tsx
@@ -0,0 +1,70 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal, LemonTextArea } from '@posthog/lemon-ui'
+
+import { VIMRC_MAX_LENGTH } from 'lib/monaco/vimrc'
+
+import { sqlEditorVimLogic } from '../logics/sqlEditorVimLogic'
+
+export function VimrcModal({ editorKey }: { editorKey: string }): JSX.Element {
+ const { vimrcEditorKey, vimrcDraft, vimrcDraftErrors, vimrcTooLong, vimrcSaving } = useValues(sqlEditorVimLogic)
+ const { closeVimrcModal, setVimrcDraft, saveVimrc } = useActions(sqlEditorVimLogic)
+
+ return (
+ <LemonModal
+ title="Edit vimrc"
+ description={
+ <span>
+ These commands run each time Vim mode starts. Use map commands such as{' '}
+ <code>inoremap jj &lt;Esc&gt;</code>, and set commands such as <code>set cursorblink</code> or{' '}
+ <code>set relativenumber</code>. Lines that start with <code>"</code> are comments.
+ </span>
+ }
+ isOpen={vimrcEditorKey === editorKey}
+ onClose={closeVimrcModal}
+ width={600}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeVimrcModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveVimrc}
+ loading={vimrcSaving}
+ disabledReason={
+ vimrcDraftErrors.length
+ ? 'Fix the lines listed above to save'
+ : vimrcTooLong
+ ? `Keep the vimrc under ${VIMRC_MAX_LENGTH.toLocaleString()} characters to save`
+ : undefined
+ }
+ data-attr="sql-editor-vimrc-save"
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-2">
+ <LemonTextArea
+ value={vimrcDraft}
+ onChange={setVimrcDraft}
+ placeholder={'inoremap jj <Esc>\nset cursorblink'}
+ className="font-mono"
+ minRows={8}
+ maxRows={20}
+ autoFocus
+ data-attr="sql-editor-vimrc-input"
+ />
+ {vimrcDraftErrors.length ? (
+ <ul className="text-danger text-xs flex flex-col gap-1">
+ {vimrcDraftErrors.map(({ lineNumber, message }) => (
+ <li key={lineNumber}>{`Line ${lineNumber}: ${message}`}</li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts
new file mode 100644
index 000000000000..f908682a0ba4
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.test.ts
@@ -0,0 +1,250 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
+import { useMocks } from '~/mocks/jest'
+import { UserUIConfiguration } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { UserType } from '~/types'
+
+import { sqlEditorVimLogic } from './sqlEditorVimLogic'
+
+describe('sqlEditorVimLogic', () => {
+ let logic: ReturnType<typeof sqlEditorVimLogic.build>
+ let patchedUser: Partial<UserType> | null
+
+ function setUp({
+ uiConfiguration,
+ browserVimModeEnabled = false,
+ }: {
+ uiConfiguration: UserUIConfiguration | null
+ browserVimModeEnabled?: boolean
+ }): void {
+ window.localStorage.setItem(
+ 'lib.logic.userPreferencesLogic.editorVimModeEnabled',
+ JSON.stringify(browserVimModeEnabled)
+ )
+ initKeaTests()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, ui_configuration: uiConfiguration })
+ logic = sqlEditorVimLogic()
+ logic.mount()
+ }
+
+ beforeEach(() => {
+ patchedUser = null
+ useMocks({
+ patch: {
+ '/api/users/@me/': async ({ request }) => {
+ patchedUser = (await request.json()) as Partial<UserType>
+ return [200, { ...MOCK_DEFAULT_USER, ...patchedUser }]
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ window.localStorage.clear()
+ })
+
+ it.each([
+ ['nothing is saved to the account', null, true],
+ ['the account has a vimrc but no Vim mode setting', { version: 1, sql_editor: { vimrc: 'set rnu' } }, true],
+ ['the account turned Vim mode off', { version: 1, sql_editor: { vim_mode_enabled: false } }, false],
+ ])('uses the browser setting only when %s', (_description, uiConfiguration, expected) => {
+ setUp({ uiConfiguration, browserVimModeEnabled: true })
+
+ expect(logic.values.vimModeEnabled).toBe(expected)
+ })
+
+ it('saves the vimrc without dropping the sidebar settings, then closes the modal', async () => {
+ setUp({ uiConfiguration: { version: 1, sidebar: { items: { data: { visible: false } } } } })
+
+ await expectLogic(logic, () => {
+ logic.actions.openVimrcModal('first-editor')
+ logic.actions.setVimrcDraft('inoremap jj <Esc>')
+ logic.actions.saveVimrc()
+ }).toFinishAllListeners()
+
+ expect(patchedUser?.ui_configuration).toEqual({
+ version: 1,
+ sidebar: { items: { data: { visible: false } } },
+ sql_editor: { vimrc: 'inoremap jj <Esc>' },
+ })
+ expect(logic.values.isVimrcModalOpen).toBe(false)
+ expect(logic.values.vimrcSaving).toBe(false)
+ })
+
+ it('keeps menus and the vimrc modal owned by one editor', () => {
+ setUp({ uiConfiguration: { version: 1 } })
+
+ logic.actions.setEditorSettingsMenuOpen('first-editor', true)
+ expect(logic.values.editorSettingsMenuKey).toBe('first-editor')
+
+ logic.actions.setEditorSettingsMenuOpen('second-editor', true)
+ logic.actions.setEditorSettingsMenuOpen('first-editor', false)
+ expect(logic.values.editorSettingsMenuKey).toBe('second-editor')
+
+ logic.actions.openVimrcModal('second-editor')
+ expect(logic.values.editorSettingsMenuKey).toBeNull()
+ expect(logic.values.vimrcEditorKey).toBe('second-editor')
+
+ logic.actions.openVimrcModal('first-editor')
+ expect(logic.values.vimrcEditorKey).toBe('first-editor')
+
+ logic.actions.closeVimrcModal()
+ expect(logic.values.isVimrcModalOpen).toBe(false)
+ expect(logic.values.vimrcEditorKey).toBeNull()
+ })
+
+ it.each(['vimrc', 'sidebar-after-vim', 'sidebar-before-vim'] as const)(
+ 'preserves both settings when the queued change is %s',
+ async (scenario) => {
+ const patches: Partial<UserType>[] = []
+ let releaseFirstPatch: () => void = () => {}
+ let reportFirstStarted: () => void = () => {}
+ const firstStarted = new Promise<void>((resolve) => {
+ reportFirstStarted = resolve
+ })
+ const firstPatchHeld = new Promise<void>((resolve) => {
+ releaseFirstPatch = resolve
+ })
+ useMocks({
+ patch: {
+ '/api/users/@me/': async ({ request }) => {
+ const body = (await request.json()) as Partial<UserType>
+ patches.push(body)
+ if (patches.length === 1) {
+ reportFirstStarted()
+ await firstPatchHeld
+ }
+ return [200, { ...MOCK_DEFAULT_USER, ...body }]
+ },
+ },
+ })
+ setUp({ uiConfiguration: { version: 1 } })
+
+ if (scenario === 'sidebar-before-vim') {
+ uiCustomizationLogic.actions.setSidebarDensity('compact')
+ } else {
+ logic.actions.setVimModeEnabled(true)
+ }
+ await firstStarted
+
+ if (scenario === 'vimrc') {
+ logic.actions.setVimrcDraft('set relativenumber')
+ logic.actions.saveVimrc()
+ } else if (scenario === 'sidebar-after-vim') {
+ uiCustomizationLogic.actions.setSidebarDensity('compact')
+ } else {
+ logic.actions.setVimModeEnabled(true)
+ }
+ const requestsBeforeRelease = patches.length
+ const optimisticConfiguration = logic.values.uiConfiguration
+ await expectLogic(userLogic, releaseFirstPatch).toFinishAllListeners()
+
+ const expectedConfiguration = {
+ version: 1,
+ ...(scenario === 'vimrc' ? {} : { sidebar: { density: 'compact' } }),
+ sql_editor: {
+ vim_mode_enabled: true,
+ ...(scenario === 'vimrc' ? { vimrc: 'set relativenumber' } : {}),
+ },
+ }
+ expect(requestsBeforeRelease).toBe(1)
+ expect(patches).toHaveLength(2)
+ expect(optimisticConfiguration).toEqual(expectedConfiguration)
+ expect(patches[1].ui_configuration).toEqual(expectedConfiguration)
+ expect(logic.values.uiConfiguration).toEqual(expectedConfiguration)
+ }
+ )
+
+ it.each([200, 400])('keeps queued Vim changes when an unrelated update returns %s', async (status) => {
+ let releaseAccountPatch: () => void = () => {}
+ let reportAccountStarted: () => void = () => {}
+ let releaseVimPatch: () => void = () => {}
+ let reportVimStarted: () => void = () => {}
+ const accountStarted = new Promise<void>((resolve) => {
+ reportAccountStarted = resolve
+ })
+ const accountPatchHeld = new Promise<void>((resolve) => {
+ releaseAccountPatch = resolve
+ })
+ const vimStarted = new Promise<void>((resolve) => {
+ reportVimStarted = resolve
+ })
+ const vimPatchHeld = new Promise<void>((resolve) => {
+ releaseVimPatch = resolve
+ })
+ useMocks({
+ patch: {
+ '/api/users/@me/': async ({ request }) => {
+ const body = (await request.json()) as Partial<UserType>
+ if (!body.ui_configuration) {
+ reportAccountStarted()
+ await accountPatchHeld
+ return status === 400
+ ? [400, { detail: 'Update rejected by server.' }]
+ : [200, { ...MOCK_DEFAULT_USER, ...body }]
+ }
+ if (!body.ui_configuration.sql_editor?.vimrc) {
+ reportVimStarted()
+ await vimPatchHeld
+ }
+ return [200, { ...MOCK_DEFAULT_USER, ...body }]
+ },
+ },
+ })
+ setUp({ uiConfiguration: { version: 1 } })
+ silenceKeaLoadersErrors()
+ try {
+ userLogic.actions.updateUser({ theme_mode: 'dark' })
+ await accountStarted
+ logic.actions.setVimModeEnabled(true)
+ logic.actions.setVimrcDraft('set relativenumber')
+ logic.actions.saveVimrc()
+
+ const accountFinished = expectLogic(userLogic).toDispatchActions([
+ status === 400 ? 'updateUserFailure' : 'updateUserSuccess',
+ ])
+ releaseAccountPatch()
+ await accountFinished
+ await vimStarted
+
+ expect(logic.values.vimModeEnabled).toBe(true)
+ expect(logic.values.vimrc).toBe('set relativenumber')
+ expect(logic.values.vimrcSaving).toBe(true)
+
+ await expectLogic(userLogic, releaseVimPatch).toFinishAllListeners()
+ expect(logic.values.vimrcSaving).toBe(false)
+ expect(logic.values.vimrc).toBe('set relativenumber')
+ } finally {
+ releaseAccountPatch()
+ releaseVimPatch()
+ resumeKeaLoadersErrors()
+ }
+ })
+
+ it('clears the loading state only when its own vimrc save fails', async () => {
+ useMocks({ patch: { '/api/users/@me/': [400, { detail: 'Update rejected by server.' }] } })
+ setUp({ uiConfiguration: { version: 1, sql_editor: { vimrc: 'set pcre' } } })
+ silenceKeaLoadersErrors()
+ try {
+ await expectLogic(userLogic, () => {
+ logic.actions.openVimrcModal('first-editor')
+ logic.actions.setVimrcDraft('set relativenumber')
+ logic.actions.saveVimrc()
+ }).toDispatchActions(['updateUserFailure'])
+
+ expect(logic.values.vimrcSaving).toBe(false)
+ expect(logic.values.isVimrcModalOpen).toBe(true)
+ expect(logic.values.vimrc).toBe('set pcre')
+ } finally {
+ resumeKeaLoadersErrors()
+ }
+ })
+})
diff --git a/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.ts b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.ts
new file mode 100644
index 000000000000..92feeb42461e
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/logics/sqlEditorVimLogic.ts
@@ -0,0 +1,195 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { userPreferencesLogic } from 'lib/logic/userPreferencesLogic'
+import { VIMRC_MAX_LENGTH, VimrcError, parseVimrc } from 'lib/monaco/vimrc'
+
+import { UI_CONFIGURATION_VERSION, uiCustomizationLogic } from '~/layout/uiCustomizationLogic'
+import { SQLEditorConfiguration, UserUIConfiguration } from '~/queries/schema/schema-general'
+
+// The server replaces ui_configuration wholesale, so every other key, such as the sidebar settings, must be carried over.
+export function withSqlEditorPatch(
+ configuration: UserUIConfiguration | null,
+ patch: Partial<SQLEditorConfiguration>
+): UserUIConfiguration {
+ return {
+ version: UI_CONFIGURATION_VERSION,
+ ...configuration,
+ sql_editor: { ...configuration?.sql_editor, ...patch },
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sqlEditorVimLogicValues {
+ uiConfiguration: UserUIConfiguration | null // uiCustomizationLogic
+ editorVimModeEnabled: boolean // userPreferencesLogic
+ editorSettingsMenuKey: string | null
+ isVimrcModalOpen: boolean
+ sqlEditorConfiguration: SQLEditorConfiguration | null
+ vimModeEnabled: boolean
+ vimrc: string
+ vimrcDraft: string
+ vimrcDraftErrors: VimrcError[]
+ vimrcEditorKey: string | null
+ vimrcSaving: boolean
+ vimrcTooLong: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sqlEditorVimLogicActions {
+ updateUiConfiguration: (
+ configuration: UserUIConfiguration,
+ successCallback?: (() => void) | undefined,
+ failureCallback?: (() => void) | undefined
+ ) => {
+ configuration: UserUIConfiguration
+ failureCallback: (() => void) | undefined
+ successCallback: (() => void) | undefined
+ } // uiCustomizationLogic
+ closeVimrcModal: () => {
+ value: true
+ }
+ openVimrcModal: (editorKey: string) => {
+ editorKey: string
+ }
+ saveVimrc: () => {
+ value: true
+ }
+ saveVimrcFailure: () => {
+ value: true
+ }
+ setEditorSettingsMenuOpen: (
+ editorKey: string,
+ open: boolean
+ ) => {
+ editorKey: string
+ open: boolean
+ }
+ setVimModeEnabled: (enabled: boolean) => {
+ enabled: boolean
+ }
+ setVimrcDraft: (vimrcDraft: string) => {
+ vimrcDraft: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sqlEditorVimLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ isVimrcModalOpen: (vimrcEditorKey: string | null) => boolean
+ sqlEditorConfiguration: (uiConfiguration: UserUIConfiguration | null) => SQLEditorConfiguration | null
+ vimModeEnabled: (
+ sqlEditorConfiguration: SQLEditorConfiguration | null,
+ editorVimModeEnabled: boolean
+ ) => boolean
+ vimrc: (sqlEditorConfiguration: SQLEditorConfiguration | null) => string
+ vimrcDraftErrors: (vimrcDraft: string) => VimrcError[]
+ vimrcTooLong: (vimrcDraft: string) => boolean
+ }
+}
+
+export type sqlEditorVimLogicType = MakeLogicType<
+ sqlEditorVimLogicValues,
+ sqlEditorVimLogicActions,
+ Record<string, any>,
+ sqlEditorVimLogicMeta
+>
+
+export const sqlEditorVimLogic = kea<sqlEditorVimLogicType>([
+ path(['products', 'data_warehouse', 'frontend', 'shared', 'logics', 'sqlEditorVimLogic']),
+ connect(() => ({
+ values: [uiCustomizationLogic, ['uiConfiguration'], userPreferencesLogic, ['editorVimModeEnabled']],
+ actions: [uiCustomizationLogic, ['updateUiConfiguration']],
+ })),
+ actions({
+ setVimModeEnabled: (enabled: boolean) => ({ enabled }),
+ setEditorSettingsMenuOpen: (editorKey: string, open: boolean) => ({ editorKey, open }),
+ openVimrcModal: (editorKey: string) => ({ editorKey }),
+ closeVimrcModal: true,
+ setVimrcDraft: (vimrcDraft: string) => ({ vimrcDraft }),
+ saveVimrc: true,
+ saveVimrcFailure: true,
+ }),
+ reducers({
+ // The vimrc modal opens from the editor settings menu, which would otherwise stay open on top of the modal.
+ editorSettingsMenuKey: [
+ null as string | null,
+ {
+ setEditorSettingsMenuOpen: (state, { editorKey, open }) =>
+ open ? editorKey : state === editorKey ? null : state,
+ openVimrcModal: () => null,
+ },
+ ],
+ vimrcEditorKey: [
+ null as string | null,
+ {
+ openVimrcModal: (_, { editorKey }) => editorKey,
+ closeVimrcModal: () => null,
+ },
+ ],
+ vimrcDraft: [
+ '',
+ {
+ setVimrcDraft: (_, { vimrcDraft }) => vimrcDraft,
+ },
+ ],
+ vimrcSaving: [
+ false,
+ {
+ saveVimrc: () => true,
+ closeVimrcModal: () => false,
+ saveVimrcFailure: () => false,
+ },
+ ],
+ }),
+ selectors({
+ isVimrcModalOpen: [
+ (s) => [s.vimrcEditorKey],
+ (vimrcEditorKey: string | null): boolean => vimrcEditorKey !== null,
+ ],
+ sqlEditorConfiguration: [
+ (s) => [s.uiConfiguration],
+ (uiConfiguration: UserUIConfiguration | null): SQLEditorConfiguration | null =>
+ uiConfiguration?.sql_editor ?? null,
+ ],
+ vimModeEnabled: [
+ (s) => [s.sqlEditorConfiguration, s.editorVimModeEnabled],
+ // Users who turned Vim mode on before it was saved to their account keep it until they change it.
+ (sqlEditorConfiguration: SQLEditorConfiguration | null, editorVimModeEnabled: boolean): boolean =>
+ sqlEditorConfiguration?.vim_mode_enabled ?? editorVimModeEnabled,
+ ],
+ vimrc: [
+ (s) => [s.sqlEditorConfiguration],
+ (sqlEditorConfiguration: SQLEditorConfiguration | null): string => sqlEditorConfiguration?.vimrc ?? '',
+ ],
+ vimrcDraftErrors: [(s) => [s.vimrcDraft], (vimrcDraft: string): VimrcError[] => parseVimrc(vimrcDraft).errors],
+ vimrcTooLong: [(s) => [s.vimrcDraft], (vimrcDraft: string): boolean => vimrcDraft.length > VIMRC_MAX_LENGTH],
+ }),
+ listeners(({ actions, values }) => ({
+ setVimModeEnabled: ({ enabled }) => {
+ const configuration = withSqlEditorPatch(values.uiConfiguration, { vim_mode_enabled: enabled })
+ actions.updateUiConfiguration(configuration)
+ posthog.capture('sql editor vim mode toggled', { enabled })
+ },
+ openVimrcModal: () => {
+ actions.setVimrcDraft(values.vimrc)
+ posthog.capture('sql editor vimrc opened', { has_vimrc: values.vimrc.trim().length > 0 })
+ },
+ saveVimrc: () => {
+ const vimrc = values.vimrcDraft
+ const configuration = withSqlEditorPatch(values.uiConfiguration, { vimrc })
+ actions.updateUiConfiguration(
+ configuration,
+ () => {
+ actions.closeVimrcModal()
+ // Counts only. The vimrc text is free text the user typed, so it never leaves the browser in an event.
+ posthog.capture('sql editor vimrc saved', {
+ line_count: vimrc.split('\n').length,
+ command_count: parseVimrc(vimrc).commands.length,
+ })
+ },
+ actions.saveVimrcFailure
+ )
+ },
+ })),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4e781ec5a52d..0d1e9ce79ab2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -73133,7 +73133,7 @@ export namespace Schemas {
passkeys_enabled_for_2fa?: boolean | null;
/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */
hide_mcp_hints?: boolean;
- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
ui_configuration?: unknown;
/** @nullable */
readonly onboarding_skipped_at: string | null;
@@ -82710,7 +82710,7 @@ export namespace Schemas {
passkeys_enabled_for_2fa?: boolean | null;
/** When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions. */
hide_mcp_hints?: boolean;
- /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
+ /** Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true. */
ui_configuration?: unknown;
/** @nullable */
readonly onboarding_skipped_at?: string | null;
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 5da3f85e3f38..1ed8eb8ba231 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -5566,6 +5566,6 @@ export const UsersPartialUpdateBody = () => zod.object({
.unknown()
.optional()
.describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
+ 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true.'
),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json
index a0173aeb77df..322268d8f775 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/user-settings-update.json
@@ -150,7 +150,7 @@
]
},
"ui_configuration": {
- "description": "Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true."
+ "description": "Per-user UI customization, validated against the `UserUIConfiguration` schema. Covers sidebar section and item visibility, and SQL editor settings such as Vim mode and the vimrc. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown. Once `sidebar.starred_products_setup_completed` is true, an update that omits it keeps it true."
},
"uuid": {
"description": "User UUID, or `@me` to target the authenticated user.",