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(phai): capture PostHog AI chat outcomes from the sandbox runtime (#88532)

Georgiy Tarasovfc795e82e71a
diff --git a/ee/hogai/chat_agent/runner.py b/ee/hogai/chat_agent/runner.py
index d7ce6872c4e6..58c75c71531b 100644
--- a/ee/hogai/chat_agent/runner.py
+++ b/ee/hogai/chat_agent/runner.py
@@ -190,5 +190,8 @@ class ChatAgentRunner(BaseAgentRunner):
"slack_workspace_domain": self._conversation.slack_workspace_domain,
"$session_id": self._session_id,
"agent_mode": self._selected_agent_mode,
+ # The sandbox runtime emits this same event when its run terminalizes. Without a
+ # runtime tag the two halves of every series are indistinguishable.
+ "agent_runtime": "langgraph",
},
)
diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.py
index d10ac947dab2..e66307c59968 100644
--- a/products/posthog_ai/backend/message_routing.py
+++ b/products/posthog_ai/backend/message_routing.py
@@ -312,6 +312,7 @@ class SandboxSession(BaseSandboxService):
initial_permission_mode=initial_permission_mode,
interaction_origin=POSTHOG_AI_INTERACTION_ORIGIN,
pending_user_message=wrapped,
+ converted_from_langgraph=convert_to_acp,
)
state_updates = ph_state.model_dump(mode="json", by_alias=True, exclude_unset=True)
# Persist the enriched run state and conversation linkage together, under the row lock so a
diff --git a/products/posthog_ai/backend/run_state.py b/products/posthog_ai/backend/run_state.py
index 766bf9624fc2..4f31d2aeea33 100644
--- a/products/posthog_ai/backend/run_state.py
+++ b/products/posthog_ai/backend/run_state.py
@@ -30,3 +30,7 @@ class PostHogAIRunState(RunState):
# (``state__await_user_message=True`` in products/tasks/backend/logic/services/warm.py), so an alias
# here would change the stored key and silently stop the filter from matching — opening the cap.
await_user_message: bool = False
+ # Set on the first Run of a conversation that moved here from the LangGraph runtime. The
+ # conversation carries its history across the flip, so its chat analytics must not report it
+ # as a new one (products/tasks/.../update_task_run_status.py reads this key).
+ converted_from_langgraph: bool = False
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index d65d04448ff8..e30d8773c21b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
import pytest
from unittest.mock import patch
@@ -5,7 +7,7 @@ from asgiref.sync import async_to_sync
from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
-from products.tasks.backend.models import Loop, TaskRun
+from products.tasks.backend.models import Loop, Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
SANDBOX_GONE_STATE_KEY,
TIMED_OUT_INACTIVITY_STATE_KEY,
@@ -313,12 +315,122 @@ class TestUpdateTaskRunStatusActivity:
@pytest.mark.django_db(transaction=True)
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_repeated_terminal_update_does_not_double_capture(self, mock_capture, activity_environment, test_task_run):
+ test_task_run.task.origin_product = Task.OriginProduct.POSTHOG_AI
+ test_task_run.task.save(update_fields=["origin_product"])
input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.COMPLETED)
async_to_sync(activity_environment.run)(update_task_run_status, input_data)
async_to_sync(activity_environment.run)(update_task_run_status, input_data)
completed = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_completed"]
assert len(completed) == 1
+ chats = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "chat with ai"]
+ assert len(chats) == 1
+
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "origin_product,status,expected_event",
+ [
+ (Task.OriginProduct.POSTHOG_AI, TaskRun.Status.COMPLETED, "chat with ai"),
+ (Task.OriginProduct.POSTHOG_AI, TaskRun.Status.FAILED, "chat with ai failed"),
+ (Task.OriginProduct.USER_CREATED, TaskRun.Status.COMPLETED, None),
+ (Task.OriginProduct.USER_CREATED, TaskRun.Status.FAILED, None),
+ ],
+ )
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_posthog_ai_chat_outcome_is_captured_per_origin_and_status(
+ self, mock_capture, activity_environment, test_task_run, origin_product, status, expected_event
+ ):
+ test_task_run.task.origin_product = origin_product
+ test_task_run.task.save(update_fields=["origin_product"])
+
+ async_to_sync(activity_environment.run)(
+ update_task_run_status,
+ UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=status,
+ error_message="boom" if status == TaskRun.Status.FAILED else None,
+ ),
+ )
+
+ chats = [c for c in mock_capture.call_args_list if str(c.kwargs.get("event", "")).startswith("chat with ai")]
+ if expected_event is None:
+ assert chats == []
+ return
+ assert [c.kwargs["event"] for c in chats] == [expected_event]
+ props = chats[0].kwargs["properties"]
+ assert props["agent_runtime"] == "sandbox"
+ assert props["agent_mode"] is None
+ assert props["is_new_conversation"] is True
+ if status == TaskRun.Status.FAILED:
+ assert props["error_message"] == "boom"
+
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "predecessor_state,run_state,expected_is_new",
+ [
+ # An earlier run that held a chat continues the conversation.
+ ({}, {}, False),
+ # An earlier prewarm nobody typed into does not — the next message resumes into a
+ # successor, so counting it would report the first real chat as a continuation.
+ ({"prewarmed": True, "await_user_message": True}, {}, True),
+ # A conversation carried over from LangGraph is continued, however little sandbox
+ # history it has: the conversion starts it on a fresh task with no earlier run.
+ (None, {"converted_from_langgraph": True}, False),
+ (None, {}, True),
+ ],
+ )
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_prior_history_decides_whether_a_conversation_is_new(
+ self, mock_capture, activity_environment, test_task_run, predecessor_state, run_state, expected_is_new
+ ):
+ test_task_run.task.origin_product = Task.OriginProduct.POSTHOG_AI
+ test_task_run.task.save(update_fields=["origin_product"])
+ if run_state:
+ test_task_run.state = run_state
+ test_task_run.save(update_fields=["state", "updated_at"])
+ if predecessor_state is not None:
+ predecessor = TaskRun.objects.create(
+ task=test_task_run.task,
+ team=test_task_run.team,
+ status=TaskRun.Status.COMPLETED,
+ state=predecessor_state,
+ )
+ # `created_at` is auto_now_add, so pin the ordering rather than trusting two inserts
+ # microseconds apart.
+ TaskRun.objects.filter(id=predecessor.id).update(created_at=test_task_run.created_at - timedelta(seconds=1))
+
+ async_to_sync(activity_environment.run)(
+ update_task_run_status,
+ UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.COMPLETED),
+ )
+
+ chats = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "chat with ai"]
+ assert len(chats) == 1
+ assert chats[0].kwargs["properties"]["is_new_conversation"] is expected_is_new
+
+ @pytest.mark.django_db(transaction=True)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_a_prewarm_nobody_typed_into_is_not_a_chat(self, mock_capture, activity_environment, test_task_run):
+ test_task_run.task.origin_product = Task.OriginProduct.POSTHOG_AI
+ test_task_run.task.title = ""
+ test_task_run.task.description = ""
+ test_task_run.task.save(update_fields=["origin_product", "title", "description", "updated_at"])
+ test_task_run.state = {"prewarmed": True, "await_user_message": True}
+ test_task_run.save(update_fields=["state", "updated_at"])
+
+ async_to_sync(_run_update_task_run_status)(
+ activity_environment,
+ UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=TaskRun.Status.COMPLETED,
+ timed_out_inactivity=True,
+ ),
+ )
+
+ events = [c.kwargs.get("event") for c in mock_capture.call_args_list]
+ assert not [e for e in events if str(e).startswith("chat with ai")]
+ # Only the chat reading is suppressed — the run still completed, and still reports it.
+ assert "task_run_completed" in events
@pytest.mark.django_db(transaction=True)
def test_terminal_retry_completes_loop_bookkeeping_exactly_once(self, activity_environment, test_task_run):
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index 31d6f9098e4d..1283d841b649 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -1,7 +1,8 @@
from dataclasses import dataclass
-from typing import Optional
+from typing import Any, Optional
from django.db import transaction
+from django.db.models import Q
from django.utils import timezone
from temporalio import activity
@@ -11,7 +12,7 @@ from posthog.temporal.common.utils import asyncify
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.metrics import observe_prewarmed_unused_if_never_activated, observe_wizard_run_unbound
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.metrics import record_run_token_usage
from products.tasks.backend.temporal.observability import log_with_activity_context
@@ -153,6 +154,75 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
)
+def _capture_posthog_ai_chat_analytics(
+ task_run: TaskRun, input: UpdateTaskRunStatusInput, *, termination_reason: Optional[str]
+) -> None:
+ """Emit the PostHog AI chat outcome events, the sandbox counterpart to legacy `chat with ai`.
+
+ PostHog AI usage series are built on `chat with ai`, which only the LangGraph runner emits
+ (`ee/hogai/chat_agent/runner.py`). A sandbox conversation never reaches that runner, so without
+ this the series decay to zero as conversations move over.
+
+ This sits on the run transition rather than on each turn, so it fires only once the outcome is
+ known. A run spans every turn its sandbox stays alive, so the event counts runs where the legacy
+ one counted turns — `usage_turns` carries the turn count for a series that needs it.
+ """
+ if task_run.task.origin_product != Task.OriginProduct.POSTHOG_AI:
+ return
+ state = task_run.state if isinstance(task_run.state, dict) else {}
+ if state.get("await_user_message"):
+ # A prewarmed sandbox that idled out before anyone typed into it. The inactivity timeout
+ # terminalizes it as completed, so without this guard, opening the panel and walking away
+ # counts as a chat. PostHog AI removes the key when it delivers the first message; that
+ # removal is best-effort, so a failed one drops a real chat rather than inventing one.
+ return
+ properties = {
+ "agent_runtime": "sandbox",
+ # Agent modes are a LangGraph concept, and the sandbox runtime has none.
+ "agent_mode": None,
+ "is_new_conversation": _is_first_chat_run_of_task(task_run, state),
+ "duration_seconds": task_run._duration_seconds(),
+ "termination_reason": termination_reason,
+ }
+ if input.status == TaskRun.Status.COMPLETED:
+ task_run.capture_event("chat with ai", properties)
+ return
+ task_run.capture_event(
+ "chat with ai failed",
+ {
+ **properties,
+ "error_message": truncate_error_message(input.error_message or task_run.error_message),
+ "error_type": input.error_type or "unspecified",
+ },
+ )
+
+
+def _is_first_chat_run_of_task(task_run: TaskRun, state: dict[str, Any]) -> bool:
+ """Whether this run opened the conversation, the run-level reading of `is_new_conversation`.
+
+ A terminal run resumes into a successor rather than reopening, so "no earlier run" is what
+ separates a new conversation from a continued one. Two kinds of earlier history do not count:
+
+ - A prewarm nobody typed into. It idles out on its own and the next message resumes into a
+ successor, so counting it would report the user's first real chat as a continuation.
+ - The LangGraph half of a converted conversation. That conversation already counted once on
+ the legacy runtime, and its sandbox side starts on a fresh task with no earlier run.
+ """
+ if state.get("converted_from_langgraph"):
+ return False
+ # Match the prewarm on the key's absence rather than with `exclude`. A queryset `exclude` on a
+ # JSON key compares NULL for every row that lacks the key, so it would drop exactly the earlier
+ # runs that did hold a chat and report every conversation as new.
+ held_a_chat = ~Q(state__has_key="await_user_message") | Q(state__await_user_message=False)
+ return (
+ not TaskRun.objects.filter(
+ task_id=task_run.task_id, team_id=task_run.team_id, created_at__lt=task_run.created_at
+ )
+ .filter(held_a_chat)
+ .exists()
+ )
+
+
def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInput) -> None:
"""Emit the terminal analytics event and token-expenditure metrics.
@@ -191,6 +261,8 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInp
},
)
+ _capture_posthog_ai_chat_analytics(task_run, input, termination_reason=termination_reason)
+
state = task_run.state if isinstance(task_run.state, dict) else {}
usage = state.get("token_usage")
if isinstance(usage, dict):