: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(tasks): capture agent state at termination (#85316)
Alessandro Pogliaghi9a668410db81
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 3535089ba754..713a339a5e71 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -448,6 +448,8 @@ async def _relay_loop(if _is_end_of_turn(event_data):agent_active[0] = False+ if workflow_handle is not None:+ await _signal_safely(workflow_handle, "agent_state_changed", arg=False)if sandbox_id and background_logs_enabled:asyncio.create_task(_emit_agentsh_events(sandbox_id, run_id, last_audit_ts_ns))if task_run is not None and task_run.mode == "interactive":@@ -467,6 +469,8 @@ async def _relay_loop(await asyncio.to_thread(_persist_final_message, run_id, final_text)elif not agent_active[0] and _is_active_agent_update(event_data):agent_active[0] = True+ if workflow_handle is not None:+ await _signal_safely(workflow_handle, "agent_state_changed", arg=True)# Agent-design signal fan-out: first session/update opens the# child relay; tool_call → step, agent_message_chunk → markdown.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.pyindex e8b161274c40..62d000ae9df6 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@@ -229,11 +229,20 @@ class TestUpdateTaskRunStatusActivity:status=status,timed_out_inactivity=timed_out_inactivity,timeout_marker=timeout_marker,+ agent_active_at_termination=False,+ end_of_turn_received=True,+ last_agent_heartbeat_at="2026-08-19T10:00:00+00:00",+ seconds_since_last_agent_heartbeat=1800.0,)async_to_sync(activity_environment.run)(update_task_run_status, input_data)captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == expected_event]- assert captured[0].kwargs["properties"]["termination_reason"] == expected_reason+ properties = captured[0].kwargs["properties"]+ assert properties["termination_reason"] == expected_reason+ assert properties["agent_active_at_termination"] is False+ assert properties["end_of_turn_received"] is True+ assert properties["last_agent_heartbeat_at"] == "2026-08-19T10:00:00+00:00"+ assert properties["seconds_since_last_agent_heartbeat"] == 1800.0@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(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.pyindex b00a2e4cd20a..fa9be8eda9a0 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@@ -35,7 +35,7 @@ _TERMINAL_STATE_MARKERS = (_TERMINAL_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)-@dataclass+@dataclass(frozen=False)class UpdateTaskRunStatusInput:run_id: strstatus: str@@ -47,6 +47,10 @@ class UpdateTaskRunStatusInput:# One of _TERMINAL_STATE_MARKERS, recorded as a True key in TaskRun.state.# Optional with a default for the same in-flight payload reason as error_type.timeout_marker: Optional[str] = None+ agent_active_at_termination: Optional[bool] = None+ end_of_turn_received: Optional[bool] = None+ last_agent_heartbeat_at: Optional[str] = None+ seconds_since_last_agent_heartbeat: Optional[float] = None@activity.defn@@ -149,10 +153,20 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInptry:marker = TIMED_OUT_INACTIVITY_STATE_KEY if input.timed_out_inactivity else input.timeout_markertermination_reason = marker if marker in _TERMINAL_STATE_MARKERS else None+ relay_state = {+ "agent_active_at_termination": input.agent_active_at_termination,+ "end_of_turn_received": input.end_of_turn_received,+ "last_agent_heartbeat_at": input.last_agent_heartbeat_at,+ "seconds_since_last_agent_heartbeat": input.seconds_since_last_agent_heartbeat,+ }if input.status == TaskRun.Status.COMPLETED:task_run.capture_event("task_run_completed",- {"duration_seconds": task_run._duration_seconds(), "termination_reason": termination_reason},+ {+ "duration_seconds": task_run._duration_seconds(),+ "termination_reason": termination_reason,+ **relay_state,+ },)else:task_run.capture_event(@@ -162,6 +176,7 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInp"error_type": input.error_type or "unspecified","duration_seconds": task_run._duration_seconds(),"termination_reason": termination_reason,+ **relay_state,},)diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex fe662035e989..3d42feab4148 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -2356,6 +2356,16 @@ class TestContinueAsNew:wf._context = ctxreturn wf+ async def test_agent_state_tracks_end_of_turn(self) -> None:+ workflow_instance = ProcessTaskWorkflow()++ await workflow_instance.agent_state_changed(True)+ assert workflow_instance._agent_active is True+ assert workflow_instance._end_of_turn_received is False++ await workflow_instance.agent_state_changed(False)+ assert (workflow_instance._agent_active, workflow_instance._end_of_turn_received) == (False, True)+def test_build_and_restore_round_trips_loop_state(self, monkeypatch) -> None:chain_start = datetime(2026, 7, 16, 9, 0, tzinfo=UTC)monkeypatch.setattr(@@ -2371,6 +2381,9 @@ class TestContinueAsNew:wf._first_user_message_received = Truewf._is_agent_design_enabled = Truewf._last_active_time = datetime(2026, 7, 16, 10, 30, tzinfo=UTC)+ wf._agent_active = False+ wf._end_of_turn_received = True+ wf._last_agent_heartbeat_at = datetime(2026, 7, 16, 10, 29, tzinfo=UTC)wf._slack_thread_context = {"channel": "C1"}wf._posthog_mcp_scopes = "full"@@ -2394,6 +2407,9 @@ class TestContinueAsNew:assert restored._is_agent_design_enabled is True# The datetime survives the ISO round-trip.assert restored._last_active_time == datetime(2026, 7, 16, 10, 30, tzinfo=UTC)+ assert restored._agent_active is False+ assert restored._end_of_turn_received is True+ assert restored._last_agent_heartbeat_at == datetime(2026, 7, 16, 10, 29, tzinfo=UTC)# The wall-clock cap anchors on the chain start, so the first execution seeds it from# its own start_time and every later continuation carries that same value forward.assert restored._chain_started_at == chain_startdiff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 2b2da61cee70..8f9a5c3b76a2 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -147,7 +147,7 @@ def _message_dedupe_key(return f"{actor_user_id or ''}:{actor_slack_user_id}:{message_id}"-@dataclass+@dataclass(frozen=False)class ResumedSandboxState:"""Loop state carried across continue_as_new to re-attach without re-provisioning."""@@ -167,6 +167,9 @@ class ResumedSandboxState:# ISO8601 start of the whole continue_as_new chain, so the wall-clock cap is not# reset by a continuation. None on payloads written before this field existed.chain_started_at: Optional[str] = None+ agent_active: Optional[bool] = None+ end_of_turn_received: Optional[bool] = None+ last_agent_heartbeat_at: Optional[str] = None@dataclass@@ -376,6 +379,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):# reason a run ended stays machine-readable without abusing error_message.self._completion_timeout_marker: Optional[str] = Noneself._heartbeat_received: bool = False+ self._agent_active: Optional[bool] = None+ self._end_of_turn_received: Optional[bool] = None+ self._last_agent_heartbeat_at: Optional[datetime] = Noneself._prewarmed: bool = Falseself._first_user_message_received: bool = Falseself._sandbox_gone: bool = False@@ -1354,6 +1360,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):last_active_time=self._last_active_time.isoformat() if self._last_active_time else None,accepted_message_ids=self._accepted_message_ids,chain_started_at=self._chain_start_time().isoformat(),+ agent_active=self._agent_active,+ end_of_turn_received=self._end_of_turn_received,+ last_agent_heartbeat_at=(+ self._last_agent_heartbeat_at.isoformat() if self._last_agent_heartbeat_at else None+ ),),)@@ -1378,6 +1389,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._accepted_message_ids = resumed.accepted_message_idsself._accepted_message_id_set = set(resumed.accepted_message_ids)self._last_active_time = datetime.fromisoformat(resumed.last_active_time) if resumed.last_active_time else None+ self._agent_active = resumed.agent_active+ self._end_of_turn_received = resumed.end_of_turn_received+ self._last_agent_heartbeat_at = (+ datetime.fromisoformat(resumed.last_agent_heartbeat_at) if resumed.last_agent_heartbeat_at else None+ )async def _get_task_processing_context(self, input: ProcessTaskInput) -> TaskProcessingContext:context = await workflow.execute_activity(@@ -2049,6 +2065,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):error_type: Optional[str] = None,timeout_marker: Optional[str] = None,) -> None:+ seconds_since_last_agent_heartbeat = (+ (workflow.now() - self._last_agent_heartbeat_at).total_seconds() if self._last_agent_heartbeat_at else None+ )await workflow.execute_activity(update_task_run_status,UpdateTaskRunStatusInput(@@ -2058,6 +2077,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):timed_out_inactivity=timed_out_inactivity,error_type=error_type,timeout_marker=timeout_marker,+ agent_active_at_termination=self._agent_active,+ end_of_turn_received=self._end_of_turn_received,+ last_agent_heartbeat_at=(+ self._last_agent_heartbeat_at.isoformat() if self._last_agent_heartbeat_at else None+ ),+ seconds_since_last_agent_heartbeat=seconds_since_last_agent_heartbeat,),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),@@ -2414,8 +2439,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):async def heartbeat(self, agent_active: bool = False) -> None:if not agent_active:return+ now = workflow.now()self._heartbeat_received = True- self._last_active_time = workflow.now()+ self._last_active_time = now+ self._last_agent_heartbeat_at = now++ @temporalio.workflow.signal+ async def agent_state_changed(self, agent_active: bool) -> None:+ self._agent_active = agent_active+ self._end_of_turn_received = not agent_active@temporalio.workflow.signalasync def send_followup_message(