:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ph-ai): add client-executed tool round trip for contextual tools (#63311)
Carlos Marchal87ce2b9e949b
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex 65b8628bc0c1..c49b334d6c8b 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -45,7 +45,7 @@ from products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.core.ai_event_truncation import ai_event_truncatorfrom ee.hogai.core.base import BaseAssistantGraphfrom ee.hogai.core.stream_processor import AssistantStreamProcessorProtocol-from ee.hogai.tool import ApprovalRequest+from ee.hogai.tool import ApprovalRequest, ClientToolCallRequestfrom ee.hogai.utils.exceptions import (AGENT_RUN_UNHANDLED_ERROR_COUNTER,HTTPX_TRANSPORT_EXCEPTIONS,@@ -466,6 +466,10 @@ class BaseAgentRunner(ABC):# No need to yield a message here - the form will be displayed to the user through the tool call args# and the answers comes through the tool call result ui_payloadshould_not_update_state = True+ elif isinstance(interrupt.value, ClientToolCallRequest):+ # Nothing to stream (the tool call args are already in the thread); skipping+ # the state update lets an abandoned round trip start fresh, like approvals+ should_not_update_state = Trueelif isinstance(interrupt.value, ApprovalRequest):# Check if this is an ApprovalRequest from interrupt() in a toolshould_not_update_state = Truediff --git a/ee/hogai/core/test/test_runner.py b/ee/hogai/core/test/test_runner.pyindex aa5a81aa68a1..fec924f7fea2 100644--- a/ee/hogai/core/test/test_runner.py+++ b/ee/hogai/core/test/test_runner.py@@ -15,6 +15,7 @@ from posthog.schema import AssistantEventType, FailureMessagefrom products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.core.base import BaseAssistantGraph+from ee.hogai.tool import ClientToolCallRequestfrom ee.hogai.utils.types.base import AssistantState, ConversationTitleAction, PartialAssistantState@@ -741,3 +742,84 @@ class TestRunnerConversationTitleAction(BaseTest):self.assertEqual(len(conversation_events), 1)_, conversation = conversation_events[0]self.assertEqual(conversation.title, "Streamed Title")+++class TestRunnerClientToolCallInterrupt(BaseTest):+ """+ A ClientToolCallRequest interrupt must stream nothing and leave graph state untouched,+ so the frontend handler can resume it with a payload (or a new human message can abandon+ it and start fresh).+ """++ def setUp(self):+ super().setUp()+ self.conversation = Conversation.objects.create(team=self.team, user=self.user)++ def _create_runner_with_interrupt(self, interrupt_value):+ from ee.hogai.core.runner import BaseAgentRunner++ async def empty_stream():+ return+ yield++ mock_graph = MagicMock()+ mock_graph.astream = MagicMock(return_value=empty_stream())+ mock_state = MagicMock()+ mock_state.values = {}+ mock_state.next = ["pending_node"]+ mock_state.tasks = [MagicMock(interrupts=[MagicMock(value=interrupt_value)])]+ mock_graph.aget_state = AsyncMock(return_value=mock_state)+ mock_graph.aupdate_state = AsyncMock()++ mock_stream_processor = MagicMock()+ mock_stream_processor.mark_id_as_streamed = MagicMock()++ class TestRunner(BaseAgentRunner):+ def get_initial_state(self):+ return AssistantState(messages=[])++ def get_resumed_state(self):+ return PartialAssistantState(messages=[])++ runner = TestRunner(+ team=self.team,+ conversation=self.conversation,+ user=self.user,+ graph_class=cast(type[BaseAssistantGraph], mock_graph),+ state_type=AssistantState,+ partial_state_type=PartialAssistantState,+ stream_processor=mock_stream_processor,+ use_checkpointer=True,+ )+ runner._graph = mock_graph+ return runner, mock_graph++ async def _collect_message_events(self, runner):+ with (+ patch.object(runner, "_init_or_update_state", new_callable=AsyncMock, return_value=None),+ patch.object(runner, "_lock_conversation", return_value=mock_lock_conversation()),+ ):+ results = []+ async for event_type, payload in runner.astream(+ stream_message_chunks=False, stream_first_message=False, stream_only_assistant_messages=True+ ):+ results.append((event_type, payload))+ return [payload for event_type, payload in results if event_type == AssistantEventType.MESSAGE]++ async def test_streams_nothing_and_skips_state_update(self):+ runner, mock_graph = self._create_runner_with_interrupt(+ ClientToolCallRequest(tool_name="create_form", original_tool_call_id="call_1")+ )++ messages = await self._collect_message_events(runner)++ self.assertEqual(messages, [])+ mock_graph.aupdate_state.assert_not_called()++ async def test_string_interrupt_still_streams_message_and_updates_state(self):+ runner, mock_graph = self._create_runner_with_interrupt("Please clarify your request")++ messages = await self._collect_message_events(runner)++ self.assertTrue(any(getattr(m, "content", None) == "Please clarify your request" for m in messages))+ mock_graph.aupdate_state.assert_called_once()diff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.pyindex 7d29aaa2312b..cb0782cd56d1 100644--- a/ee/hogai/test/test_tool.py+++ b/ee/hogai/test/test_tool.py@@ -1,13 +1,14 @@from posthog.test.base import BaseTestfrom unittest.mock import patch+from langgraph.errors import GraphInterruptfrom pydantic import BaseModelfrom posthog.rbac.user_access_control import UserAccessControlfrom ee.hogai.core.context import set_node_pathfrom ee.hogai.registry import CONTEXTUAL_TOOL_NAME_TO_TOOL, _import_max_tools-from ee.hogai.tool import MaxTool+from ee.hogai.tool import ClientToolCallRequest, MaxToolfrom ee.hogai.tool_errors import (MaxToolAccessDeniedError,MaxToolError,@@ -123,6 +124,76 @@ class TestMaxToolNodePath(BaseTest):self.assertEqual(result[2].name, "max_tool.read_taxonomy")+class TestMaxToolClientExecution(BaseTest):+ def _create_tool(self) -> DummyTool:+ return DummyTool(+ team=self.team,+ user=self.user,+ node_path=(NodePath(name="root", tool_call_id="call_123", message_id="msg_1"),),+ )++ def test_interrupts_with_client_tool_call_request(self):+ tool = self._create_tool()++ with patch("ee.hogai.tool.interrupt") as mock_interrupt:+ mock_interrupt.side_effect = GraphInterrupt()++ with self.assertRaises(GraphInterrupt):+ tool.request_client_execution()++ request = mock_interrupt.call_args.args[0]+ self.assertIsInstance(request, ClientToolCallRequest)+ self.assertEqual(request.tool_name, "read_taxonomy")+ self.assertEqual(request.original_tool_call_id, "call_123")++ def test_returns_client_result_verbatim(self):+ tool = self._create_tool()++ with patch("ee.hogai.tool.interrupt") as mock_interrupt:+ mock_interrupt.return_value = {+ "action": "client_tool_result",+ "result": {"valid": False, "error": "no rule matched"},+ }++ result = tool.request_client_execution()++ self.assertEqual(result, {"valid": False, "error": "no rule matched"})++ def test_raises_retryable_error_on_invalid_resume_payload(self):+ tool = self._create_tool()++ with patch("ee.hogai.tool.interrupt") as mock_interrupt:+ mock_interrupt.return_value = {"action": "approve", "proposal_id": "prop_1"}++ with self.assertRaises(MaxToolRetryableError):+ tool.request_client_execution()++ def test_accepts_result_addressed_to_this_tool_call(self):+ tool = self._create_tool()++ with patch("ee.hogai.tool.interrupt") as mock_interrupt:+ mock_interrupt.return_value = {+ "action": "client_tool_result",+ "tool_call_id": "call_123",+ "result": {"ok": True},+ }++ self.assertEqual(tool.request_client_execution(), {"ok": True})++ def test_raises_retryable_error_on_result_for_a_different_tool_call(self):+ tool = self._create_tool()++ with patch("ee.hogai.tool.interrupt") as mock_interrupt:+ mock_interrupt.return_value = {+ "action": "client_tool_result",+ "tool_call_id": "call_999",+ "result": {"ok": True},+ }++ with self.assertRaises(MaxToolRetryableError):+ tool.request_client_execution()++class TestMaxToolErrorHierarchy(BaseTest):"""Test the MaxToolError exception hierarchy and retry strategies."""diff --git a/ee/hogai/tool.py b/ee/hogai/tool.pyindex cb1979205803..2606ea0128c1 100644--- a/ee/hogai/tool.py+++ b/ee/hogai/tool.py@@ -13,7 +13,7 @@ from langchain_core.tools import BaseToolfrom langgraph.types import interruptfrom pydantic import BaseModel, ValidationError-from posthog.schema import ApprovalResumePayload, AssistantTool+from posthog.schema import ApprovalResumePayload, AssistantTool, ClientToolResultPayloadfrom posthog.models import Team, Userfrom posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl@@ -55,6 +55,17 @@ class ApprovalRequest(BaseModel):original_tool_call_id: str | None = None+class ClientToolCallRequest(BaseModel):+ """Interrupt payload when a tool hands execution to its client-side handler.++ Nothing is streamed: the frontend detects the pending call from the thread, runs the+ registered handler, and resumes with a ClientToolResultPayload.+ """++ tool_name: str+ original_tool_call_id: str | None = None++class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):# LangChain's default is just "content", but we always want to return the tool call artifact too# - it becomes the `ui_payload`@@ -403,6 +414,24 @@ class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):None,)+ def request_client_execution(self) -> dict[str, Any]:+ """Pause the graph until this tool's frontend handler resumes the conversation.++ The handler receives this tool call's arguments. Returns the handler's result dict;+ validate its domain shape in the calling tool.+ """+ response = interrupt(+ ClientToolCallRequest(tool_name=self.name, original_tool_call_id=self._original_tool_call_id)+ )+ try:+ payload = ClientToolResultPayload.model_validate(response)+ except ValidationError as e:+ raise MaxToolRetryableError(f"Invalid client tool result: {e}")+ # All interrupts pending in one superstep receive the same resume value — fail loudly on misdelivery+ if payload.tool_call_id and self._original_tool_call_id and payload.tool_call_id != self._original_tool_call_id:+ raise MaxToolRetryableError("The client tool result was addressed to a different tool call")+ return payload.result+def _reconstruct_kwargs_from_payload(self, payload: dict) -> dict:"""Reconstruct kwargs from stored payload (Pydantic deserialization)."""args_schema = getattr(self, "args_schema", None)diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 18e8abe82883..827979672b72 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -11747,6 +11747,26 @@"required": ["bytes_read", "rows_read", "estimated_rows_total", "time_elapsed", "active_cpu_time"],"type": "object"},+ "ClientToolResultPayload": {+ "additionalProperties": false,+ "properties": {+ "action": {+ "const": "client_tool_result",+ "type": "string"+ },+ "result": {+ "additionalProperties": {},+ "description": "Result produced by the tool's client-side handler, returned verbatim to the tool awaiting it",+ "type": "object"+ },+ "tool_call_id": {+ "description": "Tool call id this result answers — echoed back so misdelivery fails loudly instead of silently",+ "type": "string"+ }+ },+ "required": ["action", "result"],+ "type": "object"+ },"CohortPropertyFilter": {"additionalProperties": false,"description": "Sync with nodejs/src/types.ts",@@ -37319,6 +37339,9 @@},{"$ref": "#/definitions/FormDismissPayload"+ },+ {+ "$ref": "#/definitions/ClientToolResultPayload"}]},diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex 4c197b77ea8b..5393c8a4c49b 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -189,7 +189,15 @@ export interface FormDismissPayload {action: 'dismiss_form'}-export type ResumePayload = ApprovalResumePayload | FormResumePayload | FormDismissPayload+export interface ClientToolResultPayload {+ action: 'client_tool_result'+ /** Tool call id this result answers — echoed back so misdelivery fails loudly instead of silently */+ tool_call_id?: string+ /** Result produced by the tool's client-side handler, returned verbatim to the tool awaiting it */+ result: Record<string, unknown>+}++export type ResumePayload = ApprovalResumePayload | FormResumePayload | FormDismissPayload | ClientToolResultPayloadexport interface AssistantMessageMetadata {form?: AssistantFormdiff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 8e9b52a1b169..a4ea2f161d74 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -80,6 +80,11 @@ export interface ToolDefinition<N extends string = string> {alpha?: boolean/** Agent modes this tool is available in (defined in backend presets) */modes?: AgentMode[]+ /**+ * Set for tools using ToolRegistration.clientExecution, so a pending call is resumed with+ * a refusal (instead of stranded) after the owning view deregistered the handler.+ */+ clientExecuted?: boolean}/** Active instance of a tool. */@@ -117,6 +122,13 @@ export interface ToolRegistration extends Pick<ToolDefinition, 'name' | 'descripsuggestions?: string[]/** The callback function that will be executed with the LLM's tool call output */callback?: (toolOutput: any, conversationId: string) => void | Promise<void>+ /**+ * Optional: executes part of the tool client-side. Runs with the tool call's arguments when+ * the backend pauses via `MaxTool.request_client_execution()`; the returned result resumes+ * the conversation and becomes that call's return value. Keep results small (verdicts, ids):+ * they ride a Temporal resume payload capped at ~2MiB.+ */+ clientExecution?: (args: Record<string, any>) => Promise<Record<string, unknown>>}export interface RecordingsWidgetDef {diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 1a7e3b50f758..2ed6cfc0002a 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -30,7 +30,7 @@ import {import { initKeaTests } from '~/test/init'import { Conversation, ConversationDetail, ConversationStatus, ConversationType } from '~/types'-import { EnhancedToolCall } from './max-constants'+import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'import { maxContextLogic } from './maxContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { maxLogic } from './maxLogic'@@ -914,6 +914,159 @@ describe('maxThreadLogic', () => {})})+ describe('client tool execution round trip', () => {+ const pendingClientToolThread = (): any[] => [+ {+ type: AssistantMessageType.Human,+ content: 'Do the thing',+ id: 'human-1',+ status: 'completed',+ },+ {+ type: AssistantMessageType.Assistant,+ content: '',+ id: 'assistant-1',+ status: 'completed',+ tool_calls: [{ id: 'tc-1', name: 'search', args: { payload: 'data' } }],+ },+ ]++ it('runs the registered handler and resumes with its result, even while conversationLoading is still true', async () => {+ const streamSpy = mockStream()+ const clientExecution = jest.fn().mockResolvedValue({ ok: true })+ maxGlobalLogic().actions.registerTool({+ identifier: 'search',+ name: 'Search PostHog data',+ clientExecution,+ } as any)+ // The round trip must fire even though conversationLoading is still true at this point+ logic.actions.setConversation(MOCK_IN_PROGRESS_CONVERSATION)+ logic.actions.setThread(pendingClientToolThread())++ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['executePendingClientToolCall', 'continueWithClientToolResult', 'streamConversation'])++ expect(clientExecution).toHaveBeenCalledWith({ payload: 'data' })+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ content: null,+ conversation: MOCK_CONVERSATION_ID,+ resume_payload: {+ action: 'client_tool_result',+ tool_call_id: 'tc-1',+ result: { ok: true },+ },+ }),+ expect.any(Object)+ )+ })++ it('resumes with a refusal when a statically-marked client tool has no registered handler', async () => {+ const streamSpy = mockStream()+ logic.actions.setThread(pendingClientToolThread())++ TOOL_DEFINITIONS['search'].clientExecuted = true+ try {+ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['continueWithClientToolResult'])+ } finally {+ delete TOOL_DEFINITIONS['search'].clientExecuted+ }++ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ resume_payload: expect.objectContaining({+ action: 'client_tool_result',+ tool_call_id: 'tc-1',+ result: { client_execution_error: expect.stringContaining('no longer open') },+ }),+ }),+ expect.any(Object)+ )+ })++ it('attempts the resume only once per tool call', async () => {+ mockStream()+ const clientExecution = jest.fn().mockResolvedValue({ ok: true })+ maxGlobalLogic().actions.registerTool({+ identifier: 'search',+ name: 'Search PostHog data',+ clientExecution,+ } as any)+ logic.actions.setThread(pendingClientToolThread())++ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['continueWithClientToolResult'])+ // A failing resume turn re-fires completeThreadGeneration with the same dangling call+ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['executePendingClientToolCall'])+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(clientExecution).toHaveBeenCalledTimes(1)+ })++ it('drops the resume when a newer turn replaced the pending call while the handler ran', async () => {+ const streamSpy = mockStream()+ let resolveHandler: (value: Record<string, unknown>) => void = () => {}+ const clientExecution = jest+ .fn()+ .mockImplementation(() => new Promise<Record<string, unknown>>((resolve) => (resolveHandler = resolve)))+ maxGlobalLogic().actions.registerTool({+ identifier: 'search',+ name: 'Search PostHog data',+ clientExecution,+ } as any)+ logic.actions.setThread(pendingClientToolThread())++ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['executePendingClientToolCall'])+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(clientExecution).toHaveBeenCalled()++ // A user message completes a whole new turn while the handler runs — resume must be dropped+ logic.actions.setThread([+ ...pendingClientToolThread(),+ { type: AssistantMessageType.Human, content: 'Never mind', id: 'human-2', status: 'completed' },+ { type: AssistantMessageType.Assistant, content: 'OK!', id: 'assistant-2', status: 'completed' },+ ] as any)+ resolveHandler({ ok: true })+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(streamSpy).not.toHaveBeenCalled()+ })++ it('does nothing when the turn has no pending client tool call', async () => {+ const streamSpy = mockStream()+ const clientExecution = jest.fn()+ maxGlobalLogic().actions.registerTool({+ identifier: 'search',+ name: 'Search PostHog data',+ clientExecution,+ } as any)+ logic.actions.setThread([+ {+ type: AssistantMessageType.Assistant,+ content: 'All done!',+ id: 'assistant-1',+ status: 'completed',+ } as any,+ ])++ await expectLogic(logic, () => {+ logic.actions.completeThreadGeneration()+ }).toDispatchActions(['executePendingClientToolCall'])+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(clientExecution).not.toHaveBeenCalled()+ expect(streamSpy).not.toHaveBeenCalled()+ })+ })+describe('traceId functionality', () => {it('sets and stores traceId correctly', async () => {const testTraceId = 'test-trace-id-123'diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex b8d7e492ce16..1c84c43e372f 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -68,7 +68,7 @@ import { LogEntry, parseLogEvent } from 'products/tasks/frontend/lib/parse-logs'import { handsFreeLogic } from './handsFreeLogic'import { summariseAssistantThread } from './handsFreeUtils'-import { EnhancedToolCall, MODE_DEFINITIONS, ToolRegistration } from './max-constants'+import { EnhancedToolCall, MODE_DEFINITIONS, TOOL_DEFINITIONS, ToolRegistration } from './max-constants'import { MaxBillingContext, MaxBillingContextSubscriptionLevel, maxBillingContextLogic } from './maxBillingContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'@@ -77,6 +77,7 @@ import { MaxUIContext } from './maxTypes'import { MAX_SLASH_COMMANDS, SlashCommand } from './slash-commands'import { getToolCallDescriptionAndWidgetDef } from './toolCallDisplay'import {+ findPendingClientToolCall,getAgentModeForScene,isAssistantMessage,isAssistantToolCallMessage,@@ -265,6 +266,8 @@ export const maxThreadLogic = kea<maxThreadLogicType>([formAnswers,}),continueAfterFormDismissal: true,+ continueWithClientToolResult: (result: Record<string, unknown>, toolCallId: string) => ({ result, toolCallId }),+ executePendingClientToolCall: true,continueAfterApproval: (proposalId: string) => ({ proposalId }),continueAfterRejection: (proposalId: string, feedback?: string) => ({proposalId,@@ -1216,6 +1219,8 @@ export const maxThreadLogic = kea<maxThreadLogicType>([},completeThreadGeneration: () => {+ actions.executePendingClientToolCall()+const handsFree = handsFreeLogic.findMounted({ panelId: props.panelId })if (handsFree?.values.isActive) {handsFree.actions.speakAssistantResponse(summariseAssistantThread(values.threadRaw))@@ -1361,6 +1366,73 @@ export const maxThreadLogic = kea<maxThreadLogicType>([false // Don't add to thread - no human message to show)},+ executePendingClientToolCall: async () => {+ // Guard on streamingActive, not threadLoading: conversationLoading is still true here+ // because completeThreadGeneration resets the status after dispatching this action+ if (values.conversationId !== values.activeThreadKey || values.streamingActive) {+ return+ }+ // Include statically-marked tools so a deregistered handler refuses instead of stranding the call+ const clientToolNames = new Set([+ ...Object.values(values.toolMap)+ .filter((tool) => tool.clientExecution)+ .map((tool) => tool.identifier as string),+ ...Object.entries(TOOL_DEFINITIONS)+ .filter(([, definition]) => definition.clientExecuted)+ .map(([name]) => name),+ ])+ const pending = findPendingClientToolCall(values.threadRaw, clientToolNames)+ if (!pending) {+ return+ }+ // One attempt per call: a failing resume turn re-fires completeThreadGeneration with+ // the same dangling call, which would re-run the handler's side effects unboundedly+ cache.resumedClientToolCallIds ??= new Set<string>()+ if (cache.resumedClientToolCallIds.has(pending.toolCallId)) {+ return+ }+ cache.resumedClientToolCallIds.add(pending.toolCallId)+ const handler = values.toolMap[pending.toolName]?.clientExecution+ let result: Record<string, unknown>+ if (!handler) {+ result = {+ client_execution_error:+ 'The PostHog view that executes this tool client-side is no longer open, so the call could not be completed.',+ }+ } else {+ try {+ result = (await handler(pending.args)) ?? {}+ } catch (error) {+ result = { client_execution_error: String(error) }+ }+ }+ // A user message during the handler abandons the interrupt server-side — drop the+ // resume unless the same call is still dangling+ const stillPending = findPendingClientToolCall(values.threadRaw, clientToolNames)+ if (+ values.conversationId !== values.activeThreadKey ||+ values.streamingActive ||+ stillPending?.toolCallId !== pending.toolCallId+ ) {+ return+ }+ actions.continueWithClientToolResult(result, pending.toolCallId)+ },+ continueWithClientToolResult: ({ result, toolCallId }) => {+ actions.streamConversation(+ {+ agent_mode: values.isSandboxMode ? null : values.agentMode,+ is_sandbox: values.isSandboxMode || undefined,+ content: null,+ conversation: values.conversationId,+ // Refresh tool context so the resumed generation sees state the handler just changed+ contextual_tools: Object.fromEntries(values.tools.map((tool) => [tool.identifier, tool.context])),+ resume_payload: { action: 'client_tool_result', tool_call_id: toolCallId, result },+ },+ 0,+ false // Don't add to thread - no human message to show+ )+ },continueAfterApproval: ({ proposalId }) => {actions.clearQueuedMessages()// Persist the approved status so the card can display itdiff --git a/frontend/src/scenes/max/useMaxTool.ts b/frontend/src/scenes/max/useMaxTool.tsindex cb1ff92e6bde..271fb57d10f0 100644--- a/frontend/src/scenes/max/useMaxTool.ts+++ b/frontend/src/scenes/max/useMaxTool.ts@@ -38,6 +38,7 @@ export function useMaxTool({contextDescription,introOverride,callback,+ clientExecution,suggestions,active = true,initialMaxPrompt,@@ -63,6 +64,7 @@ export function useMaxTool({introOverride,suggestions,callback,+ clientExecution,})return (): void => deregisterTool(identifier)}@@ -75,6 +77,7 @@ export function useMaxTool({introOverride,suggestions,callback,+ clientExecution,registerTool,deregisterTool,])diff --git a/frontend/src/scenes/max/utils.test.ts b/frontend/src/scenes/max/utils.test.tsindex ab806d169f75..7a2bd975ec34 100644--- a/frontend/src/scenes/max/utils.test.ts+++ b/frontend/src/scenes/max/utils.test.ts@@ -6,7 +6,7 @@ import {} from '~/queries/schema/schema-assistant-messages'import { EnhancedToolCall } from './max-constants'-import { isMultiQuestionFormMessage, threadEndsWithMultiQuestionForm } from './utils'+import { findPendingClientToolCall, isMultiQuestionFormMessage, threadEndsWithMultiQuestionForm } from './utils'describe('max/utils', () => {describe('isMultiQuestionFormMessage()', () => {@@ -212,4 +212,73 @@ describe('max/utils', () => {expect(threadEndsWithMultiQuestionForm(messages)).toBe(false)})})++ describe('findPendingClientToolCall()', () => {+ const clientToolNames = new Set(['my_client_tool'])++ const humanMessage = (content: string): RootAssistantMessage =>+ ({ type: AssistantMessageType.Human, content }) as unknown as RootAssistantMessage++ const toolResultMessage = (toolCallId: string): RootAssistantMessage =>+ ({+ type: AssistantMessageType.ToolCall,+ tool_call_id: toolCallId,+ content: 'done',+ }) as unknown as RootAssistantMessage++ const assistantMessageWithCall = (id: string, name = 'my_client_tool'): RootAssistantMessage =>+ ({+ type: AssistantMessageType.Assistant,+ content: '',+ tool_calls: [{ id, name, args: { payload: 'data' } }],+ }) as unknown as RootAssistantMessage++ it('finds a dangling client tool call at the end of the thread', () => {+ const pending = findPendingClientToolCall([assistantMessageWithCall('tc-1')], clientToolNames)++ expect(pending).toEqual({+ toolName: 'my_client_tool',+ toolCallId: 'tc-1',+ args: { payload: 'data' },+ })+ })++ it('finds a dangling client tool call even when a sibling tool result lands after it', () => {+ const messages = [+ humanMessage('Set up a parser'),+ assistantMessageWithCall('tc-1'),+ toolResultMessage('tc-other'), // a parallel server-side tool finished after+ ]++ expect(findPendingClientToolCall(messages, clientToolNames)?.toolCallId).toBe('tc-1')+ })++ it('returns null when the client tool call already has a result message', () => {+ const messages = [assistantMessageWithCall('tc-1'), toolResultMessage('tc-1')]++ expect(findPendingClientToolCall(messages, clientToolNames)).toBeNull()+ })++ it('ignores dangling calls from previous turns', () => {+ // An abandoned call followed by a new human message starts a fresh turn.+ const messages = [+ assistantMessageWithCall('tc-1'),+ humanMessage('Never mind, do something else'),+ { type: AssistantMessageType.Assistant, content: 'Sure!' } as unknown as RootAssistantMessage,+ ]++ expect(findPendingClientToolCall(messages, clientToolNames)).toBeNull()+ })++ it('returns null for tools that are not client-executed', () => {+ const messages = [assistantMessageWithCall('tc-2', 'create_form')]++ expect(findPendingClientToolCall(messages, clientToolNames)).toBeNull()+ })++ it('returns null for an empty thread or a thread ending with a human message', () => {+ expect(findPendingClientToolCall([], clientToolNames)).toBeNull()+ expect(findPendingClientToolCall([humanMessage('Hello')], clientToolNames)).toBeNull()+ })+ })})diff --git a/frontend/src/scenes/max/utils.ts b/frontend/src/scenes/max/utils.tsindex 66bf2b797ccb..12fbcb9384c4 100644--- a/frontend/src/scenes/max/utils.ts+++ b/frontend/src/scenes/max/utils.ts@@ -121,6 +121,41 @@ export function threadEndsWithMultiQuestionForm(messages: RootAssistantMessage[]return false}+export interface PendingClientToolCall {+ toolName: string+ toolCallId: string+ args: Record<string, any>+}++// A client tool call is pending when the current turn contains it with no result message.+// The whole turn is scanned, not just the last message: a sibling server-side tool's result+// may land after the assistant message carrying the client call.+export function findPendingClientToolCall(+ messages: RootAssistantMessage[],+ clientToolNames: Set<string>+): PendingClientToolCall | null {+ const lastHumanIndex = messages.findLastIndex(isHumanMessage)+ const currentTurn = messages.slice(lastHumanIndex + 1)++ const completedToolCallIds = new Set<string>()+ for (const message of messages) {+ if (message.type === AssistantMessageType.ToolCall && 'tool_call_id' in message) {+ completedToolCallIds.add((message as { tool_call_id: string }).tool_call_id)+ }+ }+ for (const message of currentTurn) {+ if (!isAssistantMessage(message) || !message.tool_calls?.length) {+ continue+ }+ for (const toolCall of message.tool_calls) {+ if (clientToolNames.has(toolCall.name) && !completedToolCallIds.has(toolCall.id)) {+ return { toolName: toolCall.name, toolCallId: toolCall.id, args: toolCall.args ?? {} }+ }+ }+ }+ return null+}+export function castAssistantQuery(query: AnyAssistantGeneratedQuery | QuerySchemaRoot | null): QuerySchemaRoot | null {if (query) {return query as QuerySchemaRootdiff --git a/posthog/schema.py b/posthog/schema.pyindex 53ba1d2bf98e..cf27fdce5f17 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -818,6 +818,21 @@ class ChartSettingsFormatting(BaseModel):suffix: str | None = None+class ClientToolResultPayload(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ action: Literal["client_tool_result"] = "client_tool_result"+ result: dict[str, Any] = Field(+ ...,+ description=("Result produced by the tool's client-side handler, returned verbatim to the tool awaiting it"),+ )+ tool_call_id: str | None = Field(+ default=None,+ description=("Tool call id this result answers — echoed back so misdelivery fails loudly instead of silently"),+ )++class CompareFilter(BaseModel):model_config = ConfigDict(extra="forbid",@@ -5871,8 +5886,10 @@ class ResultCustomization(RootModel[ResultCustomizationByValue | ResultCustomizaroot: ResultCustomizationByValue | ResultCustomizationByPosition-class ResumePayload(RootModel[ApprovalResumePayload | FormResumePayload | FormDismissPayload]):- root: ApprovalResumePayload | FormResumePayload | FormDismissPayload+class ResumePayload(+ RootModel[ApprovalResumePayload | FormResumePayload | FormDismissPayload | ClientToolResultPayload]+):+ root: ApprovalResumePayload | FormResumePayload | FormDismissPayload | ClientToolResultPayloadclass RetentionResult(BaseModel):