Skip to content

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

fix(workflows): restore template autocomplete while editing (#104165)

Michael Reichenbach970efd28a163
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
index 4e713d82f037..9cfcbc1ac905 100644
--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
@@ -45,7 +45,8 @@ import { EmailTemplater } from '../../../scenes/hog-functions/email-templater/Em
import { EmailFieldErrors } from '../../../scenes/hog-functions/email-templater/types'
import { CUSTOM_INPUT_RENDERERS } from './customInputRenderers'
import { cyclotronJobInputLogic, formatJsonValue } from './cyclotronJobInputLogic'
-import { CyclotronJobTemplateSuggestionsButton } from './CyclotronJobTemplateSuggestions'
+import { CyclotronJobTemplateSuggestionsButton, useTemplateEditorCursor } from './CyclotronJobTemplateSuggestions'
+import { insertTemplateReference, templateReferenceForOption } from './cyclotronJobTemplateSuggestionsLogic'
import { CyclotronJobInputIntegration } from './integrations/CyclotronJobInputIntegration'
import { CyclotronJobInputIntegrationField } from './integrations/CyclotronJobInputIntegrationField'
import { CyclotronJobInputIntegrationMulti } from './integrations/CyclotronJobInputIntegrationMulti'
@@ -260,7 +261,10 @@ function JsonConfigField(props: {
props.onChange?.({ ...props.input, templating })
}
onOptionSelect={(option) => {
- void copyToClipboard(`{${option.example}}`, 'template code')
+ void copyToClipboard(
+ templateReferenceForOption(option, templatingKind),
+ 'template code'
+ )
}}
/>
</span>
@@ -325,6 +329,7 @@ function CyclotronJobTemplateInput(props: {
}): JSX.Element {
const templating = props.input.templating ?? 'hog'
const displayValue = coerceTemplateValueForDisplay(props.input.value, props.templating ? templating : false)
+ const { onEditorMount, cursorOffset } = useTemplateEditorCursor()
if (!props.templating) {
return (
@@ -344,8 +349,9 @@ function CyclotronJobTemplateInput(props: {
minHeight="37" // Match other inputs
value={displayValue}
onChange={(val) => props.onChange?.({ ...props.input, value: val ?? '' })}
- language={props.input.templating === 'hog' ? 'hogTemplate' : 'liquid'}
+ language={templating === 'hog' ? 'hogTemplate' : 'liquid'}
globals={props.sampleGlobalsWithInputs ?? undefined}
+ onMount={onEditorMount}
/>
<span className="absolute top-0 right-0 z-10 p-px opacity-0 transition-opacity group-hover:opacity-100">
<CyclotronJobTemplateSuggestionsButton
@@ -353,7 +359,14 @@ function CyclotronJobTemplateInput(props: {
value={displayValue}
setTemplatingEngine={(templating) => props.onChange?.({ ...props.input, templating })}
onOptionSelect={(option) => {
- props.onChange?.({ ...props.input, value: `${displayValue} {${option.example}}` })
+ props.onChange?.({
+ ...props.input,
+ value: insertTemplateReference(
+ displayValue,
+ templateReferenceForOption(option, templating),
+ cursorOffset()
+ ),
+ })
}}
/>
</span>
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobTemplateSuggestions.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobTemplateSuggestions.tsx
index ca2c7465c3ac..3c0d29a2aa5a 100644
--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobTemplateSuggestions.tsx
+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobTemplateSuggestions.tsx
@@ -1,5 +1,6 @@
import { useActions, useValues } from 'kea'
-import { useState } from 'react'
+import type { IDisposable, editor } from 'monaco-editor'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { IconCode, IconExternal } from '@posthog/icons'
import { LemonButton, LemonDropdown, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'
@@ -9,6 +10,50 @@ import {
cyclotronJobTemplateSuggestionsLogic,
} from './cyclotronJobTemplateSuggestionsLogic'
+export type TemplateEditorCursor = {
+ /** Hand to the Monaco editor's `onMount` */
+ onEditorMount: (editor: editor.IStandaloneCodeEditor) => void
+ /** Offset the caret last sat at, or null while it has never been placed in this editor */
+ cursorOffset: () => number | null
+}
+
+/**
+ * Records where the caret sits in a Monaco editor so a picked suggestion lands there. Opening the
+ * suggestions dropdown moves focus out of the editor, so the position has to be tracked as it
+ * changes rather than read at the moment an option is picked.
+ */
+export function useTemplateEditorCursor(): TemplateEditorCursor {
+ const offsetRef = useRef<number | null>(null)
+ const listenerRef = useRef<IDisposable | null>(null)
+
+ const onEditorMount = useCallback((editorInstance: editor.IStandaloneCodeEditor): void => {
+ // A remount hands us a fresh editor, so drop the old listener before it can report a
+ // position from an editor the user is no longer typing in
+ listenerRef.current?.dispose()
+ offsetRef.current = null
+
+ const recordPosition = (): void => {
+ const position = editorInstance.getPosition()
+ offsetRef.current = position ? (editorInstance.getModel()?.getOffsetAt(position) ?? null) : null
+ }
+ const cursorListener = editorInstance.onDidChangeCursorPosition(recordPosition)
+ const focusListener = editorInstance.onDidFocusEditorText(recordPosition)
+ listenerRef.current = {
+ dispose: () => {
+ cursorListener.dispose()
+ focusListener.dispose()
+ },
+ }
+ if (editorInstance.hasTextFocus()) {
+ recordPosition()
+ }
+ }, [])
+
+ useEffect(() => () => listenerRef.current?.dispose(), [])
+
+ return { onEditorMount, cursorOffset: () => offsetRef.current }
+}
+
export type CyclotronJobTemplateSuggestionsProps = {
templating: 'hog' | 'liquid'
setTemplatingEngine?: (templating: 'hog' | 'liquid') => void
diff --git a/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.test.ts b/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.test.ts
new file mode 100644
index 000000000000..ffd5c7a76031
--- /dev/null
+++ b/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.test.ts
@@ -0,0 +1,102 @@
+import { act, renderHook } from '@testing-library/react'
+import type { editor } from 'monaco-editor'
+
+import { useTemplateEditorCursor } from './CyclotronJobTemplateSuggestions'
+import {
+ CyclotronJobTemplateOption,
+ insertTemplateReference,
+ templateReferenceForOption,
+} from './cyclotronJobTemplateSuggestionsLogic'
+
+const optionFor = (example: string): CyclotronJobTemplateOption => ({
+ key: 'example',
+ description: 'An example',
+ example,
+})
+
+describe('cyclotron job template suggestions', () => {
+ describe('templateReferenceForOption', () => {
+ it.each([
+ ['a hog expression is wrapped in braces', 'hog', `$1 ?? 'Default value'`, `{$1 ?? 'Default value'}`],
+ ['a hog function call is wrapped in braces', 'hog', 'concat($1, $2)', '{concat($1, $2)}'],
+ [
+ 'a liquid output tag keeps its own braces',
+ 'liquid',
+ '{{ person.properties.email }}',
+ '{{ person.properties.email }}',
+ ],
+ [
+ 'a liquid block tag keeps its own braces',
+ 'liquid',
+ '{% if condition %} Yes {% else %} No {% endif %}',
+ '{% if condition %} Yes {% else %} No {% endif %}',
+ ],
+ [
+ 'a bare liquid expression is wrapped in output braces',
+ 'liquid',
+ 'person.properties.email',
+ '{{ person.properties.email }}',
+ ],
+ ] as [string, 'hog' | 'liquid', string, string][])('%s', (_name, templating, example, expected) => {
+ expect(templateReferenceForOption(optionFor(example), templating)).toBe(expected)
+ })
+ })
+
+ it.each([false, true])('inserts at the initial cursor when the editor starts focused: %s', (startsFocused) => {
+ let focusEditor = (): void => {}
+ let moveCursor = (): void => {}
+ let column = 1
+ const disposeCursor = jest.fn()
+ const disposeFocus = jest.fn()
+ const editorInstance = {
+ getPosition: () => ({ lineNumber: 1, column }),
+ getModel: () => ({ getOffsetAt: (position: { column: number }) => position.column - 1 }),
+ hasTextFocus: () => startsFocused,
+ onDidChangeCursorPosition: (callback: () => void) => {
+ moveCursor = callback
+ return { dispose: disposeCursor }
+ },
+ onDidFocusEditorText: (callback: () => void) => {
+ focusEditor = callback
+ return { dispose: disposeFocus }
+ },
+ } as unknown as editor.IStandaloneCodeEditor
+ const { result, unmount } = renderHook(() => useTemplateEditorCursor())
+ act(() => result.current.onEditorMount(editorInstance))
+ if (!startsFocused) {
+ expect(insertTemplateReference('Hi there', '{person.name}', result.current.cursorOffset())).toBe(
+ 'Hi there{person.name}'
+ )
+ act(() => focusEditor())
+ }
+ expect(insertTemplateReference('Hi there', '{person.name}', result.current.cursorOffset())).toBe(
+ '{person.name}Hi there'
+ )
+ column = 4
+ act(() => moveCursor())
+ expect(insertTemplateReference('Hi there', '{person.name}', result.current.cursorOffset())).toBe(
+ 'Hi {person.name}there'
+ )
+ unmount()
+ expect(disposeCursor).toHaveBeenCalledTimes(1)
+ expect(disposeFocus).toHaveBeenCalledTimes(1)
+ })
+
+ describe('insertTemplateReference', () => {
+ it.each([
+ ['at a cursor in the middle of the text', 'Hi , welcome', 3, 'Hi {person.name}, welcome'],
+ ['at a cursor at the start of the text', 'Hi there', 0, '{person.name}Hi there'],
+ ['at a cursor at the end of the text', 'Hi there', 8, 'Hi there{person.name}'],
+ ['into empty text', '', 0, '{person.name}'],
+ ] as [string, string, number, string][])('inserts %s', (_name, value, cursorOffset, expected) => {
+ expect(insertTemplateReference(value, '{person.name}', cursorOffset)).toBe(expected)
+ })
+
+ it.each([
+ ['the cursor position is unknown', null],
+ ['the tracked cursor is past the end of the current text', 99],
+ ] as [string, number | null][])('appends when %s', (_name, cursorOffset) => {
+ expect(insertTemplateReference('Hi there', '{person.name}', cursorOffset)).toBe('Hi there{person.name}')
+ })
+ })
+})
diff --git a/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.tsx b/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.tsx
index 98ff8d382f33..cc5e3aadc2b4 100644
--- a/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.tsx
+++ b/frontend/src/lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic.tsx
@@ -75,6 +75,32 @@ const LIQUID_USAGE_EXAMPLES: CyclotronJobTemplateOption[] = [
},
]
+/**
+ * The text a picked suggestion inserts into a field. Hog examples are bare expressions that need
+ * delimiters, while liquid examples carry their own, so wrapping every example would produce
+ * `{{{ ... }}}`. Every call site goes through here so the two engines can't drift apart again.
+ */
+export function templateReferenceForOption(option: CyclotronJobTemplateOption, templating: 'hog' | 'liquid'): string {
+ const example = option.example.trim()
+ const alreadyDelimited = example.startsWith('{') && example.endsWith('}')
+ if (alreadyDelimited) {
+ return example
+ }
+ return templating === 'liquid' ? `{{ ${example} }}` : `{${example}}`
+}
+
+/**
+ * Puts `reference` where the caret last sat. Both a null `cursorOffset` (the caret was never placed
+ * in this field) and an offset past the end (the value changed underneath it) fall back to
+ * appending.
+ */
+export function insertTemplateReference(value: string, reference: string, cursorOffset: number | null): string {
+ if (cursorOffset === null || cursorOffset < 0 || cursorOffset > value.length) {
+ return `${value}${reference}`
+ }
+ return `${value.slice(0, cursorOffset)}${reference}${value.slice(cursorOffset)}`
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cyclotronJobTemplateSuggestionsLogicValues {
allOptions: CyclotronJobTemplateOption[]
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsx
index 342dfa903937..c4df452cad95 100644
--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx
+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx
@@ -6,14 +6,13 @@ import * as monacoModule from 'monaco-editor'
import { IDisposable, editor, editor as importedEditor } from 'monaco-editor'
import { useEffect, useMemo, useRef, useState } from 'react'
-import 'lib/monaco/monacoEnvironment'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { themeLogic } from 'lib/logic/themeLogic'
import { enableClipboardPaste } from 'lib/monaco/clipboardPaste'
-import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
import type { codeEditorLogicType } from 'lib/monaco/codeEditorLogic'
+import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
import { findNextFocusableElement, findPreviousFocusableElement } from 'lib/monaco/domUtils'
import { trackFindWidgetVisibility } from 'lib/monaco/findWidgetBodyClass'
import { initCodeownersLanguage } from 'lib/monaco/languages/codeowners'
@@ -23,7 +22,9 @@ import { initHogQLLanguage } from 'lib/monaco/languages/hogQL'
import { initHogTemplateLanguage } from 'lib/monaco/languages/hogTemplate'
import { initLiquidLanguage } from 'lib/monaco/languages/liquid'
import { clearLogicReference, initModel } from 'lib/monaco/modelLogicReference'
+import 'lib/monaco/monacoEnvironment'
import { sharedMonacoOverflowRoot } from 'lib/monaco/sharedMonacoOverflowRoot'
+import { retriggerSuggestionsAfterDeletion } from 'lib/monaco/suggestionRetrigger'
import { inStorybookTestRunner } from 'lib/utils/dom'
import { AnyDataNode, HogLanguage, HogQLMetadataResponse, NodeKind } from '~/queries/schema/schema-general'
@@ -486,6 +487,8 @@ export function CodeEditor({
remeasureFontsWhenReady(monaco)
monacoDisposables.current.push(trackFindWidgetVisibility(editor))
+ monacoDisposables.current.push(retriggerSuggestionsAfterDeletion(editor))
+
// Override Monaco's suggestion widget styling to prevent truncation
const styleId = 'monaco-suggestion-widget-fix'
const overrideSuggestionWidgetStyling = (): void => {
diff --git a/frontend/src/lib/monaco/suggestionRetrigger.test.ts b/frontend/src/lib/monaco/suggestionRetrigger.test.ts
new file mode 100644
index 000000000000..2ab835d408df
--- /dev/null
+++ b/frontend/src/lib/monaco/suggestionRetrigger.test.ts
@@ -0,0 +1,149 @@
+import {
+ SuggestionRetriggerEditor,
+ TemplateLanguage,
+ insideTemplateExpression,
+ retriggerSuggestionsAfterDeletion,
+} from 'lib/monaco/suggestionRetrigger'
+
+import { HogLanguage } from '~/queries/schema/schema-general'
+
+type ContentChangeListener = Parameters<SuggestionRetriggerEditor['onDidChangeModelContent']>[0]
+
+/** The slice of IStandaloneCodeEditor the retrigger reads, driven by hand in the tests. */
+function fakeEditor(
+ textBeforeCursor: string,
+ initialLanguage: string = HogLanguage.hogTemplate
+): {
+ editor: SuggestionRetriggerEditor
+ trigger: jest.Mock
+ delete_: () => void
+ insert: () => void
+ setLanguage: (language: string) => void
+} {
+ let listener: ContentChangeListener | null = null
+ let language = initialLanguage
+ const trigger = jest.fn()
+ const editor = {
+ onDidChangeModelContent: (callback: ContentChangeListener) => {
+ listener = callback
+ return { dispose: () => (listener = null) }
+ },
+ hasTextFocus: () => true,
+ getModel: () => ({
+ getValue: () => textBeforeCursor,
+ getOffsetAt: () => textBeforeCursor.length,
+ getLanguageId: () => language,
+ }),
+ getPosition: () => ({ lineNumber: 1, column: textBeforeCursor.length + 1 }),
+ trigger,
+ }
+ return {
+ editor,
+ trigger,
+ delete_: () => listener?.({ isFlush: false, changes: [{ text: '', rangeLength: 1 }] }),
+ insert: () => listener?.({ isFlush: false, changes: [{ text: 'a', rangeLength: 0 }] }),
+ setLanguage: (next: string) => (language = next),
+ }
+}
+
+describe('suggestionRetrigger', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ test.each<[TemplateLanguage, string, boolean]>([
+ [HogLanguage.hogTemplate, 'Hi {person.pro', true],
+ [HogLanguage.hogTemplate, 'Hi {f({a: 1})', true],
+ [HogLanguage.hogTemplate, 'Hi {person.properties.name} ', false],
+ [HogLanguage.hogTemplate, 'escaped \\{ brace ', false],
+ [HogLanguage.hogTemplate, 'Quoted "{...}"', false],
+ [HogLanguage.hogTemplate, 'Quoted inside {"{...}"', true],
+ [HogLanguage.hogTemplate, 'Quoted {"{"}', false],
+ [HogLanguage.hogTemplate, `Hi {concat('{"id": "', event.uuid, '"}')} thanks`, false],
+ [HogLanguage.hogTemplate, "Hi {concat('}', person.pro", true],
+ [HogLanguage.hogTemplate, "Don't forget {person.pro", true],
+ [HogLanguage.hogTemplate, "Hi {concat('person.pro", false],
+ [HogLanguage.liquid, '{{ person.pro', true],
+ [HogLanguage.liquid, '{% if person.pro', true],
+ [HogLanguage.liquid, '{{ person.properties.name }} ', false],
+ [HogLanguage.liquid, '{{ "}}" | append: person.pro', true],
+ [HogLanguage.liquid, "{% if person.name == '%}' and person.pro", true],
+ [HogLanguage.liquid, '{{ "}}" | append: person.name }}', false],
+ [HogLanguage.liquid, "{% if person.name == '%}' %}", false],
+ [HogLanguage.liquid, '{{ person.name %} person.pro', true],
+ [HogLanguage.liquid, '{% if person.name }} and person.pro', true],
+ [HogLanguage.liquid, '{{ person.name }} {% if person.pro', true],
+ [HogLanguage.liquid, "Don't forget {{ person.name }} then {{ person.pro", true],
+ [HogLanguage.liquid, '{{ "{%" }} outside', false],
+ [HogLanguage.liquid, "{{ 'person.pro", false],
+ [HogLanguage.liquid, '{{ "escaped \\" }}" | append: person.pro', true],
+ [HogLanguage.liquid, 'Hi there ', false],
+ ])('insideTemplateExpression for %s with %p is %p', (language, before, expected) => {
+ expect(insideTemplateExpression(before, language)).toBe(expected)
+ })
+
+ test.each([
+ [HogLanguage.hogTemplate, 'Hi {person.pro'],
+ [HogLanguage.liquid, '{{ "}}" | append: person.pro'],
+ ])('a burst of deletions fires a single trigger only after the pause in %s', (language, text) => {
+ const { editor, trigger, delete_ } = fakeEditor(text, language)
+ retriggerSuggestionsAfterDeletion(editor)
+
+ for (let i = 0; i < 10; i++) {
+ delete_()
+ jest.advanceTimersByTime(50)
+ }
+ expect(trigger).not.toHaveBeenCalled()
+
+ jest.advanceTimersByTime(300)
+ expect(trigger).toHaveBeenCalledTimes(1)
+ expect(trigger).toHaveBeenCalledWith('deletionRetrigger', 'editor.action.triggerSuggest', {})
+ })
+
+ test('an insertion after a deletion cancels the pending reopen', () => {
+ const { editor, trigger, delete_, insert } = fakeEditor('Hi {person.pro')
+ retriggerSuggestionsAfterDeletion(editor)
+
+ delete_()
+ insert()
+ jest.advanceTimersByTime(1000)
+
+ expect(trigger).not.toHaveBeenCalled()
+ })
+
+ test('does not reopen when the deletions leave the cursor outside an expression', () => {
+ const { editor, trigger, delete_ } = fakeEditor('Hi there ')
+ retriggerSuggestionsAfterDeletion(editor)
+
+ delete_()
+ jest.advanceTimersByTime(1000)
+
+ expect(trigger).not.toHaveBeenCalled()
+ })
+
+ test('reads the language from the model at fire time, not from registration', () => {
+ const { editor, trigger, delete_, setLanguage } = fakeEditor('Hi {person.pro')
+ retriggerSuggestionsAfterDeletion(editor)
+
+ setLanguage(HogLanguage.liquid)
+ delete_()
+ jest.advanceTimersByTime(1000)
+
+ expect(trigger).not.toHaveBeenCalled()
+ })
+
+ test('disposal cancels a pending reopen', () => {
+ const { editor, trigger, delete_ } = fakeEditor('Hi {person.pro')
+ const disposable = retriggerSuggestionsAfterDeletion(editor)
+
+ delete_()
+ disposable.dispose()
+ jest.advanceTimersByTime(1000)
+
+ expect(trigger).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/monaco/suggestionRetrigger.ts b/frontend/src/lib/monaco/suggestionRetrigger.ts
new file mode 100644
index 000000000000..5d697aa80241
--- /dev/null
+++ b/frontend/src/lib/monaco/suggestionRetrigger.ts
@@ -0,0 +1,141 @@
+import type { IDisposable, IPosition, editor } from 'monaco-editor'
+
+import { HogLanguage } from '~/queries/schema/schema-general'
+
+export type TemplateLanguage = HogLanguage.hogTemplate | HogLanguage.liquid
+
+export type SuggestionRetriggerEditor = Pick<editor.IStandaloneCodeEditor, 'hasTextFocus' | 'trigger'> & {
+ getPosition: () => IPosition | null
+ getModel: () => Pick<editor.ITextModel, 'getValue' | 'getOffsetAt' | 'getLanguageId'> | null
+ onDidChangeModelContent: (
+ listener: (event: {
+ isFlush: boolean
+ changes: Pick<editor.IModelContentChange, 'text' | 'rangeLength'>[]
+ }) => void
+ ) => IDisposable
+}
+
+/** How long backspacing has to pause before suggestions reopen. Shorter than this and holding
+ * backspace would still fire a backend autocomplete request per repeated keystroke. */
+const DELETION_DEBOUNCE_MS = 300
+
+export function isTemplateLanguage(language: string | undefined): language is TemplateLanguage {
+ return language === HogLanguage.hogTemplate || language === HogLanguage.liquid
+}
+
+/**
+ * Whether the cursor sits inside a template expression: `{...}` for hog templates, `{{ ... }}` or
+ * `{% ... %}` for liquid. Only text up to the cursor is considered, so an expression the user has
+ * not closed yet still counts as open. A cursor in a string literal of the expression does not count,
+ * because the backend gives no suggestions there.
+ */
+export function insideTemplateExpression(textBeforeCursor: string, language: TemplateLanguage): boolean {
+ if (language === HogLanguage.liquid) {
+ let closingDelimiter: '}}' | '%}' | null = null
+ for (let index = 0; index < textBeforeCursor.length; index++) {
+ const character = textBeforeCursor[index]
+ const delimiter = textBeforeCursor.slice(index, index + 2)
+ if (closingDelimiter === null) {
+ if (delimiter === '{{' || delimiter === '{%') {
+ closingDelimiter = delimiter === '{{' ? '}}' : '%}'
+ index++
+ }
+ } else if (character === "'" || character === '"') {
+ index = skipStringLiteral(textBeforeCursor, index)
+ if (index >= textBeforeCursor.length) {
+ return false
+ }
+ } else if (delimiter === closingDelimiter) {
+ closingDelimiter = null
+ index++
+ }
+ }
+ return closingDelimiter !== null
+ }
+ let depth = 0
+ for (let index = 0; index < textBeforeCursor.length; index++) {
+ const character = textBeforeCursor[index]
+ if (character === '\\') {
+ index++
+ } else if (depth > 0 && (character === "'" || character === '"')) {
+ // Braces inside a string literal are content, not delimiters. Only inside an
+ // expression though: in the surrounding prose a lone quote (the apostrophe in
+ // "don't") is plain text, not the start of a literal.
+ index = skipStringLiteral(textBeforeCursor, index)
+ if (index >= textBeforeCursor.length) {
+ return false
+ }
+ } else if (character === '{') {
+ depth++
+ } else if (character === '}' && depth > 0) {
+ depth--
+ }
+ }
+ return depth > 0
+}
+
+/** Returns the index of the closing quote, or the end of the text for an unterminated literal. */
+function skipStringLiteral(text: string, openingQuoteIndex: number): number {
+ const quote = text[openingQuoteIndex]
+ for (let index = openingQuoteIndex + 1; index < text.length; index++) {
+ if (text[index] === '\\') {
+ index++
+ } else if (text[index] === quote) {
+ return index
+ }
+ }
+ return text.length
+}
+
+/**
+ * Monaco closes the suggest widget on backspace and does not reopen it, so a user correcting a
+ * chain has to retype a trigger character. Reopen it once the deletions pause, while the cursor is
+ * still inside a template expression. Debounced because each reopen costs a backend autocomplete
+ * request, and those share the project's query rate limit - one request per pause is fine, one per
+ * deleted character is not.
+ */
+export function retriggerSuggestionsAfterDeletion(editorInstance: SuggestionRetriggerEditor): IDisposable {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
+ const cancel = (): void => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ }
+
+ const listener = editorInstance.onDidChangeModelContent((event) => {
+ const isDeletion =
+ !event.isFlush && event.changes.some((change) => change.text === '' && change.rangeLength > 0)
+ // An insertion triggers Monaco's own suggestions, so it also cancels any pending reopen.
+ cancel()
+ if (!isDeletion) {
+ return
+ }
+ timeout = setTimeout(() => {
+ timeout = null
+ const model = editorInstance.getModel()
+ const position = editorInstance.getPosition()
+ if (!model || !position || !editorInstance.hasTextFocus()) {
+ return
+ }
+ // Read the language at fire time: the language selector swaps it on the live
+ // model after mount, and a stale language would scan with the wrong rules.
+ const languageId = model.getLanguageId()
+ if (!isTemplateLanguage(languageId)) {
+ return
+ }
+ if (!insideTemplateExpression(model.getValue().slice(0, model.getOffsetAt(position)), languageId)) {
+ return
+ }
+ editorInstance.trigger('deletionRetrigger', 'editor.action.triggerSuggest', {})
+ }, DELETION_DEBOUNCE_MS)
+ })
+
+ return {
+ dispose: (): void => {
+ cancel()
+ listener.dispose()
+ },
+ }
+}
diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
index 852ff3333b80..aa1f8a9e5128 100644
--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
@@ -16,7 +16,14 @@ import {
LemonSelect,
} from '@posthog/lemon-ui'
-import { CyclotronJobTemplateSuggestionsButton } from 'lib/components/CyclotronJob/CyclotronJobTemplateSuggestions'
+import {
+ CyclotronJobTemplateSuggestionsButton,
+ useTemplateEditorCursor,
+} from 'lib/components/CyclotronJob/CyclotronJobTemplateSuggestions'
+import {
+ insertTemplateReference,
+ templateReferenceForOption,
+} from 'lib/components/CyclotronJob/cyclotronJobTemplateSuggestionsLogic'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -84,6 +91,7 @@ function AddAdvancedFieldButtons(): JSX.Element | null {
function PlainTextEditor(): JSX.Element {
const { logicProps, templatingEngine } = useValues(emailTemplaterLogic)
const { setTemplatingEngine } = useActions(emailTemplaterLogic)
+ const { onEditorMount, cursorOffset } = useTemplateEditorCursor()
return (
<LemonField name="text" className="flex flex-col flex-1">
@@ -95,7 +103,13 @@ function PlainTextEditor(): JSX.Element {
setTemplatingEngine={setTemplatingEngine}
value={value}
onOptionSelect={(option) => {
- onChange(`${value || ''}${option.example}`)
+ onChange(
+ insertTemplateReference(
+ value || '',
+ templateReferenceForOption(option, templatingEngine),
+ cursorOffset()
+ )
+ )
}}
/>
</span>
@@ -104,6 +118,7 @@ function PlainTextEditor(): JSX.Element {
language={templatingEngine === 'hog' ? 'hogTemplate' : 'liquid'}
value={value}
onChange={onChange}
+ onMount={onEditorMount}
globals={logicProps.variables}
options={{
wordWrap: 'on',
@@ -446,6 +461,7 @@ function LiquidSupportedText({
}): JSX.Element {
const { templatingEngine } = useValues(emailTemplaterLogic)
const { setTemplatingEngine } = useActions(emailTemplaterLogic)
+ const { onEditorMount, cursorOffset } = useTemplateEditorCursor()
const templating = templatingEngine ?? 'hog'
@@ -457,7 +473,13 @@ function LiquidSupportedText({
setTemplatingEngine={setTemplatingEngine}
value={value}
onOptionSelect={(option) => {
- onChange?.(`${value || ''}${option.example}`)
+ onChange?.(
+ insertTemplateReference(
+ value || '',
+ templateReferenceForOption(option, templating),
+ cursorOffset()
+ )
+ )
}}
/>
</span>
@@ -468,6 +490,7 @@ function LiquidSupportedText({
value={value}
language={templating === 'hog' ? 'hogTemplate' : 'liquid'}
onChange={onChange}
+ onMount={onEditorMount}
/>
</span>
)
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.py
index 6cc7f1f198ba..8defe457327d 100644
--- a/posthog/hogql/autocomplete.py
+++ b/posthog/hogql/autocomplete.py
@@ -72,6 +72,12 @@ PROPERTY_DEFINITION_LIMIT = 220
# `properties` bags (person, groups, a user-defined input) never carry person property setters.
EVENT_PROPERTIES_GLOBALS_CHAIN = ["event", "properties"]
+# `parse_string_template` prepends a magic "F'" to flip the parser into template mode, so every node
+# position it reports is shifted by that prefix. Keep this list in step with the languages below
+# that are parsed with it, or the cursor resolves to the wrong node.
+STRING_TEMPLATE_LANGUAGES = (HogLanguage.HOG_TEMPLATE, HogLanguage.LIQUID, HogLanguage.HOG_JSON)
+STRING_TEMPLATE_PREFIX_OFFSET = len("F'")
+
def _get_direct_connection_metadata(context: HogQLContext) -> Optional[dict]:
metadata = context.direct_postgres_connection_metadata
@@ -640,32 +646,29 @@ def get_hogql_autocomplete(
raise ValueError(f"Unsupported autocomplete language: {query.language}")
with timings.measure("find_node"):
- # to account for the magic F' symbol we append to change antlr's mode
- extra = 2 if query.language == HogLanguage.HOG_TEMPLATE else 0
+ extra = STRING_TEMPLATE_PREFIX_OFFSET if query.language in STRING_TEMPLATE_LANGUAGES else 0
find_node = GetNodeAtPositionTraverser(root_node, query_start + extra, query_end + extra)
node = find_node.node
parent_node = find_node.parent_node
- if HogLanguage.HOG_TEMPLATE and isinstance(node, ast.Constant):
- # Do not show suggestions if not inside the {} part in a template string
+ if isinstance(node, ast.Constant):
+ # The cursor sits in literal text: outside the {} of a template string, or inside a
+ # string literal elsewhere. Neither takes suggestions.
continue
if isinstance(query.globals, dict):
if isinstance(node, ast.Field):
+ # Offer the members of whatever holds the chain element under the cursor, so the
+ # author gets the level they are editing rather than the end of the chain
loop_globals: dict | None = query.globals
entered_chain: list[str] = []
- for index, key in enumerate(node.chain):
- if MATCH_ANY_CHARACTER in str(key):
- break
- if loop_globals is not None and str(key) in loop_globals:
- loop_globals = loop_globals[str(key)]
- entered_chain.append(str(key))
- elif index == len(node.chain) - 1:
- break
- else:
+ for key in node.chain[: chain_index_at_cursor(node, query_to_try, query_start, extra)]:
+ if MATCH_ANY_CHARACTER in str(key) or not isinstance(loop_globals, dict):
loop_globals = None
break
- if loop_globals is not None:
+ loop_globals = loop_globals.get(str(key))
+ entered_chain.append(str(key))
+ if isinstance(loop_globals, dict):
# The sample event backing these globals is a real captured event, so its
# property bag can still carry properties we no longer offer for querying.
excluded_keys = (
@@ -977,6 +980,18 @@ def extract_json_row(query_to_try, query_start, query_end):
return query_to_try, query_start, query_end
+def chain_index_at_cursor(node: ast.Field, source: str, cursor: int, node_offset: int) -> int:
+ # Which element of `node.chain` the cursor sits on, so callers can resolve the levels before it.
+ # Chain elements carry no positions of their own, so this counts the dots between the start of
+ # the field and the cursor: a quoted key holding a dot lands one level off, showing suggestions
+ # from the wrong level rather than failing. Without a position, assume the last element.
+ last_index = max(0, len(node.chain) - 1)
+ if node.start is None:
+ return last_index
+ field_start = max(0, node.start - node_offset)
+ return max(0, min(source[field_start:cursor].count("."), last_index))
+
+
def add_globals_to_suggestions(
globalVars: dict, response: HogQLAutocompleteResponse, excluded_keys: set[str] | None = None
):
diff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.py
index c941212b1a88..2ad02ab71a75 100644
--- a/posthog/hogql/test/test_autocomplete.py
+++ b/posthog/hogql/test/test_autocomplete.py
@@ -89,6 +89,21 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):
)
return get_hogql_autocomplete(query=autocomplete, team=self.team, database_arg=database)
+ def _at_cursor(
+ self, language: HogLanguage, query_with_cursor: str, database: Optional[Database] = None
+ ) -> HogQLAutocompleteResponse:
+ # "|" marks where the cursor sits, and is stripped before the query is sent
+ position = query_with_cursor.index("|")
+ autocomplete = HogQLAutocomplete(
+ kind="HogQLAutocomplete",
+ query=query_with_cursor.replace("|", "", 1),
+ language=language,
+ globals={"event": "$pageview", "person": {"properties": {"email": "[email protected]", "name": "Tim"}}},
+ startPosition=position,
+ endPosition=position,
+ )
+ return get_hogql_autocomplete(query=autocomplete, team=self.team, database_arg=database)
+
def _program(
self, query: str, start: int, end: int, database: Optional[Database] = None
) -> HogQLAutocompleteResponse:
@@ -558,6 +573,91 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):
results = self._json(query=query, start=5, end=6, database=database)
assert len(results.suggestions) == 0
+ @parameterized.expand(
+ [
+ ("hog_template", HogLanguage.HOG_TEMPLATE, "Hi {person.|} bye", ["properties"]),
+ ("hog_template_nested", HogLanguage.HOG_TEMPLATE, "Hi {person.properties.|} bye", ["email", "name"]),
+ ("liquid", HogLanguage.LIQUID, "Hi {{ person.| }} bye", ["properties"]),
+ ("liquid_nested", HogLanguage.LIQUID, "Hi {{ person.properties.| }} bye", ["email", "name"]),
+ ("hog_json", HogLanguage.HOG_JSON, '{"message": "Hi {person.|} bye"}', ["properties"]),
+ ("hog_json_nested", HogLanguage.HOG_JSON, '{"message": "Hi {person.properties.|} bye"}', ["email", "name"]),
+ ]
+ )
+ def test_autocomplete_template_drills_into_globals(
+ self, _name: str, language: HogLanguage, query: str, expected_labels: list[str]
+ ):
+ results = self._at_cursor(language, query, database=Database.create_for(team=self.team))
+
+ assert [suggestion.label for suggestion in results.suggestions] == expected_labels
+
+ @parameterized.expand(
+ [
+ ("hog_template_first", HogLanguage.HOG_TEMPLATE, "Hi {pe|rson.properties.email}", ["event", "person"]),
+ ("hog_template_middle", HogLanguage.HOG_TEMPLATE, "Hi {person.pro|perties.email}", ["properties"]),
+ ("hog_template_last", HogLanguage.HOG_TEMPLATE, "Hi {person.properties.em|ail}", ["email", "name"]),
+ ("liquid_first", HogLanguage.LIQUID, "Hi {{ pe|rson.properties.email }}", ["event", "person"]),
+ ("liquid_middle", HogLanguage.LIQUID, "Hi {{ person.pro|perties.email }}", ["properties"]),
+ ("liquid_last", HogLanguage.LIQUID, "Hi {{ person.properties.em|ail }}", ["email", "name"]),
+ (
+ "hog_json_first",
+ HogLanguage.HOG_JSON,
+ '{"message": "Hi {pe|rson.properties.email}"}',
+ ["event", "person"],
+ ),
+ ("hog_json_middle", HogLanguage.HOG_JSON, '{"message": "Hi {person.pro|perties.email}"}', ["properties"]),
+ ("hog_json_last", HogLanguage.HOG_JSON, '{"message": "Hi {person.properties.em|ail}"}', ["email", "name"]),
+ # Dots outside the extracted JSON string value must not count as chain levels
+ (
+ "hog_json_after_dotted_rows",
+ HogLanguage.HOG_JSON,
+ '{\n "url": "https://example.com/a.b",\n "message": "Hi {person.pro|perties.email}"\n}',
+ ["properties"],
+ ),
+ ]
+ )
+ def test_autocomplete_template_suggests_the_level_of_the_chain_element_under_the_cursor(
+ self, _name: str, language: HogLanguage, query: str, expected_labels: list[str]
+ ):
+ results = self._at_cursor(language, query, database=Database.create_for(team=self.team))
+
+ # Hog templates also offer every Hog function, which is not what this pins down
+ assert [
+ suggestion.label
+ for suggestion in results.suggestions
+ if suggestion.kind == AutocompleteCompletionItemKind.VARIABLE
+ ] == expected_labels
+
+ @parameterized.expand(
+ [
+ ("hog_template_empty", HogLanguage.HOG_TEMPLATE, "Hi there {|}"),
+ ("hog_template_start", HogLanguage.HOG_TEMPLATE, "Hi {| person.properties.email} bye"),
+ ("liquid_empty", HogLanguage.LIQUID, "Hi there {{ |}}"),
+ ("liquid_start", HogLanguage.LIQUID, "Hi {{| person.properties.email }} bye"),
+ ("hog_json_empty", HogLanguage.HOG_JSON, '{"message": "Hi {|}"}'),
+ ]
+ )
+ def test_autocomplete_template_suggests_top_level_globals_at_the_start_of_an_expression(
+ self, _name: str, language: HogLanguage, query: str
+ ):
+ results = self._at_cursor(language, query, database=Database.create_for(team=self.team))
+
+ assert {"event", "person"} <= {suggestion.label for suggestion in results.suggestions}
+
+ @parameterized.expand(
+ [
+ ("hog_template_before", HogLanguage.HOG_TEMPLATE, "H|i {person.properties.email} bye"),
+ ("hog_template_after", HogLanguage.HOG_TEMPLATE, "Hi {person.properties.email}| bye"),
+ ("liquid_before", HogLanguage.LIQUID, "H|i {{ person.properties.email }} bye"),
+ ("liquid_after", HogLanguage.LIQUID, "Hi {{ person.properties.email }}| bye"),
+ ]
+ )
+ def test_autocomplete_template_has_no_suggestions_outside_braces(
+ self, _name: str, language: HogLanguage, query: str
+ ):
+ results = self._at_cursor(language, query, database=Database.create_for(team=self.team))
+
+ assert results.suggestions == []
+
def test_autocomplete_hog(self):
database = Database.create_for(team=self.team)
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.test.ts
index 0a6073b686ff..81488de1516b 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.test.ts
@@ -1,3 +1,5 @@
+import { CyclotronJobInvocationGlobals } from '~/types'
+
import { buildSampleGlobals, filterInputsSchemaForTrigger } from './HogFlowFunctionConfiguration'
// The stored shape a Slack message workflow carries. The trigger type alone no longer identifies
@@ -14,6 +16,102 @@ const githubTrigger = {
describe('HogFlowFunctionConfiguration', () => {
describe('buildSampleGlobals', () => {
+ const realSampleGlobals: CyclotronJobInvocationGlobals = {
+ project: { id: 2, name: 'Real project', url: 'https://app.example.com/project/2' },
+ source: { name: 'Send email', url: 'https://app.example.com/project/2/workflows/1' },
+ event: {
+ uuid: '0192f0e1-0000-0000-0000-000000000000',
+ event: 'purchase_completed',
+ elements_chain: '',
+ distinct_id: 'real-distinct-id',
+ properties: { plan_tier: 'enterprise' },
+ timestamp: '2026-01-01T00:00:00Z',
+ url: 'https://app.example.com/project/2/events/0192f0e1',
+ },
+ person: {
+ id: '0192f0e1-1111-1111-1111-111111111111',
+ properties: { company: 'Acme' },
+ name: 'Real person',
+ url: 'https://app.example.com/person/0192f0e1',
+ },
+ groups: {},
+ }
+ it('prefers the property names of the real sample event over placeholders', () => {
+ const globals = buildSampleGlobals({ type: 'event' }, undefined, realSampleGlobals)
+
+ expect(globals.event.properties).toEqual({ plan_tier: 'enterprise' })
+ expect(globals.event.event).toBe('purchase_completed')
+ expect(globals.person.properties).toEqual({ company: 'Acme' })
+ })
+
+ // Mirrors createExampleEvent, which hogFlowEditorTestLogic supplies for every non-event trigger.
+ const exampleSampleGlobals: CyclotronJobInvocationGlobals = {
+ project: { id: 2, name: 'Default project', url: 'https://app.example.com/project/2' },
+ source: { name: 'Unnamed', url: 'https://app.example.com/project/2/workflows/1' },
+ event: {
+ uuid: '0192f0e1-2222-2222-2222-222222222222',
+ event: '$pageview',
+ elements_chain: '',
+ distinct_id: '0192f0e1-3333-3333-3333-333333333333',
+ properties: {
+ $current_url: 'https://app.example.com/project/2/workflows/1',
+ $browser: 'Chrome',
+ this_is_an_example_event: true,
+ },
+ timestamp: '2026-01-01T00:00:00Z',
+ url: 'https://app.example.com/project/2/events/0192f0e1',
+ },
+ person: {
+ id: '0192f0e1-4444-4444-4444-444444444444',
+ properties: { email: '[email protected]' },
+ name: 'Example person',
+ url: 'https://app.example.com/person/0192f0e1',
+ },
+ groups: {},
+ }
+
+ // Only event triggers query a real event; every other trigger gets a synthesized $pageview that
+ // must not overwrite the event the worker really backfills for a batch run.
+ it('ignores the synthesized example event for a batch trigger', () => {
+ const globals = buildSampleGlobals({ type: 'batch' }, undefined, exampleSampleGlobals)
+
+ expect(globals.event.event).toBe('$batch_hog_flow_invocation')
+ expect(globals.event.properties).toEqual({})
+ })
+
+ // createGlobalsFromResponse leaves person undefined for an event with no person, so an overlay
+ // that spreads the sample would drop person out of the autocomplete for anonymous events.
+ it('keeps the placeholder for a global the real sample leaves undefined', () => {
+ const globals = buildSampleGlobals({ type: 'event' }, undefined, {
+ ...realSampleGlobals,
+ person: undefined,
+ })
+
+ expect(globals.person.properties).toHaveProperty('email')
+ })
+
+ it('keeps trigger-specific globals the real sample cannot supply', () => {
+ const globals = buildSampleGlobals({ type: 'webhook' }, undefined, realSampleGlobals)
+
+ expect(globals.request).toHaveProperty('body')
+ expect('event' in globals).toBe(false)
+ })
+
+ it.each([
+ ['with a real sample', realSampleGlobals],
+ ['without a real sample', null],
+ ])('merges workflow variables %s', (_label, sample) => {
+ const globals = buildSampleGlobals(
+ { type: 'event' },
+ [
+ { key: 'name', type: 'string' },
+ { key: 'count', type: 'number' },
+ ],
+ sample
+ )
+
+ expect(globals.variables).toEqual({ name: 'example_value', count: 123 })
+ })
it.each([
['event', { type: 'event' }, { event: true, person: true, groups: true, request: false }],
['batch', { type: 'batch' }, { event: true, person: true, groups: false, request: false }],
@@ -23,7 +121,9 @@ describe('HogFlowFunctionConfiguration', () => {
// GitHub-triggered runs are person-less too.
['github event', githubTrigger, { event: true, person: false, groups: false, request: false }],
])('exposes the right globals for a %s trigger', (_name, trigger, present) => {
- const globals = buildSampleGlobals(trigger, undefined)
+ const globals = buildSampleGlobals(trigger, undefined, exampleSampleGlobals)
+ expect(globals).toHaveProperty('project')
+ expect(globals).toHaveProperty('source')
Object.entries(present).forEach(([key, shouldExist]) => {
expect(key in globals).toBe(shouldExist)
})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
index db9dea063d15..2fa33b51ec45 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx
@@ -11,9 +11,10 @@ import { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { CyclotronJobInputType, HogFunctionMappingType } from '~/types'
+import { CyclotronJobInputType, CyclotronJobInvocationGlobals, HogFunctionMappingType } from '~/types'
import { workflowLogic } from '../../../workflowLogic'
+import { hogFlowEditorTestLogic } from '../../panel/testing/hogFlowEditorTestLogic'
import { isGithubEventTriggerConfig } from '../../registry/triggers/githubTriggerFilters'
import { isSlackMessageTriggerConfig } from '../../registry/triggers/slackTriggerFilters'
import { CustomerTaskWorkflowReferenceInput } from './CustomerTaskWorkflowReferenceInput'
@@ -24,9 +25,19 @@ import { WorkflowAutoSaveIndicator } from './WorkflowAutoSaveIndicator'
// The available globals depend on the trigger type: batch runs have no external triggering event,
// but the worker backfills a real event.distinct_id at dequeue, so batch must expose `event` too or
// the editor wrongly flags {event.distinct_id} as unknown.
+//
+// The trigger type decides which globals exist, while `realSampleGlobals` (a recent matching event,
+// loaded by the test panel) decides what is inside them, so autocomplete offers the property names
+// the run will actually carry rather than invented ones. Only an event trigger gets a real sample:
+// hogFlowEditorTestLogic synthesizes an example $pageview for every other trigger, whose property
+// names a batch or webhook run never carries, so the sample is ignored outside an event trigger.
+// Placeholders stand in for the rest: globals the sample has not loaded yet, globals it leaves
+// undefined such as `person` on an anonymous event, and globals such as `request` that no event
+// carries at all.
export function buildSampleGlobals(
trigger: { type?: string; filters?: unknown } | undefined | null,
- variables: Array<Record<string, any>> | undefined | null
+ variables: Array<Record<string, any>> | undefined | null,
+ realSampleGlobals?: CyclotronJobInvocationGlobals | null
): Record<string, any> {
const triggerType = trigger?.type
const workflowVariables: Record<string, any> = {}
@@ -45,8 +56,18 @@ export function buildSampleGlobals(
}
})
+ // The worker attaches project and source to every step invocation whatever the trigger
+ // (buildHogFunctionInvocation), so they are never unknown globals.
const sampleGlobals: Record<string, any> = {
- variables: workflowVariables,
+ project: {
+ id: 1,
+ name: 'Example project',
+ url: 'https://example.com/project/1',
+ },
+ source: {
+ name: 'Example step',
+ url: 'https://example.com/project/1/workflows/1',
+ },
}
if (triggerType === 'webhook') {
@@ -145,7 +166,15 @@ export function buildSampleGlobals(
}
}
- return sampleGlobals
+ const realGlobalsByKey: Record<string, unknown> = (triggerType === 'event' ? realSampleGlobals : null) ?? {}
+
+ return {
+ ...Object.fromEntries(
+ Object.entries(sampleGlobals).map(([key, placeholder]) => [key, realGlobalsByKey[key] ?? placeholder])
+ ),
+ // Variables are author-declared, so no run samples them and the typed placeholders always stand.
+ variables: workflowVariables,
+ }
}
// The AI task step's Slack thread toggle only means something when a Slack message can start
@@ -180,7 +209,10 @@ export function HogFlowFunctionConfiguration({
warnings?: Record<string, string>
emailFieldErrors?: EmailFieldErrors
}): JSX.Element {
- const { workflow, hogFunctionTemplatesById, hogFunctionTemplatesByIdLoading } = useValues(workflowLogic)
+ const { workflow, logicProps, hogFunctionTemplatesById, hogFunctionTemplatesByIdLoading } = useValues(workflowLogic)
+ // The test panel loads a recent matching event; reuse it so autocomplete offers the property
+ // names this workflow really carries. Already mounted by the surrounding step detail panel.
+ const { sampleGlobals: realSampleGlobals } = useValues(hogFlowEditorTestLogic(logicProps))
const { currentTeam, currentTeamLoading } = useValues(teamLogic)
const { updateCurrentTeam } = useActions(teamLogic)
@@ -214,7 +246,7 @@ export function HogFlowFunctionConfiguration({
return <TemplateNotFoundFallback templateId={templateId} />
}
- const sampleGlobals = buildSampleGlobals(workflow?.trigger, workflow?.variables)
+ const sampleGlobals = buildSampleGlobals(workflow?.trigger, workflow?.variables, realSampleGlobals)
// Native push carries a long tail of optional Android/iOS override fields. Keep the core message
// fields inline and tuck the platform-specific ones into collapsed sections so the form stays flat.