: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): keep waiting for the agent while repo session hooks run (#107897)
Alessandro Pogliaghi38f3c9b44124
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts b/products/desktop/packages/agent/src/adapters/claude/session/initialization.tsindex e63875df0005..d0286306f538 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts@@ -1,7 +1,7 @@import type { Readable } from "node:stream";import { StringDecoder } from "node:string_decoder";-type InitializationPhase = "sdk_initialization" | "setup_hooks";+export type InitializationPhase = "sdk_initialization" | "setup_hooks";export interface CliOutputSummary {lines: number;diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 6d0720de7743..9eac71ed379d 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -713,6 +713,42 @@ describe("AgentServer HTTP Mode", () => {});}, 30000);+ it("reports the initialization phase the runtime agent published", async () => {+ const s = createServer();+ await s.start();+ const { extNotification } = (+ s as unknown as {+ createCloudClient(payload: {+ run_id: string;+ task_id: string;+ team_id: number;+ user_id: number;+ distinct_id: string;+ }): {+ extNotification(+ method: string,+ params: Record<string, unknown>,+ ): Promise<void>;+ };+ }+ ).createCloudClient({+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "user-1",+ });++ await extNotification(POSTHOG_NOTIFICATIONS.STATUS, {+ status: "setup_hooks",+ });++ const response = await fetch(`http://localhost:${port}/health`);+ expect(await response.json()).toMatchObject({+ initializationPhase: "setup_hooks",+ });+ }, 30000);+it.each([{label: "uses a valid run-state system prompt",diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex a078dac91e67..646150b36a14 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -76,6 +76,7 @@ import {type InProcessAcpConnection,} from "../adapters/acp-connection";import { setAlwaysAskMcpServers } from "../adapters/claude/mcp/tool-metadata";+import type { InitializationPhase } from "../adapters/claude/session/initialization";import {getSessionJsonlPath,hydrateSessionJsonl,@@ -575,6 +576,7 @@ export class AgentServer {typeof createAcpConnection> | null = null;private initializationFailureCode: string | undefined;+ private initializationPhase: InitializationPhase | undefined;private initializingSseController: SseController | null = null;private initializingTelemetry: OtelRunTelemetry | undefined;private pendingEvents: Record<string, unknown>[] = [];@@ -792,6 +794,7 @@ export class AgentServer {status: "ok",hasSession: !!this.session,readiness: boot.state,+ initializationPhase: this.initializationPhase,failureCode: this.initializationFailureCode,bootMs: this.sessionReadyBootMs,sessionInitMs: this.sessionInitMs,@@ -5042,6 +5045,13 @@ export class AgentServer {method: string,params: Record<string, unknown>,) => {+ if (+ method === POSTHOG_NOTIFICATIONS.STATUS &&+ (params.status === "sdk_initialization" ||+ params.status === "setup_hooks")+ ) {+ this.initializationPhase = params.status;+ }this.logger.debug("Extension notification", { method, params });},sessionUpdate: async (params: {diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex 0fdbb869d5a6..d24476a2d046 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -249,6 +249,15 @@ def _credential_marker(*sources: str) -> str | None:return None+def _health_initialization_phase(health_response: str) -> str | None:+ try:+ payload = json.loads(health_response or "{}")+ except ValueError:+ return None+ phase = payload.get("initializationPhase") if isinstance(payload, dict) else None+ return phase if isinstance(phase, str) else None++def _health_duration_ms(stdout: str) -> int | None:for line in stdout.splitlines():if line.startswith(AGENT_SERVER_HEALTH_DURATION_PREFIX):@@ -441,6 +450,11 @@ class AgentServerLaunchMixin(SandboxBase):timeout_seconds=5,)diagnostics["health_response"] = health_result.stdout.strip()[:500]+ if _health_initialization_phase(health_result.stdout) == "setup_hooks":+ diagnostics["failure_reason"] = (+ "agent server still running the repository's SessionStart hooks when the startup budget ended"+ )+ return diagnosticsegress = self._probe_session_init_egress()diagnostics["egress_probe"] = egressdiff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 58f981597994..04c9a29d7584 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -891,6 +891,7 @@ def wait_for_health_check(HEALTH_CURL_MAX_TIME_SECONDS = 2+SETUP_HOOKS_BUDGET_SECONDS = 630def build_health_check_command(@@ -904,8 +905,10 @@ def build_health_check_command(# The attempt count assumes an instant poll. A poll that waits on curl or python startup# would otherwise outrun the exec timeout, and the caller never sees the loop's result.budget_seconds = health_check_budget_seconds(max_attempts, poll_interval)+ hooks_budget_seconds = max(budget_seconds, SETUP_HOOKS_BUDGET_SECONDS)+ hooks_max_attempts = max(max_attempts, int(hooks_budget_seconds / poll_interval) if poll_interval > 0 else 0)return (- "SECONDS=0; i=0; while :; do "+ f"SECONDS=0; i=0; max_attempts={max_attempts}; budget={budget_seconds}; while :; do "" i=$((i + 1)); "f"{process_check}"f" body=$(curl -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "@@ -916,10 +919,13 @@ def build_health_check_command(" python3 -c '""import json, sys; ""payload = json.loads(sys.argv[1]); "- 'sys.exit(0 if payload.get("status") == "ok" and payload.get("hasSession") is True else 1)'- f'\' "$body" && echo "ok:$i" && exit 0; '+ 'ready = payload.get("status") == "ok" and payload.get("hasSession") is True; '+ 'sys.exit(0 if ready else 2 if payload.get("initializationPhase") == "setup_hooks" else 1)'+ '\' "$body"; ready=$?; '+ ' if [ "$ready" = "0" ]; then echo "ok:$i"; exit 0; fi; '+ f' if [ "$ready" = "2" ]; then max_attempts={hooks_max_attempts}; budget={hooks_budget_seconds}; fi; '" fi; "- f' if [ "$i" -ge {max_attempts} ] || [ "$SECONDS" -ge {budget_seconds} ]; then exit 1; fi; '+ ' if [ "$i" -ge "$max_attempts" ] || [ "$SECONDS" -ge "$budget" ]; then exit 1; fi; 'f" sleep {poll_interval}; ""done")@@ -930,7 +936,8 @@ def health_check_budget_seconds(max_attempts: int = 60, poll_interval: float = 0def health_check_timeout_seconds(max_attempts: int = 60, poll_interval: float = 0.5) -> int:- return max(30, health_check_budget_seconds(max_attempts, poll_interval) + HEALTH_CURL_MAX_TIME_SECONDS + 5)+ budget_seconds = max(health_check_budget_seconds(max_attempts, poll_interval), SETUP_HOOKS_BUDGET_SECONDS)+ return max(30, budget_seconds + HEALTH_CURL_MAX_TIME_SECONDS + 5)SandboxClass = type[SandboxBase]diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 5d0c495734a0..6b7f320943c7 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -1544,6 +1544,29 @@ class TestStartupFailureDiagnostics:assert "never reported hasSession=true" in diagnostics["failure_reason"]assert diagnostics["host_pressure"] == "ok"+ def test_reports_running_session_hooks_without_probing_egress(self) -> None:+ sandbox = self._sandbox()++ def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:+ if "/health" in command:+ return ExecutionResult(+ stdout='{"status":"ok","hasSession":false,"initializationPhase":"setup_hooks"}',+ stderr="",+ exit_code=0,+ error=None,+ )+ return ExecutionResult(stdout="ok", stderr="", exit_code=0, error=None)++ with (+ patch.object(sandbox, "is_running", return_value=True),+ patch.object(sandbox, "execute", side_effect=_exec) as execute,+ ):+ diagnostics = sandbox._diagnose_startup_failure(allowed_domains=["github.com"])++ assert "SessionStart hooks" in diagnostics["failure_reason"]+ assert "egress_probe" not in diagnostics+ assert all("http_code=" not in call.args[0] for call in execute.call_args_list)+def test_skips_probes_when_the_log_shows_a_missing_credential(self) -> None:sandbox = self._sandbox()diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.pyindex c37b33be28ae..f50bf8883acb 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py@@ -53,6 +53,30 @@ def test_health_check_loop_stops_at_wall_clock_budget(tmp_path, body, expected_eassert elapsed < budget + poll_delay + poll_interval + 2+def test_health_check_loop_outlasts_its_budget_while_session_hooks_run(tmp_path: Path) -> None:+ max_attempts, poll_interval, hook_polls = 20, 0.01, 30+ curl = tmp_path / "curl"+ curl.write_text(+ "#!/bin/bash\n"+ f"count=$(( $(cat {tmp_path}/polls 2>/dev/null || echo 0) + 1 )); echo $count > {tmp_path}/polls\n"+ f'if [ "$count" -le {hook_polls} ]; then printf \'%s\' \'{{"status":"ok","hasSession":false,"initializationPhase":"setup_hooks"}}\'; '+ 'else printf \'%s\' \'{"status":"ok","hasSession":true}\'; fi\n'+ )+ curl.chmod(0o755)+ env = {**os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}"}++ completed = subprocess.run(+ ["bash", "-c", build_health_check_command(port=1, max_attempts=max_attempts, poll_interval=poll_interval)],+ env=env,+ capture_output=True,+ text=True,+ timeout=60,+ )++ assert completed.returncode == 0, completed.stderr+ assert completed.stdout.strip() == f"ok:{hook_polls + 1}"++def _run_preflight(tmp_path: Path, health_body: str, capability_tokens: str) -> subprocess.CompletedProcess[str]:bin_dir = tmp_path / "bin"bin_dir.mkdir()diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex d6940d9c0d37..e6fe4ddf8082 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -2465,7 +2465,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):workflow_start_at=self._workflow_start_at_iso(),boot_excluded_ms=boot_excluded_ms,),- start_to_close_timeout=timedelta(minutes=5),+ start_to_close_timeout=timedelta(minutes=15),retry_policy=RetryPolicy(maximum_attempts=3),)@@ -2523,7 +2523,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):workflow_start_at=self._workflow_start_at_iso(),boot_excluded_ms=boot_excluded_ms,),- start_to_close_timeout=timedelta(minutes=5),+ start_to_close_timeout=timedelta(minutes=15),retry_policy=RetryPolicy(maximum_attempts=3),)