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(phai): sandbox warming, oauth app, and llm-gateway product config (#64881)

Georgiy Tarasovd42cf20d89cc
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index fbaee70a8655..ee080b6e0708 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -11,8 +11,12 @@ from posthog.utils import get_instance_region
ARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"
ARRAY_APP_CLIENT_ID_EU = "AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9"
ARRAY_APP_CLIENT_ID_DEV = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ"
+POSTHOG_AI_APP_CLIENT_ID_US = "N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu"
+POSTHOG_AI_APP_CLIENT_ID_EU = "0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi"
+POSTHOG_AI_APP_CLIENT_ID_DEV = "DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1"
McpScopePreset = Literal["read_only", "full", "signals_scout"]
+SandboxOAuthApplication = Literal["array", "posthog_ai"]
INTERNAL_SCOPES: list[str] = [
@@ -112,19 +116,52 @@ def has_write_scopes(scopes: PosthogMcpScopes) -> bool:
return any(s in MCP_WRITE_SCOPES for s in scopes)
-def get_array_app() -> OAuthApplication:
- region = get_instance_region()
+def _get_client_id_for_region(*, region: str | None, us: str, eu: str, dev: str) -> str:
if region == "EU":
- client_id = ARRAY_APP_CLIENT_ID_EU
- elif region == "US":
- client_id = ARRAY_APP_CLIENT_ID_US
- else:
- client_id = ARRAY_APP_CLIENT_ID_DEV
+ return eu
+ if region == "US":
+ return us
+ return dev
+
+
+def _get_oauth_app_for_client_id(client_id: str, app_name: str, region: str | None) -> OAuthApplication:
+ if not client_id:
+ raise RuntimeError(f"{app_name} app not configured for region {region}")
try:
return OAuthApplication.objects.get(client_id=client_id)
except OAuthApplication.DoesNotExist as err:
- raise RuntimeError(f"Array app not found for region {region} (client_id={client_id})") from err
+ raise RuntimeError(f"{app_name} app not found for region {region} (client_id={client_id})") from err
+
+
+def get_array_app() -> OAuthApplication:
+ region = get_instance_region()
+ client_id = _get_client_id_for_region(
+ region=region,
+ us=ARRAY_APP_CLIENT_ID_US,
+ eu=ARRAY_APP_CLIENT_ID_EU,
+ dev=ARRAY_APP_CLIENT_ID_DEV,
+ )
+
+ return _get_oauth_app_for_client_id(client_id, "Array", region)
+
+
+def get_posthog_ai_app() -> OAuthApplication:
+ region = get_instance_region()
+ client_id = _get_client_id_for_region(
+ region=region,
+ us=POSTHOG_AI_APP_CLIENT_ID_US,
+ eu=POSTHOG_AI_APP_CLIENT_ID_EU,
+ dev=POSTHOG_AI_APP_CLIENT_ID_DEV,
+ )
+
+ return _get_oauth_app_for_client_id(client_id, "PostHog AI", region)
+
+
+def get_sandbox_oauth_app(application: SandboxOAuthApplication = "array") -> OAuthApplication:
+ if application == "posthog_ai":
+ return get_posthog_ai_app()
+ return get_array_app()
def create_oauth_access_token_for_user(
@@ -133,9 +170,10 @@ def create_oauth_access_token_for_user(
*,
scopes: PosthogMcpScopes = "read_only",
include_internal_scopes: bool = True,
+ application: SandboxOAuthApplication = "array",
) -> str:
resolved = resolve_scopes(scopes, include_internal_scopes=include_internal_scopes)
- app = get_array_app()
+ app = get_sandbox_oauth_app(application)
token_value = generate_random_oauth_access_token(None)
OAuthAccessToken.objects.create(
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index 4c71a5f53d87..f975679c8347 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -1,13 +1,16 @@
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
+from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User
from posthog.temporal.oauth import (
INTERNAL_SCOPES,
MCP_READ_SCOPES,
MCP_WRITE_SCOPES,
+ POSTHOG_AI_APP_CLIENT_ID_DEV,
SCOUT_INTERNAL_SCOPES,
SCOUT_USER_WRITE_SCOPES,
+ create_oauth_access_token_for_user,
has_write_scopes,
resolve_scopes,
)
@@ -126,3 +129,39 @@ class TestHasWriteScopes(SimpleTestCase):
)
def test_has_write_scopes(self, _name: str, scopes, expected: bool) -> None:
assert has_write_scopes(scopes) == expected
+
+
+class TestCreateOAuthAccessTokenForUser(TestCase):
+ def _create_oauth_app(self, client_id: str, name: str) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ client_id=client_id,
+ name=name,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="http://localhost:8237/callback",
+ algorithm="RS256",
+ )
+
+ def _create_user_and_team(self) -> tuple[User, Team]:
+ organization = Organization.objects.create(name="OAuth test org")
+ team = Team.objects.create(organization=organization, name="OAuth test team")
+ user = User.objects.create(email="[email protected]")
+ return user, team
+
+ @override_settings(CLOUD_DEPLOYMENT="DEV")
+ def test_posthog_ai_application_uses_dev_app(self) -> None:
+ app = self._create_oauth_app(POSTHOG_AI_APP_CLIENT_ID_DEV, "PostHog AI Dev App")
+ user, team = self._create_user_and_team()
+
+ token = create_oauth_access_token_for_user(user, team.id, application="posthog_ai")
+
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert access_token.application_id == app.id
+ assert access_token.scoped_teams == [team.id]
+
+ @override_settings(CLOUD_DEPLOYMENT="DEV")
+ def test_posthog_ai_application_requires_existing_app(self) -> None:
+ user, team = self._create_user_and_team()
+
+ with self.assertRaisesRegex(RuntimeError, "PostHog AI app not found"):
+ create_oauth_access_token_for_user(user, team.id, application="posthog_ai")
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 55ffc066674d..f61be2d8244a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -125,6 +125,7 @@ __all__ = [
"get_task_run",
"get_task_run_detail",
"get_task_run_sandbox_connection",
+ "capture_relay_command_telemetry",
"get_task_run_stream_info",
"get_task_summaries",
"is_internal_debug_team",
@@ -1732,6 +1733,64 @@ def get_task_run_sandbox_connection(
)
+# Relay control verbs whose outcome PostHog AI funnels track. Captured here (gated on
+# origin_product) so the generic relay stays product-agnostic while the conversation layer stops
+# firing them as the renderer drives permission/cancel through `runs/{run}/command/`.
+_POSTHOG_AI_RELAY_TELEMETRY_METHODS: frozenset[str] = frozenset({"cancel", "permission_response"})
+
+
+def capture_relay_command_telemetry(
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ method: str,
+ params: dict | None,
+ success: bool,
+) -> None:
+ """Emit PostHog AI control-verb telemetry for a relayed agent command.
+
+ Preserves the ``task_run_cancelled`` / ``permission_responded`` funnels once the renderer moves
+ permission/cancel onto the generic relay. ``conversation_id`` is intentionally null (the relay
+ has no conversation); ``TaskRun.capture_event`` stamps ``origin_product``/``run_id`` so
+ generic-task usage stays out of the PostHog AI funnels. Mirrors the old conversation-layer
+ semantics: a cancel is recorded only when it actually reached the agent, while a permission
+ response is recorded with its forward ``success`` either way.
+ """
+ if method not in _POSTHOG_AI_RELAY_TELEMETRY_METHODS:
+ return
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None or run.task.origin_product != Task.OriginProduct.POSTHOG_AI:
+ return
+
+ params = params or {}
+ if method == "cancel":
+ if not success:
+ return
+ run.capture_event(
+ "task_run_cancelled",
+ {
+ "execution_type": "sandbox",
+ "surface": "relay",
+ "conversation_id": None,
+ "cancel_source": "user",
+ },
+ )
+ return
+
+ run.capture_event(
+ "permission_responded",
+ {
+ "execution_type": "sandbox",
+ "surface": "relay",
+ "conversation_id": None,
+ "request_id": params.get("requestId"),
+ "option_id": params.get("optionId"),
+ "success": success,
+ },
+ )
+
+
# --- Task run relay (Slack) ---
diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.py
new file mode 100644
index 000000000000..5e07307f939e
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_warm.py
@@ -0,0 +1,179 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework.exceptions import PermissionDenied, Throttled
+
+from posthog.exceptions import QuotaLimitExceeded
+
+from products.tasks.backend.logic.services.warm import SandboxWarmer
+from products.tasks.backend.models import Task, TaskRun
+
+WARM = "products.tasks.backend.logic.services.warm"
+_CAPS = SandboxWarmer.ORIGIN_PRODUCT_CAPS[Task.OriginProduct.POSTHOG_AI]
+
+
+class TestSandboxWarmerWarm(APIBaseTest):
+ def _task(self, *, origin=Task.OriginProduct.POSTHOG_AI, created_by=None) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=origin,
+ created_by=created_by or self.user,
+ )
+
+ def _warm_run_on_new_task(self, *, created_by=None) -> TaskRun:
+ task = self._task(created_by=created_by)
+ return task.create_run(mode="interactive", extra_state={"await_user_message": True})
+
+ def test_provisions_warm_run_when_task_has_no_runs(self):
+ task = self._task()
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=False),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = SandboxWarmer(task, user=self.user).warm(extra_state={"systemPrompt": "SYS"})
+
+ assert result.just_created is True
+ run = result.run
+ assert run.state["await_user_message"] is True
+ assert run.state["initial_permission_mode"] == "default"
+ assert run.state["systemPrompt"] == "SYS"
+ assert run.state["mode"] == "interactive"
+ assert "resume_from_run_id" not in run.state
+
+ m_workflow.assert_called_once()
+ _, kwargs = m_workflow.call_args
+ assert kwargs["run_id"] == str(run.id)
+ assert kwargs["create_pr"] is False
+ assert kwargs["posthog_mcp_scopes"] == "full"
+
+ def test_idempotent_when_non_terminal_run_exists(self):
+ task = self._task()
+ existing = task.create_run(mode="interactive", extra_state={"await_user_message": True})
+
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=False),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = SandboxWarmer(task, user=self.user).warm()
+
+ assert result.just_created is False
+ assert result.run.id == existing.id
+ assert task.runs.count() == 1
+ m_workflow.assert_not_called()
+
+ def test_rewarms_with_resume_after_terminal_run(self):
+ task = self._task()
+ terminal = task.create_run(mode="interactive", extra_state={"snapshot_external_id": "snap-1"})
+ terminal.status = TaskRun.Status.COMPLETED
+ terminal.save(update_fields=["status"])
+
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=False),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = SandboxWarmer(task, user=self.user).warm()
+
+ assert result.just_created is True
+ assert result.run.id != terminal.id
+ assert result.run.state["await_user_message"] is True
+ assert result.run.state["resume_from_run_id"] == str(terminal.id)
+ # Snapshot carried forward so the warm session reuses the prior Run's filesystem.
+ assert result.run.state["snapshot_external_id"] == "snap-1"
+ m_workflow.assert_called_once()
+
+ def test_dispatch_is_deferred_to_commit(self):
+ # No captureOnCommitCallbacks: the test transaction never commits, so the on_commit dispatch
+ # must not fire — proving provisioning isn't done inside the atomic block.
+ task = self._task()
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=False),
+ ):
+ result = SandboxWarmer(task, user=self.user).warm()
+ m_workflow.assert_not_called()
+
+ assert result.just_created is True
+ assert task.runs.count() == 1
+
+ def test_over_quota_raises_and_creates_no_run(self):
+ task = self._task()
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=True),
+ ):
+ with self.assertRaises(QuotaLimitExceeded):
+ SandboxWarmer(task, user=self.user).warm()
+
+ assert task.runs.count() == 0
+ m_workflow.assert_not_called()
+
+ def test_unregistered_origin_product_is_rejected(self):
+ # Fail-closed: only origin products with a registered quota gate may warm.
+ task = self._task(origin=Task.OriginProduct.USER_CREATED)
+ with self.assertRaises(PermissionDenied):
+ SandboxWarmer(task, user=self.user).warm()
+ assert task.runs.count() == 0
+
+ def test_over_cap_raises_throttled(self):
+ for _ in range(_CAPS.per_user):
+ self._warm_run_on_new_task()
+
+ task = self._task()
+ with (
+ patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
+ patch(f"{WARM}.is_team_limited", return_value=False),
+ ):
+ with self.assertRaises(Throttled):
+ SandboxWarmer(task, user=self.user).warm()
+
+ assert task.runs.count() == 0
+ m_workflow.assert_not_called()
+
+
+class TestSandboxWarmerAtCapacity(APIBaseTest):
+ def _warm_run_on_new_task(self, *, created_by=None, status=TaskRun.Status.QUEUED, warm=True) -> TaskRun:
+ task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ created_by=created_by or self.user,
+ )
+ extra = {"await_user_message": True} if warm else {}
+ run = task.create_run(mode="interactive", extra_state=extra)
+ if status != TaskRun.Status.QUEUED:
+ run.status = status
+ run.save(update_fields=["status"])
+ return run
+
+ def test_counts_only_warm_non_terminal_runs(self):
+ origin = Task.OriginProduct.POSTHOG_AI
+
+ # Terminal warm runs drop from the count via the status filter.
+ for _ in range(_CAPS.per_user):
+ self._warm_run_on_new_task(status=TaskRun.Status.CANCELLED)
+ assert SandboxWarmer.at_capacity(origin, self.team, self.user) is False
+
+ # Activated (await_user_message cleared) non-terminal runs drop via the state filter.
+ for _ in range(_CAPS.per_user):
+ self._warm_run_on_new_task(warm=False)
+ assert SandboxWarmer.at_capacity(origin, self.team, self.user) is False
+
+ # Genuine warm runs do count.
+ for _ in range(_CAPS.per_user):
+ self._warm_run_on_new_task()
+ assert SandboxWarmer.at_capacity(origin, self.team, self.user) is True
+
+ def test_per_org_cap_counts_across_users(self):
+ origin = Task.OriginProduct.POSTHOG_AI
+ other = self._create_user("[email protected]")
+ for _ in range(_CAPS.per_org):
+ self._warm_run_on_new_task(created_by=other)
+
+ # The requesting user holds no warm runs, but the org cap is full.
+ assert SandboxWarmer.at_capacity(origin, self.team, self.user) is True
diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.py
new file mode 100644
index 000000000000..16053cb774c7
--- /dev/null
+++ b/products/tasks/backend/logic/services/warm.py
@@ -0,0 +1,177 @@
+"""Generic sandbox warming for products/tasks.
+
+Warming eagerly boots a sandbox + ACP session on an interactive Run that idles
+awaiting the first ``user_message``, so first-token latency drops from a cold boot
+to roughly model-invocation time. The mechanic plus its guardrails — a per-product
+quota gate and a warm-pool concurrency cap — live here so every product warms through
+one implementation rather than reimplementing provisioning, quota, and idempotency.
+
+The trigger (when to warm) and Task ownership (birth + linking to the product's own
+entity) stay per-product: ``SandboxWarmer`` operates on an *existing* Task. PostHog AI's
+prewarm is the only caller today; the registries below are fail-closed, so a product
+must opt in with a quota gate before it can warm.
+"""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+from django.db import transaction
+
+import structlog
+from rest_framework.exceptions import PermissionDenied, Throttled
+
+from posthog.exceptions import QuotaLimitExceeded
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.client import execute_task_processing_workflow
+
+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass
+class WarmResult:
+ """Outcome of a warm request — the Run to open against, and whether it was just provisioned."""
+
+ run: TaskRun
+ just_created: bool
+
+
+@dataclass(frozen=True)
+class WarmPoolCaps:
+ per_user: int
+ per_org: int
+
+
+def _ai_credits_checker(team: Team, user: User) -> None:
+ if is_team_limited(team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY):
+ raise QuotaLimitExceeded(
+ "Your organization reached its AI credit usage limit. Increase the limits in Billing settings, "
+ "or ask an org admin to do so."
+ )
+
+
+class SandboxWarmer:
+ """Idempotently warm a sandbox Run for an existing Task, enforcing the product's quota gate and a
+ state-derived warm-pool cap, then dispatching the processing workflow after commit.
+
+ The quota gate and cap are also exposed as classmethods (keyed on team/user, not a Task) so a
+ caller can gate *before* it births a Task — an over-quota or over-cap warm must not leave behind a
+ runless Task the next message can't continue.
+ """
+
+ # A warm Run is non-terminal and idling; these are the statuses it can hold before activation.
+ _NON_TERMINAL_STATUSES: frozenset[str] = frozenset({TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS})
+
+ # Each checker returns None or raises a DRF APIException; the in-process caller can't return an HTTP
+ # Response, so the contract is exception-based and DRF renders the status from any depth. Fail-closed:
+ # a product warms only once it registers a gate here, else it would provision sandboxes with no ceiling.
+ ORIGIN_PRODUCT_QUOTA: dict[str, Callable[[Team, User], None]] = {
+ Task.OriginProduct.POSTHOG_AI: _ai_credits_checker,
+ }
+
+ ORIGIN_PRODUCT_CAPS: dict[str, WarmPoolCaps] = {
+ Task.OriginProduct.POSTHOG_AI: WarmPoolCaps(per_user=2, per_org=10),
+ }
+ _DEFAULT_CAPS: WarmPoolCaps = WarmPoolCaps(per_user=2, per_org=10)
+
+ def __init__(self, task: "Task", *, user: User) -> None:
+ self.task = task
+ self.user = user
+
+ @classmethod
+ def enforce_quota(cls, origin_product: str, team: Team, user: User) -> None:
+ """Raise if ``team`` may not warm a Run for ``origin_product`` (over quota, or product not registered)."""
+ checker = cls.ORIGIN_PRODUCT_QUOTA.get(origin_product)
+ if checker is None:
+ raise PermissionDenied(f"Warming is not enabled for origin product '{origin_product}'.")
+ checker(team, user)
+
+ @classmethod
+ def at_capacity(cls, origin_product: str, team: Team, user: User) -> bool:
+ """True if the user or org already holds the max concurrent *warm* Runs.
+
+ Counts only Runs still awaiting their first message (``state.await_user_message`` set) — so the
+ warm-pool budget and the active (AI-credit) budget are disjoint: activating a warm Run clears the
+ flag and drops it from this count for free, and a terminal Run drops via the status filter. No
+ increment/decrement counter is kept; the count is derived from state. The cross-task count is not
+ serialized by the per-Task lock, so it may overshoot slightly under heavy concurrency — acceptable
+ for a best-effort resource guard.
+ """
+ caps = cls.ORIGIN_PRODUCT_CAPS.get(origin_product, cls._DEFAULT_CAPS)
+ # `await_user_message` is stored literally (the field is alias-free in PostHogAIRunState); see the
+ # comment there before adding an alias, which would silently break this filter and open the cap.
+ warm_runs = TaskRun.objects.filter(
+ task__origin_product=origin_product,
+ status__in=cls._NON_TERMINAL_STATUSES,
+ state__await_user_message=True,
+ ).exclude(task__deleted=True)
+
+ if warm_runs.filter(task__created_by_id=user.pk).count() >= caps.per_user:
+ return True
+ return warm_runs.filter(task__team__organization_id=team.organization_id).count() >= caps.per_org
+
+ def warm(self, *, mode: str = "interactive", extra_state: dict[str, Any] | None = None) -> WarmResult:
+ """Idempotently ensure the Task has a warm Run, then dispatch the processing workflow after commit.
+
+ - Idempotent: if the Task already has a non-terminal Run, return it without provisioning.
+ - Fresh: a Task with no Runs gets a new warm Run; a Task whose latest Run is terminal gets a
+ successor that resumes from it (filesystem reuse via ``snapshot_external_id``).
+ - ``extra_state`` carries product-specific Run state the generic warmer can't know (e.g. PostHog
+ AI's ``systemPrompt``); it is merged into the warm Run's initial state.
+
+ Raises ``QuotaLimitExceeded`` (402) / ``PermissionDenied`` (403) when gated, and ``Throttled``
+ (429) when the warm pool is full.
+ """
+ # Quota is a gateway/cache call — check it before taking the row lock, never while holding it.
+ self.enforce_quota(self.task.origin_product, self.task.team, self.user)
+
+ new_run: TaskRun
+ with transaction.atomic():
+ locked = Task.objects.select_for_update().get(id=self.task.id)
+ existing = locked.latest_run
+ if existing is not None and not existing.is_terminal:
+ # A warm Run already idling, or an active Run in progress — either way, no double-provision.
+ return WarmResult(run=existing, just_created=False)
+
+ if self.at_capacity(locked.origin_product, locked.team, self.user):
+ raise Throttled(detail="Warm-pool capacity reached. Release an idle warm session and try again.")
+
+ run_state: dict[str, Any] = {
+ "await_user_message": True,
+ "initial_permission_mode": "default",
+ **(extra_state or {}),
+ }
+ if existing is not None:
+ # Latest Run is terminal — resume into a successor so the warm session reuses its filesystem.
+ run_state["resume_from_run_id"] = str(existing.id)
+ snapshot_external_id = (existing.state or {}).get("snapshot_external_id")
+ if snapshot_external_id:
+ run_state["snapshot_external_id"] = snapshot_external_id
+
+ new_run = locked.create_run(mode=mode, extra_state=run_state)
+
+ # Dispatch only after the row commits, so a rollback can't leave an orphaned sandbox.
+ task_id, run_id, team_id, user_id = str(locked.id), str(new_run.id), self.task.team_id, self.user.pk
+ transaction.on_commit(
+ lambda: execute_task_processing_workflow(
+ task_id=task_id,
+ run_id=run_id,
+ team_id=team_id,
+ user_id=user_id,
+ create_pr=False,
+ posthog_mcp_scopes="full",
+ )
+ )
+
+ logger.info(
+ "sandbox_warm_run_provisioned",
+ task_id=str(self.task.id),
+ run_id=str(new_run.id),
+ origin_product=self.task.origin_product,
+ )
+ return WarmResult(run=new_run, just_created=True)
diff --git a/products/tasks/backend/management/commands/setup_tasks_oauth.py b/products/tasks/backend/management/commands/setup_tasks_oauth.py
index 165fe8aa43aa..c851ce26b95d 100644
--- a/products/tasks/backend/management/commands/setup_tasks_oauth.py
+++ b/products/tasks/backend/management/commands/setup_tasks_oauth.py
@@ -2,7 +2,11 @@ from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from posthog.models import OAuthApplication
-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
+from posthog.models.oauth import OAuthApplicationAuthBrand
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
+
+ARRAY_REDIRECT_URIS = "http://localhost:8237/callback http://localhost:8239/callback"
+POSTHOG_AI_REDIRECT_URIS = "http://localhost:8000/authorize"
class Command(BaseCommand):
@@ -12,16 +16,39 @@ class Command(BaseCommand):
if not settings.DEBUG:
raise CommandError("This command can only be run with DEBUG=1")
- app, created = OAuthApplication.objects.get_or_create(
- client_id=ARRAY_APP_CLIENT_ID_DEV,
- defaults={
+ self._setup_app(
+ ARRAY_APP_CLIENT_ID_DEV,
+ {
"name": "Array Dev App",
"client_type": OAuthApplication.CLIENT_PUBLIC,
"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
- "redirect_uris": "http://localhost:8237/callback http://localhost:8239/callback",
+ "redirect_uris": ARRAY_REDIRECT_URIS,
+ "algorithm": "RS256",
+ },
+ )
+ self._setup_app(
+ POSTHOG_AI_APP_CLIENT_ID_DEV,
+ {
+ "name": "PostHog AI Dev App",
+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": POSTHOG_AI_REDIRECT_URIS,
"algorithm": "RS256",
+ "auth_brand": OAuthApplicationAuthBrand.POSTHOG.value,
+ "is_verified": True,
+ "is_first_party": True,
},
)
+
+ def _setup_app(self, client_id: str, defaults: dict[str, object]) -> None:
+ if not client_id:
+ self.stdout.write(self.style.WARNING(f"Skipping {defaults['name']}; no client_id configured"))
+ return
+
+ app, created = OAuthApplication.objects.get_or_create(
+ client_id=client_id,
+ defaults=defaults,
+ )
if created:
self.stdout.write(self.style.SUCCESS(f"Created OAuthApplication '{app.name}' (client_id={app.client_id})"))
else:
diff --git a/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py
new file mode 100644
index 000000000000..fe701606624b
--- /dev/null
+++ b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py
@@ -0,0 +1,23 @@
+from io import StringIO
+
+from django.core.management import call_command
+from django.test import TestCase, override_settings
+
+from posthog.models import OAuthApplication
+from posthog.models.oauth import OAuthApplicationAuthBrand
+from posthog.temporal.oauth import POSTHOG_AI_APP_CLIENT_ID_DEV
+
+
+class TestSetupTasksOAuth(TestCase):
+ @override_settings(DEBUG=True)
+ def test_creates_posthog_ai_dev_oauth_app(self) -> None:
+ call_command("setup_tasks_oauth", stdout=StringIO())
+
+ app = OAuthApplication.objects.get(client_id=POSTHOG_AI_APP_CLIENT_ID_DEV)
+ assert app.name == "PostHog AI Dev App"
+ assert app.client_type == OAuthApplication.CLIENT_CONFIDENTIAL
+ assert app.authorization_grant_type == OAuthApplication.GRANT_AUTHORIZATION_CODE
+ assert app.redirect_uris == "http://localhost:8000/authorize"
+ assert app.auth_brand == OAuthApplicationAuthBrand.POSTHOG.value
+ assert app.is_verified is True
+ assert app.is_first_party is True
diff --git a/products/tasks/backend/migrations/0040_alter_task_origin_product.py b/products/tasks/backend/migrations/0040_alter_task_origin_product.py
new file mode 100644
index 000000000000..432e10774e20
--- /dev/null
+++ b/products/tasks/backend/migrations/0040_alter_task_origin_product.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.2.14 on 2026-06-17 15:14
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0039_codeprsnapshot_head_branch"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="task",
+ name="origin_product",
+ field=models.CharField(
+ choices=[
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("automation", "Automation"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index fc8df184e26c..a616661a1e83 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0039_codeprsnapshot_head_branch
+0040_alter_task_origin_product
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 50196d5ed58b..47be770898a9 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -65,6 +65,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
SLACK = "slack", "Slack"
SUPPORT_QUEUE = "support_queue", "Support Queue"
SESSION_SUMMARIES = "session_summaries", "Session Summaries"
+ POSTHOG_AI = "posthog_ai", "PostHog AI"
# Unlike the others (which indicate direct creation from that product, e.g. a "fix this error" button),
# signal report tasks originate indirectly via signals from other products.
SIGNAL_REPORT = "signal_report", "Signal Report"
@@ -318,20 +319,16 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
raise Exception("Cannot hard delete Task. Use soft_delete() instead.")
@staticmethod
- def create_and_run(
+ def _build_task(
*,
team: Team,
title: str,
description: str,
origin_product: "Task.OriginProduct",
- user_id: int, # Will be used to validate the tasks feature flag and create a personal api key for interacting with PostHog.
- repository: str | None = None, # Format: "organization/repository", e.g. "posthog/posthog-js"
- create_pr: bool = True,
- mode: str = "background",
+ user_id: int,
+ repository: str | None = None,
slack_thread_context: Optional["SlackThreadContext"] = None,
slack_thread_url: str | None = None,
- start_workflow: bool = True,
- posthog_mcp_scopes: PosthogMcpScopes = "full",
branch: str | None = None,
signal_report_id: str | None = None,
ai_stage: str | None = None,
@@ -344,9 +341,13 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
sandbox_resources: "SandboxResources | None" = None,
sandbox_timeout_seconds: int | None = None,
inactivity_timeout_seconds: int | None = None,
- ) -> "Task":
- from products.tasks.backend.temporal.client import execute_task_processing_workflow
+ ) -> tuple["Task", dict[str, Any]]:
+ """Create the Task row and assemble the initial run's `extra_state`.
+ Shared by `create_and_run` (which then creates and dispatches the run) and
+ `create_without_run` (which discards the run state). One path keeps the
+ GitHub-integration resolution and authorship logic from drifting between them.
+ """
created_by = User.objects.get(id=user_id)
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
@@ -469,6 +470,107 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
if inactivity_timeout_seconds is not None:
extra_state["inactivity_timeout_seconds"] = inactivity_timeout_seconds
+ return task, extra_state
+
+ @staticmethod
+ def create_without_run(
+ *,
+ team: Team,
+ title: str,
+ description: str,
+ origin_product: "Task.OriginProduct",
+ user_id: int,
+ repository: str | None = None,
+ slack_thread_context: Optional["SlackThreadContext"] = None,
+ slack_thread_url: str | None = None,
+ branch: str | None = None,
+ signal_report_id: str | None = None,
+ sandbox_environment_id: str | None = None,
+ internal: bool = False,
+ output_schema: type[BaseModel] | dict | None = None,
+ interaction_origin: str | None = None,
+ model: str | None = None,
+ initial_permission_mode: str | None = None,
+ ) -> "Task":
+ """Create the Task row without an initial run or workflow.
+
+ For callers that own run creation themselves — e.g. the sandbox warm path
+ (`products/tasks/backend/services/warm.py`), which creates the first run with its
+ own state. The run `extra_state` assembled by `_build_task` is discarded here.
+ """
+ task, _ = Task._build_task(
+ team=team,
+ title=title,
+ description=description,
+ origin_product=origin_product,
+ user_id=user_id,
+ repository=repository,
+ slack_thread_context=slack_thread_context,
+ slack_thread_url=slack_thread_url,
+ branch=branch,
+ signal_report_id=signal_report_id,
+ sandbox_environment_id=sandbox_environment_id,
+ internal=internal,
+ output_schema=output_schema,
+ interaction_origin=interaction_origin,
+ model=model,
+ initial_permission_mode=initial_permission_mode,
+ )
+ return task
+
+ @staticmethod
+ def create_and_run(
+ *,
+ team: Team,
+ title: str,
+ description: str,
+ origin_product: "Task.OriginProduct",
+ user_id: int, # Will be used to validate the tasks feature flag and create a personal api key for interacting with PostHog.
+ repository: str | None = None, # Format: "organization/repository", e.g. "posthog/posthog-js"
+ create_pr: bool = True,
+ mode: str = "background",
+ slack_thread_context: Optional["SlackThreadContext"] = None,
+ slack_thread_url: str | None = None,
+ start_workflow: bool = True,
+ posthog_mcp_scopes: PosthogMcpScopes = "full",
+ branch: str | None = None,
+ signal_report_id: str | None = None,
+ sandbox_environment_id: str | None = None,
+ internal: bool = False,
+ output_schema: type[BaseModel] | dict | None = None,
+ interaction_origin: str | None = None,
+ model: str | None = None,
+ initial_permission_mode: str | None = None,
+ sandbox_resources: "SandboxResources | None" = None,
+ sandbox_timeout_seconds: int | None = None,
+ inactivity_timeout_seconds: int | None = None,
+ ai_stage: str | None = None,
+ ) -> "Task":
+ from products.tasks.backend.temporal.client import execute_task_processing_workflow
+
+ task, extra_state = Task._build_task(
+ team=team,
+ title=title,
+ description=description,
+ origin_product=origin_product,
+ user_id=user_id,
+ repository=repository,
+ slack_thread_context=slack_thread_context,
+ slack_thread_url=slack_thread_url,
+ branch=branch,
+ signal_report_id=signal_report_id,
+ sandbox_environment_id=sandbox_environment_id,
+ internal=internal,
+ output_schema=output_schema,
+ interaction_origin=interaction_origin,
+ model=model,
+ initial_permission_mode=initial_permission_mode,
+ sandbox_resources=sandbox_resources,
+ sandbox_timeout_seconds=sandbox_timeout_seconds,
+ inactivity_timeout_seconds=inactivity_timeout_seconds,
+ ai_stage=ai_stage,
+ )
+
task_run = task.create_run(mode=mode, extra_state=extra_state or None, branch=branch)
if start_workflow:
@@ -896,8 +998,18 @@ class TaskRun(models.Model):
update = params.get("update", {}) if isinstance(params, dict) else {}
return update.get("sessionUpdate") == "agent_message_chunk" if isinstance(update, dict) else False
- def append_log(self, entries: list[dict]):
- """Append log entries to S3 storage."""
+ # Default S3 retention for a freshly-created run log. Live runs auto-expire after a month;
+ # callers that must preserve a log indefinitely pass `ttl_days=None` so it is never tagged for
+ # expiry — user history must not silently vanish after 30 days.
+ DEFAULT_LOG_TTL_DAYS = 30
+
+ def append_log(self, entries: list[dict], *, ttl_days: int | None = DEFAULT_LOG_TTL_DAYS):
+ """Append log entries to S3 storage.
+
+ `ttl_days` tags a newly-created log file for expiry; pass `None` to write a log that is
+ never auto-expired. The tag is only applied on
+ first write — re-tagging an existing log would not change a TTL already in flight.
+ """
entries = [e for e in entries if not self._is_agent_message_chunk(e)]
if not entries:
return
@@ -910,12 +1022,12 @@ class TaskRun(models.Model):
object_storage.write(self.log_url, content)
- if is_new_file:
+ if is_new_file and ttl_days is not None:
try:
object_storage.tag(
self.log_url,
{
- "ttl_days": "30",
+ "ttl_days": str(ttl_days),
"team_id": str(self.team_id),
},
)
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 6d63a12261c3..4dbb6a7e2e67 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1263,6 +1263,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
status=status.HTTP_502_BAD_GATEWAY,
)
+ # A warm Run has now received a human message — drop the warm flag so the warm-pool cap
+ # (see products/tasks/backend/logic/services/warm.py) stops counting it. No-op for Runs
+ # that were never warm; best-effort, since a failure only over-counts the pool until terminal.
+ try:
+ tasks_facade.update_task_run_state(pk, remove_keys=["await_user_message"])
+ except Exception:
+ logger.warning("Failed to clear await_user_message for task run %s", pk)
+
response_payload: dict[str, Any] = {
"jsonrpc": request.validated_data["jsonrpc"],
"result": {"queued": True},
@@ -1309,6 +1317,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
payload=command_payload,
)
+ tasks_facade.capture_relay_command_telemetry(
+ pk, task_id, self.team_id, method=method, params=params, success=agent_response.ok
+ )
if agent_response.ok:
return Response(agent_response.json())
@@ -1333,18 +1344,27 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
except http_requests.ConnectionError:
logger.warning(f"Agent server unreachable for task run {pk}")
+ tasks_facade.capture_relay_command_telemetry(
+ pk, task_id, self.team_id, method=method, params=params, success=False
+ )
return Response(
TaskRunErrorResponseSerializer({"error": "Agent server is not reachable"}).data,
status=status.HTTP_502_BAD_GATEWAY,
)
except http_requests.Timeout:
logger.warning(f"Agent server request timed out for task run {pk}")
+ tasks_facade.capture_relay_command_telemetry(
+ pk, task_id, self.team_id, method=method, params=params, success=False
+ )
return Response(
TaskRunErrorResponseSerializer({"error": "Agent server request timed out"}).data,
status=status.HTTP_504_GATEWAY_TIMEOUT,
)
except Exception:
logger.exception(f"Failed to proxy command to agent server for task run {pk}")
+ tasks_facade.capture_relay_command_telemetry(
+ pk, task_id, self.team_id, method=method, params=params, success=False
+ )
return Response(
TaskRunErrorResponseSerializer({"error": "Failed to send command to agent server"}).data,
status=status.HTTP_502_BAD_GATEWAY,
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 75cc2a71a945..c75912008f33 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -3,6 +3,7 @@ from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_EU,
ARRAY_APP_CLIENT_ID_US,
PosthogMcpScopes,
+ SandboxOAuthApplication,
create_oauth_access_token_for_user as _create_oauth_access_token_for_user,
)
@@ -18,8 +19,14 @@ __all__ = [
]
+def _oauth_application_for_task(task: Task) -> SandboxOAuthApplication:
+ if task.origin_product == Task.OriginProduct.POSTHOG_AI:
+ return "posthog_ai"
+ return "array"
+
+
def create_oauth_access_token(task: Task, *, scopes: PosthogMcpScopes = "read_only") -> str:
- """Create an OAuth access token for the Array app, scoped to the task's team.
+ """Create an OAuth access token for the task's sandbox app, scoped to the task's team.
OAuth tokens auto-expire after 6 hours, so no cleanup is needed.
"""
@@ -30,12 +37,23 @@ def create_oauth_access_token(task: Task, *, scopes: PosthogMcpScopes = "read_on
cause=RuntimeError(f"Task {task.id} missing created_by field"),
)
- return create_oauth_access_token_for_user(task.created_by, task.team_id, scopes=scopes)
-
-
-def create_oauth_access_token_for_user(user, team_id: int, *, scopes: PosthogMcpScopes = "read_only") -> str:
- """Create an OAuth access token for the Array app, scoped to a specific team."""
+ return create_oauth_access_token_for_user(
+ task.created_by,
+ task.team_id,
+ scopes=scopes,
+ application=_oauth_application_for_task(task),
+ )
+
+
+def create_oauth_access_token_for_user(
+ user,
+ team_id: int,
+ *,
+ scopes: PosthogMcpScopes = "read_only",
+ application: SandboxOAuthApplication = "array",
+) -> str:
+ """Create an OAuth access token for a sandbox app, scoped to a specific team."""
try:
- return _create_oauth_access_token_for_user(user, team_id, scopes=scopes)
+ return _create_oauth_access_token_for_user(user, team_id, scopes=scopes, application=application)
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from err
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
new file mode 100644
index 000000000000..74c95929cf2e
--- /dev/null
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -0,0 +1,42 @@
+from unittest.mock import MagicMock, patch
+
+from products.tasks.backend.models import Task
+from products.tasks.backend.temporal.oauth import create_oauth_access_token
+
+
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_posthog_ai_task_uses_posthog_ai_oauth_application(mock_create: MagicMock) -> None:
+ task = MagicMock(
+ id="task-id",
+ created_by=MagicMock(),
+ team_id=123,
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ )
+
+ assert create_oauth_access_token(task) == "token"
+
+ mock_create.assert_called_once_with(
+ task.created_by,
+ 123,
+ scopes="read_only",
+ application="posthog_ai",
+ )
+
+
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> None:
+ task = MagicMock(
+ id="task-id",
+ created_by=MagicMock(),
+ team_id=123,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+
+ assert create_oauth_access_token(task) == "token"
+
+ mock_create.assert_called_once_with(
+ task.created_by,
+ 123,
+ scopes="read_only",
+ application="array",
+ )
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index cab1cb815355..35871ec31e2d 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11,8 +11,10 @@ from urllib.parse import quote
from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
+from django.db import connection
from django.http import StreamingHttpResponse
from django.test import TestCase, override_settings
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone as django_timezone
import jwt
@@ -788,6 +790,32 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertIn("latest_run", task2_data)
self.assertIsNone(task2_data["latest_run"])
+ def test_list_tasks_latest_run_no_per_task_query(self):
+ # The list endpoint prefetches "runs"; latest_run must reuse that cache so the
+ # query count does not scale with the number of tasks (or runs per task).
+ url = "/api/projects/@current/tasks/"
+ task1 = self.create_task("Task 1")
+ TaskRun.objects.create(task=task1, team=self.team, status=TaskRun.Status.QUEUED)
+ TaskRun.objects.create(task=task1, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ # Warm the request first so one-time auth/access-control queries don't skew the count.
+ self.client.get(url)
+ with CaptureQueriesContext(connection) as ctx:
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ baseline = len(ctx.captured_queries)
+
+ # Add a second task with multiple runs; the query count must stay constant.
+ task2 = self.create_task("Task 2")
+ TaskRun.objects.create(task=task2, team=self.team, status=TaskRun.Status.QUEUED)
+ TaskRun.objects.create(task=task2, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ TaskRun.objects.create(task=task2, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ with self.assertNumQueries(baseline):
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 2)
+
def test_retrieve_task(self):
task = self.create_task("Test Task")
@@ -5956,6 +5984,155 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["json"]["params"]["configId"], "mode")
self.assertEqual(call_kwargs["json"]["params"]["value"], "plan")
+ def _create_posthog_ai_task(self, created_by: User | None = None):
+ return Task.objects.create(
+ team=self.team,
+ created_by=created_by or self.user,
+ title="Max session",
+ description="Max session",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ )
+
+ def _capture_calls_for_event(self, mock_capture, event):
+ return [call for call in mock_capture.call_args_list if call.kwargs.get("event") == event]
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_emits_permission_responded_telemetry_for_posthog_ai(self, mock_post, mock_capture):
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-4", "result": {"acknowledged": True}})
+ task = self._create_posthog_ai_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {
+ "jsonrpc": "2.0",
+ "method": "permission_response",
+ "params": {"requestId": "perm-1", "optionId": "allow"},
+ "id": "req-4",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ calls = self._capture_calls_for_event(mock_capture, "permission_responded")
+ self.assertEqual(len(calls), 1)
+ props = calls[0].kwargs["properties"]
+ self.assertEqual(props["origin_product"], Task.OriginProduct.POSTHOG_AI)
+ self.assertEqual(props["run_id"], str(run.id))
+ self.assertEqual(props["request_id"], "perm-1")
+ self.assertEqual(props["option_id"], "allow")
+ self.assertTrue(props["success"])
+ self.assertEqual(props["surface"], "relay")
+ self.assertIsNone(props["conversation_id"])
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_emits_task_run_cancelled_telemetry_for_posthog_ai(self, mock_post, mock_capture):
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-2", "result": {"cancelled": True}})
+ task = self._create_posthog_ai_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": "cancel", "id": "req-2"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ calls = self._capture_calls_for_event(mock_capture, "task_run_cancelled")
+ self.assertEqual(len(calls), 1)
+ props = calls[0].kwargs["properties"]
+ self.assertEqual(props["origin_product"], Task.OriginProduct.POSTHOG_AI)
+ self.assertEqual(props["cancel_source"], "user")
+ self.assertEqual(props["surface"], "relay")
+ self.assertIsNone(props["conversation_id"])
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_no_control_verb_telemetry_for_non_posthog_ai(self, mock_post, mock_capture):
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-2", "result": {"cancelled": True}})
+ # USER_CREATED task (e.g. PostHog Code) — the generic relay must not emit PostHog AI funnels.
+ task = self.create_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": "cancel", "id": "req-2"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(self._capture_calls_for_event(mock_capture, "task_run_cancelled"), [])
+ self.assertEqual(self._capture_calls_for_event(mock_capture, "permission_responded"), [])
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_permission_telemetry_marks_forward_failure(self, mock_post, mock_capture):
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"error": "agent rejected"}, status_code=502)
+ task = self._create_posthog_ai_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {
+ "jsonrpc": "2.0",
+ "method": "permission_response",
+ "params": {"requestId": "perm-1", "optionId": "allow"},
+ "id": "req-4",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
+ calls = self._capture_calls_for_event(mock_capture, "permission_responded")
+ self.assertEqual(len(calls), 1)
+ self.assertFalse(calls[0].kwargs["properties"]["success"])
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_cancel_failure_emits_no_telemetry(self, mock_post, mock_capture):
+ # The conversation layer recorded a cancel only when it actually reached the agent;
+ # the relay mirrors that — a failed forward records nothing.
+ reset_sandbox_jwt_key_cache()
+ self._mock_agent_response(mock_post, {"error": "agent rejected"}, status_code=502)
+ task = self._create_posthog_ai_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": "cancel", "id": "req-2"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
+ self.assertEqual(self._capture_calls_for_event(mock_capture, "task_run_cancelled"), [])
+
+ def test_command_denied_for_other_users_posthog_ai_run(self):
+ # Auth equivalence for the relay cutover: a same-team user who did not create the PostHog AI
+ # task cannot command its run (404 via task_visibility_q), matching the conversation layer's
+ # `conversation.user == request.user` check. Removing the conversation-layer check is safe.
+ other_user = self.create_organization_user("victim")
+ task = self._create_posthog_ai_task(created_by=other_user)
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {"jsonrpc": "2.0", "method": "cancel", "id": "req-2"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
def test_command_fails_without_sandbox_url(self):
task = self.create_task()
run = TaskRun.objects.create(
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index afbdbcc5c7f4..ca14ddaaeaf5 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -485,6 +485,7 @@ export interface PaginatedTaskDetailDTOListApi {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply
@@ -499,6 +500,7 @@ export const OriginProductEnumApi = {
Slack: 'slack',
SupportQueue: 'support_queue',
SessionSummaries: 'session_summaries',
+ PosthogAi: 'posthog_ai',
SignalReport: 'signal_report',
SignalsScout: 'signals_scout',
SupportReply: 'support_reply',
@@ -540,6 +542,7 @@ export interface TaskWriteApi {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply */
@@ -605,6 +608,7 @@ export interface PatchedTaskWriteApi {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply */
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 0bbe12673f7b..2e2d7c65f48f 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -253,16 +253,17 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'slack',
'support_queue',
'session_summaries',
+ 'posthog_ai',
'signal_report',
'signals_scout',
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -325,16 +326,17 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
'slack',
'support_queue',
'session_summaries',
+ 'posthog_ai',
'signal_report',
'signals_scout',
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -397,16 +399,17 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
'slack',
'support_queue',
'session_summaries',
+ 'posthog_ai',
'signal_report',
'signals_scout',
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
diff --git a/products/tasks/package.json b/products/tasks/package.json
index 0b70e0fa896d..528a95ab0404 100644
--- a/products/tasks/package.json
+++ b/products/tasks/package.json
@@ -1,7 +1,7 @@
{
"name": "@posthog/products-tasks",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/logic -v --tb=short",
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/logic backend/management -v --tb=short",
"backend:contract-check": "echo 'Contract files unchanged'"
},
"dependencies": {
diff --git a/services/llm-gateway/src/llm_gateway/products/__init__.py b/services/llm-gateway/src/llm_gateway/products/__init__.py
index abb443074f84..37027fdc79f0 100644
--- a/services/llm-gateway/src/llm_gateway/products/__init__.py
+++ b/services/llm-gateway/src/llm_gateway/products/__init__.py
@@ -1,4 +1,7 @@
from llm_gateway.products.config import (
+ POSTHOG_AI_DEV_APP_ID,
+ POSTHOG_AI_EU_APP_ID,
+ POSTHOG_AI_US_APP_ID,
POSTHOG_CODE_EU_APP_ID,
POSTHOG_CODE_US_APP_ID,
PRODUCTS,
@@ -14,6 +17,9 @@ from llm_gateway.products.config import (
__all__ = [
"POSTHOG_CODE_EU_APP_ID",
"POSTHOG_CODE_US_APP_ID",
+ "POSTHOG_AI_DEV_APP_ID",
+ "POSTHOG_AI_EU_APP_ID",
+ "POSTHOG_AI_US_APP_ID",
"PRODUCTS",
"ProductConfig",
"TWIG_EU_APP_ID",
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index a141e87c3c63..538ce6e08522 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -32,6 +32,9 @@ TWIG_US_APP_ID = POSTHOG_CODE_US_APP_ID
TWIG_EU_APP_ID = POSTHOG_CODE_EU_APP_ID
WIZARD_US_APP_ID = "019a0c79-b69d-0000-f31b-b41345208c9d"
WIZARD_EU_APP_ID = "019a12d0-6edd-0000-0458-86616af3a3db"
+POSTHOG_AI_US_APP_ID = "019ee060-3a0e-0000-7e9c-4e6b48dfae66"
+POSTHOG_AI_EU_APP_ID = "019ee061-5620-0000-1a0d-ab1160fceeb1"
+POSTHOG_AI_DEV_APP_ID = "019edb1a-cce4-0000-1f6d-682061862da9"
# Shared by `posthog_code` and `slack_app` — the agent that runs in the sandbox
# is the same code regardless of where the task was initiated, so the model
@@ -157,6 +160,12 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allow_api_keys=True,
billable=False,
),
+ "posthog_ai": ProductConfig(
+ allowed_application_ids=frozenset({POSTHOG_AI_US_APP_ID, POSTHOG_AI_EU_APP_ID, POSTHOG_AI_DEV_APP_ID}),
+ allowed_models=None, # any model
+ allow_api_keys=True,
+ billable=True,
+ ),
}
@@ -219,7 +228,8 @@ def check_product_access(
Check if request is authorized for product.
Returns (allowed, error_message).
"""
- config = get_product_config(product)
+ resolved_product = resolve_product_alias(product)
+ config = PRODUCTS.get(resolved_product)
if config is None:
return False, f"Unknown product: {product}"
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 46cd2fcbdb0c..863b8c47370f 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -6,6 +6,9 @@ from fastapi import HTTPException
from llm_gateway.products.config import (
ALLOWED_PRODUCTS,
BEDROCK_MODELS,
+ POSTHOG_AI_DEV_APP_ID,
+ POSTHOG_AI_EU_APP_ID,
+ POSTHOG_AI_US_APP_ID,
POSTHOG_CODE_EU_APP_ID,
POSTHOG_CODE_US_APP_ID,
PRODUCT_ALIASES,
@@ -66,6 +69,13 @@ class TestCheckProductAccess:
("signals", "oauth_access_token", "any-app-id", "claude-haiku-4-5", False, "not authorized"),
("signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-haiku-4-5", True, None),
("signals", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, "claude-sonnet-4-5", True, None),
+ # posthog_ai allows API keys with any model and OAuth from the PostHog AI app.
+ ("posthog_ai", "personal_api_key", None, "claude-sonnet-4-5", True, None),
+ ("posthog_ai", "personal_api_key", None, "gpt-5.3-codex", True, None),
+ ("posthog_ai", "oauth_access_token", "any-app-id", "claude-sonnet-4-5", False, "not authorized"),
+ ("posthog_ai", "oauth_access_token", POSTHOG_AI_US_APP_ID, "claude-sonnet-4-5", True, None),
+ ("posthog_ai", "oauth_access_token", POSTHOG_AI_EU_APP_ID, "gpt-5.3-codex", True, None),
+ ("posthog_ai", "oauth_access_token", POSTHOG_AI_DEV_APP_ID, "claude-3-opus", True, None),
# unknown product
("unknown", "personal_api_key", None, None, False, "Unknown product"),
],
@@ -324,6 +334,27 @@ class TestCheckProductAccess:
assert error is not None
assert "not authorized" in error
+ @pytest.mark.parametrize(
+ "application_id",
+ [
+ POSTHOG_AI_US_APP_ID,
+ POSTHOG_AI_EU_APP_ID,
+ POSTHOG_AI_DEV_APP_ID,
+ ],
+ )
+ def test_posthog_ai_allows_oauth_apps(self, application_id: str):
+ allowed, error = check_product_access("posthog_ai", "oauth_access_token", application_id, "claude-sonnet-4-5")
+ assert allowed is True
+ assert error is None
+
+ def test_posthog_ai_rejects_posthog_code_oauth_app(self):
+ allowed, error = check_product_access(
+ "posthog_ai", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-4-5"
+ )
+ assert allowed is False
+ assert error is not None
+ assert "not authorized" in error
+
class TestBackwardsCompatibility:
def test_twig_app_id_constants_are_aliases(self):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1049be51a04c..21bc4836fe9c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29080,6 +29080,7 @@ export namespace Schemas {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply
@@ -29095,6 +29096,7 @@ export namespace Schemas {
Slack: 'slack',
SupportQueue: 'support_queue',
SessionSummaries: 'session_summaries',
+ PosthogAi: 'posthog_ai',
SignalReport: 'signal_report',
SignalsScout: 'signals_scout',
SupportReply: 'support_reply',
@@ -39618,6 +39620,7 @@ export namespace Schemas {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply */
@@ -48733,6 +48736,7 @@ export namespace Schemas {
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
+ * * `posthog_ai` - PostHog AI
* * `signal_report` - Signal Report
* * `signals_scout` - Signals Scout
* * `support_reply` - Support Reply */