:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(frontend): load the command palette on its first open (#126885)
Paul D'Ambra1815e776826d
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex 1c6e1803de4c..dff9cbe44f68 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -104,8 +104,8 @@ const ROOTS = [{root: AUTHENTICATED_SHELL,label: 'authenticated shell (every logged-in page)',- // 2026-11-01: 5.21 MiB eager output, stable CSS included. ~0.3% headroom.- budgetBytes: 5_480_000,+ // 2026-11-01: 4.14 MiB eager output, stable CSS included. ~0.3% headroom.+ budgetBytes: 4_360_000,forbidden: ['node_modules/monaco-editor/','products/product_analytics/frontend/insights/activityDescriptions',@@ -142,6 +142,9 @@ const ROOTS = ['node_modules/re2js/',// react-markdown and its remark plugins load on first render. Shell code uses LazyLemonMarkdown.'node_modules/react-markdown/',+ // The command palette loads on its first open, and its flagged search pulls in quill.+ 'src/lib/components/Command/Command.tsx',+ 'packages/quill/packages/',// The zod-en-locale-only plugin in common/esbuilder/utils.mjs keeps every locale except// `en` out of the build. A hit on another locale means zod moved its locales barrel and// the plugin no longer matches it.@@ -185,8 +188,8 @@ const ROOTS = ['src/scenes/project-homepage/today/TodayHome.tsx',],label: 'today home path',- // 2026-11-01: 5.65 MiB, stable CSS included. ~0.3% headroom.- budgetBytes: 5_945_000,+ // 2026-11-01: 5.05 MiB, stable CSS included. ~0.3% headroom.+ budgetBytes: 5_310_000,forbidden: ['src/scenes/project-homepage/ai-first/AiFirstHomepage.tsx','src/scenes/project-homepage/today/TodayReportPage.tsx',@@ -203,8 +206,8 @@ const ROOTS = ['src/scenes/project-homepage/ai-first/AiFirstHomepage.tsx',],label: 'AI-first home path',- // 2026-10-30: 7.46 MiB, stable CSS included. ~1% headroom.- budgetBytes: 7_900_000,+ // 2026-11-01: 6.44 MiB, stable CSS included. ~1% headroom.+ budgetBytes: 6_820_000,forbidden: ['products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx','products/posthog_ai/frontend/components/tool/widgets/RecordingsWidget.tsx',diff --git a/frontend/src/lib/components/Command/Command.tsx b/frontend/src/lib/components/Command/Command.tsxindex 74e26aadc584..516681db1361 100644--- a/frontend/src/lib/components/Command/Command.tsx+++ b/frontend/src/lib/components/Command/Command.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useCallback } from 'react'+import { Suspense, useCallback, useEffect } from 'react'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'@@ -7,23 +7,34 @@ import { DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/DialogPrimitive/Diimport { cn } from 'lib/utils/css-classes'import { navigateToHref } from 'lib/utils/navigateToHref'import { newInternalTab } from 'lib/utils/newInternalTab'+import { lazyWithRetry } from 'lib/utils/retryImport'import { todayShellLogic } from '~/layout/today/todayShellLogic'-import { CommandKSearch } from '../CommandKSearch/CommandKSearch'import { Search } from '../Search/Search'import { SearchItem } from '../Search/searchItems'import { commandLogic } from './commandLogic'+// Only flagged users render it, so the palette chunk skips quill for everyone else.+const CommandKSearch = lazyWithRetry(() =>+ import('../CommandKSearch/CommandKSearch').then(({ CommandKSearch }) => ({ default: CommandKSearch }))+)+const TODAY_PHONE_SHEET ='max-md:top-0 max-md:h-dvh max-md:w-screen max-md:max-w-none max-md:max-h-none max-md:supports-[max-height:1dvh]:max-h-none max-md:rounded-none max-md:border-0'export function Command(): JSX.Element {- const { isCommandOpen } = useValues(commandLogic)+ const { isCommandOpen, pendingText } = useValues(commandLogic)const { todayRailEnabled } = useValues(todayShellLogic)- const { closeCommand } = useActions(commandLogic)+ const { closeCommand, commandInputReady } = useActions(commandLogic)const newCommandKSearch = useFeatureFlag('NEW_COMMAND_K_SEARCH')+ useEffect(() => {+ if (!newCommandKSearch) {+ commandInputReady()+ }+ }, [newCommandKSearch, commandInputReady])+const handleItemSelect = useCallback((item: SearchItem, openInNewTab?: boolean) => {closeCommand()@@ -55,7 +66,11 @@ export function Command(): JSX.Element {><DialogPrimitiveTitle>Command</DialogPrimitiveTitle>{/* Mounted only while open, which scopes the search's caches and requests to one use of the palette. */}- {isCommandOpen && <CommandKSearch />}+ {isCommandOpen && (+ <Suspense fallback={null}>+ <CommandKSearch />+ </Suspense>+ )}</DialogPrimitive>)}@@ -70,6 +85,7 @@ export function Command(): JSX.Element {<Search.RootlogicKey="command"isActive={isCommandOpen}+ defaultSearchValue={pendingText}onItemSelect={handleItemSelect}onAskAiClick={handleAskAiClick}showAskAiLinkdiff --git a/frontend/src/lib/components/Command/commandLogic.test.ts b/frontend/src/lib/components/Command/commandLogic.test.tsnew file mode 100644index 000000000000..d2f5fd0a45f0--- /dev/null+++ b/frontend/src/lib/components/Command/commandLogic.test.ts@@ -0,0 +1,50 @@+import { initKeaTests } from '~/test/init'++import { commandLogic } from './commandLogic'++describe('commandLogic', () => {+ let logic: ReturnType<typeof commandLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = commandLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('keeps the palette opening when the shortcut is pressed again before the input is ready', () => {+ logic.actions.toggleCommand('keyboard-shortcut')+ logic.actions.toggleCommand('keyboard-shortcut')+ expect(logic.values.isCommandOpen).toBe(true)++ logic.actions.commandInputReady()+ logic.actions.toggleCommand('keyboard-shortcut')+ expect(logic.values.isCommandOpen).toBe(false)+ })++ it('holds keys typed before the input is ready until the palette closes', () => {+ const pageInput = document.createElement('input')+ document.body.append(pageInput)+ pageInput.focus()+ logic.actions.toggleCommand('keyboard-shortcut')++ for (const key of ['d', 'a', 's', 'x', 'Backspace', 'h']) {+ pageInput.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))+ }+ const paste = new Event('paste', { bubbles: true, cancelable: true }) as ClipboardEvent+ Object.defineProperty(paste, 'clipboardData', { value: { getData: () => 'board' } })+ pageInput.dispatchEvent(paste)+ expect(paste.defaultPrevented).toBe(true)++ logic.actions.commandInputReady()+ pageInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'z', bubbles: true, cancelable: true }))+ expect(logic.values.pendingText).toBe('dashboard')++ logic.actions.closeCommand()+ expect(logic.values.pendingText).toBe('')+ pageInput.remove()+ })+})diff --git a/frontend/src/lib/components/Command/commandLogic.tsx b/frontend/src/lib/components/Command/commandLogic.tsxindex 6830eb15bd88..94d0a156a78c 100644--- a/frontend/src/lib/components/Command/commandLogic.tsx+++ b/frontend/src/lib/components/Command/commandLogic.tsx@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, beforeUnmount, kea, listeners, path, reducers } from 'kea'import posthog from 'lib/posthog-typed'@@ -7,15 +7,27 @@ export type CommandOpenSource = 'keyboard-shortcut' | 'nav-search-button' | 'nav// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commandLogicValues {+ hasOpenedCommand: boolean+ isCommandInputReady: booleanisCommandOpen: booleanopenSource: CommandOpenSource | null+ pendingText: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commandLogicActions {+ bufferKey: (key: string) => {+ key: string+ }+ bufferPaste: (text: string) => {+ text: string+ }closeCommand: () => {value: true}+ commandInputReady: () => {+ value: true+ }openCommand: (source: CommandOpenSource) => {source: CommandOpenSource}@@ -26,12 +38,19 @@ export interface commandLogicActions {export type commandLogicType = MakeLogicType<commandLogicValues, commandLogicActions>+function isTypedCharacter(event: KeyboardEvent): boolean {+ return event.key.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey && !event.isComposing+}+export const commandLogic = kea<commandLogicType>([path(['lib', 'components', 'Command', 'commandLogic']),actions({openCommand: (source: CommandOpenSource) => ({ source }),closeCommand: true,toggleCommand: (source: CommandOpenSource) => ({ source }),+ commandInputReady: true,+ bufferKey: (key: string) => ({ key }),+ bufferPaste: (text: string) => ({ text }),}),reducers({isCommandOpen: [@@ -39,25 +58,83 @@ export const commandLogic = kea<commandLogicType>([{openCommand: () => true,closeCommand: () => false,- toggleCommand: (state) => !state,+ },+ ],+ // Stays true after the first open, so the shell loads the palette once and keeps it mounted.+ hasOpenedCommand: [+ false,+ {+ openCommand: () => true,+ },+ ],+ isCommandInputReady: [+ false,+ {+ commandInputReady: () => true,+ },+ ],+ // Keys typed while the palette chunk loads, so the search input starts with them.+ pendingText: [+ '',+ {+ bufferKey: (state, { key }) => (key === 'Backspace' ? state.slice(0, -1) : state + key),+ bufferPaste: (state, { text }) => state + text,+ closeCommand: () => '',},],openSource: [null as CommandOpenSource | null,{openCommand: (_, { source }) => source,- toggleCommand: (_, { source }) => source,},],}),- listeners(({ values }) => ({- openCommand: ({ source }) => {- posthog.capture('command menu opened', { source })- },- toggleCommand: ({ source }) => {- if (values.isCommandOpen) {- posthog.capture('command menu opened', { source })+ listeners(({ actions, values, cache }) => {+ const stopBuffering = (): void => {+ if (cache.bufferKeys) {+ window.removeEventListener('keydown', cache.bufferKeys, true)+ window.removeEventListener('paste', cache.bufferPaste, true)+ cache.bufferKeys = null}- },- })),+ }+ return {+ toggleCommand: ({ source }) => {+ if (!values.isCommandOpen) {+ actions.openCommand(source)+ } else if (values.isCommandInputReady) {+ actions.closeCommand()+ }+ // A second press while the palette loads keeps it opening, because the user has not seen it yet.+ },+ openCommand: ({ source }) => {+ posthog.capture('command menu opened', { source })+ if (!values.isCommandInputReady && !cache.bufferKeys) {+ cache.bufferKeys = (event: KeyboardEvent): void => {+ if (event.key === 'Escape') {+ actions.closeCommand()+ } else if (event.key === 'Backspace' || isTypedCharacter(event)) {+ event.preventDefault()+ event.stopPropagation()+ actions.bufferKey(event.key)+ }+ }+ cache.bufferPaste = (event: ClipboardEvent): void => {+ event.preventDefault()+ event.stopPropagation()+ actions.bufferPaste(event.clipboardData?.getData('text/plain') ?? '')+ }+ window.addEventListener('keydown', cache.bufferKeys, true)+ window.addEventListener('paste', cache.bufferPaste, true)+ }+ },+ commandInputReady: stopBuffering,+ closeCommand: stopBuffering,+ }+ }),+ beforeUnmount(({ cache }) => {+ if (cache.bufferKeys) {+ window.removeEventListener('keydown', cache.bufferKeys, true)+ window.removeEventListener('paste', cache.bufferPaste, true)+ }+ }),])diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsxindex 713b8d3c849c..ea6355a1a528 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx@@ -91,6 +91,7 @@ export type CommitVia = 'tab' | 'enter' | 'space' | 'paste' | 'click' | 'typed'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commandKSearchLogicValues {openSource: CommandOpenSource | null // commandLogic+ pendingText: string // commandLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModelgroupTypes: Map<GroupTypeIndex, GroupType> // groupsModel@@ -151,6 +152,9 @@ export interface commandKSearchLogicActions {closeCommand: () => {value: true} // commandLogic+ commandInputReady: () => {+ value: true+ } // commandLogicensureAllMembersLoaded: () => {value: true} // membersLogic@@ -381,7 +385,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([connect(() => ({values: [commandLogic,- ['openSource'],+ ['openSource', 'pendingText'],searchListsLogic({ commandPalette: true }),['starredItems',@@ -412,7 +416,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([],actions: [commandLogic,- ['closeCommand'],+ ['closeCommand', 'commandInputReady'],membersLogic,['ensureAllMembersLoaded'],teamLogic,@@ -1055,8 +1059,12 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([},}}),- afterMount(({ values }) => {+ afterMount(({ actions, values }) => {posthog.capture('command k search opened', { source: values.openSource })+ if (values.pendingText) {+ actions.inputChanged(values.pendingText, values.pendingText.length, false)+ }+ actions.commandInputReady()}),beforeUnmount(({ values }) => {if (!values.resultOpened) {diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex 349544232c96..5cb8d65aa6cb 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -1,8 +1,8 @@import { useMountedLogic, useValues } from 'kea'-import { Suspense } from 'react'+import { Suspense, useEffect } from 'react'import { Slide, ToastContainer } from 'react-toastify'-import { Command } from 'lib/components/Command/Command'+import { commandLogic } from 'lib/components/Command/commandLogic'import { productSetupPreloadLogic } from 'lib/components/ProductEmptyState/productSetupPreloadLogic'import { globalSetupLogic, useSetupHighlight } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'@@ -11,6 +11,7 @@ import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { billingLogic } from 'lib/logic/billing/billingLogic'import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { runWhenIdle } from 'lib/utils/async'import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'import { lazyWithRetry } from 'lib/utils/retryImport'import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'@@ -33,6 +34,16 @@ import { sceneLogic } from './sceneLogic'const TerminalDock = lazyWithRetry(() =>import('./terminal/TerminalDock').then(({ TerminalDock }) => ({ default: TerminalDock })))+const importCommand = (): Promise<typeof import('lib/components/Command/Command')> =>+ import('lib/components/Command/Command')+const Command = lazyWithRetry(() => importCommand().then(({ Command }) => ({ default: Command })))+// Off the eager path but fetched on idle, so the first open skips the network. The lazy component retries a failed import.+function preloadCommand(withCommandKSearch: boolean): void {+ void importCommand().catch(() => {})+ if (withCommandKSearch) {+ void import('lib/components/CommandKSearch/CommandKSearch').catch(() => {})+ }+}// Staff-only, so everyone else skips the chunk and the toolbar selector code it pulls in.const InternalFeedbackWidget = lazyWithRetry(() =>import('~/layout/InternalFeedback/InternalFeedbackWidget').then(({ InternalFeedbackWidget }) => ({@@ -67,6 +78,12 @@ export default function AuthenticatedShell({ children }: { children: React.Reactconst { featureFlags } = useValues(featureFlagLogic)const { isDarkModeOn } = useValues(themeLogic)const { user } = useValues(userLogic)+ const { hasOpenedCommand } = useValues(commandLogic)+ const newCommandKSearch = !!featureFlags[FEATURE_FLAGS.NEW_COMMAND_K_SEARCH]+ useEffect(+ () => (isEmbeddedPageFrame() ? undefined : runWhenIdle(() => preloadCommand(newCommandKSearch))),+ [newCommandKSearch]+ )const showInternalFeedback =!!featureFlags[FEATURE_FLAGS.INTERNAL_FEEDBACK_WIDGET] && !!user?.email?.toLowerCase().endsWith('@posthog.com')const runSyncEnabled = featureFlags[FEATURE_FLAGS.WIZARD_RUN_SYNC] === 'wizard-run'@@ -106,7 +123,15 @@ export default function AuthenticatedShell({ children }: { children: React.React</Suspense></ErrorBoundary>)}- <Command />+ {hasOpenedCommand && (+ <ErrorBoundary>+ <ChunkLoadErrorBoundary>+ <Suspense fallback={null}>+ <Command />+ </Suspense>+ </ChunkLoadErrorBoundary>+ </ErrorBoundary>+ )}<ImpersonationNotice /><ErrorBoundary><ChunkLoadErrorBoundary>