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): show the question a turn-ending tool call asks the user (#91567)

Bernat Torres29a3cb581fc9
diff --git a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
index 78ae21b00ece..c33404e948b5 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
+++ b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
@@ -400,19 +400,19 @@ describe('buildStreamItems — internal messages (thinking, tool_result) collaps
})
})
-describe('buildStreamItems — intermediate assistant narration collapses, final answer stays', () => {
+describe('buildStreamItems — assistant tool activity: narration collapses, a turn-ending ask bubbles', () => {
const toolRole = (text: string): CompatMessage => ({ role: 'tool', content: text }) as unknown as CompatMessage
- const toolCall = (name: string): CompatMessage =>
+ const toolCall = (name: string, args: unknown = {}): CompatMessage =>
({
role: 'assistant',
content: '',
- tool_calls: [{ type: 'function', id: 'toolu_1', function: { name, arguments: {} } }],
+ tool_calls: [{ type: 'function', id: 'toolu_1', function: { name, arguments: args } }],
}) as unknown as CompatMessage
- const assistantWithToolCall = (text: string, name: string): CompatMessage =>
+ const assistantWithToolCall = (text: string, name: string, args: unknown = {}): CompatMessage =>
({
role: 'assistant',
content: text,
- tool_calls: [{ type: 'function', id: 'toolu_1', function: { name, arguments: {} } }],
+ tool_calls: [{ type: 'function', id: 'toolu_1', function: { name, arguments: args } }],
}) as unknown as CompatMessage
it('collapses Anthropic-style narration (split text msg) that precedes a tool result', () => {
@@ -492,6 +492,118 @@ describe('buildStreamItems — intermediate assistant narration collapses, final
])
expect(items.map((i) => i.kind)).toEqual(['bubble', 'bubble', 'bubble'])
})
+
+ it.each<[string, CompatMessage[], string]>([
+ [
+ 'object arguments nested Desktop-style ({questions: [{question}]})',
+ [
+ userText('Set up my workspace'),
+ thinking('deciding what to ask'),
+ toolCall('AskUserQuestion', {
+ questions: [{ question: 'Which workspace should I use?', options: ['a', 'b'] }],
+ }),
+ ],
+ 'Which workspace should I use?',
+ ],
+ [
+ 'truncated string arguments (partial JSON), trimmed',
+ [userText('Deploy this'), toolCall('ask_user_question', '{"question": " Which region? ", "singleSel')],
+ 'Which region?',
+ ],
+ [
+ 'whitespace-only own text falling back to the arguments',
+ [userText('Deploy this'), assistantWithToolCall(' ', 'ask_user', { question: 'Which region?' })],
+ 'Which region?',
+ ],
+ [
+ 'a parallel sibling call whose payload must not shadow the question',
+ [
+ userText('Assign it'),
+ toolCall('ask_user_question', { question: 'Who should own this?' }),
+ toolCall('log_progress', { message: 'internal note' }),
+ ],
+ 'Who should own this?',
+ ],
+ [
+ 'trailing non-substantive messages after the ask',
+ [
+ userText('Assign it'),
+ toolCall('ask_user_question', { question: 'Who should own this?' }),
+ assistant(''),
+ userText('<system_reminder>context refreshed</system_reminder>'),
+ ],
+ 'Who should own this?',
+ ],
+ [
+ 'a Codex-style request_user_input call',
+ [userText('Review the plan'), toolCall('request_user_input', { question: 'Apply this plan?' })],
+ 'Apply this plan?',
+ ],
+ [
+ 'several questions in one call, joined in order',
+ [
+ userText('Set up my workspace'),
+ toolCall('AskUserQuestion', {
+ questions: [{ question: 'Which workspace?' }, { question: 'Which region?' }],
+ }),
+ ],
+ 'Which workspace?\n\nWhich region?',
+ ],
+ ])('bubbles a turn-ending ask with %s', (_label, messages, expected) => {
+ const items = buildStreamItems(messages)
+ const bubbles = items.flatMap((item) => (item.kind === 'bubble' ? [item] : []))
+ // Exactly the user's message and the ask — no shadowed payloads, no blank extras.
+ expect(bubbles.map((item) => item.text)).toEqual([messages[0].content, expected])
+ expect(bubbles[1].nonText).toBe(false)
+ })
+
+ it("bubbles the assistant's spoken words for an Anthropic-split ask (text and tool_use as siblings)", () => {
+ const items = buildStreamItems([
+ userText('Deploy this'),
+ assistant('Which region should I deploy to?'),
+ toolCall('ask_user', { options: ['eu', 'us'] }),
+ ])
+ // The spoken text is the bubble, not a demoted "reasoning" pill, and not duplicated.
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'bubble'])
+ expect(items[1]).toMatchObject({ text: 'Which region should I deploy to?' })
+ })
+
+ it.each([
+ ['git_commit', { message: 'fix: adjust the gate' }],
+ // "Task" contains "ask": a substring gate would bubble the subagent prompt as speech.
+ ['Task', { prompt: 'You are a subagent. Find the flaky test.' }],
+ ])("never renders a routine trailing %s call's payload as assistant speech", (name, args) => {
+ const items = buildStreamItems([userText('Fix the bug'), toolCall(name, args)])
+ expect(items.map((i) => i.kind)).toEqual(['bubble'])
+ })
+
+ it('keeps trailing narration internal when its tool call is not an ask', () => {
+ const items = buildStreamItems([
+ userText('Fix the bug'),
+ assistantWithToolCall('Committing the fix now.', 'git_commit', { message: 'fix: adjust' }),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].labels).toEqual(['reasoning'])
+ }
+ })
+
+ it('does not resurface an ask that a tool result already answered', () => {
+ const items = buildStreamItems([
+ userText('Deploy'),
+ toolCall('ask_user', { question: 'Which region?' }),
+ toolResult('eu'),
+ assistant('Done, deployed to EU.'),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ expect(items[2]).toMatchObject({ text: 'Done, deployed to EU.' })
+ expect(items.some((i) => i.kind === 'bubble' && i.text.includes('Which region?'))).toBe(false)
+ })
+
+ it('renders nothing extra when a trailing ask carries no readable text', () => {
+ const items = buildStreamItems([userText('Deploy'), toolCall('ask_user', {})])
+ expect(items.map((i) => i.kind)).toEqual(['bubble'])
+ })
})
describe('captureUnrenderableMessageOnce', () => {
diff --git a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
index 91089ab200bd..31c248e74305 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
@@ -5,7 +5,7 @@ import { IconChevronRight } from '@posthog/icons'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { MessageTemplate } from 'products/posthog_ai/frontend/api/primitives'
+import { MessageTemplate, parseSandboxQuestions } from 'products/posthog_ai/frontend/api/primitives'
import { CompatMessage } from '../types'
import {
@@ -18,6 +18,7 @@ import {
getInternalTagName,
isInternalToolResultUserMessage,
isToolStepItem,
+ parseToolArgumentsForDisplay,
} from '../utils'
// Roles that carry no user-visible content in a chat-app view. System prompts
@@ -154,7 +155,85 @@ function pillSideFor(labels: string[]): 'left' | 'right' {
return labels.length > 0 && AGENT_SIDE_LABELS.has(labels[0]) ? 'left' : 'right'
}
+// Only a tool we know asks the user may render its payload as speech, because routine trailing
+// calls like git_commit(message=…) can carry text-like arguments too. Exact names, so nothing
+// over-fires; an unknown ask tool keeps the hidden pill until its name is added here. The
+// normalization makes one entry cover the camelCase, snake_case, and kebab-case spellings.
+const ASK_TOOL_NAMES = new Set(['askuserquestion', 'askfollowupquestion', 'askhuman', 'askuser', 'requestuserinput'])
+
+function isAskLikeToolName(name: unknown): boolean {
+ return typeof name === 'string' && ASK_TOOL_NAMES.has(name.toLowerCase().replace(/[^a-z0-9]/g, ''))
+}
+
+function hasAskLikeCall(message: CompatMessage): boolean {
+ return (message.tool_calls ?? []).some((call) => isAskLikeToolName(call.function?.name))
+}
+
+function askQuestionText(message: CompatMessage): string {
+ return (message.tool_calls ?? [])
+ .filter((call) => isAskLikeToolName(call.function?.name))
+ .map((call) => parseToolArgumentsForDisplay(call.function?.arguments))
+ .flatMap((parsed) => (parsed.kind === 'parsed' ? parseSandboxQuestions(parsed.value) : []))
+ .map((question) => question.question.trim())
+ .filter((text) => text.length > 0)
+ .join('\n\n')
+}
+
+function isPlainAssistant(message: CompatMessage): boolean {
+ return message.role === 'assistant' && getInternalLabel(message) === undefined
+}
+
+// Trailing messages that do not end the turn. A tool result does end it, because it means the
+// call was answered and the turn moved on.
+function isTailSkippable(message: CompatMessage): boolean {
+ if (isToolResultEntry(message)) {
+ return false
+ }
+ if (HIDDEN_ROLES.has(message.role) || getInternalLabel(message) !== undefined) {
+ return true
+ }
+ return extractText(message).trim().length === 0 && !hasNonTextContent(message) && !isToolCallMessage(message)
+}
+
+interface TrailingAsk {
+ anchorIndex: number
+ text: string
+ consumedIndices: Set<number>
+}
+
+// A turn that ends on an ask-like call is the assistant handing the turn to the user, which
+// makes it the turn's content. Providers split one turn into different message shapes, so the
+// unit is the whole trailing run: spoken words win, the ask call's arguments are the fallback.
+function findTrailingAsk(messages: CompatMessage[]): TrailingAsk | null {
+ const tailStart = messages.findLastIndex((message) => !isPlainAssistant(message) && !isTailSkippable(message)) + 1
+ const assistantEntries = messages
+ .slice(tailStart)
+ .map((message, offset) => ({ message, index: tailStart + offset }))
+ .filter(({ message }) => isPlainAssistant(message))
+ if (!assistantEntries.some(({ message }) => hasAskLikeCall(message))) {
+ return null
+ }
+ const spoken = assistantEntries
+ .map(({ message }) => extractText(message).trim())
+ .filter((text) => text.length > 0)
+ .join('\n\n')
+ const text =
+ spoken || assistantEntries.map(({ message }) => askQuestionText(message)).find((t) => t.length > 0) || ''
+ if (!text) {
+ return null
+ }
+ const consumed = assistantEntries.filter(
+ ({ message }) => hasAskLikeCall(message) || extractText(message).trim().length > 0
+ )
+ return {
+ anchorIndex: consumed[consumed.length - 1].index,
+ text,
+ consumedIndices: new Set(consumed.map(({ index }) => index)),
+ }
+}
+
function classifyMessages(messages: CompatMessage[]): SessionEntry[] {
+ const trailingAsk = findTrailingAsk(messages)
const result: SessionEntry[] = []
for (let i = 0; i < messages.length; i++) {
const message = messages[i]
@@ -166,6 +245,14 @@ function classifyMessages(messages: CompatMessage[]): SessionEntry[] {
result.push({ kind: 'internal', message, label: internalLabel })
continue
}
+ if (trailingAsk !== null && i === trailingAsk.anchorIndex) {
+ // nonText stays false: the ask is rendered, so the unrenderable capture would misfire.
+ result.push({ kind: 'bubble', message, text: trailingAsk.text, nonText: false })
+ continue
+ }
+ if (trailingAsk?.consumedIndices.has(i)) {
+ continue
+ }
const text = extractText(message)
const nonText = hasNonTextContent(message)
if (text.length === 0 && !nonText) {
@@ -259,7 +346,10 @@ export function TranscriptBubbleStream({
boxClassName={item.message.role === 'user' ? 'bg-fill-tertiary' : undefined}
>
{item.text && (
- <LemonMarkdown className="whitespace-pre-wrap break-words">{item.text}</LemonMarkdown>
+ // Trace content is untrusted, so external images must not auto-load.
+ <LemonMarkdown className="whitespace-pre-wrap break-words" disableImages>
+ {item.text}
+ </LemonMarkdown>
)}
{item.nonText && <div className="italic text-muted text-xs mt-1">(has attachments)</div>}
</MessageTemplate>
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index 478e25c24ed1..2f7b3aa5132e 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -84,6 +84,7 @@ export type { DebugLogsMenuProps } from '../components/DebugLogsMenu'
export { PermissionInput } from '../components/PermissionInput'
export { QuestionInput } from '../components/QuestionInput'
+export { parseSandboxQuestions } from '../policy/questionUtils'
export { ResourcesBar } from '../components/ResourcesBar'
export { ContextUsageBar } from '../components/ContextUsageBar'
export { QuestionField, MultiFieldQuestion, isFieldValid } from '../components/QuestionField'