: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
import type { Monaco } from '@monaco-editor/react'
import { MakeLogicType, actions, connect, kea, key, path, props, propsChanged, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
// Note: we can oly import types and not values from monaco-editor, because otherwise some Monaco code breaks
// auto reload in development. Specifically, on this line:
// `export const suggestWidgetStatusbarMenu = new MenuId('suggestWidgetStatusBar')`
// `new MenuId('suggestWidgetStatusBar')` causes the app to crash, because it cannot be called twice in the same
// JS context, and that's exactly what happens on auto-reload when the new script chunks are loaded. Unfortunately
// esbuild doesn't support manual chunks as of 2023, so we can't just put Monaco in its own chunk, which would prevent
// re-importing. As for @monaco-editor/react, it does some lazy loading and doesn't have this problem.
import { MarkerSeverity, editor } from 'monaco-editor'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { performQuery } from '~/queries/query'
import { setLatestVersionsOnQuery } from '~/queries/schema/query-versions'
import {
AnyDataNode,
HogLanguage,
HogQLFilters,
HogQLMetadata,
HogQLMetadataResponse,
HogQLNotice,
NodeKind,
} from '~/queries/schema/schema-general'
import type { FeatureFlagsSet } from '../logic/featureFlagLogic'
import { noticeLink } from './noticeLink'
import { characterOffsetToUtf16 } from './offsets'
import { getContextSourceQuery } from './sourceQueryUtils'
const METADATA_LANGUAGES = [HogLanguage.hog, HogLanguage.hogQL, HogLanguage.hogQLExpr, HogLanguage.hogTemplate]
const VIM_COMMAND_HISTORY_LIMIT = 50
export interface ModelMarker extends editor.IMarkerData {
hogQLFix?: string
hogQLAIFixPrompt?: string
start: number
end: number
}
export interface CodeEditorLogicProps {
key: string
query: string
metadataQuery?: string
/** Character offset of metadataQuery within the full editor text, for correct marker positioning */
metadataQueryOffset?: number
language: string
sourceQuery?: AnyDataNode
metadataFilters?: HogQLFilters
monaco?: Monaco | null
editor?: editor.IStandaloneCodeEditor | null
globals?: Record<string, any>
onError?: (error: string | null) => void
/** Ask for per-filter index eligibility. Costs a second resolution pass server-side, so set it only where the result is rendered. */
indexUsage?: boolean
onMetadata?: (metadata: HogQLMetadataResponse | null) => void
onMetadataLoading?: (loading: boolean) => void
onFixWithAI?: (prompt: string) => void
/** How long to wait after an edit before validating. Set it higher where an error interrupts the user. */
metadataDebounceMs?: number
/** Validate against freshly fetched sources. Set it where the result blocks an action, because it costs a fetch per validation. */
metadataFreshSources?: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codeEditorLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
error: string | null
hasErrors: boolean
metadata: [string, HogQLMetadataResponse] | null
metadataLoading: boolean
modelMarkers: ModelMarker[]
modelMarkersLoading: boolean
vimCommandHistory: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codeEditorLogicActions {
appendVimCommand: (command: string) => {
command: string
}
reloadMetadata: () => {
value: true
}
reloadMetadataFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
reloadMetadataSuccess: (
metadata: [string, HogQLMetadataResponse] | null,
payload?: {
value: true
}
) => {
metadata: [string, HogQLMetadataResponse] | null
payload?: {
value: true
}
}
reloadMetadataSuccessFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
reloadMetadataSuccessSuccess: (
modelMarkers: ModelMarker[],
payload?: {
metadata: [string, HogQLMetadataResponse] | null
payload?: {
value: true
}
}
) => {
modelMarkers: ModelMarker[]
payload?: {
metadata: [string, HogQLMetadataResponse] | null
payload?: {
value: true
}
}
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codeEditorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
hasErrors: (modelMarkers: ModelMarker[]) => boolean
error: (hasErrors: boolean, modelMarkers: ModelMarker[]) => string | null
}
}
export type codeEditorLogicType = MakeLogicType<
codeEditorLogicValues,
codeEditorLogicActions,
CodeEditorLogicProps,
codeEditorLogicMeta
>
const DEFAULT_METADATA_DEBOUNCE_MS = 300
export const codeEditorLogic = kea<codeEditorLogicType>([
path(['lib', 'monaco', 'hogQLMetadataProvider']),
props({} as CodeEditorLogicProps),
key((props) => props.key),
actions({
reloadMetadata: true,
appendVimCommand: (command: string) => ({ command }),
}),
connect(() => ({
values: [featureFlagLogic, ['featureFlags']],
})),
loaders(({ props }) => ({
metadata: [
null as null | [string, HogQLMetadataResponse],
{
reloadMetadata: async (_, breakpoint) => {
const model = props.editor?.getModel()
if (!model || !props.monaco || !METADATA_LANGUAGES.includes(props.language as HogLanguage)) {
props.onMetadata?.(null)
return null
}
await breakpoint(props.metadataDebounceMs ?? DEFAULT_METADATA_DEBOUNCE_MS)
const query = props.metadataQuery ?? props.query
if (query === '') {
props.onMetadata?.(null)
return null
}
const variables =
props.sourceQuery?.kind === NodeKind.HogQLQuery
? (props.sourceQuery.variables ?? undefined)
: undefined
const connectionId =
props.sourceQuery?.kind === NodeKind.HogQLQuery
? (props.sourceQuery.connectionId ?? undefined)
: undefined
const sourceQuery = getContextSourceQuery(props.sourceQuery, query)
const response = await performQuery<HogQLMetadata>(
setLatestVersionsOnQuery(
{
kind: NodeKind.HogQLMetadata,
language: props.language as HogLanguage,
query: query,
filters: props.metadataFilters,
globals: props.globals,
sourceQuery,
variables,
connectionId,
indexUsage: props.indexUsage,
freshSources: props.metadataFreshSources,
},
{ recursion: false }
)
)
breakpoint()
props.onMetadata?.(response)
return [query, response]
},
},
],
modelMarkers: [
[] as ModelMarker[],
{
reloadMetadataSuccess: ({ metadata }) => {
const model = props.editor?.getModel()
if (!model || !metadata) {
return []
}
const markers: ModelMarker[] = []
const [query, metadataResponse] = metadata
const markerOffset = props.metadataQueryOffset ?? 0
function noticeToMarker(error: HogQLNotice, severity: MarkerSeverity): ModelMarker {
// Notice offsets count characters, so they need converting to the UTF-16
// units Monaco addresses before they can locate anything in the model.
const start = model!.getPositionAt(
characterOffsetToUtf16(query, error.start ?? 0) + markerOffset
)
const end = model!.getPositionAt(
characterOffsetToUtf16(query, error.end ?? query.length) + markerOffset
)
return {
start: error.start ?? 0,
startLineNumber: start.lineNumber,
startColumn: start.column,
end: error.end ?? query.length,
endLineNumber: end.lineNumber,
endColumn: end.column,
message: error.message ?? 'Unknown error',
severity: severity,
hogQLFix: error.fix?.startsWith('ai_prompt:') ? undefined : error.fix,
hogQLAIFixPrompt: error.fix?.startsWith('ai_prompt:')
? error.fix.slice('ai_prompt:'.length)
: undefined,
code: noticeLink(error.url, props.monaco),
}
}
for (const notice of metadataResponse?.errors ?? []) {
markers.push(noticeToMarker(notice, 8 /* MarkerSeverity.Error */))
}
for (const notice of metadataResponse?.warnings ?? []) {
markers.push(noticeToMarker(notice, 4 /* MarkerSeverity.Warning */))
}
for (const notice of metadataResponse?.notices ?? []) {
markers.push(noticeToMarker(notice, 1 /* MarkerSeverity.Hint */))
}
props.monaco?.editor.setModelMarkers(model, 'hogql', markers)
return markers
},
},
],
})),
reducers({
vimCommandHistory: [
[] as string[],
{ persist: true, storageKey: 'posthog-vim-command-history' },
{
appendVimCommand: (state, { command }) => {
if (!command) {
return state
}
const deduped = state.filter((c) => c !== command)
return [...deduped, command].slice(-VIM_COMMAND_HISTORY_LIMIT)
},
},
],
}),
selectors({
hasErrors: [
(s) => [s.modelMarkers],
(modelMarkers: ModelMarker[]) =>
!!(modelMarkers ?? []).filter((e) => e.severity === 8 /* MarkerSeverity.Error */).length,
],
error: [
(s) => [s.hasErrors, s.modelMarkers],
(hasErrors: boolean, modelMarkers: ModelMarker[]) => {
const firstError = modelMarkers.find((e) => e.severity === 8 /* MarkerSeverity.Error */)
return hasErrors && firstError
? `Error on line ${firstError.startLineNumber}, column ${firstError.startColumn}`
: null
},
],
}),
subscriptions(({ props }) => ({
error: (error) => {
props.onError?.(error)
},
metadataLoading: (loading) => {
props.onMetadataLoading?.(loading)
},
})),
propsChanged(({ actions, props }, oldProps) => {
const previousConnectionId =
oldProps.sourceQuery?.kind === NodeKind.HogQLQuery ? (oldProps.sourceQuery.connectionId ?? null) : null
const nextConnectionId =
props.sourceQuery?.kind === NodeKind.HogQLQuery ? (props.sourceQuery.connectionId ?? null) : null
if (
props.query !== oldProps.query ||
props.metadataQuery !== oldProps.metadataQuery ||
props.metadataQueryOffset !== oldProps.metadataQueryOffset ||
props.language !== oldProps.language ||
props.editor !== oldProps.editor ||
nextConnectionId !== previousConnectionId
) {
actions.reloadMetadata()
}
}),
])