: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
fix(tasks): forward turn success from the agent-proxy callback (#108247)
Alessandro Pogliaghie7707272d2e5
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.pyindex 144f80a88dd3..68196e42e3a8 100644--- a/products/tasks/backend/agent_proxy_callback.py+++ b/products/tasks/backend/agent_proxy_callback.py@@ -149,7 +149,7 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:task_run = TaskRun.objects.select_related("task__created_by").get(id=run_id, task_id=task_id, team_id=team_id)- task_run.signal_agent_turn_completed()+ task_run.signal_agent_turn_completed(succeeded=data["turn_succeeded"])dispatched = dispatch_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})diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex d0a5c2b7619d..d8ba63c8c590 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -4924,6 +4924,14 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):"to mark the agent idle without sending a completion notification or updating activity."),)+ turn_succeeded = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Whether 'awaiting_input' reports a turn that ended with the 'end_turn' stop reason. "+ "False for any other stop reason."+ ),+ )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/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.pyindex 24b6e86347dc..9358f5fb099c 100644--- a/products/tasks/backend/tests/test_agent_proxy_callback.py+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py@@ -279,16 +279,22 @@ class TestAgentProxyCallback(TestCase):int(turn_completed is False),)- def test_awaiting_input_signals_turn_end_but_skips_push_for_background_run(self) -> None:+ @parameterized.expand([("omitted", None, False), ("succeeded", True, True), ("not_succeeded", False, False)])+ def test_awaiting_input_signals_turn_end_but_skips_push_for_background_run(+ self, _name: str, turn_succeeded: bool | None, expected_succeeded: bool+ ) -> None:+ body = self._body(kind="awaiting_input", agent_active=False)+ if turn_succeeded is not None:+ body["turn_succeeded"] = turn_succeededwith (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())+ response = self._post(body, token=self._token())self.assertEqual(response.status_code, 200)self.assertFalse(response.json()["dispatched"])notify.assert_not_called()- signal_turn_completed.assert_called_once()+ signal_turn_completed.assert_called_once_with(succeeded=expected_succeeded)def test_turn_failed_signals_workflow_completion_as_failed(self) -> None:with patch(diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.tsindex 1279c8efe37d..1ef5b2495e0b 100644--- a/services/agent-proxy/src/lib/side-effects.ts+++ b/services/agent-proxy/src/lib/side-effects.ts@@ -92,6 +92,27 @@ export function isPiTurnError(event: Record<string, unknown>): boolean {return piTurnCompleted !== null && piTurnCompleted['stopReason'] === PI_STOP_REASON_ERROR}+export function turnCompletedSuccessfully(event: Record<string, unknown>): boolean {+ if (event['type'] === PI_EVENT_TYPE) {+ const piTurnCompleted = asPiTurnCompletedEvent(event)+ return piTurnCompleted !== null && piTurnCompleted['stopReason'] === STOP_REASON_END_TURN+ }+ 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>+ const payload = notif['method'] === TURN_COMPLETE_METHOD ? notif['params'] : notif['result']+ return (+ typeof payload === 'object' &&+ payload !== null &&+ (payload as Record<string, unknown>)['stopReason'] === STOP_REASON_END_TURN+ )+}+export function isIdleResumeTurnComplete(event: Record<string, unknown>): boolean {if (event['type'] !== ACP_NOTIFICATION_TYPE) {return false@@ -212,10 +233,11 @@ function fireCallback(options: {releaseClaim?: () => Promise<void>turnCompleted?: boolean+ turnSucceeded?: booleanbudgetSteer?: { sequence: number; timestamp?: string; params: Record<string, unknown> }} = {}): void {- const { releaseClaim, turnCompleted, budgetSteer } = options+ const { releaseClaim, turnCompleted, turnSucceeded, budgetSteer } = optionsif (!config.djangoCallbackBaseUrl) {// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.void releaseMilestoneClaim(releaseClaim, runId, kind)@@ -243,6 +265,7 @@ function fireCallback(task_id: taskId,team_id: teamId,turn_completed: turnCompleted,+ turn_succeeded: turnSucceeded,})const headers: Record<string, string> = {@@ -376,6 +399,7 @@ export async function heartbeatWorkflowIfNeeded(// dispatch the push notification for interactive mode runs.fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config, {turnCompleted: !isIdleResumeTurnComplete(event),+ turnSucceeded: turnCompletedSuccessfully(event),})}returndiff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 5204f57ea57a..a79e49442190 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -1434,8 +1434,22 @@ describe('ingest-handler', () => {// -----------------------------------------------------------------------describe('heartbeatWorkflowIfNeeded', () => {- it('sets agent inactive and fires awaiting_input for a turn-complete event', async () => {- const fired: { kind: string }[] = []+ it.each([+ [+ 'an end_turn turn-complete event',+ {+ type: 'notification',+ notification: { method: '_posthog/turn_complete', params: { stopReason: 'end_turn' } },+ },+ true,+ ],+ [+ 'a turn-complete event without end_turn',+ { type: 'notification', notification: { method: '_posthog/turn_complete' } },+ false,+ ],+ ])('sets agent inactive and fires awaiting_input for %s', async (_label, event, expectedSucceeded) => {+ const fired: { kind: string; turn_succeeded?: boolean }[] = []const originalFetch = global.fetchglobal.fetch = vi.fn(async (_, init) => {fired.push(JSON.parse(String((init as RequestInit).body)))@@ -1443,12 +1457,11 @@ describe('ingest-handler', () => {}) as typeof fetchconst config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })- const event = { type: 'notification', notification: { method: '_posthog/turn_complete' } }await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)expect(await redisStream.getAgentActive()).toBe(false)await new Promise((r) => setTimeout(r, 0))- expect(fired.some((f) => f.kind === 'awaiting_input')).toBe(true)+ expect(fired.find((f) => f.kind === 'awaiting_input')?.turn_succeeded).toBe(expectedSucceeded)global.fetch = originalFetch})diff --git a/services/agent-proxy/tests/lib/side-effects.test.ts b/services/agent-proxy/tests/lib/side-effects.test.tsindex a3d22a1d1dce..7dbb82a07f8c 100644--- a/services/agent-proxy/tests/lib/side-effects.test.ts+++ b/services/agent-proxy/tests/lib/side-effects.test.ts@@ -1,7 +1,13 @@import { readFileSync } from 'node:fs'import { describe, expect, it } from 'vitest'-import { isIdleResumeTurnComplete, isPiTurnError, isSessionUpdate, isTurnComplete } from '../../src/lib/side-effects.js'+import {+ isIdleResumeTurnComplete,+ isPiTurnError,+ isSessionUpdate,+ isTurnComplete,+ turnCompletedSuccessfully,+} from '../../src/lib/side-effects.js'const cases = JSON.parse(readFileSync(new URL('../../../../ee/hogai/sandbox/turn_event_contract.json', import.meta.url), 'utf8')@@ -11,7 +17,7 @@ const cases = JSON.parse(expect: Record<string, boolean>}[]-// The fixture also carries expectations for predicates only the Python side has, so+// The fixture also carries expectations for predicates only one side has, so// each side compares the keys it implements.describe('turn event contract', () => {it.each(cases)('$name', ({ event, expect: expected }) => {@@ -20,6 +26,7 @@ describe('turn event contract', () => {idle_resume: isIdleResumeTurnComplete(event),pi_error: isPiTurnError(event),session_update: isSessionUpdate(event),+ successful: turnCompletedSuccessfully(event),}expect(actual).toEqual(Object.fromEntries(Object.keys(actual).map((key) => [key, expected[key]])))})