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): stop reporting a finished turn for an idle sandbox resume (#102378)

Alessandro Pogliaghif64ca95f34a2
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 2acc175f48d9..0caf5af022e2 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -36,6 +36,8 @@ Follow-up messages collect in "Up next" and send after the first response finish
Once the agent starts, Steer can send them before the current turn ends.
The thread hides empty and whitespace-only assistant messages during streaming and history replay.
+An idle sandbox resume does not run an agent turn, so it does not send a finished notification or mark the run's activity completed.
+
The chat history filters for PostHog AI, Slack, and Desktop show tasks created by the current user.
These requests wait until the current user's ID is available, including filter changes, searches, and refreshes.
When the user loads, the pending request uses the active filter and search term.
diff --git a/ee/hogai/sandbox/__init__.py b/ee/hogai/sandbox/__init__.py
index ccca8487aa51..34ef0d4f39de 100644
--- a/ee/hogai/sandbox/__init__.py
+++ b/ee/hogai/sandbox/__init__.py
@@ -1,16 +1,20 @@
from ee.hogai.sandbox.types import (
+ IDLE_RESUME_STOP_REASON,
PI_RUNTIME_ERROR_MESSAGE,
STOP_REASON_END_TURN,
TURN_COMPLETE_METHOD,
+ is_idle_resume_turn_complete,
is_turn_complete,
pi_turn_error,
turn_complete_trace_id,
)
__all__ = [
+ "IDLE_RESUME_STOP_REASON",
"PI_RUNTIME_ERROR_MESSAGE",
"STOP_REASON_END_TURN",
"TURN_COMPLETE_METHOD",
+ "is_idle_resume_turn_complete",
"is_turn_complete",
"pi_turn_error",
"turn_complete_trace_id",
diff --git a/ee/hogai/sandbox/types.py b/ee/hogai/sandbox/types.py
index 208ac28628bd..b6e12960b1ba 100644
--- a/ee/hogai/sandbox/types.py
+++ b/ee/hogai/sandbox/types.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from collections.abc import Mapping
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict
@@ -13,6 +14,7 @@ TURN_COMPLETE_METHOD = "_posthog/turn_complete"
# Stop reasons
STOP_REASON_END_TURN = "end_turn"
+IDLE_RESUME_STOP_REASON = "idle_resume"
# pi agent event shapes
PI_EVENT_TYPE = "pi_event"
@@ -22,7 +24,7 @@ PI_STOP_REASON_ERROR = "error"
PI_RUNTIME_ERROR_MESSAGE = "The agent stopped with a runtime error"
-def is_turn_complete(event: dict) -> bool:
+def is_turn_complete(event: Mapping[str, object]) -> bool:
"""Check if a sandbox event signals the agent finished a turn.
Matches the raw ACP prompt response (``result.stopReason == "end_turn"``), the synthetic
@@ -37,13 +39,25 @@ def is_turn_complete(event: dict) -> bool:
return isinstance(pi_event, dict) and pi_event.get("type") == PI_TURN_COMPLETED_TYPE
if event.get("type") != ACP_NOTIFICATION_TYPE:
return False
- notification = event.get("notification", {})
+ notification = event.get("notification")
+ if not isinstance(notification, dict):
+ return False
if notification.get("method") == TURN_COMPLETE_METHOD:
return True
result = notification.get("result")
return isinstance(result, dict) and result.get("stopReason") == STOP_REASON_END_TURN
+def is_idle_resume_turn_complete(event: Mapping[str, object]) -> bool:
+ if event.get("type") != ACP_NOTIFICATION_TYPE:
+ return False
+ notification = event.get("notification")
+ if not isinstance(notification, dict) or notification.get("method") != TURN_COMPLETE_METHOD:
+ return False
+ params = notification.get("params")
+ return isinstance(params, dict) and params.get("stopReason") == IDLE_RESUME_STOP_REASON
+
+
def pi_turn_error(event: dict) -> bool:
"""True when a pi ``turn_completed`` event reports a terminal runtime failure.
@@ -59,7 +73,7 @@ def pi_turn_error(event: dict) -> bool:
return pi_event.get("stopReason") == PI_STOP_REASON_ERROR
-def turn_complete_trace_id(event: dict) -> str | None:
+def turn_complete_trace_id(event: Mapping[str, object]) -> str | None:
"""The finished turn's gateway trace id, when the agent reported one.
Only the synthetic ``_posthog/turn_complete`` notification carries it; the agent
@@ -67,7 +81,9 @@ def turn_complete_trace_id(event: dict) -> str | None:
on the turn's ``$ai_generation`` events. Absent for a turn that ran without the
traceparent hook, and for the raw ACP prompt response, which has no such field.
"""
- notification = event.get("notification") or {}
+ notification = event.get("notification")
+ if not isinstance(notification, dict):
+ return None
params = notification.get("params")
if not isinstance(params, dict):
return None
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index dcde203390f9..0467cd0a3d43 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -15,7 +15,7 @@ from products.tasks.backend.presentation.serializers import (
AgentProxyCallbackResponseSerializer,
TaskRunErrorResponseSerializer,
)
-from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
+from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
@@ -146,9 +146,7 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:
id=run_id, task_id=task_id, team_id=team_id
)
task_run.signal_agent_turn_completed()
- if task_run.mode == "interactive":
- notify_task_run_turn_completed(task_run)
- dispatched = True
+ dispatched = dispatch_task_run_turn_completed(task_run, turn_completed=data["turn_completed"])
except TaskRun.DoesNotExist:
logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
except Exception:
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 730aaae15814..46cd8d0ab4fb 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -32,9 +32,9 @@ from products.tasks.backend.logic.stream.redis_stream import (
)
from products.tasks.backend.metrics import observe_stream_write_skipped
from products.tasks.backend.models import TaskRun
-from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
+from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
-from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_turn_complete, pi_turn_error
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_idle_resume_turn_complete, is_turn_complete, pi_turn_error
logger = structlog.get_logger(__name__)
@@ -398,7 +398,7 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id
if pi_turn_error(event):
await _dispatch_turn_failed(run_id)
else:
- await _dispatch_turn_completed(run_id)
+ await _dispatch_turn_completed(run_id, turn_completed=not is_idle_resume_turn_complete(event))
return
if _is_session_update(event):
@@ -449,11 +449,11 @@ def _signal_agent_boot_milestone(
return task_run.signal_agent_boot_milestone(milestone)
-async def _dispatch_turn_completed(run_id: str) -> None:
- await sync_to_async(_dispatch_turn_completed_sync, thread_sensitive=True)(run_id)
+async def _dispatch_turn_completed(run_id: str, *, turn_completed: bool = True) -> None:
+ await sync_to_async(_dispatch_turn_completed_sync, thread_sensitive=True)(run_id, turn_completed=turn_completed)
-def _dispatch_turn_completed_sync(run_id: str) -> None:
+def _dispatch_turn_completed_sync(run_id: str, *, turn_completed: bool = True) -> None:
if not settings.TEST:
close_old_connections()
@@ -464,10 +464,7 @@ def _dispatch_turn_completed_sync(run_id: str) -> None:
return
task_run.signal_agent_turn_completed()
- if task_run.mode != "interactive":
- return
-
- notify_task_run_turn_completed(task_run)
+ dispatch_task_run_turn_completed(task_run, turn_completed=turn_completed)
async def _dispatch_turn_failed(run_id: str) -> None:
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index eecc8e7bffb2..3ba1b80314b6 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -359,6 +359,12 @@ TASK_RUN_WIZARD_UNBOUND_TOTAL = Counter(
labelnames=["status"],
)
+TURN_COMPLETED_SUPPRESSED_TOTAL = Counter(
+ "posthog_tasks_turn_completed_suppressed_total",
+ "Interactive turn completion notifications and activity updates suppressed by ingest",
+ labelnames=["reason"],
+)
+
PUSH_DISPATCHER_FAILURES_TOTAL = Counter(
"posthog_tasks_push_dispatcher_failures_total",
"Push-notification dispatch attempts that failed and were swallowed by the best-effort dispatcher",
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index e64d61c455c6..be77d349b422 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -4596,6 +4596,14 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):
"This is true for 'heartbeat' and 'agent_activity', and false otherwise."
),
)
+ turn_completed = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text=(
+ "Whether 'awaiting_input' reports a completed turn. Set false for an idle sandbox resume "
+ "to mark the agent idle without sending a completion notification or updating activity."
+ ),
+ )
task_id = serializers.CharField(
max_length=36,
help_text="UUID of the Task that owns this run. Must match the JWT claim.",
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
index 568da315a8b5..fbbb4bea37ba 100644
--- a/products/tasks/backend/push_dispatcher.py
+++ b/products/tasks/backend/push_dispatcher.py
@@ -31,7 +31,11 @@ from posthog.models.user import User
from posthog.models.user_push_token import UserPushToken
from posthog.tasks.push_notifications import send_user_push
-from products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL, PUSH_DISPATCHER_OUTCOMES_TOTAL
+from products.tasks.backend.metrics import (
+ PUSH_DISPATCHER_FAILURES_TOTAL,
+ PUSH_DISPATCHER_OUTCOMES_TOTAL,
+ TURN_COMPLETED_SUPPRESSED_TOTAL,
+)
from products.tasks.backend.models import Task, TaskPresence
from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.visibility import task_visibility_q
@@ -89,6 +93,16 @@ def notify_task_run_turn_completed(task_run: TaskRun) -> None:
_enqueue(task_run, kind="turn_completed", body=f'"{_task_title(task_run)}" finished')
+def dispatch_task_run_turn_completed(task_run: TaskRun, *, turn_completed: bool = True) -> bool:
+ if task_run.mode != "interactive":
+ return False
+ if not turn_completed:
+ TURN_COMPLETED_SUPPRESSED_TOTAL.labels(reason="idle_resume").inc()
+ return False
+ notify_task_run_turn_completed(task_run)
+ return True
+
+
def notify_task_handoff(task: Task, *, recipient: User, actor: User | None, message_id: UUID) -> None:
"""Fire a push notification when a task is handed off to ``recipient``.
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.py
index 221a45ccb1d1..07b81d36d619 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
@@ -37,6 +37,7 @@ from products.tasks.backend.models import (
Task as TaskModel,
TaskRun as TaskRunModel,
)
+from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeout
from products.tasks.backend.temporal.metrics import increment_tool_call_only_heartbeat
@@ -46,7 +47,13 @@ from products.tasks.backend.temporal.process_task.utils import (
is_slack_interaction_state,
)
-from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_turn_complete, pi_turn_error, turn_complete_trace_id
+from ee.hogai.sandbox import (
+ PI_RUNTIME_ERROR_MESSAGE,
+ is_idle_resume_turn_complete,
+ is_turn_complete,
+ pi_turn_error,
+ turn_complete_trace_id,
+)
logger = structlog.get_logger(__name__)
@@ -544,7 +551,13 @@ async def _relay_loop(
# Hop off the event loop because the turn-completion dispatcher
# performs sync Redis I/O and a potential network call to
# the feature-flag service.
- asyncio.create_task(asyncio.to_thread(_safe_dispatch_turn_completed, task_run))
+ asyncio.create_task(
+ asyncio.to_thread(
+ _safe_dispatch_turn_completed,
+ task_run,
+ turn_completed=not is_idle_resume_turn_complete(event_data),
+ )
+ )
if (
not turn_failed
and is_agent_design_enabled
@@ -984,7 +997,7 @@ def _is_terminal_event(event_data: dict) -> bool:
return method in TERMINAL_NOTIFICATION_METHODS
-def _safe_dispatch_turn_completed(task_run: TaskRunModel) -> None:
+def _safe_dispatch_turn_completed(task_run: TaskRunModel, *, turn_completed: bool = True) -> None:
"""Schedule a notification when an interactive run finishes a turn.
Must be called via ``asyncio.to_thread`` (as the caller does) because the
@@ -993,9 +1006,7 @@ def _safe_dispatch_turn_completed(task_run: TaskRunModel) -> None:
dispatch never bubbles into the relay loop.
"""
try:
- from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
-
- notify_task_run_turn_completed(task_run)
+ dispatch_task_run_turn_completed(task_run, turn_completed=turn_completed)
except Exception:
logger.warning(
"relay_sandbox_events_push_dispatch_failed",
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
index 121d6d5ffe50..7f37c19150bd 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
@@ -2,6 +2,7 @@ import json
import time
import asyncio
import importlib
+from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
@@ -12,6 +13,7 @@ import httpx
import httpx_sse
import temporalio.client
from parameterized import parameterized
+from prometheus_client import REGISTRY
from temporalio.exceptions import ApplicationError
from products.tasks.backend.models import Task, TaskRun
@@ -83,6 +85,9 @@ class TestIsTurnComplete:
{"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}},
True,
),
+ ("null_notification", {"type": "notification", "notification": None}, False),
+ ("scalar_notification", {"type": "notification", "notification": "turn_completed"}, False),
+ ("array_notification", {"type": "notification", "notification": []}, False),
]
)
def test_is_turn_complete(self, _name: str, event_data: dict, expected: bool):
@@ -857,8 +862,35 @@ class TestRelaySandboxEventsErrorHandling:
redis_stream.release_first_agent_activity.assert_not_awaited()
assert redis_stream.claim_first_agent_activity.await_count == 2
- async def test_relay_fails_the_run_instead_of_completing_it_on_a_pi_runtime_error(
- self, monkeypatch: pytest.MonkeyPatch
+ @pytest.mark.parametrize(
+ ("event", "turn_failed", "turn_completed"),
+ [
+ ({"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}}, True, False),
+ (
+ {"type": "notification", "notification": {"method": TURN_COMPLETE_METHOD}},
+ False,
+ True,
+ ),
+ (
+ {
+ "type": "notification",
+ "notification": {"method": TURN_COMPLETE_METHOD, "params": {"stopReason": "end_turn"}},
+ },
+ False,
+ True,
+ ),
+ (
+ {
+ "type": "notification",
+ "notification": {"method": TURN_COMPLETE_METHOD, "params": {"stopReason": "idle_resume"}},
+ },
+ False,
+ False,
+ ),
+ ],
+ )
+ async def test_relay_handles_turn_completion(
+ self, monkeypatch: pytest.MonkeyPatch, event: dict[str, object], turn_failed: bool, turn_completed: bool
) -> None:
redis_stream = SimpleNamespace(
write_event=AsyncMock(),
@@ -870,7 +902,7 @@ class TestRelaySandboxEventsErrorHandling:
release_first_agent_activity=AsyncMock(),
)
events = [
- {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}},
+ event,
{"type": "notification", "notification": {"method": "_posthog/task_complete"}},
]
@@ -899,6 +931,21 @@ class TestRelaySandboxEventsErrorHandling:
)
monkeypatch.setattr("posthog.temporal.common.client.async_connect", AsyncMock(return_value=client))
+ dispatch_done = asyncio.Event()
+
+ async def run_sync(func: Callable[..., object], *args: object, **kwargs: object) -> object:
+ result = func(*args, **kwargs)
+ dispatch_done.set()
+ return result
+
+ notify = MagicMock()
+ monkeypatch.setattr("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed", notify)
+ monkeypatch.setattr(relay_sandbox_events_module.asyncio, "to_thread", run_sync)
+ metric = "posthog_tasks_turn_completed_suppressed_total"
+ labels = {"reason": "idle_resume"}
+ suppressed_before = REGISTRY.get_sample_value(metric, labels) or 0
+ task_run = TaskRun(state={"mode": "interactive"})
+
await _relay_loop(
events_url="https://sandbox.example/events",
headers={"Authorization": "Bearer token"},
@@ -906,10 +953,21 @@ class TestRelaySandboxEventsErrorHandling:
redis_stream=cast(TaskRunRedisStream, redis_stream),
run_id="run-id",
task_id="task-id",
+ task_run=task_run,
)
- assert call("complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE]) in handle.signal.await_args_list
- assert call("agent_state_changed", arg=False) not in handle.signal.await_args_list
+ if turn_failed:
+ handle.signal.assert_awaited_once_with("complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE])
+ else:
+ await asyncio.wait_for(dispatch_done.wait(), timeout=5)
+ handle.signal.assert_awaited_once_with("agent_state_changed", arg=False)
+ if turn_completed:
+ notify.assert_called_once_with(task_run)
+ else:
+ notify.assert_not_called()
+ assert (REGISTRY.get_sample_value(metric, labels) or 0) - suppressed_before == int(
+ not turn_failed and not turn_completed
+ )
@parameterized.expand(
[
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
index e4d862813d94..dff434371e78 100644
--- a/products/tasks/backend/tests/test_agent_proxy_callback.py
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
from django.test import TestCase, override_settings
from parameterized import parameterized
+from prometheus_client import REGISTRY
from posthog.models import Organization, Team
@@ -160,21 +161,39 @@ class TestAgentProxyCallback(TestCase):
self.assertTrue(response.json()["dispatched"])
signal_milestone.assert_called_once_with(milestone)
- def test_awaiting_input_dispatches_for_interactive_run(self) -> None:
+ @parameterized.expand([("omitted", None), ("completed", True), ("idle_resume", False)])
+ def test_awaiting_input_dispatches_for_interactive_run(self, _name: str, turn_completed: bool | None) -> None:
run = self.task.create_run(mode="interactive")
- with patch("products.tasks.backend.agent_proxy_callback.notify_task_run_turn_completed") as notify:
+ body = self._body(kind="awaiting_input", agent_active=False)
+ if turn_completed is not None:
+ body["turn_completed"] = turn_completed
+ metric = "posthog_tasks_turn_completed_suppressed_total"
+ labels = {"reason": "idle_resume"}
+ suppressed_before = REGISTRY.get_sample_value(metric, labels) or 0
+ with (
+ patch("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed") as notify,
+ patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed,
+ ):
response = self._post(
- self._body(kind="awaiting_input", agent_active=False),
+ body,
token=self._token(run),
run_id=str(run.id),
)
self.assertEqual(response.status_code, 200)
- self.assertTrue(response.json()["dispatched"])
- notify.assert_called_once()
+ self.assertEqual(response.json()["dispatched"], turn_completed is not False)
+ signal_turn_completed.assert_called_once()
+ if turn_completed is False:
+ notify.assert_not_called()
+ else:
+ notify.assert_called_once()
+ self.assertEqual(
+ (REGISTRY.get_sample_value(metric, labels) or 0) - suppressed_before,
+ int(turn_completed is False),
+ )
def test_awaiting_input_signals_turn_end_but_skips_push_for_background_run(self) -> None:
with (
- patch("products.tasks.backend.agent_proxy_callback.notify_task_run_turn_completed") as notify,
+ patch("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed") as notify,
patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed,
):
response = self._post(self._body(kind="awaiting_input", agent_active=False), token=self._token())
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index ef420ab679d8..4f0020f28b06 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -393,17 +393,22 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(body["accepted"], 1)
self.assertEqual(self._read_notification_methods(), ["session/update"])
+ @parameterized.expand([("omitted", None), ("completed", "end_turn"), ("idle_resume", "idle_resume")])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_turn_complete_ingest_notifies_interactive_run(self) -> None:
+ def test_turn_complete_ingest_notifies_interactive_run(self, _name: str, stop_reason: str | None) -> None:
self.task.created_by = User.objects.create_user("[email protected]", None, "Ingest")
self.task.save(update_fields=["created_by"])
self.task_run.state = {"mode": "interactive"}
self.task_run.save(update_fields=["state"])
token = self._create_token()
- with patch(
- "products.tasks.backend.logic.stream.event_ingest.notify_task_run_turn_completed"
- ) as notify_turn_completed:
+ metric = "posthog_tasks_turn_completed_suppressed_total"
+ labels = {"reason": "idle_resume"}
+ suppressed_before = REGISTRY.get_sample_value(metric, labels) or 0
+ with (
+ patch("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed") as notify_turn_completed,
+ patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed,
+ ):
status, body = self._call_ingest(
token,
[
@@ -411,7 +416,10 @@ class TestTaskRunEventIngest(TestCase):
"seq": 1,
"event": {
"type": "notification",
- "notification": {"method": "_posthog/turn_complete"},
+ "notification": {
+ "method": "_posthog/turn_complete",
+ "params": {"stopReason": stop_reason} if stop_reason else {},
+ },
},
}
],
@@ -419,8 +427,16 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(status, 200)
self.assertEqual(body["accepted"], 1)
- notify_turn_completed.assert_called_once()
- self.assertEqual(notify_turn_completed.call_args.args[0].id, self.task_run.id)
+ signal_turn_completed.assert_called_once()
+ if stop_reason == "idle_resume":
+ notify_turn_completed.assert_not_called()
+ else:
+ notify_turn_completed.assert_called_once()
+ self.assertEqual(notify_turn_completed.call_args.args[0].id, self.task_run.id)
+ self.assertEqual(
+ (REGISTRY.get_sample_value(metric, labels) or 0) - suppressed_before,
+ int(stop_reason == "idle_resume"),
+ )
@parameterized.expand(
[
diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.ts
index 7040272ffc2f..b44c786aaf2d 100644
--- a/services/agent-proxy/src/lib/side-effects.ts
+++ b/services/agent-proxy/src/lib/side-effects.ts
@@ -21,6 +21,7 @@ import type { SideEffectKind } from './types.js'
const ACP_NOTIFICATION_TYPE = 'notification'
const TURN_COMPLETE_METHOD = '_posthog/turn_complete'
const STOP_REASON_END_TURN = 'end_turn'
+const IDLE_RESUME_STOP_REASON = 'idle_resume'
const ACP_METHOD_SESSION_UPDATE = 'session/update'
const AGENT_COMMAND_DISPATCHED_METHOD = '_posthog/agent_command_dispatched'
const ACP_GENERATION_UPDATES = new Set([
@@ -91,6 +92,26 @@ export function isPiTurnError(event: Record<string, unknown>): boolean {
return piTurnCompleted !== null && piTurnCompleted['stopReason'] === PI_STOP_REASON_ERROR
}
+export function isIdleResumeTurnComplete(event: Record<string, unknown>): boolean {
+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {
+ return false
+ }
+ const notification = event['notification']
+ if (typeof notification !== 'object' || notification === null) {
+ return false
+ }
+ const notif = notification as Record<string, unknown>
+ if (notif['method'] !== TURN_COMPLETE_METHOD) {
+ return false
+ }
+ const params = notif['params']
+ return (
+ typeof params === 'object' &&
+ params !== null &&
+ (params as Record<string, unknown>)['stopReason'] === IDLE_RESUME_STOP_REASON
+ )
+}
+
// isSessionUpdate mirrors event_ingest.py:_is_session_update exactly.
export function isSessionUpdate(event: Record<string, unknown>): boolean {
if (event['type'] !== ACP_NOTIFICATION_TYPE) {
@@ -188,8 +209,9 @@ function fireCallback(
teamId: number,
originalToken: string,
config: Config,
- releaseClaim?: () => Promise<void>
+ options: { releaseClaim?: () => Promise<void>; turnCompleted?: boolean } = {}
): void {
+ const { releaseClaim, turnCompleted } = options
if (!config.djangoCallbackBaseUrl) {
// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.
void releaseMilestoneClaim(releaseClaim, runId, kind)
@@ -197,7 +219,13 @@ function fireCallback(
}
const url = `${config.djangoCallbackBaseUrl}/internal/tasks/runs/${runId}/agent-proxy-callback/`
- const body = JSON.stringify({ kind, agent_active: agentActive, task_id: taskId, team_id: teamId })
+ const body = JSON.stringify({
+ kind,
+ agent_active: agentActive,
+ task_id: taskId,
+ team_id: teamId,
+ turn_completed: turnCompleted,
+ })
const headers: Record<string, string> = {
'Content-Type': 'application/json',
@@ -278,13 +306,13 @@ export async function heartbeatWorkflowIfNeeded(
config: Config
): Promise<void> {
if (isAgentCommandDispatched(event) && (await redisStream.claimFirstAgentCommand())) {
- fireCallback(runId, 'command_dispatched', false, taskId, teamId, originalToken, config, () =>
- redisStream.releaseFirstAgentCommand()
- )
+ fireCallback(runId, 'command_dispatched', false, taskId, teamId, originalToken, config, {
+ releaseClaim: () => redisStream.releaseFirstAgentCommand(),
+ })
} else if (isAgentGenerationEvent(event) && (await redisStream.claimFirstAgentActivity())) {
- fireCallback(runId, 'agent_activity', true, taskId, teamId, originalToken, config, () =>
- redisStream.releaseFirstAgentActivity()
- )
+ fireCallback(runId, 'agent_activity', true, taskId, teamId, originalToken, config, {
+ releaseClaim: () => redisStream.releaseFirstAgentActivity(),
+ })
}
if (isTurnComplete(event)) {
@@ -296,7 +324,9 @@ export async function heartbeatWorkflowIfNeeded(
} else {
// Let Django decide whether the run is interactive; it will only
// dispatch the push notification for interactive mode runs.
- fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config)
+ fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config, {
+ turnCompleted: !isIdleResumeTurnComplete(event),
+ })
}
return
}
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index 5f66376cd5a8..34f9c7b65212 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -1065,7 +1065,11 @@ describe('ingest-handler', () => {
// Side effects: turn-complete
// -----------------------------------------------------------------------
- it('sets agent inactive and fires awaiting_input callback on turn-complete event', async () => {
+ it.each([
+ ['omitted', {}, true],
+ ['completed', { stopReason: 'end_turn' }, true],
+ ['idle_resume', { stopReason: 'idle_resume' }, false],
+ ])('sets agent inactive and reports completion for %s turn-complete', async (_name, params, turnCompleted) => {
const fetchCalls: { url: string; body: unknown }[] = []
const originalFetch = global.fetch
global.fetch = vi.fn(async (url, init) => {
@@ -1078,8 +1082,9 @@ describe('ingest-handler', () => {
const turnCompleteEvent = {
type: 'notification',
- notification: { method: '_posthog/turn_complete' },
+ notification: { method: '_posthog/turn_complete', params },
}
+ await redisStream.setAgentActive(true)
const ndjson = JSON.stringify({ seq: 1, event: turnCompleteEvent }) + '\n'
const ctx = makeContext({ body: makeStringBody(ndjson) })
const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
@@ -1094,7 +1099,11 @@ describe('ingest-handler', () => {
const callbackCall = fetchCalls.find((c) => c.url.includes('agent-proxy-callback'))
expect(callbackCall).toBeTruthy()
- expect(callbackCall?.body).toMatchObject({ kind: 'awaiting_input', agent_active: false })
+ expect(callbackCall?.body).toMatchObject({
+ kind: 'awaiting_input',
+ agent_active: false,
+ turn_completed: turnCompleted,
+ })
global.fetch = originalFetch
})