: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
feat(llma): highlight template variables in playground editors (#109889)
Juraj Majerikf32caddd1ace
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3446b3d42d16..54174d291034 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2396,6 +2396,14 @@ snapshots:hash: v1.k794b7964.ae48cad5026490b72a00755968184d4aef55e01b978188b1ad0c34d5f4df6883.dVI9MoFnL4jip4GBIIupVtdW7byejX3o_IDjf0RKep4components-table-preview--without-table--light:hash: v1.k794b7964.15b40253c10f34fef6a9363cd4e88aee574718b204c803f59a4a93fe3b6cabca.tSfXY29oNnrjD-aHKTyMNKGYN6lzqm3ajXqYMBE2jJI+ components-template-variable-text-area--empty-with-placeholder--dark:+ hash: v1.k794b7964.84e43e5771b11639bd4d1c16409e2d73bf8166d109b67912a0e2d4a3b39d9191.ueUS2-8172KoyCV3fyNkJNviTjjDo2wplaknHFu-Y8c+ components-template-variable-text-area--empty-with-placeholder--light:+ hash: v1.k794b7964.a8e5f099f44b706d4c464850109669860bb49c47d85c87161339462a26347fa1.Nm8kRcnKBQJy6_yCR1JbiCc1ukYDIr2tTaf5p_SDuDs+ components-template-variable-text-area--filled-and-unfilled-variables--dark:+ hash: v1.k794b7964.e66bf82a582145f768e6a70a9696d7740cb012c2022c398b68a0311ef0aa8a37.yDQ1kPl_Hi9xOUuxr9j5k7-ZlW9fyhYL3VnQRYg0nMk+ components-template-variable-text-area--filled-and-unfilled-variables--light:+ hash: v1.k794b7964.1377bea2cf4a8e52c8da776a97346ea4c8c1becd10a9fe80abbe820d56d666e4.b5L2IxrKavjH9TYToZRloZVq1ZmlgYbvPU90Nc04Otwcomponents-tz-label--absolute-timestamp--dark:hash: v1.k794b7964.e5939abb9b33f906d4d27d30344bb10dece07742fd0921be4d0875d2d977d81e.0x8wWYgIz71dN5jLN8DG2WgaaSA4lInr-a2JEd4MzuIcomponents-tz-label--absolute-timestamp--light:diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsxindex 67d11f2bb7a6..198122e9d758 100644--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx@@ -24,7 +24,6 @@ import {LemonSkeleton,LemonSwitch,LemonTag,- LemonTextArea,Spinner,Link,LemonDivider,@@ -59,8 +58,10 @@ import {type PromptConfig,} from './llmPlaygroundPromptsLogic'import { llmPlaygroundRunLogic, type ComparisonItem, type UsageSummary } from './llmPlaygroundRunLogic'+import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'import { PlaygroundSaveMenu } from './PlaygroundSaveMenu'import { PlaygroundVariablesPanel } from './PlaygroundVariablesPanel'+import { TemplateVariableTextArea } from './TemplateVariableTextArea'// Cap inline JSON previews at 20 lines so they don't dominate the layoutconst INLINE_JSON_MAX_LINES = 20@@ -877,6 +878,7 @@ function getRoleDotClass(role: string): string {function SystemMessageDisplay({ promptId }: { promptId: string }): JSX.Element {const prompt = usePromptConfig(promptId)const { promptConfigs, editModal, collapsedSections, linkedSource } = useValues(llmPlaygroundPromptsLogic)+ const { unfilledVariables } = useValues(llmPlaygroundVariablesLogic)const { setSystemPrompt, setEditModal, toggleCollapsed } = useActions(llmPlaygroundPromptsLogic)const { submitPrompt } = useActions(llmPlaygroundRunLogic)@@ -973,13 +975,12 @@ function SystemMessageDisplay({ promptId }: { promptId: string }): JSX.Element {evaluations apply those rules when they run.</p>)}- <LemonTextArea- className="text-sm w-full"+ <TemplateVariableTextAreaplaceholder="System instructions for the AI assistant..."value={prompt.systemPrompt}onChange={(value) => setSystemPrompt(value, promptId)}+ unfilledVariables={unfilledVariables}minRows={2}- maxRows={undefined}onPressCmdEnter={() => submitPrompt()}/></div>@@ -1003,11 +1004,11 @@ function SystemMessageDisplay({ promptId }: { promptId: string }): JSX.Element {<div className="space-y-4"><div><label className="font-semibold mb-1 block text-sm">System instructions</label>- <LemonTextArea- className="text-sm w-full"+ <TemplateVariableTextAreaplaceholder="System instructions for the AI assistant..."value={prompt.systemPrompt}onChange={(value) => setSystemPrompt(value, promptId)}+ unfilledVariables={unfilledVariables}minRows={8}/></div>@@ -1027,6 +1028,7 @@ function MessageDisplay({index: number}): JSX.Element {const { editModal, collapsedSections } = useValues(llmPlaygroundPromptsLogic)+ const { unfilledVariables } = useValues(llmPlaygroundVariablesLogic)const { updateMessage, deleteMessage, setEditModal, toggleCollapsed } = useActions(llmPlaygroundPromptsLogic)const { submitPrompt } = useActions(llmPlaygroundRunLogic)@@ -1050,7 +1052,9 @@ function MessageDisplay({]const trimmedContent = message.content.trim()- const useJsonEditor = trimmedContent.startsWith('{') || trimmedContent.startsWith('[')+ // A leading `{{` is a template token, not JSON (no valid JSON starts with it)+ const useJsonEditor =+ (trimmedContent.startsWith('{') && !trimmedContent.startsWith('{{')) || trimmedContent.startsWith('[')return (<>@@ -1120,13 +1124,12 @@ function MessageDisplay({/></div>) : (- <LemonTextArea- className="text-sm w-full"+ <TemplateVariableTextAreaplaceholder={`Enter ${message.role} message here...`}value={message.content}onChange={handleContentChange}+ unfilledVariables={unfilledVariables}minRows={2}- maxRows={undefined}onPressCmdEnter={() => submitPrompt()}/>)}@@ -1150,11 +1153,11 @@ function MessageDisplay({<div className="space-y-4"><div><label className="font-semibold mb-1 block text-sm">Message content</label>- <LemonTextArea- className="text-sm w-full"+ <TemplateVariableTextAreaplaceholder={`Enter ${message.role} message here...`}value={message.content}onChange={handleContentChange}+ unfilledVariables={unfilledVariables}minRows={8}/></div>diff --git a/products/ai_observability/frontend/playground/TemplateVariableTextArea.scss b/products/ai_observability/frontend/playground/TemplateVariableTextArea.scssnew file mode 100644index 000000000000..609d3cdc26ed--- /dev/null+++ b/products/ai_observability/frontend/playground/TemplateVariableTextArea.scss@@ -0,0 +1,83 @@+// The editor paints its text twice: a backdrop div that can style the `{{variable}}` tokens, and+// the real textarea on top holding the caret and selection. The two layers must lay text out+// identically or the caret lands away from the glyphs under it, so every property that affects+// line breaking is declared once for both.+//+// This is SCSS rather than utility classes because `.LemonTextArea` sets its own font-size,+// line-height, color and background in plain unlayered CSS, which beats Tailwind's layered+// utilities no matter their specificity; and `LemonTextArea` puts its `className` on both its+// wrapper and the textarea, so styling through it would give the wrapper a second copy of the+// padding.+.TemplateVariableTextArea {+ position: relative;++ // Everything that decides where a line breaks. The two layers must agree on all of it.+ // No scrollbar-gutter on purpose: these editors autosize without a row cap, so no scrollbar+ // ever appears, and react-textarea-autosize 8.3.4 does not copy the property to its hidden+ // measuring textarea, so declaring it would make the measured height drift from the real one.+ &__backdrop,+ textarea.LemonTextArea {+ padding: 0.5rem;+ font-family: inherit;+ font-size: 0.875rem;+ line-height: 1.5;+ overflow-wrap: break-word;+ white-space: pre-wrap;+ }++ &__backdrop {+ position: absolute;+ inset: 0;++ // The backdrop is positioned and the field's wrapper is not, so without an explicit order+ // the backdrop paints over the field, hiding both the caret and the field's own border.+ z-index: 0;+ overflow: hidden;+ color: var(--color-text-primary);+ pointer-events: none;+ background-color: var(--color-bg-fill-input);++ // Matches the field's 1px border, so both layers wrap text at the same width.+ border: 1px solid transparent;+ border-radius: var(--radius);+ }++ // Color only, same weight and size: these spans sit under a transparent textarea, and any+ // property that changes glyph advance widths would pull the caret away from the text.+ &__variable {+ color: var(--color-accent);+ }++ // The warning color alone reads too close to the accent; the wavy underline makes an+ // unfilled token unmistakable, and text-decoration leaves glyph metrics untouched.+ &__variable--unfilled {+ color: var(--color-text-warning);+ text-decoration: underline wavy var(--color-text-warning);+ text-underline-offset: 3px;+ }++ // `LemonTextArea` puts this class on its wrapper and its textarea; both only need to sit+ // above the backdrop, and the wrapper must keep the border and padding the design system+ // gives it.+ &__field {+ position: relative;+ z-index: 1;++ // `.input-like` fills its background on focus, and this layer sits above the backdrop, so+ // without this the text vanishes the moment the field is focused. The backdrop owns the+ // background; this layer stays glass all the way down.+ background-color: transparent;+ }++ // The backdrop paints the text and the background; the textarea keeps the caret, selection,+ // and placeholder.+ textarea.LemonTextArea {+ color: transparent;+ caret-color: var(--color-text-primary);+ background-color: transparent;++ &::placeholder {+ color: var(--color-text-tertiary);+ }+ }+}diff --git a/products/ai_observability/frontend/playground/TemplateVariableTextArea.stories.tsx b/products/ai_observability/frontend/playground/TemplateVariableTextArea.stories.tsxnew file mode 100644index 000000000000..d2608f101909--- /dev/null+++ b/products/ai_observability/frontend/playground/TemplateVariableTextArea.stories.tsx@@ -0,0 +1,54 @@+import { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { TemplateVariableTextArea } from './TemplateVariableTextArea'++const meta: Meta<typeof TemplateVariableTextArea> = {+ title: 'Components/Template Variable Text Area',+ component: TemplateVariableTextArea,+ parameters: {+ docs: {+ description: {+ component:+ 'The AI playground prompt editor. `{{variables}}` with a value render in the accent color, unfilled ones in the warning color. The highlight comes from a backdrop div behind a transparent textarea, so typing must keep the caret exactly on the glyphs.',+ },+ },+ },+}+export default meta+type Story = StoryObj<typeof TemplateVariableTextArea>++export const FilledAndUnfilledVariables: Story = {+ render: function Render() {+ const [value, setValue] = useState(+ 'You are a helpful assistant for {{company}}.\n' ++ 'Answer every question about {{topic}} in a {{tone}} tone. ' ++ 'A long line should wrap identically in both layers, so the caret stays on the glyphs even after wrapping. ' ++ 'Literal braces like {{ spaced }} and {{}} stay plain.\n' ++ // An unbroken token must break at the same point in both layers+ 'data:application/x-unbroken-token;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+ )+ return (+ <div className="max-w-200">+ <TemplateVariableTextArea value={value} onChange={setValue} unfilledVariables={['tone']} minRows={2} />+ </div>+ )+ },+}++export const EmptyWithPlaceholder: Story = {+ render: function Render() {+ const [value, setValue] = useState('')+ return (+ <div className="max-w-200">+ <TemplateVariableTextArea+ value={value}+ onChange={setValue}+ unfilledVariables={[]}+ placeholder="System instructions for the AI assistant..."+ minRows={2}+ />+ </div>+ )+ },+}diff --git a/products/ai_observability/frontend/playground/TemplateVariableTextArea.tsx b/products/ai_observability/frontend/playground/TemplateVariableTextArea.tsxnew file mode 100644index 000000000000..4c4b6a2ac9db--- /dev/null+++ b/products/ai_observability/frontend/playground/TemplateVariableTextArea.tsx@@ -0,0 +1,87 @@+import './TemplateVariableTextArea.scss'++import { useEffect, useLayoutEffect, useRef } from 'react'++import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'++import { segmentTemplateText } from './playgroundTemplating'++/** A prompt editor that paints `{{variables}}` in place: accent when filled, warning when not.+ *+ * A textarea can't style its own contents, so the visible text is a backdrop div rendering the+ * same string; the textarea sits on top contributing the caret and selection over transparent+ * glyphs. `TemplateVariableTextArea.scss` holds every metric the two layers share, and explains+ * why. Tokens are recolored but never re-weighted: a weight change would alter glyph widths in+ * the proportional font and pull the caret away from the text.+ */+export function TemplateVariableTextArea({+ value,+ onChange,+ unfilledVariables,+ placeholder,+ minRows,+ onPressCmdEnter,+}: {+ value: string+ onChange: (value: string) => void+ unfilledVariables: string[]+ placeholder?: string+ minRows?: number+ onPressCmdEnter?: () => void+}): JSX.Element {+ const backdropRef = useRef<HTMLDivElement | null>(null)+ const textAreaRef = useRef<HTMLTextAreaElement | null>(null)++ // The field autosizes to its content, so it should never scroll; the sync is insurance+ // against rounding leaving the textarea a pixel scrollable.+ const syncScroll = (): void => {+ if (backdropRef.current && textAreaRef.current) {+ backdropRef.current.scrollTop = textAreaRef.current.scrollTop+ backdropRef.current.scrollLeft = textAreaRef.current.scrollLeft+ }+ }+ useLayoutEffect(syncScroll, [value])+ // `LemonTextArea` forwards only a few textarea attributes, and `onScroll` isn't among them,+ // so the listener goes on the element itself rather than widening the shared component.+ useEffect(() => {+ const element = textAreaRef.current+ element?.addEventListener('scroll', syncScroll)+ return () => element?.removeEventListener('scroll', syncScroll)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ return (+ <div className="TemplateVariableTextArea w-full">+ <div ref={backdropRef} aria-hidden className="TemplateVariableTextArea__backdrop">+ {segmentTemplateText(value).map((segment, index) =>+ segment.variableName === null ? (+ <span key={index}>{segment.text}</span>+ ) : (+ <span+ key={index}+ className={+ unfilledVariables.includes(segment.variableName)+ ? 'TemplateVariableTextArea__variable--unfilled'+ : 'TemplateVariableTextArea__variable'+ }+ >+ {segment.text}+ </span>+ )+ )}+ {/* A trailing newline is collapsed when it ends the div's content, which would drop+ the backdrop a line behind the textarea while typing at the end. */}+ {'\n'}+ </div>+ <LemonTextArea+ ref={textAreaRef}+ value={value}+ onChange={onChange}+ placeholder={placeholder}+ minRows={minRows}+ onPressCmdEnter={onPressCmdEnter}+ className="TemplateVariableTextArea__field"+ />+ </div>+ )+}diff --git a/products/ai_observability/frontend/playground/playgroundTemplating.test.ts b/products/ai_observability/frontend/playground/playgroundTemplating.test.tsindex d39a2f499a74..187c8b85d509 100644--- a/products/ai_observability/frontend/playground/playgroundTemplating.test.ts+++ b/products/ai_observability/frontend/playground/playgroundTemplating.test.ts@@ -1,4 +1,4 @@-import { extractVariables, substituteVariables } from './playgroundTemplating'+import { extractVariables, segmentTemplateText, substituteVariables } from './playgroundTemplating'describe('playgroundTemplating', () => {// The syntax must stay identical to the SDK compile helpers (@posthog/ai and@@ -26,4 +26,14 @@ describe('playgroundTemplating', () => {const value = '{"amount": "$& USD",\n "note": "$\' end"}'expect(substituteVariables('data: {{payload}}', { payload: value })).toBe(`data: ${value}`)})++ it('segments text without losing a character, tagging only the variable tokens', () => {+ // The editor backdrop renders these segments behind a transparent textarea;+ // a dropped or duplicated character pulls the caret off the glyphs under it.+ const text = 'Hi {{name}}, about {{ spaced }} and {{topic}} tail'+ const segments = segmentTemplateText(text)+ expect(segments.map((s) => s.text).join('')).toBe(text)+ expect(segments.filter((s) => s.variableName !== null).map((s) => s.variableName)).toEqual(['name', 'topic'])+ expect(segmentTemplateText('')).toEqual([])+ })})diff --git a/products/ai_observability/frontend/playground/playgroundTemplating.ts b/products/ai_observability/frontend/playground/playgroundTemplating.tsindex 7d90f95fc005..3354cf6026ac 100644--- a/products/ai_observability/frontend/playground/playgroundTemplating.ts+++ b/products/ai_observability/frontend/playground/playgroundTemplating.ts@@ -8,6 +8,34 @@*/const TEMPLATE_VARIABLE_REGEX = /\{\{([\w.-]+)\}\}/g+export interface TemplateSegment {+ text: string+ /** The variable name when this segment is a `{{name}}` token, null for plain text. */+ variableName: string | null+}++/**+ * Split text into plain runs and `{{name}}` tokens, for rendering the same string+ * with the tokens styled. The concatenated segment texts must equal the input+ * exactly: the editor backdrop renders these behind a transparent textarea, and a+ * dropped character pulls the caret away from the glyphs under it.+ */+export function segmentTemplateText(text: string): TemplateSegment[] {+ const segments: TemplateSegment[] = []+ let index = 0+ for (const match of text.matchAll(TEMPLATE_VARIABLE_REGEX)) {+ if (match.index > index) {+ segments.push({ text: text.slice(index, match.index), variableName: null })+ }+ segments.push({ text: match[0], variableName: match[1] })+ index = match.index + match[0].length+ }+ if (index < text.length) {+ segments.push({ text: text.slice(index), variableName: null })+ }+ return segments+}+/** Distinct variable names in order of first appearance. */export function extractVariables(text: string): string[] {const names: string[] = []