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.

feat(aio): cut long messages in the trace view behind show more (#130096)

Carlos Marchal3c7fd53884e0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e2aa69b72be5..c6226caec831 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9611,9 +9611,9 @@ snapshots:
scenes-app-ai-observability-trace-view-input-and-output--narrow--light:
hash: v1.k794b7964.2093a8432528d040a3c433caf91227eaffa82246e46ad5cb466ca8755717ae4f.vfvKmUf9vZ_2nN_Ce3gnb9jFFewE19_zoTiWQBc16rE
scenes-app-ai-observability-trace-view-input-and-output--nothing-captured--dark:
- hash: v1.k794b7964.6d24d0a35b6c649c100c4247c718aa12795e0d0e88ee733712a14b66ce44855b.j_Rlr-Qpq0Ao6NdLr9xTRW_nCe9BE_KlegtujABtBEQ
+ hash: v1.k794b7964.802d93596c3d2872141600813f464190dc8ba20f4e2771357116ce1b87038743.RGtlRa_SUdDe-7DKk-mqCce2i3sO74XAd0_UoEzxDWI
scenes-app-ai-observability-trace-view-input-and-output--nothing-captured--light:
- hash: v1.k794b7964.c4736210c4020316c3919c07b130f2dfced3d9b3bf1d3bf20812de5e6cbe09cb.MK4OlUcpeZYowFy5QKVBrtDb406UljEJQPsGZOeWHMU
+ hash: v1.k794b7964.88685670bb3105f5ba7b4e1d57a8a8c7f70ff7c2bb13a58960761806064791d4.Ev5p2yMPeOrY4dz3Ze7frdDqhqIfjdakGlsal1-zcWU
scenes-app-ai-observability-trace-view-input-and-output--plain-text--dark:
hash: v1.k794b7964.7fd00d08731a5408c839a1ed97b520656422ac32c37f772b00e4a3668ef12736.c2p_t6b1B2m0KcGIt_muoyQtWpBNr3Zkqpwo9lbCUno
scenes-app-ai-observability-trace-view-input-and-output--plain-text--light:
@@ -9635,9 +9635,9 @@ snapshots:
scenes-app-ai-observability-trace-view-message-block--system--light:
hash: v1.k794b7964.ffba007bef0bb3d88a7d76cf05f6bd7eae8626cb2027b38afa684ec669c233ae.bAErL7JXROqNqeiqMP_6sOznuplGxjmqckTMhGYVh3w
scenes-app-ai-observability-trace-view-message-block--thinking-and-tool-call--dark:
- hash: v1.k794b7964.cde60354c80299d3638977425db0cb4757b64384a4d7be14fc8eb9a7847f13fa.fBRYJkJEyUAN64ETcPb7Lp8_oMRRN5uI8dTgEvWyPw4
+ hash: v1.k794b7964.7ecd40a1c4a6bc002c87a321b8b5733a53f09f180999cd956e1fc8602e2f6d32.Eqz2JqNMEtB5xbaI4qVku3SOtzliDbqGGM4zxgtTXUc
scenes-app-ai-observability-trace-view-message-block--thinking-and-tool-call--light:
- hash: v1.k794b7964.007f73323ef9783d2b4f1f9a1582f5661e10bc6bacda198c80f134132e400756.fSHkBlIzRWnP8opjiiK5eHDqWsx3fzrU_RSWPKi4hXU
+ hash: v1.k794b7964.9cecbd3ca8e982d71c011387c6675e7b3fa21ead41e9bc9df481b633933c2624.AnqQsMXcnCzygTwlL3PPLoTbDGyHOhkT0RB-BK6vrXw
scenes-app-ai-observability-trace-view-message-block--tool-call--dark:
hash: v1.k794b7964.a02691eee1ea1c9906c82f586cdcfea5165beb5ef4c2e6356b22c916a31421c7.HaO2MuOIOHjpzP0q9xC9yslC9Im8GH_YzSSKCB54Y54
scenes-app-ai-observability-trace-view-message-block--tool-call--light:
@@ -9702,6 +9702,14 @@ snapshots:
hash: v1.k794b7964.82b22f4c10a39f0aa9826b69c13ae643149e1a1c417cad2658edb5df53759082.AgL9H1xNLACw2MqAYxsQcPGO6i9Y3Y2x5Xg4Ikb5_Ng
scenes-app-ai-observability-trace-view-message-part--tool-call-error--light:
hash: v1.k794b7964.9c640525c426692ef4419bb2122ff247fdec849da7b0f9bd2920499b227870d8.MtXCXbZkKYltcu1oDBwF0_z-CizjoAsEaL5UtK3AcaA
+ scenes-app-ai-observability-trace-view-message-part--tool-call-long-result-folded--dark:
+ hash: v1.k794b7964.366cad3bd5a8df98056f19b6df1677d499f5d661f105f3e83f4c654e2ff57a4f.fPAqzX655Gi5X1LBumG0U6Te5bTVGxnNuGsVy7B0jtw
+ scenes-app-ai-observability-trace-view-message-part--tool-call-long-result-folded--light:
+ hash: v1.k794b7964.7d9ae646017ebf33e948f8f4fab2018e4f3fa70501fc8d6f4cffe34ecdcc066b.YEzrXchKHdsuYMcR60EwXHtasVy_t50Igx8rzBWftiU
+ scenes-app-ai-observability-trace-view-message-part--tool-call-long-result-open-wraps--dark:
+ hash: v1.k794b7964.c5babe1aeb6a92cbc937a0d55e89a8f7e08cf17aee6eb5594442dce9feb4cf28.30WnjZtv8LPdLK2Me2ZtPjDTBOoXAaij8pcmMMnDwyA
+ scenes-app-ai-observability-trace-view-message-part--tool-call-long-result-open-wraps--light:
+ hash: v1.k794b7964.b6f35a6095388ee0822a5244ed29bbf1c22413283502e959af307d28ed6e81c3.GJlP6txJBndSn56h_4Q_V1U-8XFo3JQW3CxzrvOKVIE
scenes-app-ai-observability-trace-view-message-part--tool-call-multiline-args--dark:
hash: v1.k794b7964.0072496f4b97ec00108b138e09cfefc2008acf2001d63bc93152b80252f692fa.W-BkAWOeT5GTkqKVYKYWdOLT-mljqcjQDQKAKig_n0s
scenes-app-ai-observability-trace-view-message-part--tool-call-multiline-args--light:
@@ -9822,6 +9830,14 @@ snapshots:
hash: v1.k794b7964.bda2d5985bf7439273c42268b1279aa6eb2fee37e1aaafb4c199e98b1a8b7e94.oySozMrViJSTs1dyaKsz_3EdiTOd9MBj91nk8MO71fc
scenes-app-ai-observability-trace-view-raw-event--no-trace-event--light:
hash: v1.k794b7964.4a4e729043d00b03247ce25fe10de02bc132f3811c6c288032abcd36ed2fea03.REnmV4U-vFpxUJB4Lfun1zLM9Tf8tvqFDafAwrTYKeo
+ scenes-app-ai-observability-trace-view-show-more--cut--dark:
+ hash: v1.k794b7964.470c709e5fbeb7d3921f56f60b98721ae2e40cb4123866e3c731d5ea610f5802.l0WLGdU6Ls5ltsttUnsOknzKBYJT3MELj6Ohna0aT8k
+ scenes-app-ai-observability-trace-view-show-more--cut--light:
+ hash: v1.k794b7964.5932cef60c91a0be8d15cfb0a3c98ba9bb2743ac5407e677fc5aeadc3b3ee1a6.QhEh6FKLLDwpZvewhSdAS0ZHTPOnKI9xnr_SdaqR6Ms
+ scenes-app-ai-observability-trace-view-show-more--cut-narrow--dark:
+ hash: v1.k794b7964.295afa65d42c75c60d2dd72a97431c1eafc303b17d376047a9113686d47ef54a.xuPyM7zmv-HJ2WdtGinCAED-ofm32iGbLxf1DWScL8Y
+ scenes-app-ai-observability-trace-view-show-more--cut-narrow--light:
+ hash: v1.k794b7964.eb1c21d03e7c5eff4b6f4b16b6d17473ffa9afcda4b3369ccd456b740ca96f89.CKZbQLVVC3pJCP1egL0KnenScMa0Y2iFA6YhBGpzO08
scenes-app-ai-observability-trace-view-summary-mode--failed--dark:
hash: v1.k794b7964.4abf12b65d07c1688d5305420fcfd87486bc224fd7fe0b433836ae676cc142eb.YqxYGmoK_sCUVQrzcp1_CIU0VYJ25biVjgFTiFiotvE
scenes-app-ai-observability-trace-view-summary-mode--failed--light:
@@ -9907,9 +9923,9 @@ snapshots:
scenes-app-ai-observability-trace-view-thread-bubble--assistant-selectable--light:
hash: v1.k794b7964.a7c547a1c48e311f1cf64ced49b4ea3025ff93d94bd63cab52ad2244481dbd74.79wz-B7pI2avOapkn-qckimbwZ6M0vtkhg8A1U7XMIw
scenes-app-ai-observability-trace-view-thread-bubble--internal-tool-call--dark:
- hash: v1.k794b7964.32e9b428121d4f8c80488d784a95bbd87452e214b3b8808ceae6a1fda4cd6f13.cLM8_cIi_nkyS6s5yohky7klFDbJ3QczUEOQYM7dlmA
+ hash: v1.k794b7964.f7b086b7dc12076bd9bdabb4fe7b73d4c07af9206a5aa3e395aebe49607a36c3.ppX2MgEvlel1lUj9NIdPgcGM6mi6hsNT5KTk5tqq7w4
scenes-app-ai-observability-trace-view-thread-bubble--internal-tool-call--light:
- hash: v1.k794b7964.fddcc2353f5dc6078ec04c47cb21f2057bef8353af6debbe179ed1e15a043f8c.vq-uiOjHY4HIyDU1E3k1rNFIhUb92YBe8vt4jHs6lNY
+ hash: v1.k794b7964.2480a6aebe4405598abf113886a3557605dc6289a8f41bb65dfde0121d35b39c.qws2AQHO37VRk3roPh2hOekMPjmpmzjxdPPgcpbGkd4
scenes-app-ai-observability-trace-view-thread-bubble--user--dark:
hash: v1.k794b7964.83049135b36c7c60b327513dd970b891a15d630015793f09249af6b7ee1c986d.GrIDy7IWCkKLQlJvpkXlAH88GMaRd1do31KkJYgPulc
scenes-app-ai-observability-trace-view-thread-bubble--user--light:
@@ -10143,9 +10159,9 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-view--narrow-with-search--light:
hash: v1.k794b7964.6a8ac851ef14cc825a406c45b49d5cb339534dd733e364ddbc6106fbe4d812bc.mbnG8RQiZphGvIJ_Ocx_1Xy1VcMHNH_Bw8HhyAHEYac
scenes-app-ai-observability-trace-view-trace-view--sample-anthropic-thinking-tool-use--dark:
- hash: v1.k794b7964.1a371a2a02a8f0219aff1401f27d95bf7a351189dd84a6c1461ca26f36601b65.SNmwL7EKMN8FACCLahr_9rg4MS08Ug1duIqvb5QEBNI
+ hash: v1.k794b7964.3ac5d1de0fc8d8ff646a440e6e46b437b6dbfe13e4016763868ce52b1d8d732f.f5pSrVbDRctLwoV-SRR1Aw4COyGqKSrPCaiSUZRJGPc
scenes-app-ai-observability-trace-view-trace-view--sample-anthropic-thinking-tool-use--light:
- hash: v1.k794b7964.c03199575071d2230f6e5e28345ac3803249563cb1a778808640a4979814c8fc.5Z4jFpNu0C2F7Ofm2CxcNQMEwpt5lrgi2pqViX9YAC4
+ hash: v1.k794b7964.0dd0cbf40d624daa2a6d90ebf518317e4ff1b28741fadbdd874ade3cfa827f96.5Oxm9t5KMS4NCuAZ2XpmqcYba5s5HcUFaloKfLT2EL4
scenes-app-ai-observability-trace-view-trace-view--sample-claude-code-session--dark:
hash: v1.k794b7964.6a9ef30fc5fb27a557ab0801b5a88faea73218b200dc9a366549bc4ba306889b.60sME7zmv5kfnYbDNTvsr5i3jndZcd8ECeqDdBLcL3g
scenes-app-ai-observability-trace-view-trace-view--sample-claude-code-session--light:
@@ -10155,9 +10171,9 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-view--sample-lang-chain-image-error--light:
hash: v1.k794b7964.312f3920b8f9a87be9221e25bcec7154e9f2a6d207d74c90da527fa79d7d1e2e.Y3Jk-v4WNEd9KndKzQLMiPa70cMJF9J3JZfHiyvr-CI
scenes-app-ai-observability-trace-view-trace-view--sample-open-ai-agents-with-evals--dark:
- hash: v1.k794b7964.bcc266de53a3438996e08bd00a9075706271fc5603c348afee6df62427405009.axJcMXuVyBt2FPZ4PHCGmZGJHWgWNJ_8lPRcaHZ0XdQ
+ hash: v1.k794b7964.ca62f0c97babd0410430ef647af00bb9c036be1101be4620988c5c7b2c86d5ff.4CWCE0R8kni50HaV9HIiNFRac46-QctNCsAMbiGIouM
scenes-app-ai-observability-trace-view-trace-view--sample-open-ai-agents-with-evals--light:
- hash: v1.k794b7964.94c893b61a0a00873d0a02b4c77ffddca448099f38585450e2c04feaaece6bea.E44zW50CqWpResxLXkz_AbfEgWnR6IVhJGAF6nQJOwM
+ hash: v1.k794b7964.569d4a8c21c706488b982333bea0a259fcf28ad024e36fd6fd7b2d795e01aff5.UZThKVpRX-cOkIa9LRWMAr55UhWdmJ2ZmzkrJFDqViQ
scenes-app-ai-observability-trace-view-trace-view--span-selected--dark:
hash: v1.k794b7964.ad1e7f6bb23db08a85a1d544904214d19f867ba5e905900fadcf1e453640f8c5.xeolQ6bTfRJjr-8byrw30Lq9B6oo0Urw4LFYd3MJi7A
scenes-app-ai-observability-trace-view-trace-view--span-selected--light:
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/jsonNumbers.ts b/products/ai_observability/frontend/redesign/trace/adapter/jsonNumbers.ts
new file mode 100644
index 000000000000..8ce4fc5b84f2
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/jsonNumbers.ts
@@ -0,0 +1,34 @@
+// A JSON string, which is skipped, or a JSON number literal.
+const JSON_TOKEN = /"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g
+const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/
+
+/** The exact decimal value of a number literal as sign, significant digits and exponent, so equal values compare equal. */
+function canonicalDecimal(literal: string): string {
+ const match = DECIMAL.exec(literal)
+ if (!match) {
+ return literal
+ }
+ const [, sign, integer, fraction = '', exponent = '0'] = match
+ let digits = (integer + fraction).replace(/^0+/, '')
+ let power = Number(exponent) - fraction.length
+ while (digits.endsWith('0')) {
+ digits = digits.slice(0, -1)
+ power += 1
+ }
+ return digits === '' ? '0' : `${sign}${digits}e${power}`
+}
+
+function losesPrecision(literal: string): boolean {
+ const parsed = Number(literal)
+ return !Number.isFinite(parsed) || canonicalDecimal(literal) !== canonicalDecimal(String(parsed))
+}
+
+/** Whether `JSON.parse` would change any number in this JSON text, by rounding it or turning it into null. */
+export function hasLossyNumber(json: string): boolean {
+ for (const [token] of json.matchAll(JSON_TOKEN)) {
+ if (!token.startsWith('"') && losesPrecision(token)) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts
index e326f1316714..03ffd926564e 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts
@@ -38,19 +38,40 @@ describe('toThreadMessages', () => {
},
],
},
- { role: 'tool', tool_call_id: 'call-1', content: '{"total_usd":180}' },
+ { role: 'tool', tool_call_id: 'call-1', content: '{"total_usd":180.50}' },
{ role: 'assistant', content: 'Two seats were added.' },
],
options('assistant', 'out', 'gen-1')
)
expect(messages).toHaveLength(2)
expect(messages[0].parts).toEqual([
- { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: '{"total_usd":180}' },
+ { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: { total_usd: 180.5 } },
])
expect(messages[0].isInternal).toBe(true)
expect(messages[1]).toMatchObject({ role: 'assistant', isInternal: false })
})
+ it.each([
+ ['plain text', 'No invoice for that month.'],
+ ['a JSON scalar', '42'],
+ ['JSON whose integers would lose digits', '{"invoice_id":1234567890123456789}'],
+ ['JSON whose decimals would lose digits', '{"amount":123456789012345.6789}'],
+ ['JSON whose numbers overflow to null', '{"value":1e309}'],
+ ])('keeps a tool result that is %s as its exact text', (_name, content) => {
+ const [message] = toThreadMessages(
+ [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ type: 'function', id: 'call-1', function: { name: 'lookup', arguments: '{}' } }],
+ },
+ { role: 'tool', tool_call_id: 'call-1', content },
+ ],
+ options('assistant', 'out', 'gen-1')
+ )
+ expect(message.parts).toEqual([{ kind: 'toolCall', name: 'lookup', args: {}, result: content }])
+ })
+
it('marks unmatched tool results as internal tool messages', () => {
const [message] = toThreadMessages(
[{ role: 'tool', tool_call_id: 'gone', content: 'late result' }],
@@ -166,7 +187,7 @@ describe('toThreadMessages', () => {
expect(messages[1]).toMatchObject({
isInternal: true,
parts: [
- { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: '{"total_usd":180}' },
+ { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: { total_usd: 180 } },
],
})
})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts
index 723998046e96..d88abcfe9e49 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts
@@ -4,6 +4,7 @@ import { normalizeMessages } from '../../../messageNormalization'
import { CompatMessage } from '../../../types'
import { INTERNAL_THINKING_ROLE, INTERNAL_TOOL_RESULT_ROLE, extractText, extractTextContent } from '../../../utils'
import { MessagePart, MessageRole, ThreadMessage } from '../types'
+import { hasLossyNumber } from './jsonNumbers'
import { TeamId, isAttachmentItemType, toAttachment } from './toAttachment'
const TEXT_ITEM_TYPES = new Set(['text', 'input_text', 'output_text'])
@@ -35,6 +36,17 @@ function parseArguments(args: unknown): unknown {
}
}
+// Tools often return JSON as text, which reads better as the structure it encodes. Scalars stay as written, and so
+// does a result whose numbers parsing would round, because the view must show the captured value.
+function parseToolResult(result: unknown): unknown {
+ const parsed = parseArguments(result)
+ if (!isObject(parsed) && !Array.isArray(parsed)) {
+ return result
+ }
+ // The number scan runs on valid JSON only: on malformed text its string pattern backtracks quadratically.
+ return typeof result === 'string' && hasLossyNumber(result) ? result : parsed
+}
+
// The normalizer passes some media items it has no recipe for through as their JSON text.
function parseMediaItem(content: string): ContentItem | null {
if (!content.startsWith('{')) {
@@ -136,14 +148,14 @@ export function toThreadMessages(
const role = toRole(message.role)
const { text, attachments } = contentParts(message, teamId)
- // A tool call part holds its result as text only, so a result carrying media stays its own
+ // A tool call part cannot hold attachments, so a result carrying media stays its own
// message and keeps its attachments.
const pendingCall =
role === 'tool' && message.tool_call_id && attachments.length === 0
? pendingCalls.get(message.tool_call_id)
: undefined
if (pendingCall && message.tool_call_id) {
- pendingCall.result = text || message.content
+ pendingCall.result = parseToolResult(text || message.content)
pendingCalls.delete(message.tool_call_id)
return
}
diff --git a/products/ai_observability/frontend/redesign/trace/components/IOPanel.tsx b/products/ai_observability/frontend/redesign/trace/components/IOPanel.tsx
index 6150479e7930..a0f3871e93f2 100644
--- a/products/ai_observability/frontend/redesign/trace/components/IOPanel.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/IOPanel.tsx
@@ -3,13 +3,14 @@ import { IOSection } from './IOSection'
export interface IOPanelProps {
input: unknown
output: unknown
+ highlightQuery?: string | null
}
-export function IOPanel({ input, output }: IOPanelProps): JSX.Element {
+export function IOPanel({ input, output, highlightQuery = null }: IOPanelProps): JSX.Element {
return (
<div className="flex flex-col gap-2">
- <IOSection title="Input" value={input} />
- <IOSection title="Output" value={output} />
+ <IOSection title="Input" value={input} highlightQuery={highlightQuery} />
+ <IOSection title="Output" value={output} highlightQuery={highlightQuery} />
</div>
)
}
diff --git a/products/ai_observability/frontend/redesign/trace/components/IOSection.tsx b/products/ai_observability/frontend/redesign/trace/components/IOSection.tsx
index 0b5fa768f501..2c3bb232a7f2 100644
--- a/products/ai_observability/frontend/redesign/trace/components/IOSection.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/IOSection.tsx
@@ -4,15 +4,17 @@ import { LemonSegmentedButton } from '@posthog/lemon-ui'
import { isPlainObject, toDisplayText } from './jsonText'
import { KeyValueTable } from './KeyValueTable'
+import { ShowMore } from './ShowMore'
type IOFormat = 'pretty' | 'json'
export interface IOSectionProps {
title: string
value: unknown
+ highlightQuery?: string | null
}
-export function IOSection({ title, value }: IOSectionProps): JSX.Element {
+export function IOSection({ title, value, highlightQuery = null }: IOSectionProps): JSX.Element {
const [format, setFormat] = useState<IOFormat>('pretty')
const isEmpty =
value === null ||
@@ -36,7 +38,7 @@ export function IOSection({ title, value }: IOSectionProps): JSX.Element {
/>
) : null}
</header>
- <div className="px-3 py-2">
+ <ShowMore highlightQuery={highlightQuery} className="px-3 py-2">
{isEmpty ? (
<span className="text-secondary text-sm">Nothing captured.</span>
) : isPlainObject(value) && format === 'pretty' ? (
@@ -44,9 +46,9 @@ export function IOSection({ title, value }: IOSectionProps): JSX.Element {
) : typeof value === 'string' ? (
<p className="m-0 whitespace-pre-wrap break-words text-sm">{value}</p>
) : (
- <pre className="m-0 max-h-96 overflow-auto text-xs">{toDisplayText(value)}</pre>
+ <pre className="m-0 whitespace-pre-wrap break-words text-xs">{toDisplayText(value)}</pre>
)}
- </div>
+ </ShowMore>
</section>
)
}
diff --git a/products/ai_observability/frontend/redesign/trace/components/KeyValueTable.tsx b/products/ai_observability/frontend/redesign/trace/components/KeyValueTable.tsx
index 566f6d007ab3..faecfd20482b 100644
--- a/products/ai_observability/frontend/redesign/trace/components/KeyValueTable.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/KeyValueTable.tsx
@@ -17,7 +17,7 @@ export function KeyValueTable({ entries, className }: KeyValueTableProps): JSX.E
{typeof value === 'string' ? (
<span className="whitespace-pre-wrap break-words">{value}</span>
) : (
- <pre className="m-0 overflow-auto text-xs">{toDisplayText(value)}</pre>
+ <pre className="m-0 whitespace-pre-wrap break-words text-xs">{toDisplayText(value)}</pre>
)}
</dd>
</div>
diff --git a/products/ai_observability/frontend/redesign/trace/components/MessageBlock.tsx b/products/ai_observability/frontend/redesign/trace/components/MessageBlock.tsx
index db0c0e339b0a..5bcfe3e5f4d7 100644
--- a/products/ai_observability/frontend/redesign/trace/components/MessageBlock.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/MessageBlock.tsx
@@ -6,6 +6,7 @@ import { cn } from 'lib/utils/css-classes'
import { MessageRole, ThreadMessage } from '../types'
import { MessagePartView } from './MessagePartView'
+import { ShowMore } from './ShowMore'
const ROLE_COLORS: Record<MessageRole, string> = {
system: 'text-warning',
@@ -26,9 +27,10 @@ function previewText(message: ThreadMessage): string | null {
export interface MessageBlockProps {
message: ThreadMessage
defaultOpen: boolean
+ highlightQuery?: string | null
}
-export function MessageBlock({ message, defaultOpen }: MessageBlockProps): JSX.Element {
+export function MessageBlock({ message, defaultOpen, highlightQuery = null }: MessageBlockProps): JSX.Element {
const [isOpen, setIsOpen] = useState(defaultOpen)
// Search results can arrive after the message mounts, and a message that matches them opens.
useEffect(() => {
@@ -58,11 +60,11 @@ export function MessageBlock({ message, defaultOpen }: MessageBlockProps): JSX.E
{preview ? <span className="min-w-0 truncate text-xs text-secondary">{preview}</span> : null}
</button>
{isOpen ? (
- <div className="flex flex-col gap-2 px-3 py-2 text-sm">
+ <ShowMore highlightQuery={highlightQuery} className="px-3 py-2 text-sm">
{message.parts.map((part, index) => (
- <MessagePartView key={index} part={part} />
+ <MessagePartView key={index} part={part} highlightQuery={highlightQuery} />
))}
- </div>
+ </ShowMore>
) : null}
</section>
)
diff --git a/products/ai_observability/frontend/redesign/trace/components/MessageList.test.tsx b/products/ai_observability/frontend/redesign/trace/components/MessageList.test.tsx
index e5c163f712fd..2b1ba8fe5fae 100644
--- a/products/ai_observability/frontend/redesign/trace/components/MessageList.test.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/MessageList.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { render } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { ThreadMessage } from '../types'
import { MessageList } from './MessageList'
@@ -30,4 +30,41 @@ describe('MessageList', () => {
expect(expandedStates(container)).toEqual(['true', 'false', 'true'])
})
+
+ it('cuts a message taller than the window behind Show more, and shows a search match in full', () => {
+ const height = jest.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(window.innerHeight + 1)
+ try {
+ const { rerender } = render(<MessageList messages={messages} emptyText="" openFrom={0} />)
+ expect(screen.getAllByText('Show more')).toHaveLength(3)
+
+ rerender(<MessageList messages={messages} emptyText="" openFrom={0} highlightQuery="invoice" />)
+
+ expect(screen.getAllByText('Show more')).toHaveLength(2)
+ } finally {
+ height.mockRestore()
+ }
+ })
+
+ it('shows a cut message in full when a folded tool result in it opens', async () => {
+ const height = jest.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(window.innerHeight + 1)
+ try {
+ const longResult = Array.from({ length: 12 }, (_, index) => ({ row: index }))
+ const toolMessage: ThreadMessage = {
+ id: 'm-tool',
+ role: 'assistant',
+ parts: [{ kind: 'toolCall', name: 'lookup_rows', args: {}, result: longResult }],
+ isInternal: true,
+ sourceNodeId: 'gen-1',
+ }
+ const { container } = render(<MessageList messages={[toolMessage]} emptyText="" openFrom={0} />)
+ const view = within(container)
+ expect(view.getByText('Show more')).toBeInTheDocument()
+
+ fireEvent.click(view.getByText(/^\[\{"row":0\}/))
+
+ await waitFor(() => expect(view.getByText('Show less')).toBeInTheDocument())
+ } finally {
+ height.mockRestore()
+ }
+ })
})
diff --git a/products/ai_observability/frontend/redesign/trace/components/MessageList.tsx b/products/ai_observability/frontend/redesign/trace/components/MessageList.tsx
index 7e53a1b7b5c8..263df6c6c4b6 100644
--- a/products/ai_observability/frontend/redesign/trace/components/MessageList.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/MessageList.tsx
@@ -11,7 +11,7 @@ export interface MessageListProps {
messages: ThreadMessage[]
emptyText: string
openFrom: number
- /** Messages that contain this text open too, so the search highlights in them show. */
+ /** Messages that contain this text open in full, so the search highlights in them show. */
highlightQuery?: string | null
}
@@ -48,6 +48,7 @@ export function MessageList({ messages, emptyText, openFrom, highlightQuery = nu
defaultOpen={
index >= openFrom || (!!highlightQuery && messageContainsText(message, highlightQuery))
}
+ highlightQuery={highlightQuery}
/>
</Fragment>
))}
diff --git a/products/ai_observability/frontend/redesign/trace/components/MessagePartView.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/MessagePartView.stories.tsx
index 10692d8bf930..1f9e8ab043a1 100644
--- a/products/ai_observability/frontend/redesign/trace/components/MessagePartView.stories.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/MessagePartView.stories.tsx
@@ -6,7 +6,9 @@ import {
FIXTURE_ATTACHMENT_PARTS,
FIXTURE_ATTACHMENT_REJECTED_IMAGE_URL,
FIXTURE_ATTACHMENT_SAME_ORIGIN_AUDIO,
+ withWidth,
} from '../storyFixtures'
+import { MessagePart } from '../types'
import { MessagePartView } from './MessagePartView'
const meta: Meta<typeof MessagePartView> = {
@@ -48,6 +50,23 @@ export const ToolCallMultilineArgs: Story = {
},
},
}
+const longResultPart: MessagePart = {
+ kind: 'toolCall',
+ name: 'lookup_seat_history',
+ args: { team: 'team-42', months: 2 },
+ result: {
+ history: [
+ { month: '2026-08', seats: 4, note: 'Seat count from the billing snapshot taken on the first day.' },
+ { month: '2026-09', seats: 6, note: 'Two seats added mid-month, prorated on the next invoice.' },
+ ],
+ },
+}
+export const ToolCallLongResultFolded: Story = { args: { part: longResultPart }, decorators: [withWidth(420)] }
+// A matching search query opens the fold without a click, so the snapshot does not depend on play timing.
+export const ToolCallLongResultOpenWraps: Story = {
+ args: { part: longResultPart, highlightQuery: '2026-09' },
+ decorators: [withWidth(420)],
+}
export const ToolCallError: Story = {
args: {
part: {
diff --git a/products/ai_observability/frontend/redesign/trace/components/MessagePartView.tsx b/products/ai_observability/frontend/redesign/trace/components/MessagePartView.tsx
index b70761da2eae..61f450f21d9a 100644
--- a/products/ai_observability/frontend/redesign/trace/components/MessagePartView.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/MessagePartView.tsx
@@ -6,16 +6,25 @@ import { ToolCallPart } from './ToolCallPart'
export interface MessagePartViewProps {
part: MessagePart
+ highlightQuery?: string | null
}
-export function MessagePartView({ part }: MessagePartViewProps): JSX.Element {
+export function MessagePartView({ part, highlightQuery = null }: MessagePartViewProps): JSX.Element {
switch (part.kind) {
case 'text':
return <MessageMarkdown text={part.text} />
case 'thinking':
return <ThinkingPart text={part.text} />
case 'toolCall':
- return <ToolCallPart name={part.name} args={part.args} result={part.result} isError={part.isError} />
+ return (
+ <ToolCallPart
+ name={part.name}
+ args={part.args}
+ result={part.result}
+ isError={part.isError}
+ highlightQuery={highlightQuery}
+ />
+ )
case 'attachment':
return (
<AttachmentPart mediaType={part.mediaType} name={part.name} mimeType={part.mimeType} url={part.url} />
diff --git a/products/ai_observability/frontend/redesign/trace/components/NodeDetail.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/NodeDetail.stories.tsx
index 018d98c8d880..51ef236bd5d5 100644
--- a/products/ai_observability/frontend/redesign/trace/components/NodeDetail.stories.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/NodeDetail.stories.tsx
@@ -12,6 +12,7 @@ import {
FIXTURE_GENERATION_PROPERTIES,
FIXTURE_LONG_AGENT_INPUT,
FIXTURE_LONG_AGENT_OUTPUT,
+ FIXTURE_LONG_ANSWER_MESSAGE,
FIXTURE_SPAN_PROPERTIES,
FIXTURE_STEP_FEEDBACK,
FIXTURE_TREE,
@@ -146,3 +147,11 @@ export const WithFeedback: Story = {
args: { ...base, stepFeedback: { feedback: FIXTURE_STEP_FEEDBACK, onOpen: () => {} } },
decorators: [withWidth(520)],
}
+export const LongMessage: Story = {
+ args: {
+ ...base,
+ content: { kind: 'messages', input: FIXTURE_GENERATION_INPUT, output: [FIXTURE_LONG_ANSWER_MESSAGE] },
+ },
+ decorators: [withStepScroller],
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/NodeMessagesTab.tsx b/products/ai_observability/frontend/redesign/trace/components/NodeMessagesTab.tsx
index f4429d0748ae..1519d17f7758 100644
--- a/products/ai_observability/frontend/redesign/trace/components/NodeMessagesTab.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/NodeMessagesTab.tsx
@@ -114,7 +114,12 @@ export function NodeMessagesTab({
</div>
</>
) : (
- <IOPanel input={loaded.input} output={loaded.output} />
+ <IOPanel
+ key={stepId}
+ input={loaded.input}
+ output={loaded.output}
+ highlightQuery={highlightQuery}
+ />
)}
{onViewInThread ? (
<LemonButton
diff --git a/products/ai_observability/frontend/redesign/trace/components/ShowMore.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/ShowMore.stories.tsx
new file mode 100644
index 000000000000..27938f4e2edb
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/ShowMore.stories.tsx
@@ -0,0 +1,28 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { within } from '@testing-library/dom'
+
+import { userEvent } from 'storybook/test'
+
+import { FIXTURE_LONG_ANSWER_MESSAGE, withWidth } from '../storyFixtures'
+import { MessagePartView } from './MessagePartView'
+import { ShowMore } from './ShowMore'
+
+const meta: Meta<typeof ShowMore> = {
+ title: 'Scenes-App/AI observability/Trace view/Show more',
+ component: ShowMore,
+ args: {
+ children: FIXTURE_LONG_ANSWER_MESSAGE.parts.map((part, index) => <MessagePartView key={index} part={part} />),
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof ShowMore>
+
+export const Cut: Story = {}
+export const CutNarrow: Story = { decorators: [withWidth(420)] }
+export const Expanded: Story = {
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+ play: async ({ canvasElement }) => {
+ await userEvent.click(await within(canvasElement).findByText('Show more'))
+ },
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/ShowMore.tsx b/products/ai_observability/frontend/redesign/trace/components/ShowMore.tsx
new file mode 100644
index 000000000000..77b737e79f33
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/ShowMore.tsx
@@ -0,0 +1,107 @@
+import { ReactNode, useId, useLayoutEffect, useRef, useState } from 'react'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { scrollIntoNearest } from './scrollIntoNearest'
+import { useShowsQuery } from './useShowsQuery'
+
+export interface ShowMoreProps {
+ children: ReactNode
+ /** Content whose text shows this query is never cut, so the search highlights in it stay visible. */
+ highlightQuery?: string | null
+ className?: string
+}
+
+function useIsTallerThanWindow(content: HTMLElement | null): boolean {
+ const [isTall, setIsTall] = useState(false)
+ useLayoutEffect(() => {
+ if (!content) {
+ return
+ }
+ const measure = (): void => setIsTall(content.offsetHeight > window.innerHeight)
+ measure()
+ const observer = new ResizeObserver(measure)
+ observer.observe(content)
+ window.addEventListener('resize', measure)
+ return () => {
+ observer.disconnect()
+ window.removeEventListener('resize', measure)
+ }
+ }, [content])
+ return isTall
+}
+
+/** Cuts content taller than the window to half the window's height, with a "Show more" that shows the rest. */
+export function ShowMore({ children, highlightQuery = null, className }: ShowMoreProps): JSX.Element {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [content, setContent] = useState<HTMLDivElement | null>(null)
+ const [isExpanded, setIsExpanded] = useState(false)
+ const scrollAfterCollapse = useRef(false)
+ const contentId = useId()
+ const isTall = useIsTallerThanWindow(content)
+ const isForcedOpen = useShowsQuery(content, highlightQuery)
+ const isCut = isTall && !isExpanded && !isForcedOpen
+
+ // Opening a folded value inside asks to read it, so the content must not then be cut away under it.
+ useLayoutEffect(() => {
+ if (!content) {
+ return
+ }
+ const expandOnOpen = (event: Event): void => {
+ if (event.target instanceof HTMLDetailsElement && event.target.open) {
+ setIsExpanded(true)
+ }
+ }
+ // `toggle` does not bubble, so the listener catches it in the capture phase.
+ content.addEventListener('toggle', expandOnOpen, true)
+ return () => content.removeEventListener('toggle', expandOnOpen, true)
+ }, [content])
+
+ useLayoutEffect(() => {
+ if (scrollAfterCollapse.current) {
+ scrollAfterCollapse.current = false
+ // The parent is the whole message, bubble or section, so its header comes back into view too.
+ scrollIntoNearest(containerRef.current?.parentElement ?? null)
+ }
+ }, [isExpanded])
+
+ const toggle = (): void => {
+ scrollAfterCollapse.current = isExpanded
+ setIsExpanded(!isExpanded)
+ }
+
+ return (
+ <div ref={containerRef} className={cn('flex min-w-0 flex-col gap-1', className)}>
+ {/* `clip`, unlike `hidden`, stops the trace search and the opening scroll from scrolling the cut part
+ into view. Browser find still matches text in the cut part without showing it. */}
+ <div
+ id={contentId}
+ className={cn(
+ isCut &&
+ 'max-h-[50vh] overflow-clip [mask-image:linear-gradient(to_bottom,black_calc(100%_-_4rem),transparent)]'
+ )}
+ // Keyboard focus can reach a link in the cut part, so the content opens to show it.
+ onFocus={isCut ? () => setIsExpanded(true) : undefined}
+ >
+ <div ref={setContent} className="flex min-w-0 flex-col gap-2">
+ {children}
+ </div>
+ </div>
+ {isTall && !isForcedOpen ? (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ className="self-start"
+ onClick={toggle}
+ aria-expanded={isExpanded}
+ aria-controls={contentId}
+ data-attr={isExpanded ? 'trace-view-show-less' : 'trace-view-show-more'}
+ >
+ {isExpanded ? 'Show less' : 'Show more'}
+ </LemonButton>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/Thread.tsx b/products/ai_observability/frontend/redesign/trace/components/Thread.tsx
index fa407aa90d89..7e8767e50fc3 100644
--- a/products/ai_observability/frontend/redesign/trace/components/Thread.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/Thread.tsx
@@ -50,6 +50,7 @@ export function Thread({
isActive={turns.length > 1 && turn.id === activeTurnId}
onSelectMessage={onSelectMessage}
matchingNodeIds={matchingNodeIds}
+ highlightQuery={highlightQuery}
/>
))}
</div>
diff --git a/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.stories.tsx
index 4987edd6dcd8..c2d8802bc69c 100644
--- a/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.stories.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
-import { FIXTURE_GENERATION_MESSAGES } from '../storyFixtures'
+import { FIXTURE_GENERATION_MESSAGES, FIXTURE_LONG_ANSWER_MESSAGE } from '../storyFixtures'
import { ThreadBubble } from './ThreadBubble'
const meta: Meta<typeof ThreadBubble> = {
@@ -22,3 +22,13 @@ export const User: Story = { args: { message: FIXTURE_GENERATION_MESSAGES[1] } }
export const AssistantSelectable: Story = { args: { message: FIXTURE_GENERATION_MESSAGES[3], onSelect: () => {} } }
export const Assistant: Story = { args: { message: FIXTURE_GENERATION_MESSAGES[3] } }
export const InternalToolCall: Story = { args: { message: FIXTURE_GENERATION_MESSAGES[2], onSelect: () => {} } }
+export const LongUserMessage: Story = {
+ args: {
+ message: {
+ ...FIXTURE_LONG_ANSWER_MESSAGE,
+ role: 'user',
+ parts: [FIXTURE_LONG_ANSWER_MESSAGE.parts[0], FIXTURE_LONG_ANSWER_MESSAGE.parts[0]],
+ },
+ },
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.tsx b/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.tsx
index b30a7db418d3..e6940de3c83d 100644
--- a/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/ThreadBubble.tsx
@@ -5,14 +5,21 @@ import { cn } from 'lib/utils/css-classes'
import { ThreadMessage } from '../types'
import { MessagePartView } from './MessagePartView'
+import { ShowMore } from './ShowMore'
export interface ThreadBubbleProps {
message: ThreadMessage
onSelect?: () => void
isFaded?: boolean
+ highlightQuery?: string | null
}
-export function ThreadBubble({ message, onSelect, isFaded = false }: ThreadBubbleProps): JSX.Element {
+export function ThreadBubble({
+ message,
+ onSelect,
+ isFaded = false,
+ highlightQuery = null,
+}: ThreadBubbleProps): JSX.Element {
const isUser = message.role === 'user'
const baseClassName = cn(
'flex flex-col gap-2 text-left text-sm',
@@ -22,7 +29,13 @@ export function ThreadBubble({ message, onSelect, isFaded = false }: ThreadBubbl
isFaded && 'opacity-50'
)
- const content = message.parts.map((part, index) => <MessagePartView key={index} part={part} />)
+ const content = (
+ <ShowMore highlightQuery={highlightQuery}>
+ {message.parts.map((part, index) => (
+ <MessagePartView key={index} part={part} highlightQuery={highlightQuery} />
+ ))}
+ </ShowMore>
+ )
if (!onSelect) {
return <div className={baseClassName}>{content}</div>
@@ -30,7 +43,7 @@ export function ThreadBubble({ message, onSelect, isFaded = false }: ThreadBubbl
return (
<div className={cn(baseClassName, 'flex-row items-start justify-between')}>
- <div className="flex min-w-0 flex-col gap-2">{content}</div>
+ {content}
<LemonButton
size="xsmall"
type="tertiary"
diff --git a/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.test.tsx b/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.test.tsx
index a958a46e05a0..633f2b5b30c8 100644
--- a/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.test.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.test.tsx
@@ -31,4 +31,20 @@ describe('ThreadTurn', () => {
expect(getByText('Two seats were added.').closest('.opacity-50') !== null).toBe(faded)
})
+
+ test.each([
+ ['cuts a bubble taller than the window', null, 1],
+ ['shows a bubble that holds the search query in full', 'seats', 0],
+ ])('%s', (_name, highlightQuery, readMoreCount) => {
+ const height = jest.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(window.innerHeight + 1)
+ try {
+ const { queryAllByText } = render(
+ <ThreadTurn turn={turn} isActive={false} onSelectMessage={() => {}} highlightQuery={highlightQuery} />
+ )
+
+ expect(queryAllByText('Show more')).toHaveLength(readMoreCount)
+ } finally {
+ height.mockRestore()
+ }
+ })
})
diff --git a/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.tsx b/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.tsx
index 340478ae644c..7ea786a8bb1b 100644
--- a/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/ThreadTurn.tsx
@@ -16,9 +16,16 @@ export interface ThreadTurnProps {
onSelectMessage: (sourceNodeId: string) => void
/** The steps that contain the search query, or null when nothing is searched. */
matchingNodeIds?: ReadonlySet<string> | null
+ highlightQuery?: string | null
}
-export function ThreadTurn({ turn, isActive, onSelectMessage, matchingNodeIds = null }: ThreadTurnProps): JSX.Element {
+export function ThreadTurn({
+ turn,
+ isActive,
+ onSelectMessage,
+ matchingNodeIds = null,
+ highlightQuery = null,
+}: ThreadTurnProps): JSX.Element {
const [showInternal, setShowInternal] = useState(false)
const conversational = conversationalMessages(turn.messages)
const hiddenCount = conversational.filter((message) => message.isInternal).length
@@ -47,6 +54,7 @@ export function ThreadTurn({ turn, isActive, onSelectMessage, matchingNodeIds =
isFaded={
matchingNodeIds !== null && sourceNodeId !== null && !matchingNodeIds.has(sourceNodeId)
}
+ highlightQuery={highlightQuery}
/>
)
})}
diff --git a/products/ai_observability/frontend/redesign/trace/components/ToolCallPart.tsx b/products/ai_observability/frontend/redesign/trace/components/ToolCallPart.tsx
index 49349e02448e..583e8a7f0362 100644
--- a/products/ai_observability/frontend/redesign/trace/components/ToolCallPart.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/ToolCallPart.tsx
@@ -1,29 +1,17 @@
import { IconWrench } from '@posthog/icons'
import { LemonTag } from '@posthog/lemon-ui'
-import { isPlainObject, toDisplayText } from './jsonText'
-import { KeyValueTable } from './KeyValueTable'
+import { ToolCallValue } from './ToolCallValue'
export interface ToolCallPartProps {
name: string
args: unknown
result?: unknown
isError?: boolean
+ highlightQuery?: string | null
}
-function ToolCallValue({ value }: { value: unknown }): JSX.Element {
- return (
- <div className="max-h-60 overflow-auto px-2 py-1">
- {isPlainObject(value) && Object.keys(value).length > 0 ? (
- <KeyValueTable entries={Object.entries(value)} className="gap-x-4 gap-y-1 font-mono text-xs" />
- ) : (
- <pre className="m-0 text-xs">{toDisplayText(value)}</pre>
- )}
- </div>
- )
-}
-
-export function ToolCallPart({ name, args, result, isError }: ToolCallPartProps): JSX.Element {
+export function ToolCallPart({ name, args, result, isError, highlightQuery = null }: ToolCallPartProps): JSX.Element {
return (
<div className="rounded border border-primary bg-surface-primary">
<div className="flex items-center gap-1.5 border-b border-primary px-2 py-1 text-xs font-semibold">
@@ -35,11 +23,11 @@ export function ToolCallPart({ name, args, result, isError }: ToolCallPartProps)
</LemonTag>
) : null}
</div>
- <ToolCallValue value={args} />
+ <ToolCallValue value={args} highlightQuery={highlightQuery} />
{result !== undefined ? (
<>
<div className="border-t border-primary px-2 py-1 text-xs font-semibold text-secondary">Result</div>
- <ToolCallValue value={result} />
+ <ToolCallValue value={result} highlightQuery={highlightQuery} />
</>
) : null}
</div>
diff --git a/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.test.tsx b/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.test.tsx
new file mode 100644
index 000000000000..06ef1eaebb38
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.test.tsx
@@ -0,0 +1,50 @@
+import { cleanup, render, waitFor } from '@testing-library/react'
+
+import { ToolCallValue } from './ToolCallValue'
+
+function nested(depth: number, leaf: unknown): unknown {
+ let value = leaf
+ for (let level = 0; level < depth; level++) {
+ value = { level: value }
+ }
+ return value
+}
+
+const longResult = { history: Array.from({ length: 6 }, (_, index) => ({ month: `2026-0${index + 1}`, seats: 4 })) }
+
+describe('ToolCallValue', () => {
+ afterEach(cleanup)
+
+ test.each([
+ ['shows a short value open, with no fold', { plan: 'team', seats: 6 }, null, { open: null, body: true }],
+ ['folds a long value to one line, with no body', longResult, null, { open: false, body: false }],
+ ['opens a folded value that shows the search query', longResult, '2026-05', { open: true, body: true }],
+ [
+ 'opens a folded value on text that its escaped preview hides',
+ { ...longResult, note: 'Use "invoice" here' },
+ '"invoice"',
+ { open: true, body: true },
+ ],
+ [
+ 'opens a folded value holding more items than a call takes arguments',
+ [...Array.from({ length: 200000 }, (_, index) => index), 'needle'],
+ 'needle',
+ { open: true, body: true },
+ ],
+ [
+ 'opens a folded value nested deeper than the call stack',
+ { ...longResult, deep: nested(4000, 'needle') },
+ 'needle',
+ { open: true, body: true },
+ ],
+ ])('%s', async (_name, value, highlightQuery, expected) => {
+ const { container } = render(<ToolCallValue value={value} highlightQuery={highlightQuery} />)
+
+ await waitFor(() =>
+ expect({
+ open: container.querySelector('details')?.open ?? null,
+ body: container.querySelector('dl, pre') !== null,
+ }).toEqual(expected)
+ )
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.tsx b/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.tsx
new file mode 100644
index 000000000000..383dc5108c02
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/ToolCallValue.tsx
@@ -0,0 +1,76 @@
+import { useLayoutEffect, useMemo, useState } from 'react'
+
+import { IconChevronRight } from '@posthog/icons'
+
+import { isPlainObject, searchableText, toDisplayText } from './jsonText'
+import { KeyValueTable } from './KeyValueTable'
+
+// A value longer than this folds to one line, so a message with several tool calls still shows every call.
+const FOLDED_LINES = 8
+const FOLDED_CHARS = 640
+
+export interface ToolCallValueProps {
+ value: unknown
+ highlightQuery?: string | null
+}
+
+function isLong(text: string): boolean {
+ return text.length > FOLDED_CHARS || text.split('\n').length > FOLDED_LINES
+}
+
+function ValueBody({ value }: { value: unknown }): JSX.Element {
+ return isPlainObject(value) && Object.keys(value).length > 0 ? (
+ <KeyValueTable entries={Object.entries(value)} className="gap-x-4 gap-y-1 font-mono text-xs" />
+ ) : (
+ <pre className="m-0 whitespace-pre-wrap break-words text-xs">{toDisplayText(value)}</pre>
+ )
+}
+
+function FoldedValue({ value, highlightQuery }: Required<ToolCallValueProps>): JSX.Element {
+ const [details, setDetails] = useState<HTMLDetailsElement | null>(null)
+ const [isOpen, setIsOpen] = useState(false)
+ // A closed fold holds only the escaped one-line preview, so the decoded value decides whether the query is in it.
+ const showsQuery = useMemo(
+ () => !!highlightQuery && searchableText(value).toLowerCase().includes(highlightQuery.toLowerCase()),
+ [value, highlightQuery]
+ )
+ useLayoutEffect(() => {
+ if (details && showsQuery) {
+ details.open = true
+ }
+ }, [details, showsQuery])
+
+ // Only one of the line and the body is in the page at a time. A closed fold then costs one text node however big
+ // the value is, and the search highlighter never marks text that is not shown.
+ return (
+ <details
+ ref={setDetails}
+ onToggle={(event) => setIsOpen(event.currentTarget.open)}
+ className="group min-w-0 px-2 py-1"
+ >
+ <summary
+ className="flex cursor-pointer list-none items-center gap-1 [&::-webkit-details-marker]:hidden"
+ data-attr="trace-view-tool-value-toggle"
+ >
+ <IconChevronRight className="shrink-0 text-secondary transition-transform group-open:rotate-90 motion-reduce:transition-none" />
+ {isOpen ? null : (
+ <span className="min-w-0 truncate font-mono text-xs">
+ {typeof value === 'string' ? value : JSON.stringify(value)}
+ </span>
+ )}
+ </summary>
+ {isOpen ? <ValueBody value={value} /> : null}
+ </details>
+ )
+}
+
+export function ToolCallValue({ value, highlightQuery = null }: ToolCallValueProps): JSX.Element {
+ if (isLong(toDisplayText(value))) {
+ return <FoldedValue value={value} highlightQuery={highlightQuery} />
+ }
+ return (
+ <div className="min-w-0 px-2 py-1">
+ <ValueBody value={value} />
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/jsonText.ts b/products/ai_observability/frontend/redesign/trace/components/jsonText.ts
index c5584f18d952..b9aa54e5d5a3 100644
--- a/products/ai_observability/frontend/redesign/trace/components/jsonText.ts
+++ b/products/ai_observability/frontend/redesign/trace/components/jsonText.ts
@@ -12,3 +12,27 @@ export function toDisplayText(value: unknown): string {
return String(value)
}
}
+
+/** The keys and values of a JSON value as a person reads them, with strings unescaped, for matching search text. */
+export function searchableText(value: unknown): string {
+ // An explicit stack, because a captured tool result can nest deeper than the call stack allows.
+ const parts: string[] = []
+ const pending: unknown[] = [value]
+ while (pending.length > 0) {
+ const item = pending.pop()
+ // Pushed one by one: spreading a large array into one call exceeds the engine's argument limit.
+ if (Array.isArray(item)) {
+ for (let index = item.length - 1; index >= 0; index--) {
+ pending.push(item[index])
+ }
+ } else if (isPlainObject(item)) {
+ const entries = Object.entries(item)
+ for (let index = entries.length - 1; index >= 0; index--) {
+ pending.push(entries[index][1], entries[index][0])
+ }
+ } else {
+ parts.push(String(item))
+ }
+ }
+ return parts.join('\n')
+}
diff --git a/products/ai_observability/frontend/redesign/trace/components/useSearchHighlight.ts b/products/ai_observability/frontend/redesign/trace/components/useSearchHighlight.ts
index 911d7d03ba7a..549aa9690784 100644
--- a/products/ai_observability/frontend/redesign/trace/components/useSearchHighlight.ts
+++ b/products/ai_observability/frontend/redesign/trace/components/useSearchHighlight.ts
@@ -74,13 +74,18 @@ export function useSearchHighlight(query: string | null, revealKey: number = 0):
}
const highlight = typeof CSS !== 'undefined' && CSS.highlights ? findOrCreateHighlight(CSS.highlights) : null
let ranges: Range[] = []
+ let revealFrame = 0
const mark = (): void => {
ranges.forEach((range) => highlight?.delete(range))
ranges = highlightRanges(element, query)
ranges.forEach((range) => highlight?.add(range))
if (ranges.length > 0 && revealedKey.current !== revealKey) {
revealedKey.current = revealKey
- ranges[0].startContainer.parentElement?.scrollIntoView({ block: 'nearest' })
+ // A cut block or a fold that holds the match opens on a re-render after this effect, which replaces the
+ // marked text, so the scroll waits a frame and takes the first match as it is then.
+ revealFrame = requestAnimationFrame(() =>
+ ranges[0]?.startContainer.parentElement?.scrollIntoView({ block: 'nearest' })
+ )
}
}
mark()
@@ -89,6 +94,7 @@ export function useSearchHighlight(query: string | null, revealKey: number = 0):
observer.observe(element, { childList: true, subtree: true, characterData: true })
return () => {
observer.disconnect()
+ cancelAnimationFrame(revealFrame)
ranges.forEach((range) => highlight?.delete(range))
}
}, [element, query, revealKey])
diff --git a/products/ai_observability/frontend/redesign/trace/components/useShowsQuery.ts b/products/ai_observability/frontend/redesign/trace/components/useShowsQuery.ts
new file mode 100644
index 000000000000..da0bdb0f1165
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/components/useShowsQuery.ts
@@ -0,0 +1,22 @@
+import { useLayoutEffect, useState } from 'react'
+
+/**
+ * Whether the element's rendered text contains the query. Reads the page text, the same text the search highlighter
+ * marks, because the raw message differs from it (markdown syntax, escaped JSON).
+ */
+export function useShowsQuery(element: HTMLElement | null, query: string | null): boolean {
+ const [showsQuery, setShowsQuery] = useState(false)
+ useLayoutEffect(() => {
+ if (!element || !query) {
+ setShowsQuery(false)
+ return
+ }
+ const needle = query.toLowerCase()
+ const check = (): void => setShowsQuery((element.textContent ?? '').toLowerCase().includes(needle))
+ check()
+ const observer = new MutationObserver(check)
+ observer.observe(element, { childList: true, subtree: true, characterData: true })
+ return () => observer.disconnect()
+ }, [element, query])
+ return showsQuery
+}
diff --git a/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx b/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
index 6d3452707f66..695a3fe18be1 100644
--- a/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
+++ b/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
@@ -226,6 +226,38 @@ export const FIXTURE_LONG_AGENT_OUTPUT: ThreadMessage[] = [
]),
]
+const SEAT_HISTORY = Array.from({ length: 24 }, (_, index) => ({
+ month: `2026-${String((index % 12) + 1).padStart(2, '0')}`,
+ seats: 4 + (index % 3),
+ note: 'Seat count from the billing snapshot taken on the first day of the month, before any proration.',
+}))
+
+/** An answer taller than any window: a preamble, a long report and a tool call with a long JSON result. */
+export const FIXTURE_LONG_ANSWER_MESSAGE: ThreadMessage = agentMessage('long-answer', 'assistant', [
+ {
+ kind: 'text',
+ text: [
+ 'You are a billing assistant. Answer in markdown, cite the invoice month, and never share card details.',
+ '',
+ '## Seat history',
+ '',
+ ...SEAT_HISTORY.map(({ month, seats }) => `- **${month}:** ${seats} seats, billed at the team plan rate.`),
+ '',
+ '## What changed',
+ '',
+ ...SEAT_HISTORY.map(({ month }) => `1. ${month}: the invoice shows one prorated line for the seat change.`),
+ '',
+ 'The seat count changed at most once a month, so every invoice line matches one row above.',
+ ].join('\n'),
+ },
+ {
+ kind: 'toolCall',
+ name: 'lookup_seat_history',
+ args: { team: 'team-42', months: 24 },
+ result: { team: 'team-42', history: SEAT_HISTORY },
+ },
+])
+
export const FIXTURE_TURN: ConversationTurn = {
id: 'trace-1',
timestamp: '2026-09-01T10:15:00Z',