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(posthog-ai): match parallel web search results across messages (#113718)

posthog[bot]1a95d6241d27
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 157edc38884b..8a7529f690cf 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -519,7 +519,13 @@ const Message = React.memo(function Message({
}: MessageProps): JSX.Element | null {
const { editInsightToolRegistered, registeredToolMap } = useValues(maxGlobalLogic)
const { activeSceneId } = useValues(sceneLogic)
- const { threadLoading, isSharedThread, pendingApprovalsData, resolvedApprovalStatuses } = useValues(maxThreadLogic)
+ const {
+ threadLoading,
+ isSharedThread,
+ pendingApprovalsData,
+ resolvedApprovalStatuses,
+ webSearchResultsByToolUseId,
+ } = useValues(maxThreadLogic)
const { conversationId } = useValues(maxLogic)
const groupType = message.type === 'human' ? 'human' : 'ai'
@@ -631,7 +637,7 @@ const Message = React.memo(function Message({
)
let thinkingElements = null
- const thinkingBlocks = getThinkingMessageFromResponse(message)
+ const thinkingBlocks = getThinkingMessageFromResponse(message, webSearchResultsByToolUseId)
if (thinkingBlocks) {
// Thinking should be collapsed (show "Thought") if:
// 1. The thread has finished streaming (thinking might be at the end), OR
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index 051b62037289..3f0661feee29 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -26,6 +26,7 @@ import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { uuid } from 'lib/utils/dom'
+import { objectsEqual } from 'lib/utils/objects'
import { billingLogic } from 'scenes/billing/billingLogic'
import { maxContextLogic } from 'scenes/max/maxContextLogic'
import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
@@ -70,9 +71,11 @@ import {
import {
attachedContextLogic,
getRandomThinkingMessage,
+ getWebSearchResultsByToolUseId,
isTerminalRunStatus,
INITIAL_PERMISSION_MODE,
runStreamLogic,
+ WebSearchResultsByToolUseId,
} from 'products/posthog_ai/frontend/api/logics'
import { LogEntry, parseLogEvent } from 'products/posthog_ai/frontend/lib/parse-logs'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
@@ -253,6 +256,7 @@ export interface maxThreadLogicValues {
threadRaw: ThreadMessage[]
toolCallUpdateMap: Map<string, string[]>
traceId: string | null
+ webSearchResultsByToolUseId: WebSearchResultsByToolUseId
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -662,6 +666,7 @@ export interface maxThreadLogicMeta {
currentThinkingMessage: string | null
) => ThreadMessage[]
threadMessageCount: (threadRaw: ThreadMessage[]) => number
+ webSearchResultsByToolUseId: (threadRaw: ThreadMessage[]) => WebSearchResultsByToolUseId
formPending: (threadRaw: ThreadMessage[]) => boolean
multiQuestionFormPending: (threadRaw: ThreadMessage[]) => boolean
activeMultiQuestionForm: (threadRaw: ThreadMessage[]) => MultiQuestionForm | null
@@ -2730,6 +2735,18 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
threadMessageCount: [(s) => [s.threadRaw], (threadRaw: ThreadMessage[]) => threadRaw.length],
+ webSearchResultsByToolUseId: [
+ (s) => [s.threadRaw],
+ (threadRaw: ThreadMessage[]): WebSearchResultsByToolUseId =>
+ getWebSearchResultsByToolUseId(
+ threadRaw.filter((message): message is AssistantMessage & ThreadMessage =>
+ isAssistantMessage(message)
+ )
+ ),
+ // Streaming replaces `threadRaw` on each chunk, so keep the reference stable to avoid rerendering every message.
+ { resultEqualityCheck: objectsEqual },
+ ],
+
formPending: [
(s) => [s.threadRaw],
(threadRaw: ThreadMessage[]) => {
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index 099849f5ea39..988bd4eb64d0 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -18,7 +18,13 @@ export { messageRatingsLogic } from '../logics/messageRatingsLogic'
export type { RunInteractionLogicProps, QueuedMessage } from '../logics/runInteractionLogic'
// --- Thinking-message helpers ---
-export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESSAGES } from '../utils/thinkingMessages'
+export {
+ getThinkingMessageFromResponse,
+ getRandomThinkingMessage,
+ getWebSearchResultsByToolUseId,
+ THINKING_MESSAGES,
+} from '../utils/thinkingMessages'
+export type { WebSearchResultsByToolUseId } from '../utils/thinkingMessages'
// --- Composer model/effort helpers (pure — no component imports) ---
export { resolveEffortForModel, DEFAULT_COMPOSER_MODEL, DEFAULT_COMPOSER_EFFORT } from '../utils/composerModels'
diff --git a/products/posthog_ai/frontend/utils/thinkingMessages.test.ts b/products/posthog_ai/frontend/utils/thinkingMessages.test.ts
new file mode 100644
index 000000000000..fcc217dfe3d1
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/thinkingMessages.test.ts
@@ -0,0 +1,61 @@
+import { AssistantMessage, AssistantMessageType } from '~/queries/schema/schema-assistant-messages'
+
+import { getThinkingMessageFromResponse, getWebSearchResultsByToolUseId } from './thinkingMessages'
+
+function message(thinking: Record<string, unknown>[]): AssistantMessage {
+ return { type: AssistantMessageType.Assistant, content: '', meta: { thinking } }
+}
+
+function toolUse(id: string): Record<string, unknown> {
+ return { type: 'server_tool_use', id, name: 'web_search', input: { query: id } }
+}
+
+function toolResult(toolUseId: string, content: unknown): Record<string, unknown> {
+ return { type: 'web_search_tool_result', tool_use_id: toolUseId, content }
+}
+
+const resultsFor = (name: string): { title: string; url: string }[] => [
+ { title: name, url: `https://example.com/${name}` },
+]
+
+describe('getThinkingMessageFromResponse', () => {
+ let consoleErrorSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore()
+ })
+
+ it.each([
+ {
+ case: 'result in the same message as its tool use',
+ messages: [message([toolUse('a'), toolResult('a', resultsFor('a'))])],
+ expected: [resultsFor('a')],
+ },
+ {
+ case: 'parallel searches, result in a later message than its tool use',
+ messages: [
+ message([toolUse('a')]),
+ message([toolUse('b'), toolResult('a', resultsFor('a')), toolResult('b', resultsFor('b'))]),
+ ],
+ expected: [resultsFor('a'), resultsFor('b')],
+ },
+ {
+ case: 'result still streaming',
+ messages: [message([toolUse('a'), toolResult('a', undefined)])],
+ expected: [undefined],
+ },
+ ])('attaches web search results for $case', ({ messages, expected }) => {
+ const threadResults = getWebSearchResultsByToolUseId(messages)
+ for (let render = 0; render < 2; render++) {
+ const results = messages
+ .flatMap((m) => getThinkingMessageFromResponse(m, threadResults))
+ .map((block) => (block.type === 'server_tool_use' ? block.results : null))
+ expect(results).toEqual(expected)
+ }
+ expect(consoleErrorSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/thinkingMessages.ts b/products/posthog_ai/frontend/utils/thinkingMessages.ts
index 4f11970ddfa8..891e7966606e 100644
--- a/products/posthog_ai/frontend/utils/thinkingMessages.ts
+++ b/products/posthog_ai/frontend/utils/thinkingMessages.ts
@@ -167,12 +167,17 @@ export const getRandomThinkingMessage = (): string => {
return THINKING_MESSAGES[randomIndex] + '...'
}
+interface WebSearchResult {
+ title: string
+ url: string
+}
+
interface ServerToolUseBlock {
type: 'server_tool_use'
name: string
input: Record<string, unknown>
id: string
- results?: { title: string; url: string }[]
+ results?: WebSearchResult[]
}
interface ThinkingBlock {
@@ -180,41 +185,54 @@ interface ThinkingBlock {
thinking: string
}
-export const getThinkingMessageFromResponse = (message: AssistantMessage): (ServerToolUseBlock | ThinkingBlock)[] => {
+export type WebSearchResultsByToolUseId = Record<string, WebSearchResult[]>
+
+/**
+ * Collects web search results by the ID of their `server_tool_use` block.
+ * The backend starts a new message at each `server_tool_use` block, so with parallel searches
+ * a result can arrive in a later message than its `server_tool_use` block.
+ */
+export const getWebSearchResultsByToolUseId = (messages: AssistantMessage[]): WebSearchResultsByToolUseId => {
+ const resultsByToolUseId: WebSearchResultsByToolUseId = {}
+ for (const message of messages) {
+ for (const block of message.meta?.thinking ?? []) {
+ // While a response streams, a result block can be incomplete.
+ if (
+ block.type === 'web_search_tool_result' &&
+ typeof block.tool_use_id === 'string' &&
+ Array.isArray(block.content)
+ ) {
+ resultsByToolUseId[block.tool_use_id] = block.content.map((content) => ({
+ title: content.title as string,
+ url: content.url as string,
+ }))
+ }
+ }
+ }
+ return resultsByToolUseId
+}
+
+export const getThinkingMessageFromResponse = (
+ message: AssistantMessage,
+ threadWebSearchResults?: WebSearchResultsByToolUseId
+): (ServerToolUseBlock | ThinkingBlock)[] => {
const thinkingMeta = message.meta?.thinking
if (!thinkingMeta) {
return []
}
+ const resultsByToolUseId = { ...threadWebSearchResults, ...getWebSearchResultsByToolUseId([message]) }
const blocks: (ServerToolUseBlock | ThinkingBlock)[] = []
- const toolUseIdToBlock: Record<string, ServerToolUseBlock> = {}
for (const block of thinkingMeta) {
if (block.type === 'thinking') {
blocks.push({ type: 'thinking', thinking: block.thinking as string })
} else if (block.type === 'server_tool_use') {
- toolUseIdToBlock[block.id as string] = {
+ blocks.push({
id: block.id as string,
type: 'server_tool_use',
name: block.name as string,
input: block.input as Record<string, unknown>,
- }
- blocks.push(toolUseIdToBlock[block.id as string])
- } else if (block.type === 'web_search_tool_result') {
- if (!Array.isArray(block.content)) {
- console.error('web_search_tool_result is not an array', block)
- continue // Making TypeScript happy
- }
- if (!toolUseIdToBlock[block.tool_use_id as string]) {
- console.error(
- 'tool_use_id not found - likely web_search was called in parallel with another tool',
- block,
- toolUseIdToBlock
- )
- continue
- }
- toolUseIdToBlock[block.tool_use_id as string].results = block.content.map((content) => ({
- title: content.title as string,
- url: content.url as string,
- }))
+ results: resultsByToolUseId[block.id as string],
+ })
} else if (block.type === 'reasoning') {
// OpenAI
blocks.push({ type: 'thinking', thinking: (block.summary as any[])[0].text as string })