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(tasks): measure agent boot to first activity (#90812)

Alessandro Pogliaghia004dd11f13e
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.ts
index fbdc479f8d61..ffb0594d434d 100644
--- a/products/desktop/packages/agent/src/acp-extensions.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.ts
@@ -19,6 +19,8 @@ export const POSTHOG_NOTIFICATIONS = {
/** Task run has started execution */
RUN_STARTED: "_posthog/run_started",
+ COMMAND_DISPATCHED: "_posthog/agent_command_dispatched",
+
/** Task has completed (success or failure) */
TASK_COMPLETE: "_posthog/task_complete",
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index cac802417032..79d8cd7b8bc6 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -1318,6 +1318,7 @@ describe("AgentServer HTTP Mode", () => {
clientConnection: { prompt },
};
return testServer as unknown as {
+ eventStreamSender: { enqueue: ReturnType<typeof vi.fn> };
promptWithUpstreamRetry(request: {
sessionId: string;
prompt: ContentBlock[];
@@ -1352,6 +1353,13 @@ describe("AgentServer HTTP Mode", () => {
expect(retryRequest.prompt[0].text).toContain(
"interrupted by a transient connection error",
);
+ const dispatchEvents =
+ testServer.eventStreamSender.enqueue.mock.calls.filter(
+ ([event]) =>
+ (event as { notification?: { method?: string } }).notification
+ ?.method === POSTHOG_NOTIFICATIONS.COMMAND_DISPATCHED,
+ );
+ expect(dispatchEvents).toHaveLength(1);
} finally {
vi.useRealTimers();
}
@@ -3643,6 +3651,10 @@ describe("AgentServer HTTP Mode", () => {
nativeResume: { sessionId: string; warm: boolean } | null;
prewarmedRun: boolean;
prewarmedStartupTurnPending: boolean;
+ eventStreamSender: {
+ enqueue: ReturnType<typeof vi.fn>;
+ stop: ReturnType<typeof vi.fn>;
+ };
sendInitialTaskMessage(
payload: JwtPayload,
taskRun: TaskRun | null,
@@ -3651,6 +3663,10 @@ describe("AgentServer HTTP Mode", () => {
internals.session.clientConnection.prompt = prompt;
internals.prewarmedRun = true;
internals.prewarmedStartupTurnPending = true;
+ internals.eventStreamSender = {
+ enqueue: vi.fn(),
+ stop: vi.fn(async () => {}),
+ };
internals.resumeState = {
conversation: [
{
@@ -3693,6 +3709,13 @@ describe("AgentServer HTTP Mode", () => {
expect(response.status).toBe(200);
expect(prompt).toHaveBeenCalledOnce();
+ expect(
+ internals.eventStreamSender.enqueue.mock.calls.filter(
+ ([event]) =>
+ (event as { notification?: { method?: string } }).notification
+ ?.method === POSTHOG_NOTIFICATIONS.COMMAND_DISPATCHED,
+ ),
+ ).toHaveLength(1);
const [{ prompt: promptBlocks }] = prompt.mock.calls[0] as unknown as [
{ prompt: ContentBlock[] },
];
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 7f8ef4eafc82..cea032c5cd36 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -508,6 +508,8 @@ export class AgentServer {
private config: AgentServerConfig;
private sessionReadyBootMs?: number;
private sessionInitMs?: number;
+ private httpReadyBootMs?: number;
+ private commandDispatchedRunId?: string;
private barrierReleasedAtMs?: number;
private bootTracker: AgentBootTracker;
private logger: Logger;
@@ -959,9 +961,11 @@ export class AgentServer {
port: this.config.port,
},
() => {
+ this.httpReadyBootMs = Math.round(process.uptime() * 1000);
+ this.bootTracker.markHttpReady(this.httpReadyBootMs);
this.logger.debug(
`HTTP server listening on port ${this.config.port}`,
- { bootMs: Math.round(process.uptime() * 1000) },
+ { bootMs: this.httpReadyBootMs },
);
resolve();
},
@@ -1380,6 +1384,7 @@ export class AgentServer {
}
} else {
const runPrompt = () => {
+ this.emitFirstCommandDispatched();
const promptResult = commandSession.clientConnection.prompt({
sessionId: commandSession.acpSessionId,
prompt,
@@ -1702,7 +1707,10 @@ export class AgentServer {
return;
}
- this.bootTracker = new AgentBootTracker(payload.run_id);
+ this.bootTracker = new AgentBootTracker(
+ payload.run_id,
+ this.httpReadyBootMs,
+ );
this.initializationPromise = this._doInitializeSession(
payload,
sseController,
@@ -2318,6 +2326,7 @@ export class AgentServer {
if (!session) {
throw new Error("Agent session ended before the turn could be sent");
}
+ this.emitFirstCommandDispatched();
const attempt = continueInterruptedTurn
? {
sessionId: session.acpSessionId,
@@ -5515,6 +5524,24 @@ ${commonInstructions}
}
}
+ private emitFirstCommandDispatched(): void {
+ if (!this.session) return;
+ const runId = this.session.payload.run_id;
+ if (this.commandDispatchedRunId === runId) return;
+ this.commandDispatchedRunId = runId;
+ const notification = {
+ jsonrpc: "2.0" as const,
+ method: POSTHOG_NOTIFICATIONS.COMMAND_DISPATCHED,
+ params: {},
+ };
+ this.broadcastEvent({
+ type: "notification",
+ timestamp: new Date().toISOString(),
+ notification,
+ });
+ this.session.logWriter.appendRawLine(runId, JSON.stringify(notification));
+ }
+
private flushPreSessionEvents(): void {
if (!this.session || this.preSessionEvents.length === 0) return;
const events = this.preSessionEvents;
diff --git a/products/desktop/packages/agent/src/server/boot-phases.test.ts b/products/desktop/packages/agent/src/server/boot-phases.test.ts
index a6bec2c34947..f960024a7890 100644
--- a/products/desktop/packages/agent/src/server/boot-phases.test.ts
+++ b/products/desktop/packages/agent/src/server/boot-phases.test.ts
@@ -14,7 +14,7 @@ describe("AgentBootTracker", () => {
.mockReturnValueOnce(150)
.mockReturnValueOnce(500);
- const tracker = new AgentBootTracker("run-1");
+ const tracker = new AgentBootTracker("run-1", 5);
await tracker.measure("context_fetch", async () => "ok");
tracker.markReady();
@@ -23,6 +23,7 @@ describe("AgentBootTracker", () => {
bootId: "run-1",
state: "ready",
totalMs: 50,
+ httpReadyMs: 5,
phasesMs: { context_fetch: 25 },
});
});
diff --git a/products/desktop/packages/agent/src/server/boot-phases.ts b/products/desktop/packages/agent/src/server/boot-phases.ts
index a2725e545e78..6d7da05b648b 100644
--- a/products/desktop/packages/agent/src/server/boot-phases.ts
+++ b/products/desktop/packages/agent/src/server/boot-phases.ts
@@ -18,6 +18,7 @@ export interface AgentBootSnapshot {
currentPhase?: AgentBootPhase;
failedPhase?: AgentBootPhase;
totalMs: number;
+ httpReadyMs?: number;
phasesMs: Partial<Record<AgentBootPhase, number>>;
}
@@ -28,9 +29,15 @@ export class AgentBootTracker {
private currentPhaseStartedAt?: number;
private failedPhase?: AgentBootPhase;
private totalMs?: number;
+ private httpReadyMs?: number;
private readonly phasesMs: Partial<Record<AgentBootPhase, number>> = {};
- constructor(private readonly bootId: string) {}
+ constructor(
+ private readonly bootId: string,
+ httpReadyMs?: number,
+ ) {
+ this.httpReadyMs = httpReadyMs;
+ }
async measure<T>(phase: AgentBootPhase, work: () => Promise<T>): Promise<T> {
this.start(phase);
@@ -50,6 +57,10 @@ export class AgentBootTracker {
this.state = "ready";
}
+ markHttpReady(elapsedMs?: number): void {
+ this.httpReadyMs ??= Math.max(0, Math.round(elapsedMs ?? this.elapsedMs()));
+ }
+
markFailed(): void {
this.fail();
this.finishCurrentPhase();
@@ -71,6 +82,9 @@ export class AgentBootTracker {
...(this.currentPhase ? { currentPhase: this.currentPhase } : {}),
...(this.failedPhase ? { failedPhase: this.failedPhase } : {}),
totalMs: this.totalMs ?? this.elapsedMs(),
+ ...(this.httpReadyMs !== undefined
+ ? { httpReadyMs: this.httpReadyMs }
+ : {}),
phasesMs,
};
}
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index e816b0cf7751..2eaddafb7dd6 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -41,8 +41,8 @@ logger = logging.getLogger(__name__)
summary="Agent-proxy side-effect callback",
description=(
"Internal endpoint called by the standalone Node agent-proxy after accepting an ingest event "
- "that requires a Django-side side effect. Dispatches a Temporal heartbeat signal or an "
- "awaiting-input mobile push notification depending on `kind`. "
+ "that requires a Django-side side effect. Dispatches a Temporal heartbeat, a boot milestone, "
+ "or an awaiting-input mobile push notification depending on `kind`. "
"Authenticated with the forwarded sandbox event ingest JWT plus the X-Agent-Proxy-Secret "
"shared secret (required outside local dev/test) — no session or API key involved. "
"Best-effort: always returns 200 when auth passes; side-effect failures are logged, not surfaced."
@@ -124,6 +124,18 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:
except Exception:
logger.exception("agent_proxy_callback.heartbeat_failed", extra={"run_id": run_id})
+ elif kind in {"command_dispatched", "agent_activity"}:
+ try:
+ task_run = TaskRun.objects.get(id=run_id, task_id=task_id, team_id=team_id)
+ if kind == "command_dispatched":
+ dispatched = task_run.signal_agent_boot_milestone("agent_command_dispatched")
+ else:
+ dispatched = task_run.signal_agent_boot_milestone("agent_activity_observed")
+ except TaskRun.DoesNotExist:
+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
+ except Exception:
+ logger.exception("agent_proxy_callback.milestone_failed", extra={"run_id": run_id, "kind": kind})
+
elif kind == "awaiting_input":
try:
# The push dispatcher reads task.created_by; prefetch it so the dispatch stays one query.
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 36e822f0cc41..7e4683018356 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -611,7 +611,8 @@ class SandboxBase(ABC):
result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)
payload = json.loads(result.stdout or "{}")
session_init_ms = payload.get("sessionInitMs")
- raw_phases = payload.get("boot", {}).get("phasesMs", {})
+ boot = payload.get("boot", {})
+ raw_phases = boot.get("phasesMs", {}) if isinstance(boot, dict) else {}
allowed_phases = {
"context_fetch",
"acp_initialize",
@@ -628,6 +629,13 @@ class SandboxBase(ABC):
if isinstance(raw_phases, dict)
else {}
)
+ for source, target in (("totalMs", "server_total"), ("httpReadyMs", "http_ready")):
+ duration = boot.get(source) if isinstance(boot, dict) else None
+ if isinstance(duration, int | float) and not isinstance(duration, bool):
+ phases[target] = max(0, int(duration))
+ boot_ms = payload.get("bootMs")
+ if "server_total" not in phases and isinstance(boot_ms, int | float) and not isinstance(boot_ms, bool):
+ phases["server_total"] = max(0, int(boot_ms))
return int(session_init_ms) if isinstance(session_init_ms, int | float) else None, phases
except Exception:
return None, {}
diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
index 80281f8d89ff..a01fa8abbbf5 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -52,6 +52,25 @@ def test_start_agent_server_health_check_timeout_is_retryable_and_not_captured(s
capture_exception.assert_not_called()
+def test_read_agent_server_boot_metrics_includes_process_milestones(sandbox: DockerSandbox):
+ response = ExecutionResult(
+ stdout='{"sessionInitMs":90,"boot":{"totalMs":140,"httpReadyMs":12,"phasesMs":{"context_fetch":40,"secret":1}}}',
+ stderr="",
+ exit_code=0,
+ )
+ with patch.object(sandbox, "execute", return_value=response):
+ assert sandbox.read_agent_server_boot_metrics() == (
+ 90,
+ {"context_fetch": 40, "server_total": 140, "http_ready": 12},
+ )
+
+
+def test_read_agent_server_boot_metrics_uses_pi_boot_total(sandbox: DockerSandbox):
+ response = ExecutionResult(stdout='{"sessionInitMs":90,"bootMs":140}', stderr="", exit_code=0)
+ with patch.object(sandbox, "execute", return_value=response):
+ assert sandbox.read_agent_server_boot_metrics() == (90, {"server_total": 140})
+
+
def test_build_agent_server_command_gates_exec_permission_regex(sandbox: DockerSandbox):
with_flag = sandbox._build_agent_server_command(
None, "t1", "r1", "interactive", True, posthog_exec_permission_regex=POSTHOG_EXEC_PERMISSION_REGEX
diff --git a/products/tasks/backend/logic/stream/agent_events.py b/products/tasks/backend/logic/stream/agent_events.py
new file mode 100644
index 000000000000..3668ee8b48c0
--- /dev/null
+++ b/products/tasks/backend/logic/stream/agent_events.py
@@ -0,0 +1,48 @@
+from typing import Any
+
+AGENT_COMMAND_DISPATCHED_METHOD = "_posthog/agent_command_dispatched"
+
+_ACP_GENERATION_UPDATES = frozenset(
+ {
+ "agent_message",
+ "agent_message_chunk",
+ "agent_thought_chunk",
+ "tool_call",
+ "tool_call_update",
+ }
+)
+
+_PI_GENERATION_EVENTS = frozenset(
+ {
+ "assistant_message_chunk",
+ "assistant_thought_chunk",
+ "tool_call_started",
+ "tool_call_updated",
+ }
+)
+
+
+def is_agent_command_dispatched(event: dict[str, Any]) -> bool:
+ notification = event.get("notification")
+ return (
+ event.get("type") == "notification"
+ and isinstance(notification, dict)
+ and notification.get("method") == AGENT_COMMAND_DISPATCHED_METHOD
+ )
+
+
+def is_agent_generation_event(event: dict[str, Any]) -> bool:
+ if event.get("type") == "pi_event":
+ pi_event = event.get("event")
+ return isinstance(pi_event, dict) and pi_event.get("type") in _PI_GENERATION_EVENTS
+
+ notification = event.get("notification")
+ if event.get("type") != "notification" or not isinstance(notification, dict):
+ return False
+ if notification.get("method") != "session/update":
+ return False
+ params = notification.get("params")
+ if not isinstance(params, dict):
+ return False
+ update = params.get("update")
+ return isinstance(update, dict) and update.get("sessionUpdate") in _ACP_GENERATION_UPDATES
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index f996f1388a1e..5c3c25a7e756 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -5,7 +5,7 @@ import json
import math
from collections.abc import AsyncGenerator, Awaitable, Callable
from dataclasses import dataclass
-from typing import cast
+from typing import Literal, cast
from uuid import NAMESPACE_URL, uuid5
from django.conf import settings
@@ -21,6 +21,7 @@ from products.tasks.backend.logic.services.connection_token import (
SandboxEventIngestTokenPayload,
validate_sandbox_event_ingest_token,
)
+from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_event
from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
@@ -370,6 +371,19 @@ def _parse_ingest_line(line: str) -> EventIngestEventLine | EventIngestCompleteL
async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id: str, event: dict) -> None:
+ if is_agent_command_dispatched(event) and await redis_stream.claim_first_agent_command():
+ dispatched = await sync_to_async(_signal_agent_boot_milestone, thread_sensitive=True)(
+ run_id, "agent_command_dispatched"
+ )
+ if not dispatched:
+ await redis_stream.release_first_agent_command()
+ elif is_agent_generation_event(event) and await redis_stream.claim_first_agent_activity():
+ dispatched = await sync_to_async(_signal_agent_boot_milestone, thread_sensitive=True)(
+ run_id, "agent_activity_observed"
+ )
+ if not dispatched:
+ await redis_stream.release_first_agent_activity()
+
if is_turn_complete(event):
await redis_stream.set_agent_active(False)
await _dispatch_turn_completed_if_interactive(run_id)
@@ -408,6 +422,21 @@ def _heartbeat_workflow(run_id: str, agent_active: bool) -> None:
task_run.heartbeat_workflow(agent_active=agent_active)
+def _signal_agent_boot_milestone(
+ run_id: str, milestone: Literal["agent_command_dispatched", "agent_activity_observed"]
+) -> bool:
+ if not settings.TEST:
+ close_old_connections()
+
+ try:
+ task_run = TaskRun.objects.get(id=run_id)
+ except TaskRun.DoesNotExist:
+ logger.warning("task_run_event_ingest_milestone_run_missing", run_id=run_id, milestone=milestone)
+ return False
+
+ return task_run.signal_agent_boot_milestone(milestone)
+
+
async def _dispatch_turn_completed_if_interactive(run_id: str) -> None:
await sync_to_async(_dispatch_turn_completed_if_interactive_sync, thread_sensitive=True)(run_id)
diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
index 01fc469c14ee..6daa2c2fb0c4 100644
--- a/products/tasks/backend/logic/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -105,6 +105,14 @@ def get_task_run_stream_heartbeat_key(stream_key: str) -> str:
return f"{stream_key}:ingest-heartbeat"
+def get_task_run_stream_first_command_key(stream_key: str) -> str:
+ return f"{stream_key}:ingest-first-agent-command"
+
+
+def get_task_run_stream_first_activity_key(stream_key: str) -> str:
+ return f"{stream_key}:ingest-first-agent-activity"
+
+
def get_task_run_stream_side_effect_pending_key(stream_key: str, side_effect: str, sequence: int) -> str:
return f"{stream_key}:side-effect:{side_effect}:{sequence}:pending"
@@ -328,6 +336,30 @@ class TaskRunRedisStream:
)
return bool(claimed)
+ async def claim_first_agent_command(self) -> bool:
+ claimed = await self._redis_client.set(
+ get_task_run_stream_first_command_key(self._stream_key),
+ "1",
+ ex=self._timeout,
+ nx=True,
+ )
+ return bool(claimed)
+
+ async def release_first_agent_command(self) -> None:
+ await self._redis_client.delete(get_task_run_stream_first_command_key(self._stream_key))
+
+ async def claim_first_agent_activity(self) -> bool:
+ claimed = await self._redis_client.set(
+ get_task_run_stream_first_activity_key(self._stream_key),
+ "1",
+ ex=self._timeout,
+ nx=True,
+ )
+ return bool(claimed)
+
+ async def release_first_agent_activity(self) -> None:
+ await self._redis_client.delete(get_task_run_stream_first_activity_key(self._stream_key))
+
async def claim_pending_side_effect(self, side_effect: str, sequence: int, lock_seconds: int) -> bool | None:
pending_key = get_task_run_stream_side_effect_pending_key(self._stream_key, side_effect, sequence)
lock_key = get_task_run_stream_side_effect_lock_key(self._stream_key, side_effect, sequence)
@@ -545,8 +577,16 @@ class TaskRunRedisStream:
completed_key = get_task_run_stream_completed_key(self._stream_key)
agent_active_key = get_task_run_stream_agent_active_key(self._stream_key)
heartbeat_key = get_task_run_stream_heartbeat_key(self._stream_key)
+ first_command_key = get_task_run_stream_first_command_key(self._stream_key)
+ first_activity_key = get_task_run_stream_first_activity_key(self._stream_key)
deleted = await self._redis_client.delete(
- self._stream_key, sequence_key, completed_key, agent_active_key, heartbeat_key
+ self._stream_key,
+ sequence_key,
+ completed_key,
+ agent_active_key,
+ heartbeat_key,
+ first_command_key,
+ first_activity_key,
)
return _normalize_redis_int(deleted) > 0
except Exception:
@@ -560,6 +600,8 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
completed_key = get_task_run_stream_completed_key(stream_key)
agent_active_key = get_task_run_stream_agent_active_key(stream_key)
heartbeat_key = get_task_run_stream_heartbeat_key(stream_key)
+ first_command_key = get_task_run_stream_first_command_key(stream_key)
+ first_activity_key = get_task_run_stream_first_activity_key(stream_key)
client = get_tasks_stream_redis_sync(use_dedicated)
try:
@@ -569,6 +611,8 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
completed_key,
agent_active_key,
heartbeat_key,
+ first_command_key,
+ first_activity_key,
)
return True
except Exception:
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 63ed661f3141..1529edb59162 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2313,6 +2313,27 @@ class TaskRun(models.Model):
except Exception as e:
logger.warning("task_run.heartbeat_failed", task_run_id=str(self.id), error=str(e))
+ def signal_agent_boot_milestone(
+ self, milestone: Literal["agent_command_dispatched", "agent_activity_observed"]
+ ) -> bool:
+ import asyncio
+
+ from posthog.temporal.common.client import sync_connect
+
+ try:
+ client = sync_connect()
+ handle = client.get_workflow_handle(self.workflow_id)
+ asyncio.run(handle.signal(milestone))
+ return True
+ except Exception as e:
+ logger.warning(
+ "task_run.agent_boot_milestone_failed",
+ task_run_id=str(self.id),
+ milestone=milestone,
+ error=str(e),
+ )
+ return False
+
def signal_client_activity(self) -> None:
from products.tasks.backend.redis import get_tasks_cache
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 2d2dcf38574c..47a6b599c9de 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -4205,18 +4205,18 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):
"""
kind = serializers.ChoiceField(
- choices=["heartbeat", "awaiting_input"],
+ choices=["heartbeat", "awaiting_input", "command_dispatched", "agent_activity"],
help_text=(
"Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its "
"inactivity timer. 'awaiting_input' fires a mobile push notification when an "
- "interactive run finishes a turn and is waiting for user input."
+ "interactive run finishes a turn and is waiting for user input. 'command_dispatched' "
+ "and 'agent_activity' record boot milestones."
),
)
agent_active = serializers.BooleanField(
help_text=(
"Whether the agent is currently active (true) or idle (false). "
- "For 'heartbeat' callbacks this is always true. "
- "For 'awaiting_input' callbacks this is always false."
+ "This is true for 'heartbeat' and 'agent_activity', and false otherwise."
),
)
task_id = serializers.CharField(
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index 3dae050e899d..bf348bf177df 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -169,6 +169,8 @@ class GetSandboxForRepositoryOutput:
clone_ms: int | None = None
checkout_ms: int | None = None
launch_ms: int | None = None
+ agent_prepare_ms: int | None = None
+ agent_invoke_ms: int | None = None
dev_stack_preview_sized: bool = False
agent_shadow_launched: bool = False
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 3f7b43f87a6e..086f564e0e84 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
@@ -25,6 +25,7 @@ from products.tasks.backend.logic.services.permission_broker import (
parse_permission_request,
try_auto_respond_permission_request,
)
+from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_event
from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.models import (
Task as TaskModel,
@@ -401,7 +402,6 @@ async def _relay_loop(
pending_text_parts: list[str] = []
last_text_flush: list[float] = [0.0]
final_message_tracker = FinalMessageTracker()
-
stop_heartbeat = asyncio.Event()
heartbeat_task = asyncio.create_task(
_background_heartbeat(
@@ -453,6 +453,19 @@ async def _relay_loop(
continue
await redis_stream.write_event(event_data)
+ if workflow_handle is not None:
+ if (
+ is_agent_command_dispatched(event_data)
+ and await redis_stream.claim_first_agent_command()
+ ):
+ if not await _signal_safely(workflow_handle, "agent_command_dispatched"):
+ await redis_stream.release_first_agent_command()
+ if (
+ is_agent_generation_event(event_data)
+ and await redis_stream.claim_first_agent_activity()
+ ):
+ if not await _signal_safely(workflow_handle, "agent_activity_observed"):
+ await redis_stream.release_first_agent_activity()
if task_run is not None:
permission_request = parse_permission_request(event_data)
if permission_request is not None:
@@ -807,15 +820,17 @@ async def _signal_safely(
workflow_handle: temporalio.client.WorkflowHandle,
signal_name: str,
arg: Any = None,
-) -> None:
+) -> bool:
"""Fire-and-forget signal — failures must never break the relay loop."""
try:
if arg is None:
await workflow_handle.signal(signal_name)
else:
await workflow_handle.signal(signal_name, arg=arg)
+ return True
except Exception as e:
logger.warning("slack_app_relay_signal_failed", signal=signal_name, error=str(e))
+ return False
def _is_keepalive_event(event_data: dict) -> bool:
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 040a2dcb7657..b5f4c729a395 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -322,6 +322,9 @@ class StartAgentServerOutput:
sandbox_url: str
connect_token: str | None = None
launch_ms: int | None = None
+ prepare_ms: int | None = None
+ invoke_ms: int | None = None
+ health_poll_ms: int | None = None
ready_wait_ms: int | None = None
session_init_ms: int | None = None
boot_phases_ms: dict[str, int] = field(default_factory=dict)
@@ -514,7 +517,6 @@ def _invoke_start_agent_server(
params: _LaunchParams,
*,
repo_ready_file: str | None,
- wait_for_health: bool,
) -> None:
try:
sandbox.start_agent_server(
@@ -542,23 +544,11 @@ def _invoke_start_agent_server(
event_ingest_url=params.event_ingest_url,
event_ingest_keep_stream_open=params.event_ingest_keep_stream_open,
repo_ready_file=repo_ready_file,
- wait_for_health=wait_for_health,
+ wait_for_health=False,
rtk_enabled=ctx.rtk_enabled,
peer_messaging=ctx.peer_messaging_enabled,
)
- # Record the boot identity so same-actor follow-ups within the
- # freshness window skip the redundant refresh.
- if params.mcp_configs and params.actor_user_id is not None:
- mark_sandbox_mcp_session(sandbox.id, params.actor_user_id)
-
- # Persist the effective rtk posture the agent launched with, so terminal
- # analytics can cohort runs by it (the state override alone misses the
- # kill-switch flag). Best-effort: never fail the launch over it.
- try:
- TaskRun.update_state_atomic(ctx.run_id, updates={"rtk_effective": ctx.rtk_enabled})
- except Exception:
- logger.warning("persist_rtk_effective_failed", run_id=ctx.run_id, exc_info=True)
except Exception as e:
if params.agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
@@ -575,6 +565,15 @@ def _invoke_start_agent_server(
)
+def _record_agent_server_launch(sandbox: SandboxBase, ctx: TaskProcessingContext, params: _LaunchParams) -> None:
+ if params.mcp_configs and params.actor_user_id is not None:
+ mark_sandbox_mcp_session(sandbox.id, params.actor_user_id)
+ try:
+ TaskRun.update_state_atomic(ctx.run_id, updates={"rtk_effective": ctx.rtk_enabled})
+ except Exception:
+ logger.warning("persist_rtk_effective_failed", run_id=ctx.run_id, exc_info=True)
+
+
def _spawn_post_ready_diagnostics(
ctx: TaskProcessingContext, sandbox: SandboxBase, agentsh_domains: list[str] | None
) -> None:
@@ -642,14 +641,25 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
# repo directory can never appear later. The deferred/overlap path clones in parallel
# and gates the session on the repo-ready barrier instead.
_ensure_repository_on_disk(ctx, sandbox)
- params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
-
runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
+ with StepTimer(
+ "agent_server_prepare", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ ) as prepare_timer:
+ params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
+
with StepTimer(
"agent_server_ready", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
) as ready_timer:
shadow_launched = _launch_agent_shadow(ctx, sandbox)
- _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None, wait_for_health=True)
+ with StepTimer(
+ "agent_server_invoke", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ ) as invoke_timer:
+ _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None)
+ with StepTimer(
+ "agent_server_health", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ ) as health_timer:
+ sandbox.wait_for_agent_server_ready(params.agentsh_domains)
+ _record_agent_server_launch(sandbox, ctx, params)
_record_network_enforcement_observation(ctx)
@@ -669,6 +679,9 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
return StartAgentServerOutput(
sandbox_url=input.sandbox_url,
connect_token=input.sandbox_connect_token,
+ prepare_ms=prepare_timer.elapsed_ms,
+ invoke_ms=invoke_timer.elapsed_ms,
+ health_poll_ms=health_timer.elapsed_ms,
ready_wait_ms=ready_timer.elapsed_ms,
session_init_ms=session_init_ms,
boot_phases_ms=boot_phases_ms,
@@ -690,21 +703,30 @@ def launch_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
emit_agent_log(ctx.run_id, "debug", "Launching agent server (deferred readiness)")
sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
- params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
-
repo_ready_file = REPO_READY_FILE if input.defer_for_clone else None
runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
+ with StepTimer(
+ "agent_server_prepare", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ ) as prepare_timer:
+ params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
+
with StepTimer(
"agent_server_launch", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
) as launch_timer:
shadow_launched = _launch_agent_shadow(ctx, sandbox)
- _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=repo_ready_file, wait_for_health=False)
+ with StepTimer(
+ "agent_server_invoke", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
+ ) as invoke_timer:
+ _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=repo_ready_file)
+ _record_agent_server_launch(sandbox, ctx, params)
activity.logger.info(f"Agent server process launched for task {ctx.task_id}")
return StartAgentServerOutput(
sandbox_url=input.sandbox_url,
connect_token=input.sandbox_connect_token,
launch_ms=launch_timer.elapsed_ms,
+ prepare_ms=prepare_timer.elapsed_ms,
+ invoke_ms=invoke_timer.elapsed_ms,
shadow_launched=shadow_launched,
)
@@ -745,13 +767,21 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
agentsh_domains = _agentsh_domains_for(ctx)
attempt = current_activity_attempt()
runtime = sandbox_runtime_label(ctx.use_modal_vm_sandbox)
+ prepare_ms: int | None = None
+ invoke_ms: int | None = None
try:
with StepTimer(
"agent_server_ready", boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime
) as ready_timer:
if attempt == 1:
- sandbox.wait_for_agent_server_ready(agentsh_domains)
+ with StepTimer(
+ "agent_server_health",
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as health_timer:
+ sandbox.wait_for_agent_server_ready(agentsh_domains)
else:
logger.warning(
"agent_server_readiness_retry_recovery",
@@ -761,8 +791,30 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
attempt=attempt,
)
_ensure_repository_on_disk(ctx, sandbox)
- params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
- _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None, wait_for_health=True)
+ with StepTimer(
+ "agent_server_prepare",
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as prepare_timer:
+ params = _prepare_launch(ctx, input.posthog_mcp_scopes, input.sandbox_id)
+ prepare_ms = prepare_timer.elapsed_ms
+ with StepTimer(
+ "agent_server_invoke",
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as invoke_timer:
+ _invoke_start_agent_server(sandbox, ctx, params, repo_ready_file=None)
+ invoke_ms = invoke_timer.elapsed_ms
+ with StepTimer(
+ "agent_server_health",
+ boot_path=input.boot_path,
+ origin_product=ctx.origin_product,
+ runtime=runtime,
+ ) as health_timer:
+ sandbox.wait_for_agent_server_ready(agentsh_domains)
+ _record_agent_server_launch(sandbox, ctx, params)
except Exception:
if attempt > 1:
increment_agent_server_readiness_retry(
@@ -804,6 +856,9 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
return StartAgentServerOutput(
sandbox_url=input.sandbox_url,
connect_token=input.sandbox_connect_token,
+ prepare_ms=prepare_ms,
+ invoke_ms=invoke_ms,
+ health_poll_ms=health_timer.elapsed_ms,
ready_wait_ms=ready_timer.elapsed_ms,
session_init_ms=session_init_ms,
boot_phases_ms=boot_phases_ms,
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 d6fb281f9b86..a4539ae3b420 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
@@ -5,7 +5,7 @@ from types import SimpleNamespace
from typing import cast
import pytest
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, call
import httpx
import httpx_sse
@@ -536,6 +536,100 @@ class TestRelaySandboxEventsErrorHandling:
redis_stream.mark_complete.assert_awaited_once()
redis_stream.mark_error.assert_not_awaited()
+ async def test_relay_signals_command_and_generated_activity_once(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ redis_stream = SimpleNamespace(
+ write_event=AsyncMock(),
+ mark_complete=AsyncMock(),
+ mark_error=AsyncMock(),
+ claim_first_agent_command=AsyncMock(side_effect=[True, False]),
+ release_first_agent_command=AsyncMock(),
+ claim_first_agent_activity=AsyncMock(side_effect=[True, False]),
+ release_first_agent_activity=AsyncMock(),
+ )
+ events = [
+ {
+ "type": "notification",
+ "notification": {"method": "_posthog/agent_command_dispatched", "params": {}},
+ },
+ {
+ "type": "notification",
+ "notification": {"method": "_posthog/agent_command_dispatched", "params": {}},
+ },
+ {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "user_message_chunk"}},
+ },
+ },
+ {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "plan"}},
+ },
+ },
+ {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "agent_message_chunk"}},
+ },
+ },
+ {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "tool_call"}},
+ },
+ },
+ {"type": "notification", "notification": {"method": "_posthog/task_complete"}},
+ ]
+
+ class SuccessfulEventSource:
+ response = SimpleNamespace(raise_for_status=lambda: None)
+
+ async def __aenter__(self) -> "SuccessfulEventSource":
+ return self
+
+ async def __aexit__(self, *_args: object) -> None:
+ return None
+
+ async def aiter_sse(self):
+ for event in events:
+ yield SimpleNamespace(data=json.dumps(event))
+
+ handle = SimpleNamespace(signal=AsyncMock())
+ client = SimpleNamespace(get_workflow_handle=MagicMock(return_value=handle))
+
+ monkeypatch.setattr(
+ relay_sandbox_events_module.httpx_sse, "aconnect_sse", lambda *_args, **_kwargs: SuccessfulEventSource()
+ )
+ monkeypatch.setattr(relay_sandbox_events_module, "_background_heartbeat", AsyncMock())
+ monkeypatch.setattr(
+ relay_sandbox_events_module.activity, "info", lambda: SimpleNamespace(workflow_id="workflow-1")
+ )
+ monkeypatch.setattr("posthog.temporal.common.client.async_connect", AsyncMock(return_value=client))
+
+ await _relay_loop(
+ events_url="https://sandbox.example/events",
+ headers={"Authorization": "Bearer token"},
+ params={},
+ redis_stream=cast(TaskRunRedisStream, redis_stream),
+ run_id="run-id",
+ task_id="task-id",
+ )
+
+ assert handle.signal.await_args_list == [
+ call("agent_command_dispatched"),
+ call("agent_state_changed", arg=True),
+ call("heartbeat", arg=True),
+ call("agent_activity_observed"),
+ ]
+ redis_stream.release_first_agent_command.assert_not_awaited()
+ redis_stream.release_first_agent_activity.assert_not_awaited()
+ assert redis_stream.claim_first_agent_activity.await_count == 2
+
async def test_permission_request_dispatches_to_broker(self, monkeypatch: pytest.MonkeyPatch) -> None:
redis_stream = SimpleNamespace(
write_event=AsyncMock(),
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 4b8f4ce73735..00437a1e21da 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -215,9 +215,10 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a
)
assert result.sandbox_url == "https://sandbox.example"
+ sandbox.wait_for_agent_server_ready.assert_called_once_with(None)
if expects_relaunch:
- sandbox.wait_for_agent_server_ready.assert_not_called()
sandbox.start_agent_server.assert_called_once()
+ assert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is False
record_retry.assert_called_once_with(
attempt,
"succeeded",
@@ -226,7 +227,6 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a
runtime="gvisor",
)
else:
- sandbox.wait_for_agent_server_ready.assert_called_once_with(None)
sandbox.start_agent_server.assert_not_called()
record_retry.assert_not_called()
@@ -743,6 +743,8 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker
allowed_gateway_server_ids=["srv-1"],
)
sandbox.start_agent_server.assert_called_once()
+ sandbox.wait_for_agent_server_ready.assert_called_once_with(None)
+ assert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is False
assert sandbox.start_agent_server.call_args.kwargs["event_ingest_token"] == "event-ingest-token"
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index e144c62937b3..64a0664855cc 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1116,6 +1116,108 @@ async def test_agent_shadow_result_is_reported_separately(monkeypatch):
)
+async def test_first_non_steering_command_records_dispatch_before_delivery(monkeypatch):
+ workflow_instance = ProcessTaskWorkflow()
+ context = _build_context(github_integration_id=123)
+ context.task_runtime = "pi"
+ workflow_instance._context = context
+ workflow_instance._agent_boot_interaction_telemetry_enabled = True
+ calls: list[str] = []
+
+ def schedule(event_name: str) -> None:
+ calls.append(event_name)
+
+ async def execute_activity(*_args, **_kwargs):
+ calls.append("delivered")
+
+ monkeypatch.setattr(workflow_instance, "_schedule_boot_milestone", schedule)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute_activity)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+
+ await workflow_instance._send_followup_to_sandbox("steer", [], message_id="steer-1", steer=True)
+ await workflow_instance._send_followup_to_sandbox("first", [], message_id="message-1")
+ await workflow_instance._send_followup_to_sandbox("second", [], message_id="message-2")
+
+ assert calls == ["delivered", "agent_first_command_dispatched", "delivered", "delivered"]
+
+
+async def test_pending_initial_command_records_dispatch_before_forwarding(monkeypatch):
+ workflow_instance = ProcessTaskWorkflow()
+ context = _build_context(github_integration_id=123, state={"pending_user_message": "start"})
+ context.task_runtime = "pi"
+ workflow_instance._context = context
+ workflow_instance._agent_boot_interaction_telemetry_enabled = True
+ calls: list[str] = []
+
+ def schedule(event_name: str) -> None:
+ calls.append(event_name)
+
+ async def execute_activity(*_args, **_kwargs):
+ calls.append("forwarded")
+
+ monkeypatch.setattr(workflow_instance, "_schedule_boot_milestone", schedule)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute_activity)
+
+ await workflow_instance._forward_pending_user_message()
+
+ assert calls == ["agent_first_command_dispatched", "forwarded"]
+
+
+async def test_first_agent_activity_signal_is_recorded_once(monkeypatch):
+ workflow_instance = ProcessTaskWorkflow()
+ workflow_instance._context = _build_context(github_integration_id=123)
+ workflow_instance._agent_boot_interaction_telemetry_enabled = True
+ schedule = Mock()
+ monkeypatch.setattr(workflow_instance, "_schedule_boot_milestone", schedule)
+
+ await workflow_instance.agent_activity_observed()
+ await workflow_instance.agent_activity_observed()
+
+ schedule.assert_called_once_with("agent_first_activity_observed")
+
+
+async def test_boot_milestone_contains_only_timing_and_runtime_dimensions(monkeypatch):
+ workflow_instance = ProcessTaskWorkflow()
+ workflow_instance._context = _build_context(github_integration_id=123)
+ workflow_instance._sandbox_id_for_cleanup = "sandbox-123"
+ workflow_instance._chain_started_at = datetime(2026, 8, 28, 10, 0, tzinfo=UTC)
+ workflow_instance._agent_ready_at = datetime(2026, 8, 28, 10, 0, 20, tzinfo=UTC)
+ workflow_instance._boot_path = "overlap"
+ workflow_instance._image_source = "base_image"
+ track = AsyncMock()
+ monkeypatch.setattr(workflow_instance, "_track_boot_milestone", track)
+ monkeypatch.setattr(
+ process_task_workflow_module.workflow,
+ "now",
+ Mock(return_value=datetime(2026, 8, 28, 10, 0, 21, tzinfo=UTC)),
+ )
+
+ workflow_instance._schedule_boot_milestone("agent_first_command_dispatched")
+ await workflow_instance._flush_boot_telemetry_tasks()
+
+ assert workflow_instance._boot_telemetry_tasks == []
+ track.assert_awaited_once_with(
+ "agent_first_command_dispatched",
+ {
+ "run_id": "run-id",
+ "task_id": "task-id",
+ "sandbox_id": "sandbox-123",
+ "elapsed_ms": 21_000,
+ "since_agent_ready_ms": 1_000,
+ "boot_path": "overlap",
+ "image_source": "base_image",
+ "origin_product": None,
+ "mode": "background",
+ "task_runtime": "acp",
+ "runtime_adapter": None,
+ "provider": None,
+ "sandbox_backend": "modal",
+ "transport": "sse",
+ "prewarmed": False,
+ },
+ )
+
+
@pytest.mark.django_db
class TestProcessTaskWorkflowUnit:
def test_quota_recheck_not_scheduled_for_non_pr_runs(self):
@@ -2891,6 +2993,12 @@ class TestContinueAsNew:
wf._end_of_turn_received = True
wf._last_agent_heartbeat_at = datetime(2026, 7, 16, 10, 29, tzinfo=UTC)
wf._sandbox_ttl_expires_at = datetime(2026, 7, 16, 15, 0, tzinfo=UTC)
+ wf._first_command_dispatched_recorded = True
+ wf._first_agent_activity_recorded = True
+ wf._boot_path = "overlap"
+ wf._image_source = "base_image"
+ wf._agent_ready_at = datetime(2026, 7, 16, 9, 1, tzinfo=UTC)
+ wf._agent_boot_interaction_telemetry_enabled = True
wf._slack_thread_context = {"channel": "C1"}
wf._posthog_mcp_scopes = "full"
@@ -2919,6 +3027,16 @@ class TestContinueAsNew:
assert restored._end_of_turn_received is True
assert restored._last_agent_heartbeat_at == datetime(2026, 7, 16, 10, 29, tzinfo=UTC)
assert restored._sandbox_ttl_expires_at == datetime(2026, 7, 16, 15, 0, tzinfo=UTC)
+ assert restored._first_command_dispatched_recorded is True
+ assert restored._first_agent_activity_recorded is True
+ assert restored._boot_path == "overlap"
+ assert restored._image_source == "base_image"
+ assert restored._agent_ready_at == datetime(2026, 7, 16, 9, 1, tzinfo=UTC)
+ assert restored._agent_boot_interaction_telemetry_enabled is True
+ legacy_restored = ProcessTaskWorkflow()
+ legacy_restored._agent_boot_interaction_telemetry_enabled = True
+ legacy_restored._restore_resumed_state(dataclasses.replace(rs, agent_boot_interaction_telemetry_enabled=None))
+ assert legacy_restored._agent_boot_interaction_telemetry_enabled is False
# 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_start
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index eb25861a681f..61b2ca185ccb 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -151,6 +151,7 @@ MAX_ACCEPTED_MESSAGE_IDS = 500
_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION = "tasks-cancel-sandbox-creation-on-completion"
_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE = "tasks-continue-after-repository-clone-failure"
_PATCH_ID_ASYNC_AGENT_SHADOW_RESULT = "tasks-async-agent-shadow-result"
+_PATCH_ID_AGENT_BOOT_INTERACTION_TELEMETRY = "tasks-agent-boot-interaction-telemetry"
class _TaskCompletedDuringSandboxCreation(Exception):
@@ -209,6 +210,12 @@ class ResumedSandboxState:
last_agent_heartbeat_at: Optional[str] = None
sandbox_ttl_expires_at: Optional[str] = None
sandbox_ttl_snapshot_taken: bool = False
+ first_command_dispatched_recorded: bool = False
+ first_agent_activity_recorded: bool = False
+ boot_path: str | None = None
+ image_source: str | None = None
+ agent_ready_at: str | None = None
+ agent_boot_interaction_telemetry_enabled: bool | None = None
@frozen
@@ -445,6 +452,10 @@ def _dev_stack_preview_enabled() -> bool:
return workflow.in_workflow() and workflow.patched(_PATCH_ID_DEV_STACK_PREVIEW)
+def _agent_boot_interaction_telemetry_enabled() -> bool:
+ return workflow.in_workflow() and workflow.patched(_PATCH_ID_AGENT_BOOT_INTERACTION_TELEMETRY)
+
+
@temporalio.workflow.defn(name="process-task")
class ProcessTaskWorkflow(PostHogWorkflow):
def __init__(self) -> None:
@@ -511,6 +522,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._self_driving_quota_checks_active: bool = True
self._current_slack_relay_workflow_id: Optional[str] = None
self._agent_shadow_launched = False
+ self._first_command_dispatched_recorded = False
+ self._first_agent_activity_recorded = False
+ self._boot_path: str | None = None
+ self._image_source: str | None = None
+ self._agent_ready_at: datetime | None = None
+ self._boot_telemetry_tasks: list[asyncio.Task[None]] = []
+ self._agent_boot_interaction_telemetry_enabled = False
@property
def context(self) -> TaskProcessingContext:
@@ -1126,6 +1144,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
permission_response_task: asyncio.Task[None] | None = None
preview_task: asyncio.Task[None] | None = None
agent_shadow_task: asyncio.Task[None] | None = None
+ self._agent_boot_interaction_telemetry_enabled = (
+ input.resumed_sandbox is None and _agent_boot_interaction_telemetry_enabled()
+ )
try:
self._context = await self._get_task_processing_context(input)
self._posthog_mcp_scopes = input.posthog_mcp_scopes
@@ -1214,6 +1235,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
):
if task is not None:
await self._cancel_relay(task)
+ await self._flush_boot_telemetry_tasks()
workflow.continue_as_new(self._build_resumed_input(input, sandbox_id))
event = await self._wait_for_event()
match event:
@@ -1607,6 +1629,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await self._cancel_relay(preview_task)
if agent_shadow_task is not None:
await self._cancel_relay(agent_shadow_task)
+ await self._flush_boot_telemetry_tasks()
await self._close_dev_stack_preview_progress()
cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup
@@ -1675,6 +1698,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_output = await self._get_sandbox_for_repository()
sandbox_id = sandbox_output.sandbox_id
+ self._boot_path = sandbox_output.boot_path
+ self._image_source = sandbox_output.image_source
# TODO(tasks): Re-enable snapshot creation
# if sandbox_output.should_create_snapshot and self.context.repository and self.context.github_integration_id:
@@ -1699,6 +1724,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await self._emit_progress("agent", "in_progress", "Starting agent", "setup")
agent_server_output = await self._start_agent_server(sandbox_output, boot_excluded_ms=wizard_ms)
self._agent_shadow_launched = bool(sandbox_output.agent_shadow_launched or agent_server_output.shadow_launched)
+ self._agent_ready_at = workflow.now() if self._agent_boot_interaction_telemetry_enabled else None
await self._emit_progress("agent", "completed", "Started agent", "setup")
await self._track_workflow_event(
@@ -1717,8 +1743,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"repo_clone_ms": sandbox_output.clone_ms,
"branch_checkout_ms": sandbox_output.checkout_ms,
"agent_launch_ms": sandbox_output.launch_ms,
+ "agent_prepare_ms": (
+ agent_server_output.prepare_ms
+ if agent_server_output.prepare_ms is not None
+ else sandbox_output.agent_prepare_ms
+ ),
+ "agent_invoke_ms": (
+ agent_server_output.invoke_ms
+ if agent_server_output.invoke_ms is not None
+ else sandbox_output.agent_invoke_ms
+ ),
+ "agent_health_poll_ms": agent_server_output.health_poll_ms,
"agent_ready_wait_ms": agent_server_output.ready_wait_ms,
"agent_session_init_ms": agent_server_output.session_init_ms,
+ "agent_server_total_ms": agent_server_output.boot_phases_ms.get("server_total"),
+ "agent_server_http_ready_ms": agent_server_output.boot_phases_ms.get("http_ready"),
"agent_context_fetch_ms": agent_server_output.boot_phases_ms.get("context_fetch"),
"agent_acp_initialize_ms": agent_server_output.boot_phases_ms.get("acp_initialize"),
"agent_repository_ready_ms": agent_server_output.boot_phases_ms.get("repository_ready"),
@@ -1814,6 +1853,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._sandbox_ttl_expires_at.isoformat() if self._sandbox_ttl_expires_at else None
),
sandbox_ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,
+ first_command_dispatched_recorded=self._first_command_dispatched_recorded,
+ first_agent_activity_recorded=self._first_agent_activity_recorded,
+ boot_path=self._boot_path,
+ image_source=self._image_source,
+ agent_ready_at=self._agent_ready_at.isoformat() if self._agent_ready_at else None,
+ agent_boot_interaction_telemetry_enabled=self._agent_boot_interaction_telemetry_enabled,
),
)
@@ -1849,6 +1894,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
datetime.fromisoformat(resumed.sandbox_ttl_expires_at) if resumed.sandbox_ttl_expires_at else None
)
self._sandbox_ttl_snapshot_taken = resumed.sandbox_ttl_snapshot_taken
+ self._first_command_dispatched_recorded = resumed.first_command_dispatched_recorded
+ self._first_agent_activity_recorded = resumed.first_agent_activity_recorded
+ self._boot_path = resumed.boot_path
+ self._image_source = resumed.image_source
+ self._agent_ready_at = datetime.fromisoformat(resumed.agent_ready_at) if resumed.agent_ready_at else None
+ self._agent_boot_interaction_telemetry_enabled = resumed.agent_boot_interaction_telemetry_enabled is True
async def _get_task_processing_context(self, input: ProcessTaskInput) -> TaskProcessingContext:
context = await workflow.execute_activity(
@@ -1986,10 +2037,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
overlap = bool(self.context.overlap_clone_boot_enabled and will_clone)
boot_path = "overlap" if overlap else "classic"
launch_ms: int | None = None
+ agent_prepare_ms: int | None = None
+ agent_invoke_ms: int | None = None
if overlap:
await self._emit_progress("agent", "in_progress", "Starting agent", "setup")
launch_output = await self._launch_agent_server(created, defer_for_clone=True, used_snapshot=used_snapshot)
launch_ms = launch_output.launch_ms if launch_output else None
+ agent_prepare_ms = launch_output.prepare_ms if launch_output else None
+ agent_invoke_ms = launch_output.invoke_ms if launch_output else None
self._agent_shadow_launched = bool(launch_output and launch_output.shadow_launched)
clone_ms: int | None = None
@@ -2145,6 +2200,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
clone_ms=clone_ms,
checkout_ms=checkout_ms,
launch_ms=launch_ms,
+ agent_prepare_ms=agent_prepare_ms,
+ agent_invoke_ms=agent_invoke_ms,
dev_stack_preview_sized=created.dev_stack_preview_sized,
agent_shadow_launched=self._agent_shadow_launched,
)
@@ -2347,6 +2404,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
async def _forward_pending_user_message(self) -> None:
+ state = self.context.state or {}
+ if self.context.task_runtime == "pi" and (
+ state.get("pending_user_message") or state.get("pending_user_artifact_ids")
+ ):
+ self._record_first_command_dispatched()
await workflow.execute_activity(
forward_pending_user_message,
self.context.run_id,
@@ -2487,6 +2549,56 @@ class ProcessTaskWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=1),
)
+ def _schedule_boot_milestone(self, event_name: str) -> None:
+ now = workflow.now()
+ properties = {
+ "run_id": self.context.run_id,
+ "task_id": self.context.task_id,
+ "sandbox_id": self._sandbox_id_for_cleanup,
+ "elapsed_ms": max(0, int((now - self._chain_start_time()).total_seconds() * 1000)),
+ "since_agent_ready_ms": (
+ max(0, int((now - self._agent_ready_at).total_seconds() * 1000)) if self._agent_ready_at else None
+ ),
+ "boot_path": self._boot_path,
+ "image_source": self._image_source,
+ "origin_product": self.context.origin_product,
+ "mode": self.context.mode,
+ "task_runtime": self.context.task_runtime,
+ "runtime_adapter": self.context.runtime_adapter,
+ "provider": self.context.provider,
+ "sandbox_backend": self.context.sandbox_backend,
+ "transport": "sequenced_ingest" if self.context.sandbox_event_ingest_enabled else "sse",
+ "prewarmed": self._prewarmed,
+ }
+ task = asyncio.create_task(self._track_boot_milestone(event_name, properties))
+ self._boot_telemetry_tasks.append(task)
+ task.add_done_callback(self._boot_telemetry_tasks.remove)
+
+ def _record_first_command_dispatched(self) -> None:
+ if self._first_command_dispatched_recorded or not self._agent_boot_interaction_telemetry_enabled:
+ return
+ self._first_command_dispatched_recorded = True
+ self._schedule_boot_milestone("agent_first_command_dispatched")
+
+ def _record_first_agent_activity(self) -> None:
+ if self._first_agent_activity_recorded or not self._agent_boot_interaction_telemetry_enabled:
+ return
+ self._first_agent_activity_recorded = True
+ self._schedule_boot_milestone("agent_first_activity_observed")
+
+ async def _track_boot_milestone(self, event_name: str, properties: dict[str, Any]) -> None:
+ try:
+ await self._track_workflow_event(event_name, properties)
+ except Exception as error:
+ workflow.logger.warning(
+ "agent_boot_milestone_tracking_failed",
+ extra={"run_id": self.context.run_id, "event_name": event_name, "error": str(error)},
+ )
+
+ async def _flush_boot_telemetry_tasks(self) -> None:
+ while self._boot_telemetry_tasks:
+ await asyncio.gather(*tuple(self._boot_telemetry_tasks))
+
async def _report_sandbox_deadline_outcome(self, *, outcome: str, reason: str | None, duration: timedelta) -> None:
"""Report how a sandbox deadline resolved, for the rollout's metrics.
@@ -3143,6 +3255,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._agent_active = agent_active
self._end_of_turn_received = not agent_active
+ @temporalio.workflow.signal
+ async def agent_command_dispatched(self) -> None:
+ self._record_first_command_dispatched()
+
+ @temporalio.workflow.signal
+ async def agent_activity_observed(self) -> None:
+ self._record_first_agent_activity()
+
@temporalio.workflow.signal
async def send_followup_message(
self,
@@ -3299,6 +3419,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
steer: bool = False,
user_originated: bool = True,
) -> str | None:
+ if not steer and self.context.task_runtime == "pi":
+ self._record_first_command_dispatched()
workflow.logger.info(
"send_followup_dispatch_begin",
extra={
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
index 9616d8684fb8..1f5e56ba89a2 100644
--- a/products/tasks/backend/tests/test_agent_proxy_callback.py
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -141,6 +141,23 @@ class TestAgentProxyCallback(TestCase):
self.assertFalse(response.json()["dispatched"])
heartbeat.assert_not_called()
+ @parameterized.expand(
+ [
+ ("command_dispatched", False, "agent_command_dispatched"),
+ ("agent_activity", True, "agent_activity_observed"),
+ ]
+ )
+ def test_boot_milestone_dispatches(self, kind: str, agent_active: bool, milestone: str) -> None:
+ with patch.object(TaskRun, "signal_agent_boot_milestone", return_value=True) as signal_milestone:
+ response = self._post(
+ self._body(kind=kind, agent_active=agent_active),
+ token=self._token(),
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["dispatched"])
+ signal_milestone.assert_called_once_with(milestone)
+
def test_awaiting_input_dispatches_for_interactive_run(self) -> None:
run = self.task.create_run(mode="interactive")
with patch("products.tasks.backend.agent_proxy_callback.notify_task_run_turn_completed") as notify:
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index 1fd072f1abd9..cfd336f04ef8 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -4,7 +4,7 @@ import threading
from collections.abc import Sequence
from uuid import NAMESPACE_URL, uuid5
-from unittest.mock import patch
+from unittest.mock import call, patch
from django.db import OperationalError
from django.test import TestCase, override_settings
@@ -167,31 +167,106 @@ class TestTaskRunEventIngest(TestCase):
def test_streaming_ingest_writes_ordered_events_with_explicit_completion(self) -> None:
token = self._create_token()
- with patch.object(TaskRun, "heartbeat_workflow") as heartbeat_workflow:
+ with (
+ patch.object(TaskRun, "heartbeat_workflow") as heartbeat_workflow,
+ patch.object(TaskRun, "signal_agent_boot_milestone") as signal_milestone,
+ ):
+ signal_milestone.return_value = True
status, body = self._call_ingest(
token,
[
{
"seq": 1,
- "event": {"type": "notification", "notification": {"method": "session/update"}},
+ "event": {
+ "type": "notification",
+ "notification": {"method": "_posthog/agent_command_dispatched", "params": {}},
+ },
},
{
"seq": 2,
+ "event": {
+ "type": "notification",
+ "notification": {"method": "_posthog/agent_command_dispatched", "params": {}},
+ },
+ },
+ {
+ "seq": 3,
+ "event": {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "agent_message_chunk"}},
+ },
+ },
+ },
+ {
+ "seq": 4,
+ "event": {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "tool_call"}},
+ },
+ },
+ },
+ {
+ "seq": 5,
"event": {"type": "notification", "notification": {"method": "_posthog/task_complete"}},
},
- {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 2},
+ {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 5},
],
)
self.assertEqual(status, 200)
- self.assertEqual(body["accepted"], 2)
- self.assertEqual(body["last_accepted_seq"], 2)
+ self.assertEqual(body["accepted"], 5)
+ self.assertEqual(body["last_accepted_seq"], 5)
heartbeat_workflow.assert_called_once_with(agent_active=True)
+ self.assertEqual(
+ signal_milestone.call_args_list,
+ [call("agent_command_dispatched"), call("agent_activity_observed")],
+ )
events = self._read_stream_events()
- self.assertEqual(self._read_notification_methods(), ["session/update", "_posthog/task_complete"])
+ self.assertEqual(
+ self._read_notification_methods(),
+ [
+ "_posthog/agent_command_dispatched",
+ "_posthog/agent_command_dispatched",
+ "session/update",
+ "session/update",
+ "_posthog/task_complete",
+ ],
+ )
self.assertIn({"type": "STREAM_STATUS", "status": "complete"}, events)
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_streaming_ingest_releases_failed_activity_claim(self) -> None:
+ token = self._create_token()
+
+ with patch.object(TaskRun, "signal_agent_boot_milestone", return_value=False):
+ status, _body = self._call_ingest(
+ token,
+ [
+ {
+ "seq": 1,
+ "event": {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "agent_message_chunk"}},
+ },
+ },
+ }
+ ],
+ )
+
+ async def claim_activity() -> bool:
+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(self.task_run.id)))
+ return await redis_stream.claim_first_agent_activity()
+
+ self.assertEqual(status, 200)
+ self.assertTrue(asyncio.run(claim_activity()))
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_rtk_savings_capture_uses_authenticated_ids_and_idempotent_event_uuid(self) -> None:
token = self._create_token()
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 9c6b9f1d0da5..0834dea48bfc 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -1506,7 +1506,6 @@ class TestTaskRun(TestCase):
from django.core.cache import cache
cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")
-
handle = mock_connect.return_value.get_workflow_handle.return_value
handle.signal = AsyncMock()
@@ -1521,6 +1520,22 @@ class TestTaskRun(TestCase):
cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")
+ @parameterized.expand(["agent_command_dispatched", "agent_activity_observed"])
+ @patch("posthog.temporal.common.client.sync_connect")
+ def test_signal_agent_boot_milestone(self, milestone, mock_connect):
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ )
+ handle = mock_connect.return_value.get_workflow_handle.return_value
+ handle.signal = AsyncMock()
+
+ dispatched = run.signal_agent_boot_milestone(milestone)
+
+ self.assertTrue(dispatched)
+ handle.signal.assert_awaited_once_with(milestone)
+
class TestSandboxSnapshot(TestCase):
organization: ClassVar[Organization]
diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.md
index 12e8a9af3a71..d8e23b05ea78 100644
--- a/products/tasks/docs/INSTRUMENTATION.md
+++ b/products/tasks/docs/INSTRUMENTATION.md
@@ -2,6 +2,8 @@
All analytics events tracked from the tasks backend via `posthoganalytics.capture()`.
+Update this document whenever a new event or property is added.
+
All events include group analytics via `groups()` from `posthog.event_usage`, which sets `instance`, `organization`, `customer`, and `project` groups where available.
## Standard Properties
@@ -153,8 +155,13 @@ Tracked after sandbox and agent server are provisioned.
| `repo_clone_ms` | `int` | Repository clone time |
| `branch_checkout_ms` | `int` | Branch checkout time |
| `agent_launch_ms` | `int` | Agent server launch time |
+| `agent_prepare_ms` | `int` | Backend launch configuration time |
+| `agent_invoke_ms` | `int` | Sandbox launcher and process start time |
+| `agent_health_poll_ms` | `int` | Time spent polling the agent health endpoint |
| `agent_ready_wait_ms` | `int` | Time spent waiting for the agent server |
| `agent_session_init_ms` | `int` | Agent session initialization time |
+| `agent_server_total_ms` | `int` | Agent server initialization time |
+| `agent_server_http_ready_ms` | `int` | Time from agent process start to HTTP listen |
| `agent_context_fetch_ms` | `int` | Task and run context fetch time inside agent-server |
| `agent_acp_initialize_ms` | `int` | ACP process handshake time |
| `agent_repository_ready_ms` | `int` | Time waiting on the repository-ready barrier |
@@ -177,6 +184,34 @@ Tracked after the shadow observer finishes or the result read times out. Use `ru
| `failure_class` | `str` | Allowlisted observer failure category |
| `read_timed_out` | `bool` | Whether result collection timed out |
+### `agent_first_command_dispatched`
+
+Tracked once when the first non-steering agent command is dispatched.
+
+### `agent_first_activity_observed`
+
+Tracked once when the first agent-generated message, thought, or tool call is observed.
+
+Both first-interaction events include:
+
+| Property | Type | Description |
+| ---------------------- | ------ | --------------------------------- |
+| `run_id` | `str` | UUID of the run |
+| `task_id` | `str` | UUID of the task |
+| `sandbox_id` | `str` | Sandbox identifier |
+| `elapsed_ms` | `int` | Time from the workflow start |
+| `since_agent_ready_ms` | `int` | Time from agent readiness |
+| `boot_path` | `str` | Classic or overlapping clone boot |
+| `image_source` | `str` | Sandbox image source |
+| `origin_product` | `str` | Product that created the task |
+| `mode` | `str` | Background or interactive |
+| `task_runtime` | `str` | ACP or Pi runtime |
+| `runtime_adapter` | `str` | Runtime adapter |
+| `provider` | `str` | Model provider |
+| `sandbox_backend` | `str` | Sandbox provider |
+| `transport` | `str` | SSE or sequenced event ingest |
+| `prewarmed` | `bool` | Whether the run was prewarmed |
+
### Modal VM rollout payload
The `tasks-modal-vm-sandbox` payload supports gradual rollout by origin product:
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
index a26e07296b03..51d5d7948005 100644
--- a/services/agent-proxy/src/lib/redis-stream.ts
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -52,6 +52,14 @@ export function getHeartbeatKey(streamKey: string): string {
return `${streamKey}:ingest-heartbeat`
}
+export function getFirstCommandKey(streamKey: string): string {
+ return `${streamKey}:ingest-first-agent-command`
+}
+
+export function getFirstActivityKey(streamKey: string): string {
+ return `${streamKey}:ingest-first-agent-activity`
+}
+
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
@@ -375,6 +383,24 @@ export class TaskRunRedisStream {
return result === 'OK'
}
+ async claimFirstAgentCommand(): Promise<boolean> {
+ const result = await this.redis.set(getFirstCommandKey(this.streamKey), '1', 'EX', this.timeout, 'NX')
+ return result === 'OK'
+ }
+
+ async releaseFirstAgentCommand(): Promise<void> {
+ await this.redis.del(getFirstCommandKey(this.streamKey))
+ }
+
+ async claimFirstAgentActivity(): Promise<boolean> {
+ const result = await this.redis.set(getFirstActivityKey(this.streamKey), '1', 'EX', this.timeout, 'NX')
+ return result === 'OK'
+ }
+
+ async releaseFirstAgentActivity(): Promise<void> {
+ await this.redis.del(getFirstActivityKey(this.streamKey))
+ }
+
// WATCH/MULTI optimistic retry loop (never the TEST shortcut).
// Returns stream ID string on accept, null on duplicate.
// Throws TaskRunStreamSequenceGap, TaskRunStreamAlreadyCompleted.
@@ -516,20 +542,22 @@ export class TaskRunRedisStream {
await this.writeEvent({ type: 'STREAM_STATUS', status: 'error', error: error.slice(0, 500) })
}
- // DEL all five keys atomically. Returns true if at least one key was deleted.
- // Catches all exceptions; returns false on failure.
async deleteStream(): Promise<boolean> {
try {
const sequenceKey = getSequenceKey(this.streamKey)
const completedKey = getCompletedKey(this.streamKey)
const agentActiveKey = getAgentActiveKey(this.streamKey)
const heartbeatKey = getHeartbeatKey(this.streamKey)
+ const firstCommandKey = getFirstCommandKey(this.streamKey)
+ const firstActivityKey = getFirstActivityKey(this.streamKey)
const deleted = await this.redis.del(
this.streamKey,
sequenceKey,
completedKey,
agentActiveKey,
- heartbeatKey
+ heartbeatKey,
+ firstCommandKey,
+ firstActivityKey
)
return deleted > 0
} catch {
diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.ts
index 52e702b44b25..75eac22f86ea 100644
--- a/services/agent-proxy/src/lib/side-effects.ts
+++ b/services/agent-proxy/src/lib/side-effects.ts
@@ -22,6 +22,20 @@ const ACP_NOTIFICATION_TYPE = 'notification'
const TURN_COMPLETE_METHOD = '_posthog/turn_complete'
const STOP_REASON_END_TURN = 'end_turn'
const ACP_METHOD_SESSION_UPDATE = 'session/update'
+const AGENT_COMMAND_DISPATCHED_METHOD = '_posthog/agent_command_dispatched'
+const ACP_GENERATION_UPDATES = new Set([
+ 'agent_message',
+ 'agent_message_chunk',
+ 'agent_thought_chunk',
+ 'tool_call',
+ 'tool_call_update',
+])
+const PI_GENERATION_EVENTS = new Set([
+ 'assistant_message_chunk',
+ 'assistant_thought_chunk',
+ 'tool_call_started',
+ 'tool_call_updated',
+])
// isTurnComplete mirrors ee/hogai/sandbox/types.py:is_turn_complete exactly.
// Matches both the raw ACP prompt response (result.stopReason == "end_turn")
@@ -58,6 +72,43 @@ export function isSessionUpdate(event: Record<string, unknown>): boolean {
return (notification as Record<string, unknown>)['method'] === ACP_METHOD_SESSION_UPDATE
}
+export function isAgentCommandDispatched(event: Record<string, unknown>): boolean {
+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {
+ return false
+ }
+ const notification = event['notification']
+ return (
+ typeof notification === 'object' &&
+ notification !== null &&
+ (notification as Record<string, unknown>)['method'] === AGENT_COMMAND_DISPATCHED_METHOD
+ )
+}
+
+export function isAgentGenerationEvent(event: Record<string, unknown>): boolean {
+ if (event['type'] === 'pi_event') {
+ const piEvent = event['event']
+ return (
+ typeof piEvent === 'object' &&
+ piEvent !== null &&
+ PI_GENERATION_EVENTS.has(String((piEvent as Record<string, unknown>)['type']))
+ )
+ }
+ if (!isSessionUpdate(event)) {
+ return false
+ }
+ const notification = event['notification'] as Record<string, unknown>
+ const params = notification['params']
+ if (typeof params !== 'object' || params === null) {
+ return false
+ }
+ const update = (params as Record<string, unknown>)['update']
+ return (
+ typeof update === 'object' &&
+ update !== null &&
+ ACP_GENERATION_UPDATES.has(String((update as Record<string, unknown>)['sessionUpdate']))
+ )
+}
+
// fireCallback issues a best-effort POST to the Django agent-proxy callback.
// The call is fire-and-forget: the promise is not returned to the caller.
// Any failure is logged but never thrown into the ingest path.
@@ -72,10 +123,12 @@ function fireCallback(
taskId: string,
teamId: number,
originalToken: string,
- config: Config
+ config: Config,
+ releaseClaim?: () => Promise<void>
): void {
if (!config.djangoCallbackBaseUrl) {
// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.
+ void releaseMilestoneClaim(releaseClaim, runId, kind)
return
}
@@ -103,17 +156,45 @@ function fireCallback(
// we rely on the OS TCP timeout (typically 2 min). The callback is
// best-effort so a slow/hanging response is acceptable.
})
- .then((res) => {
- if (!res.ok) {
- logger.warn('side_effect:non_2xx', { run: runId, kind, status: res.status })
+ .then(async (response) => {
+ if (!response.ok) {
+ logger.warn('side_effect:non_2xx', { run: runId, kind, status: response.status })
+ await releaseMilestoneClaim(releaseClaim, runId, kind)
+ return
+ }
+ const payload: unknown = await response.json().catch(() => null)
+ const dispatched =
+ typeof payload === 'object' &&
+ payload !== null &&
+ 'dispatched' in payload &&
+ payload.dispatched === true
+ if (!dispatched) {
+ await releaseMilestoneClaim(releaseClaim, runId, kind)
}
})
- .catch((err: unknown) => {
+ .catch(async (err: unknown) => {
const message = err instanceof Error ? err.message : String(err)
logger.error('side_effect:failed', { run: runId, kind, error: message })
+ await releaseMilestoneClaim(releaseClaim, runId, kind)
})
}
+async function releaseMilestoneClaim(
+ release: (() => Promise<void>) | undefined,
+ runId: string,
+ kind: SideEffectKind
+): Promise<void> {
+ if (!release) {
+ return
+ }
+ try {
+ await release()
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err)
+ logger.error('side_effect:claim_release_failed', { run: runId, kind, error: message })
+ }
+}
+
// heartbeatWorkflowIfNeeded implements the side-effect decision from docs/DESIGN.md §2
// and mirrors event_ingest.py:_heartbeat_workflow_if_needed exactly.
//
@@ -136,6 +217,16 @@ export async function heartbeatWorkflowIfNeeded(
originalToken: string,
config: Config
): Promise<void> {
+ if (isAgentCommandDispatched(event) && (await redisStream.claimFirstAgentCommand())) {
+ fireCallback(runId, 'command_dispatched', false, taskId, teamId, originalToken, config, () =>
+ redisStream.releaseFirstAgentCommand()
+ )
+ } else if (isAgentGenerationEvent(event) && (await redisStream.claimFirstAgentActivity())) {
+ fireCallback(runId, 'agent_activity', true, taskId, teamId, originalToken, config, () =>
+ redisStream.releaseFirstAgentActivity()
+ )
+ }
+
if (isTurnComplete(event)) {
await redisStream.setAgentActive(false)
// Let Django decide whether the run is interactive; it will only
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
index d12df8917281..3824789af373 100644
--- a/services/agent-proxy/src/lib/types.ts
+++ b/services/agent-proxy/src/lib/types.ts
@@ -141,7 +141,7 @@ export type IngestLine = IngestEventLine | IngestCompleteLine
// Side-effect callback kind (matches Python callback contract in docs/DESIGN.md)
// ---------------------------------------------------------------------------
-export type SideEffectKind = 'heartbeat' | 'awaiting_input'
+export type SideEffectKind = 'heartbeat' | 'awaiting_input' | 'command_dispatched' | 'agent_activity'
// ---------------------------------------------------------------------------
// TaskRunRedisStream method interface
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index db18b04b5c22..470b2c2b5320 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -1048,11 +1048,84 @@ describe('ingest-handler', () => {
global.fetch = originalFetch
})
+ it('dispatches the first command callback once', async () => {
+ const fetchCalls: { body: unknown }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_url, init) => {
+ fetchCalls.push({ body: JSON.parse(String((init as RequestInit).body)) })
+ return Response.json({ dispatched: true }, { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const commandEvent = {
+ type: 'notification',
+ notification: { method: '_posthog/agent_command_dispatched', params: {} },
+ }
+ const ndjson =
+ [JSON.stringify({ seq: 1, event: commandEvent }), JSON.stringify({ seq: 2, event: commandEvent })].join(
+ '\n'
+ ) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+
+ const response = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(response.status).toBe(200)
+ expect(fetchCalls.map(({ body }) => (body as { kind: string }).kind)).toEqual(['command_dispatched'])
+ global.fetch = originalFetch
+ })
+
// -----------------------------------------------------------------------
// Side effects: session/update → agent active
// -----------------------------------------------------------------------
- it('sets agent active on session/update event and fires heartbeat after claim', async () => {
+ it.each([
+ {
+ name: 'prompt echo',
+ event: {
+ type: 'notification',
+ notification: {
+ method: 'session/update',
+ params: { update: { sessionUpdate: 'user_message_chunk' } },
+ },
+ },
+ expectedKinds: ['heartbeat'],
+ expectedActive: true,
+ },
+ {
+ name: 'agent output',
+ event: {
+ type: 'notification',
+ notification: {
+ method: 'session/update',
+ params: { update: { sessionUpdate: 'agent_message_chunk' } },
+ },
+ },
+ expectedKinds: ['agent_activity', 'heartbeat'],
+ expectedActive: true,
+ },
+ {
+ name: 'restored plan',
+ event: {
+ type: 'notification',
+ notification: {
+ method: 'session/update',
+ params: { update: { sessionUpdate: 'plan' } },
+ },
+ },
+ expectedKinds: ['heartbeat'],
+ expectedActive: true,
+ },
+ {
+ name: 'command dispatch',
+ event: {
+ type: 'notification',
+ notification: { method: '_posthog/agent_command_dispatched', params: {} },
+ },
+ expectedKinds: ['command_dispatched'],
+ expectedActive: false,
+ },
+ ])('dispatches side effects for $name', async ({ event, expectedKinds, expectedActive }) => {
const fetchCalls: { url: string; body: unknown }[] = []
const originalFetch = global.fetch
global.fetch = vi.fn(async (url, init) => {
@@ -1063,23 +1136,20 @@ describe('ingest-handler', () => {
const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
mockValidate.mockResolvedValue(makeClaims())
- const sessionUpdateEvent = {
- type: 'notification',
- notification: { method: 'session/update' },
- }
- const ndjson = JSON.stringify({ seq: 1, event: sessionUpdateEvent }) + '\n'
+ const ndjson = JSON.stringify({ seq: 1, event }) + '\n'
const ctx = makeContext({ body: makeStringBody(ndjson) })
const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
expect(res.status).toBe(200)
const agentActive = await redisStream.getAgentActive()
- expect(agentActive).toBe(true)
+ expect(agentActive).toBe(expectedActive)
await new Promise((r) => setTimeout(r, 0))
- const callbackCall = fetchCalls.find((c) => c.url.includes('agent-proxy-callback'))
- expect(callbackCall).toBeTruthy()
- expect(callbackCall?.body).toMatchObject({ kind: 'heartbeat', agent_active: true })
+ const callbackKinds = fetchCalls
+ .filter((c) => c.url.includes('agent-proxy-callback'))
+ .map((c) => (c.body as { kind: string }).kind)
+ expect(callbackKinds).toEqual(expectedKinds)
global.fetch = originalFetch
})
@@ -1131,19 +1201,25 @@ describe('ingest-handler', () => {
// Side effects: best-effort (callback failure does not fail ingest)
// -----------------------------------------------------------------------
- it('still returns 200 when the Django callback throws', async () => {
+ it.each([
+ [
+ 'throws',
+ async () => {
+ throw new Error('network failure')
+ },
+ ],
+ ['answers 200 with a body that is not JSON', async () => new Response('', { status: 200 })],
+ ])('releases a command claim when the Django callback %s', async (_label, respond) => {
const originalFetch = global.fetch
- global.fetch = vi.fn(async () => {
- throw new Error('network failure')
- }) as typeof fetch
+ global.fetch = vi.fn(respond) as typeof fetch
const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
- const turnCompleteEvent = {
+ const commandEvent = {
type: 'notification',
- notification: { method: '_posthog/turn_complete' },
+ notification: { method: '_posthog/agent_command_dispatched', params: {} },
}
- const ndjson = JSON.stringify({ seq: 1, event: turnCompleteEvent }) + '\n'
+ const ndjson = JSON.stringify({ seq: 1, event: commandEvent }) + '\n'
const ctx = makeContext({ body: makeStringBody(ndjson) })
const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
// Callback failure must NOT affect ingest response
@@ -1152,6 +1228,7 @@ describe('ingest-handler', () => {
// Let the detached promise settle without crashing the test
await new Promise((r) => setTimeout(r, 10))
+ expect(await redisStream.claimFirstAgentCommand()).toBe(true)
global.fetch = originalFetch
})
diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.ts
index fe312697e11b..31aa7999f8ba 100644
--- a/services/agent-proxy/tests/lib/redis-stream.test.ts
+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts
@@ -18,6 +18,8 @@ import {
getCompletedKey,
getAgentActiveKey,
getHeartbeatKey,
+ getFirstCommandKey,
+ getFirstActivityKey,
} from '@/lib/redis-stream.js'
import {
TaskRunStreamError,
@@ -468,6 +470,8 @@ describe('redis-stream', () => {
expect(getCompletedKey(streamKey)).toBe('task-run-stream:abc-123:completed')
expect(getAgentActiveKey(streamKey)).toBe('task-run-stream:abc-123:ingest-agent-active')
expect(getHeartbeatKey(streamKey)).toBe('task-run-stream:abc-123:ingest-heartbeat')
+ expect(getFirstCommandKey(streamKey)).toBe('task-run-stream:abc-123:ingest-first-agent-command')
+ expect(getFirstActivityKey(streamKey)).toBe('task-run-stream:abc-123:ingest-first-agent-activity')
})
})
@@ -873,6 +877,39 @@ describe('redis-stream', () => {
})
})
+ describe.each([
+ {
+ name: 'command',
+ claim: (stream: TaskRunRedisStream) => stream.claimFirstAgentCommand(),
+ release: (stream: TaskRunRedisStream) => stream.releaseFirstAgentCommand(),
+ key: getFirstCommandKey,
+ },
+ {
+ name: 'activity',
+ claim: (stream: TaskRunRedisStream) => stream.claimFirstAgentActivity(),
+ release: (stream: TaskRunRedisStream) => stream.releaseFirstAgentActivity(),
+ key: getFirstActivityKey,
+ },
+ ])('first agent $name claim', ({ claim, release, key }) => {
+ it('claims once and allows retry after release', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ const first = await claim(stream)
+ const second = await claim(stream)
+
+ expect(first).toBe(true)
+ expect(second).toBe(false)
+ const exp = redis.getExpiryMs(key(streamKey))
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeGreaterThan(Date.now() + 50_000)
+ expect(exp!).toBeLessThan(Date.now() + 70_000)
+
+ await release(stream)
+
+ expect(await claim(stream)).toBe(true)
+ })
+ })
+
// -----------------------------------------------------------------------
// resumePointTrimmed + detectResumeGap
// -----------------------------------------------------------------------
@@ -1225,12 +1262,14 @@ describe('redis-stream', () => {
// -----------------------------------------------------------------------
describe('deleteStream', () => {
- it('returns true and removes all five keys', async () => {
+ it('returns true and removes all seven keys', async () => {
const { stream, redis, streamKey } = newStream()
await stream.writeEventWithSequence({ type: 'a' }, 1)
await stream.setAgentActive(true)
await stream.claimAgentActiveHeartbeat(30)
+ await stream.claimFirstAgentCommand()
+ await stream.claimFirstAgentActivity()
const deleted = await stream.deleteStream()
@@ -1240,6 +1279,8 @@ describe('redis-stream', () => {
expect(redis.getStringValue(getCompletedKey(streamKey))).toBeNull()
expect(redis.getStringValue(getAgentActiveKey(streamKey))).toBeNull()
expect(redis.getStringValue(getHeartbeatKey(streamKey))).toBeNull()
+ expect(redis.getStringValue(getFirstCommandKey(streamKey))).toBeNull()
+ expect(redis.getStringValue(getFirstActivityKey(streamKey))).toBeNull()
})
it('returns false (no error thrown) when stream does not exist', async () => {