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(aio): array json rendering (#60515)

Radu Raiceaa4d2456fdfcf
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 6944b2f6c9b0..1e7575d16e34 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -39,7 +39,6 @@ import {
} from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
-import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
import { JSONViewer } from 'lib/components/JSONViewer'
import { NotFound } from 'lib/components/NotFound'
import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
@@ -49,7 +48,7 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { IconWithCount } from 'lib/lemon-ui/icons/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { identifierToHuman, isObject, pluralize } from 'lib/utils'
+import { identifierToHuman, pluralize } from 'lib/utils'
import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { SceneExport } from 'scenes/sceneTypes'
@@ -71,6 +70,7 @@ import { EvalResultBadges } from './components/EvalResultBadges'
import { EvalsTabContent } from './components/EvalsTabContent'
import { EventContentDisplayAsync, EventContentGeneration } from './components/EventContentWithAsyncData'
import { FeedbackTag } from './components/FeedbackTag'
+import { JSONValueDisplay } from './components/JSONValueDisplay'
import { MetricTag } from './components/MetricTag'
import { SentimentBar } from './components/SentimentTag'
import {
@@ -1410,20 +1410,12 @@ function EventContentDisplay({
<LLMInputOutput
inputDisplay={
<div className="p-2 text-xs border rounded bg-[var(--color-bg-fill-secondary)]">
- {isObject(input) ? (
- <HighlightedJSONViewer src={input} collapsed={4} searchQuery={searchQuery} />
- ) : (
- <span className="font-mono">{JSON.stringify(input ?? null)}</span>
- )}
+ <JSONValueDisplay value={input} collapsed={4} searchQuery={searchQuery} />
</div>
}
outputDisplay={
<div className="p-2 text-xs border rounded bg-[var(--color-bg-fill-success-tertiary)]">
- {isObject(output) ? (
- <HighlightedJSONViewer src={output} collapsed={4} searchQuery={searchQuery} />
- ) : (
- <span className="font-mono">{JSON.stringify(output ?? null)}</span>
- )}
+ <JSONValueDisplay value={output} collapsed={4} searchQuery={searchQuery} />
</div>
}
/>
diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx
index 9dc44c6c559a..a7f9d68010c8 100644
--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx
@@ -58,6 +58,76 @@ describe('LLMMessageDisplay', () => {
expect(container.textContent).toContain(expectedSubstring)
})
+ it.each([
+ ['valid JSON object', '{"key": "value"}', 'key'],
+ ['valid JSON array', '[{"role": "assistant", "content": "hello"}]', 'role'],
+ ['truncated JSON object', '{"key": "val', 'key'],
+ ])('renders %s as JSON in expanded mode', async (_label, content, expectedSubstring) => {
+ const message: CompatMessage = { role: 'assistant', content }
+ const { container } = render(
+ <Provider>
+ <LLMMessageDisplay message={message} show />
+ </Provider>
+ )
+
+ await waitFor(() => {
+ expect(container.querySelector('.react-json-view')).toBeInTheDocument()
+ })
+ expect(container.textContent).toContain(expectedSubstring)
+ })
+
+ it.each(['{}', '[]'])('keeps empty JSON container %s as plain text in expanded mode', (content) => {
+ const message: CompatMessage = { role: 'assistant', content }
+ const { container } = render(
+ <Provider>
+ <LLMMessageDisplay message={message} show />
+ </Provider>
+ )
+
+ expect(container.querySelector('.react-json-view')).not.toBeInTheDocument()
+ expect(container.textContent).toContain(content)
+ })
+
+ it('renders output_text JSON as plain text', () => {
+ const message: CompatMessage = {
+ role: 'assistant',
+ content: JSON.stringify({ type: 'output_text', text: 'plain output text' }),
+ }
+ const { container } = render(
+ <Provider>
+ <LLMMessageDisplay message={message} show />
+ </Provider>
+ )
+
+ expect(container.textContent).toContain('plain output text')
+ expect(container.textContent).not.toContain('output_text')
+ })
+
+ it.each([
+ [
+ 'image content object',
+ { type: 'image', content: { type: 'image', image: 'https://example.com/image.png' } },
+ 'https://example.com/image.png',
+ ],
+ [
+ 'input_image object',
+ { type: 'input_image', image_url: 'https://example.com/input-image.png' },
+ 'https://example.com/input-image.png',
+ ],
+ ])('renders %s JSON as an image', (_label, content, expectedSrc) => {
+ const message: CompatMessage = {
+ role: 'assistant',
+ content: JSON.stringify(content),
+ }
+ const { container } = render(
+ <Provider>
+ <LLMMessageDisplay message={message} show />
+ </Provider>
+ )
+
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(expectedSrc)
+ })
+
it('renders content[].type=function with object arguments as a tool-call block', async () => {
const message: CompatMessage = {
role: 'assistant',
diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
index 177cedd75028..12c6d8d0a8d7 100644
--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
@@ -11,6 +11,7 @@ import { IconExclamation, IconEyeHidden } from 'lib/lemon-ui/icons'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { isObject } from 'lib/utils'
+import { getJsonContainerForDisplay, JSONValueDisplay } from '../components/JSONValueDisplay'
import { MessageSentimentBar } from '../components/SentimentTag'
import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'
import { LLMInputOutput } from '../LLMInputOutput'
@@ -22,7 +23,6 @@ import {
hasStringContentField,
isAnthropicDocumentMessage,
isAnthropicImageMessage,
- isEmptyJSONStructure,
isGeminiAudioMessage,
isGeminiDocumentMessage,
isGeminiImageMessage,
@@ -30,7 +30,6 @@ import {
isOpenAIFileMessage,
isOpenAIImageURLMessage,
looksLikeXml,
- parsePartialJSON,
parseToolArgumentsForDisplay,
} from '../utils'
import { HighlightedLemonMarkdown } from './HighlightedLemonMarkdown'
@@ -353,11 +352,34 @@ export function ConversationMessagesDisplay({
)
}
-export const ImageMessageDisplay = ({
- message,
-}: {
- message: { content?: string | { type?: string; image?: string } }
-}): JSX.Element => {
+type ImageDisplayMessage = { content?: string | { type?: string; image?: string } }
+
+function getImageDisplayMessage(value: Record<string, unknown>): ImageDisplayMessage | null {
+ if (value.type === 'input_image') {
+ return typeof value.image_url === 'string' ? { content: { type: 'image', image: value.image_url } } : null
+ }
+
+ if (value.type !== 'image') {
+ return null
+ }
+
+ if (typeof value.content === 'string') {
+ return { content: value.content }
+ }
+
+ if (isObject(value.content) && typeof value.content.image === 'string') {
+ return {
+ content: {
+ type: typeof value.content.type === 'string' ? value.content.type : 'image',
+ image: value.content.image,
+ },
+ }
+ }
+
+ return typeof value.image === 'string' ? { content: { type: 'image', image: value.image } } : null
+}
+
+export const ImageMessageDisplay = ({ message }: { message: ImageDisplayMessage }): JSX.Element => {
const { content } = message
if (typeof content === 'string') {
@@ -654,40 +676,19 @@ export const LLMMessageDisplay = React.memo(
</>
)
}
- const trimmed = typeof content === 'string' ? content.trim() : JSON.stringify(content).trim()
-
- // If content looks like JSON (starts with { or [), try to parse it
- if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
- try {
- const parsed = typeof content === 'string' ? parsePartialJSON(content) : content
- // If the partial parser returned an empty container, the input wasn't
- // actually JSON (e.g. "[Thinking: ...]" starts with "[" but is plain text)
- if (isEmptyJSONStructure(parsed)) {
- throw new Error('not JSON')
- }
- if (isObject(parsed) && parsed.type === 'image') {
- return <ImageMessageDisplay message={parsed} />
- }
- if (isObject(parsed) && parsed.type === 'input_image') {
- const message = {
- content: {
- type: 'image',
- image: String((parsed as Record<string, unknown>).image_url),
- },
- }
- return <ImageMessageDisplay message={message} />
- }
- if (isObject(parsed) && parsed.type === 'output_text' && 'text' in parsed) {
- return <span className="whitespace-pre-wrap">{String(parsed.text)}</span>
+ const parsedJsonContainer = getJsonContainerForDisplay(content, { allowEmptyContainers: false })
+
+ if (parsedJsonContainer) {
+ if (isObject(parsedJsonContainer)) {
+ const imageMessage = getImageDisplayMessage(parsedJsonContainer)
+ if (imageMessage) {
+ return <ImageMessageDisplay message={imageMessage} />
}
- if (typeof parsed === 'object' && parsed !== null) {
- return (
- <HighlightedJSONViewer src={parsed} name={null} collapsed={5} searchQuery={searchQuery} />
- )
+ if (parsedJsonContainer.type === 'output_text' && 'text' in parsedJsonContainer) {
+ return <span className="whitespace-pre-wrap">{String(parsedJsonContainer.text)}</span>
}
- } catch {
- // Not valid JSON. Fall through to Markdown/plain text handling.
}
+ return <JSONValueDisplay value={parsedJsonContainer} collapsed={5} searchQuery={searchQuery} />
}
// If the content appears to be XML, render based on the toggle.
diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
index 17966d66326d..cb357952c01a 100644
--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
@@ -1,8 +1,5 @@
import React from 'react'
-import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
-import { isObject } from 'lib/utils'
-
import {
ConversationDisplayOption,
ConversationMessagesDisplay,
@@ -10,6 +7,7 @@ import {
import { useAIData } from '../hooks/useAIData'
import { normalizeMessage, normalizeMessages } from '../utils'
import { AIDataLoading } from './AIDataLoading'
+import { JSONValueDisplay } from './JSONValueDisplay'
interface EventContentGenerationProps {
eventId: string
@@ -113,11 +111,7 @@ export function EventContentDisplayAsync({
<div>
<h3 className="font-semibold mb-2">Input</h3>
<div className="p-2 bg-surface-secondary rounded text-xs overflow-auto">
- {isObject(input) ? (
- <HighlightedJSONViewer src={input} name={null} collapsed={5} />
- ) : (
- <span className="font-mono">{JSON.stringify(input ?? null)}</span>
- )}
+ <JSONValueDisplay value={input} />
</div>
</div>
<div>
@@ -127,11 +121,7 @@ export function EventContentDisplayAsync({
raisedError ? 'bg-danger-highlight' : 'bg-surface-secondary'
}`}
>
- {isObject(output) ? (
- <HighlightedJSONViewer src={output} name={null} collapsed={5} />
- ) : (
- <span className="font-mono">{JSON.stringify(output ?? null)}</span>
- )}
+ <JSONValueDisplay value={output} />
</div>
</div>
</div>
diff --git a/products/ai_observability/frontend/components/JSONValueDisplay.test.tsx b/products/ai_observability/frontend/components/JSONValueDisplay.test.tsx
new file mode 100644
index 000000000000..a1e44b17a91d
--- /dev/null
+++ b/products/ai_observability/frontend/components/JSONValueDisplay.test.tsx
@@ -0,0 +1,53 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, waitFor } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import { JSONValueDisplay } from './JSONValueDisplay'
+
+describe('JSONValueDisplay', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ function renderValue(value: unknown): ReturnType<typeof render> {
+ return render(
+ <Provider>
+ <JSONValueDisplay value={value} />
+ </Provider>
+ )
+ }
+
+ it('renders JSON arrays with the JSON viewer', async () => {
+ const { container } = renderValue([{ role: 'user', content: [{ type: 'text', text: 'hello' }] }])
+
+ await waitFor(() => {
+ expect(container.querySelector('.react-json-view')).toBeInTheDocument()
+ })
+ expect(container.textContent).toContain('role')
+ expect(container.textContent).toContain('hello')
+ })
+
+ it('parses stringified JSON arrays before rendering', async () => {
+ const { container } = renderValue(JSON.stringify([{ role: 'user', content: 'hello' }]))
+
+ await waitFor(() => {
+ expect(container.querySelector('.react-json-view')).toBeInTheDocument()
+ })
+ expect(container.textContent).toContain('role')
+ expect(container.textContent).toContain('hello')
+ })
+
+ it('keeps bracket-prefixed plain text readable', () => {
+ const { container } = renderValue('[Thinking: not JSON]')
+
+ expect(container.querySelector('.react-json-view')).not.toBeInTheDocument()
+ expect(container.textContent).toContain('[Thinking: not JSON]')
+ })
+})
diff --git a/products/ai_observability/frontend/components/JSONValueDisplay.tsx b/products/ai_observability/frontend/components/JSONValueDisplay.tsx
new file mode 100644
index 000000000000..6bdbb9986335
--- /dev/null
+++ b/products/ai_observability/frontend/components/JSONValueDisplay.tsx
@@ -0,0 +1,60 @@
+import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
+import { isObject } from 'lib/utils'
+
+import { isEmptyJSONStructure, parsePartialJSON, safeStringify } from '../utils'
+
+export type JSONDisplayContainer = Record<string, unknown> | unknown[]
+
+export interface JSONDisplayOptions {
+ allowEmptyContainers?: boolean
+}
+
+export function isJsonContainer(value: unknown): value is JSONDisplayContainer {
+ return Array.isArray(value) || isObject(value)
+}
+
+export function getJsonContainerForDisplay(value: unknown, options?: JSONDisplayOptions): JSONDisplayContainer | null {
+ const allowEmptyContainers = options?.allowEmptyContainers ?? true
+
+ if (typeof value !== 'string') {
+ return isJsonContainer(value) && (allowEmptyContainers || !isEmptyJSONStructure(value)) ? value : null
+ }
+
+ const trimmed = value.trim()
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
+ return null
+ }
+
+ try {
+ const parsed = parsePartialJSON(value)
+ const isLiteralEmptyContainer = trimmed === '{}' || trimmed === '[]'
+ if (
+ isJsonContainer(parsed) &&
+ (!isEmptyJSONStructure(parsed) || (allowEmptyContainers && isLiteralEmptyContainer))
+ ) {
+ return parsed
+ }
+ } catch {
+ // Keep bracket-prefixed plain text, such as "[Thinking: ...]", readable.
+ }
+
+ return null
+}
+
+export function JSONValueDisplay({
+ value,
+ collapsed = 5,
+ searchQuery,
+}: {
+ value: unknown
+ collapsed?: number
+ searchQuery?: string
+}): JSX.Element {
+ const parsedValue = getJsonContainerForDisplay(value)
+
+ if (parsedValue) {
+ return <HighlightedJSONViewer src={parsedValue} name={null} collapsed={collapsed} searchQuery={searchQuery} />
+ }
+
+ return <span className="font-mono">{safeStringify(value ?? null)}</span>
+}