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(tasks): preserve parent responses across sub-agent updates (#128117)

Georgiy Tarasovfce74d5f61af
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index b40fde15058e..753fc0020d22 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -1069,6 +1069,23 @@ class TurnLogState:
refused: bool
+def _is_subagent_update(update: dict[str, object]) -> bool:
+ # Older Codex adapters omit parent metadata on updates but namespace child tool IDs.
+ tool_call_id = update.get("toolCallId")
+ if isinstance(tool_call_id, str) and tool_call_id.startswith("subagent:"):
+ return True
+ meta = update.get("_meta")
+ if not isinstance(meta, dict):
+ return False
+ for channel in ("posthog", "claudeCode"):
+ metadata = meta.get(channel)
+ if isinstance(metadata, dict):
+ parent = metadata.get("parentToolCallId")
+ if isinstance(parent, str) and parent:
+ return True
+ return False
+
+
def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:
"""
Parse S3 logs. When skip_lines > 0, only lines after that offset are inspected for end_turn
@@ -1135,6 +1152,10 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:
update = params.get("update") if isinstance(params, dict) else None
if not isinstance(update, dict):
continue
+ # Child activity can interleave with a parent's streamed answer without ending it.
+ # Child text must not become part of the response the caller validates either.
+ if _is_subagent_update(update):
+ continue
parsed_updates.append(update)
# Walk backwards from the end to find the final agent response.
# First, skip non-agent entries (e.g. usage_update) to find the last
@@ -1145,13 +1166,11 @@ def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:
found_agent_msg = False
for update in reversed(parsed_updates):
is_agent_msg = update.get("sessionUpdate") in _AGENT_MSG_TYPES
- if not found_agent_msg:
- if is_agent_msg:
- found_agent_msg = True
- else:
- continue
- if found_agent_msg and not is_agent_msg:
- break
+ if not is_agent_msg:
+ if found_agent_msg:
+ break
+ continue
+ found_agent_msg = True
text = _extract_text(update)
if text:
trailing_parts.append(text)
diff --git a/products/tasks/backend/tests/test_check_logs.py b/products/tasks/backend/tests/test_check_logs.py
index 87d9d25ae128..997a530d3f84 100644
--- a/products/tasks/backend/tests/test_check_logs.py
+++ b/products/tasks/backend/tests/test_check_logs.py
@@ -1,26 +1,88 @@
+import json
+
import pytest
from unittest.mock import patch
+from parameterized import parameterized
+
from products.tasks.backend.logic.services.custom_prompt_internals import _check_logs, _stream_new_lines
from products.tasks.backend.tests.agent_log_fixtures import (
FakeTaskRun,
_agent_message_line,
_end_turn_line,
_refusal_line,
+ _tool_call_line,
_usage_update_line,
_user_message_line,
)
class TestCheckLogs:
- def test_returns_agent_message_when_both_present(self):
- log = "\n".join([_agent_message_line("hello"), _end_turn_line()])
+ @parameterized.expand(
+ [
+ ("contiguous", None, None),
+ ("child_tool", "tool_call", "claudeCode"),
+ ("canonical_child_tool", "tool_call", "posthog"),
+ ("codex_child_tool_update", "tool_call_update", None),
+ ("child_tool_update", "tool_call_update", "claudeCode"),
+ ("child_plan", "plan", "posthog"),
+ ("child_message", "agent_message", "claudeCode"),
+ ("child_message_chunk", "agent_message_chunk", "posthog"),
+ ]
+ )
+ def test_returns_complete_parent_message(
+ self, _name: str, update_kind: str | None, metadata_channel: str | None
+ ) -> None:
+ child_lines = []
+ if update_kind is not None:
+ child_lines = [
+ json.dumps(
+ {
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": update_kind,
+ "toolCallId": "child-call" if metadata_channel else "subagent:worker:lookup",
+ "_meta": {metadata_channel: {"parentToolCallId": "child-task"}}
+ if metadata_channel
+ else {},
+ "content": {"type": "text", "text": "child answer"},
+ }
+ },
+ }
+ }
+ )
+ ]
+ log = "\n".join(
+ [
+ _agent_message_line("Searching"),
+ _tool_call_line(),
+ _agent_message_line('{"value": "'),
+ *child_lines,
+ _agent_message_line('complete"}'),
+ *child_lines,
+ _end_turn_line(),
+ ]
+ )
with patch("posthog.storage.object_storage.read", return_value=log):
state = _check_logs(FakeTaskRun())
assert state.agent_finished is True
- assert state.last_message == "hello"
+ assert state.last_message == '{"value": "complete"}'
assert state.empty_end_turn is False
+ @parameterized.expand([("tool_call",), ("tool_call_update",), ("plan",), ("user_message",)])
+ def test_parent_updates_still_separate_messages(self, update_kind: str) -> None:
+ boundary = json.dumps(
+ {"notification": {"method": "session/update", "params": {"update": {"sessionUpdate": update_kind}}}}
+ )
+ log = "\n".join(
+ [_agent_message_line("Earlier commentary"), boundary, _agent_message_line("Final answer"), _end_turn_line()]
+ )
+ with patch("posthog.storage.object_storage.read", return_value=log):
+ state = _check_logs(FakeTaskRun())
+ assert state.last_message == "Final answer"
+
def test_end_turn_without_agent_message_flags_empty_end_turn(self):
"""Regression: when skip_lines puts us past the agent_message but end_turn
is in the new lines, _check_logs must NOT rescan from 0 and return a