: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
feat(signals): mint gateway tokens for inbox, chat and suggestion runs (#93880)
Brandon83a934816fed
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex fd2d2275cdc9..f2ba8f4220af 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -168,7 +168,8 @@ per-run dollar cap. Two JSON object settings can override it:- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES` maps team IDs to caps.- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES` maps AI product names to- caps and defaults to `{"signals_implementation": "15"}`.+ caps and defaults to+ `{"signals_implementation": "15", "signals_inbox": "75", "signals_chat": "30"}`.A product override takes precedence over a team override, which takes precedenceover the default cap. Set the product override to `{}` to disable the built-indiff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex a9b74529bb03..a40bf3162284 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -72,16 +72,19 @@ SANDBOX_AI_GATEWAY_MINT_KEY: str | None = get_from_env("SANDBOX_AI_GATEWAY_MINT_# runaway run; the daily bound per team is cap x the scheduler's runs-per-day limit.# The cap must fit a run's real spend plus its in-flight admission holds: a cap near# typical spend ends runs after the work is written and before it is committed.-# TTL 0 (the default) derives TASKS_MAX_RUN_DURATION_SECONDS + 1h so a capped run-# never outlives its token; a positive value overrides.+# TTL 0 (the default) derives the run-duration cap that applies to the token's own product,+# plus 1h, so a capped run never outlives its token; a positive value overrides.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD", "10")# Per-team per-run cap overrides as a JSON object of team id to dollars, e.g. {"2": "10"}.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES", "")# Per-product per-run cap overrides as a JSON object of ai_product to dollars. A product# entry beats the team override and the default: run cost tracks the kind of work, and-# implementation runs regularly outspend every other stage.+# implementation runs regularly outspend every other stage. Each interactive cap clears its+# observed ceiling with room for the holds, because a person is waiting and nothing retries+# behind a cap that binds mid-run. Suggestion runs stay on the default.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES: str = get_from_env(- "SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES", '{"signals_implementation": "15"}'+ "SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES",+ '{"signals_implementation": "15", "signals_inbox": "75", "signals_chat": "30"}',)SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS: int = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS", 0, type_cast=int)SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=True)diff --git a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json b/products/desktop/packages/agent/src/utils/gateway-routing-cases.jsonindex be142a162797..92b209f9d8a6 100644--- a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json+++ b/products/desktop/packages/agent/src/utils/gateway-routing-cases.json@@ -11,6 +11,24 @@"origin_product": "scout_suggestions","ai_stage": "scout_suggestions","internal": true,+ "expected": "signals_scout_suggestions"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "inbox",+ "internal": false,+ "expected": "signals_inbox"+ },+ {+ "origin_product": "signals_chat",+ "ai_stage": "chat",+ "internal": false,+ "expected": "signals_chat"+ },+ {+ "origin_product": "signals_chat",+ "ai_stage": null,+ "internal": false,"expected": "signals"},{@@ -160,6 +178,34 @@"internal": true,"allowlist": "signals","expected": true+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "inbox",+ "internal": false,+ "allowlist": "signals_inbox",+ "expected": true+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "inbox",+ "internal": false,+ "allowlist": "signals_scout,signals_implementation",+ "expected": false+ },+ {+ "origin_product": "signals_chat",+ "ai_stage": "chat",+ "internal": false,+ "allowlist": "signals_chat",+ "expected": true+ },+ {+ "origin_product": "scout_suggestions",+ "ai_stage": "scout_suggestions",+ "internal": true,+ "allowlist": "signals_scout_suggestions",+ "expected": true}]}diff --git a/products/desktop/packages/agent/src/utils/gateway.test.ts b/products/desktop/packages/agent/src/utils/gateway.test.tsindex 6ea109886802..537ccfc568d4 100644--- a/products/desktop/packages/agent/src/utils/gateway.test.ts+++ b/products/desktop/packages/agent/src/utils/gateway.test.ts@@ -511,6 +511,9 @@ describe("resolveAiProduct", () => {["implementation", "signals_implementation"],["repo_selection", "signals_repo_selection"],["custom_agent", "signals_custom_agent"],+ ["inbox", "signals_inbox"],+ ["chat", "signals_chat"],+ ["scout_suggestions", "signals_scout_suggestions"],])("maps the signals %s stage to %s", (aiStage, expected) => {expect(resolveAiProduct({ product: "signals", aiStage })).toBe(expected);});diff --git a/products/desktop/packages/agent/src/utils/gateway.ts b/products/desktop/packages/agent/src/utils/gateway.tsindex 3a50b2473b4a..19aa18032e9c 100644--- a/products/desktop/packages/agent/src/utils/gateway.ts+++ b/products/desktop/packages/agent/src/utils/gateway.ts@@ -93,7 +93,8 @@ function parseAiGatewayProducts(raw: string | undefined): Set<string> {/*** Sandbox-run signals stages, which are billed per stage rather than under one* `signals` product. The stage names come from `TaskRun.state.ai_stage`, set in- * `Task._build_task` in posthog/posthog.+ * `Task._build_task` (pipeline stages) and `Task.create_run` (interactive+ * `inbox` / `chat`) in posthog/posthog.*/const SIGNALS_STAGE_PRODUCTS = new Set(["scout",@@ -101,6 +102,9 @@ const SIGNALS_STAGE_PRODUCTS = new Set(["implementation","repo_selection","custom_agent",+ "inbox",+ "chat",+ "scout_suggestions",]);/**diff --git a/products/signals/backend/scout_harness/suggestions.py b/products/signals/backend/scout_harness/suggestions.pyindex 035b29247abd..0d5042fefa22 100644--- a/products/signals/backend/scout_harness/suggestions.py+++ b/products/signals/backend/scout_harness/suggestions.py@@ -66,8 +66,7 @@ MAX_DRAFT_BODY_CHARS = 20_000# create it is supposed to be ready for.MAX_DESCRIPTION_CHARS = 4_096-# Tags every $ai_generation a suggestion run makes, so its spend is splittable out of the-# `ai_product='signals'` bucket next to `scout:<skill>` (see `runner._ai_stage`).+# Resolves a suggestion run to the `signals_scout_suggestions` gateway product.SUGGESTIONS_AI_STAGE = "scout_suggestions"SuggestionKind = Literal["canonical", "custom"]diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 341dea2b388b..2aa0d5688a3a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -843,7 +843,9 @@ def signal_report_pipeline_stage(task_id: str | UUID, team_id: int) -> str | NonA task's runs all carry the stage the pipeline started it for, so the newest run answers forthe task. ``None`` covers everything else: a scout run, a user-created task, a legacy row- predating the stamp.+ predating the stamp. A person-started Inbox run on a customer-created task carries the+ ``inbox`` stamp from ``Task.create_run``; it names no pipeline identity, so stage-to-identity+ lookups miss it."""state = (TaskRun.objects.filter(@@ -2241,9 +2243,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("loop_terminal_bookkeeping_complete",# Stamped once at run creation. The review carve-outs read ai_stage="implementation" as proof# a run is self-driving, so a PATCHable value would forge that and unlock the bot/draft bypass.- # is_interactive_signals_run reads its presence the same way, to tell a pipeline-started- # signals run from one a person started; forging it would move the run off the interactive- # budget and out of its per-run spend ceiling.+ # is_interactive_signals_run reads it the same way, so forging it would move the run off+ # the interactive budget and out of its per-run spend ceiling."ai_stage",# The server-generated head branch the run->PR link is keyed on (find_signal_implementation_run).# A PATCHable value would let a caller re-aim the approve-first carve-out at any App-authoreddiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex cfe87e738dee..d77969bf7073 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -67,6 +67,11 @@ MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"MCP_CREDENTIAL_OWNER_STATE_KEY = "mcp_credential_owner_id"MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY = "mcp_gateway_server_ids"TASK_OWNERSHIP_VERSION_STATE_KEY = "task_ownership_version"++# Stage `Task.create_run` stamps on a person-started signals run, so it resolves a mintable+# gateway product. Keyed by origin value.+INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN: dict[str, str] = {"signal_report": "inbox", "signals_chat": "chat"}+MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {"support_reply": "support","signals_scout": "scout",@@ -738,6 +743,14 @@ class Task(DeletedMetaFields, models.Model):if task.ownership_version is not None:state[TASK_OWNERSHIP_VERSION_STATE_KEY] = task.ownership_version+ # Both conditions withhold the stamp, so a caller can only cost itself the mint.+ # `internal` marks a pipeline-created task, whose reruns and resumes carry no stage+ # and would otherwise land on the wider interactive cap.+ interactive_stage = INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN.get(task.origin_product)+ if interactive_stage and not state.get("ai_stage") and not task.internal:+ if task.origin_product != Task.OriginProduct.SIGNAL_REPORT or task.signal_report_id:+ state["ai_stage"] = interactive_stage+resume_from_run_id = (extra_state or {}).get("resume_from_run_id")if resume_from_run_id is not None:resume_source = TaskRun.objects.filter(id=resume_from_run_id, task_id=task.id).only("state").first()diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex fe618ceaa374..b810506e4648 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -24,7 +24,7 @@ from products.tasks.backend.logic.services.run_actor import (is_slack_interaction_state,loop_owner_eligible_for_credentials,)-from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task+from products.tasks.backend.models import INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN, TASK_OWNERSHIP_VERSION_STATE_KEY, Taskif TYPE_CHECKING:from posthog.models.user import User@@ -77,6 +77,11 @@ def _oauth_application_for_task(task: Task) -> SandboxOAuthApplication:return "array"+# Stages `Task.create_run` stamps on person-started signals runs. Any other stage is the+# pipeline's own and marks a self-driving run.+INTERACTIVE_SIGNALS_AI_STAGES = frozenset(INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN.values())++def is_interactive_signals_run(task: Task, state: dict[str, Any] | None) -> bool:"""Whether *this run* exists because a person pressed something, not because we scheduled it.@@ -85,15 +90,17 @@ def is_interactive_signals_run(task: Task, state: dict[str, Any] | None) -> boolan implementation task, and a person can later start a second run on that same task fromthe report. One task, two runs, two different initiators.- `ai_stage` is the pipeline's own stamp on a run it started. It is absent from the task- create serializer and sits in `_PROTECTED_RUN_STATE_KEYS`, so no caller can set or forge- one — the review carve-outs already trust it as proof a run is self-driving. A signals run- without one therefore cannot have come from the pipeline, which makes the interactive- budget and its per-run ceiling the fail-closed default.+ `ai_stage` is stamped server-side once at run creation: the pipeline stamps its own stage+ on a run it started, and `Task.create_run` stamps `inbox` / `chat` on a person-started run+ so it carries a gateway product. It is absent from the task create serializer and sits in+ `_PROTECTED_RUN_STATE_KEYS`, so no caller can set or forge one — the review carve-outs+ already trust a pipeline stage as proof a run is self-driving. An interactive stage, or+ none at all, keeps the interactive budget and its per-run ceiling as the fail-closed default."""if task.origin_product not in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS:return False- return not (state or {}).get("ai_stage")+ stage = (state or {}).get("ai_stage")+ return not stage or stage in INTERACTIVE_SIGNALS_AI_STAGESdef _scopes_for_loop_fired_run(scopes: PosthogMcpScopes) -> list[str]:diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 677769f8ea64..514f89f3e60a 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -35,13 +35,16 @@ _ORIGIN_TO_GATEWAY_PRODUCT: dict[str, str] = {"posthog_ai": "posthog_ai","scout_suggestions": "signals","signal_report": "signals",+ "signals_chat": "signals","signals_scout": "signals","slack": "slack_app","support_reply": "conversations",}# Mirrors SIGNALS_STAGE_PRODUCTS + SCOUT_STAGE_PREFIX in gateway.ts.-_SIGNALS_STAGE_PRODUCTS = frozenset({"scout", "research", "implementation", "repo_selection", "custom_agent"})+_SIGNALS_STAGE_PRODUCTS = frozenset(+ {"scout", "research", "implementation", "repo_selection", "custom_agent", "inbox", "chat", "scout_suggestions"}+)_SCOUT_STAGE_PREFIX = "scout:"_MAX_CAP_USD = Decimal("10000")@@ -51,7 +54,9 @@ _MAX_CAP_DECIMAL_PLACES = 6# server-side provenance: `internal` and some origin_product values are# API-settable, so an unmapped origin marked internal resolves to# background_agents and must never mint. Signals products qualify because their-# stages are set only by server flows and the signals_scout origin is reserved.+# stages are set only by server flows: pipeline stages by the flows that start+# them, `inbox` / `chat` by `Task.create_run`. A caller owning a report can reach+# `signals_inbox`, so the per-run cap and the product's daily budget bound those two.MINTABLE_PRODUCTS = frozenset({"signals_scout",@@ -59,9 +64,16 @@ MINTABLE_PRODUCTS = frozenset("signals_implementation","signals_repo_selection","signals_custom_agent",+ "signals_inbox",+ "signals_chat",+ "signals_scout_suggestions",})+# Exempt from the background run-duration cap, so their tokens need the longer interactive+# ceiling. Mirrors the stages `Task.create_run` stamps.+INTERACTIVE_MINTABLE_PRODUCTS = frozenset({"signals_inbox", "signals_chat"})+# Minting is optional (no token = Python-gateway fallback), so the total budget# stays a few seconds: 2 attempts x 3s + one short backoff, not a 30s provisioning stall._MINT_ATTEMPTS = 2@@ -95,16 +107,22 @@ def sandbox_product_routed(ai_product: str, ai_stage: str | None, products_csv:return False-def _token_ttl_seconds() -> int:- """Token lifetime: the explicit setting, else the run-duration cap plus a settle- buffer, so a capped run cannot outlive its token (expiry under a live run fails- every remaining LLM call with no fallback). A disabled run cap derives the 24h- mint maximum; interactive sessions are cap-exempt and could still outlive it,- but only capped background products are routed. Clamped to mint bounds (60s..24h).+def _token_ttl_seconds(ai_product: str) -> int:+ """Token lifetime: the explicit setting, else this product's own run-duration cap plus a+ settle buffer, so a capped run cannot outlive its token (expiry under a live run fails+ every remaining LLM call with no fallback). Only the interactive products are exempt from+ the background cap, so only they derive the longer ceiling; giving every token the longest+ one would widen the window on a leaked background token for no run that could use it.+ A disabled cap derives the 24h mint maximum. Clamped to mint bounds (60s..24h)."""configured = int(settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS or 0)if configured <= 0:- run_cap = int(getattr(settings, "TASKS_MAX_RUN_DURATION_SECONDS", 0) or 0)+ if ai_product in INTERACTIVE_MINTABLE_PRODUCTS:+ # These runs are exempt from the background cap, so their own ceiling is the only+ # one that bounds them; zero means unbounded and derives the mint maximum.+ run_cap = int(getattr(settings, "TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS", 0) or 0)+ else:+ run_cap = int(getattr(settings, "TASKS_MAX_RUN_DURATION_SECONDS", 0) or 0)configured = run_cap + 3600 if run_cap > 0 else 86400return max(60, min(configured, 86400))@@ -172,7 +190,7 @@ def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None)body: dict[str, Any] = {"cap_usd": _token_cap_usd(team_id, ai_product),- "ttl_seconds": _token_ttl_seconds(),+ "ttl_seconds": _token_ttl_seconds(ai_product),"product": ai_product,"obo": str(team_id),}diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 854347be7cd2..8675fd5dcc34 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -4,8 +4,12 @@ from pathlib import Pathimport pytestfrom unittest.mock import MagicMock, patch+from products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGEfrom products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS+from products.tasks.backend.models import INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGINfrom products.tasks.backend.temporal.process_task.ai_gateway_token import (+ INTERACTIVE_MINTABLE_PRODUCTS,+ MINTABLE_PRODUCTS,mint_scoped_token,resolve_sandbox_ai_product,sandbox_product_routed,@@ -23,7 +27,10 @@ class TestResolveSandboxAiProduct:[("signals_scout", "scout", "signals_scout"),("signals_scout", "scout:web-analytics", "signals_scout"),- ("scout_suggestions", "scout_suggestions", "signals"),+ ("scout_suggestions", "scout_suggestions", "signals_scout_suggestions"),+ ("signal_report", "inbox", "signals_inbox"),+ ("signals_chat", "chat", "signals_chat"),+ ("signals_chat", None, "signals"),("signal_report", "research", "signals_research"),("signal_report", "implementation", "signals_implementation"),("signal_report", "repo_selection", "signals_repo_selection"),@@ -186,14 +193,37 @@ class TestMintScopedToken:def test_ttl_derives_from_run_cap_when_unset(self, mint_settings):mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60+ mint_settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS = 6 * 60 * 60with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:post.return_value = self._response(201, {"token": "phe_abc"})assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"+ # A background product is hard-capped at the shorter ceiling, so the longer one must+ # not widen its token's window.assert post.call_args.kwargs["json"]["ttl_seconds"] == 3 * 60 * 60 + 3600+ def test_ttl_covers_the_interactive_ceiling_for_interactive_products(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60+ mint_settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS = 6 * 60 * 60+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_inbox", team_id=123) == "phe_abc"+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 6 * 60 * 60 + 3600++ # Zero means no wall-clock ceiling, so the token must not shrink onto the background derivation.+ def test_ttl_clamps_to_gateway_max_when_the_interactive_ceiling_is_disabled(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60+ mint_settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS = 0+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_chat", team_id=123) == "phe_abc"+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 86400+def test_ttl_clamps_to_gateway_max_when_run_cap_disabled(self, mint_settings):mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 0+ mint_settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS = 0with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:post.return_value = self._response(201, {"token": "phe_abc"})assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"@@ -264,6 +294,17 @@ class TestAiGatewayEnvVars:assert ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout") == {}+class TestInteractiveProductSet:+ # A third stamped stage would take the longer run ceiling and a token from the shorter one.+ def test_interactive_products_are_exactly_the_stamped_stages(self):+ assert INTERACTIVE_MINTABLE_PRODUCTS == {+ f"signals_{stage}" for stage in INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN.values()+ }++ def test_interactive_products_are_mintable(self):+ assert INTERACTIVE_MINTABLE_PRODUCTS <= MINTABLE_PRODUCTS++class TestMintableGate:"""Mint scope needs server-side provenance: `internal` and some origin_productvalues are API-settable, so a routed-but-unmintable product must never mint."""@@ -282,6 +323,37 @@ class TestMintableGate:assert "AI_GATEWAY_TOKEN" not in envmint.assert_not_called()+ def test_stageless_chat_cannot_mint_for_bare_signals(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "signals,signals_chat"+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="signals_chat", ai_stage=None)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ @pytest.mark.parametrize("origin_product,ai_stage", sorted(INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN.items()))+ # Reads the stage from the map create_run stamps, so a rename fails here instead of+ # resolving bare `signals`.+ def test_stamped_interactive_stages_mint_their_own_product(self, mint_settings, origin_product, ai_stage):+ expected_product = f"signals_{ai_stage}"+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = expected_product+ with patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token",+ return_value="phe_abc",+ ) as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product=origin_product, ai_stage=ai_stage)+ assert env["AI_GATEWAY_PRODUCT"] == expected_product+ mint.assert_called_once_with(ai_product=expected_product, team_id=123, user=None)++ def test_suggestions_stage_mints_its_own_product(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "signals_scout_suggestions"+ with patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token",+ return_value="phe_abc",+ ) as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="scout_suggestions", ai_stage=SUGGESTIONS_AI_STAGE)+ assert env["AI_GATEWAY_PRODUCT"] == "signals_scout_suggestions"+ mint.assert_called_once_with(ai_product="signals_scout_suggestions", team_id=123, user=None)+class TestProvisioningBoundaries:"""Every provisioning path derives its gateway env through run_gateway_env_vars,@@ -400,6 +472,23 @@ class TestUserPinAndCapOverride:mint_scoped_token(ai_product="signals_implementation", team_id=2)assert post.call_args.kwargs["json"]["cap_usd"] == "10"+ @pytest.mark.parametrize(+ "ai_product,expected_cap",+ [("signals_inbox", "75"), ("signals_chat", "30"), ("signals_scout_suggestions", "10")],+ )+ # A cap key that stops matching the resolver's product fails here instead of quietly+ # dropping to the default. Suggestions carry no entry and take that default on purpose.+ def test_shipped_product_caps_reach_the_mint(self, settings, ai_product, expected_cap):+ settings.SANDBOX_AI_GATEWAY_URL = "https://ai-gateway.dev.posthog.dev"+ settings.SANDBOX_AI_GATEWAY_MINT_KEY = "phs_test_mint"+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD = "10"+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = ""+ # The product overrides are left alone, to assert the value the repo ships.+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product=ai_product, team_id=123)+ assert post.call_args.kwargs["json"]["cap_usd"] == expected_cap+def test_malformed_overrides_fall_back_to_default(self, mint_settings):mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = "not json"with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex d4e0824e9f07..0b08420feb82 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -6,8 +6,17 @@ from posthog.models.user import Userfrom posthog.temporal.oauth import PosthogMcpScopesfrom products.tasks.backend.exceptions import TaskInvalidStateError-from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, MCPBuiltInAgentKey, Task-from products.tasks.backend.temporal.oauth import create_oauth_access_token, create_oauth_access_token_for_run+from products.tasks.backend.models import (+ INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN,+ TASK_OWNERSHIP_VERSION_STATE_KEY,+ MCPBuiltInAgentKey,+ Task,+)+from products.tasks.backend.temporal.oauth import (+ INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS,+ create_oauth_access_token,+ create_oauth_access_token_for_run,+)@pytest.mark.parametrize(@@ -113,10 +122,18 @@ def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> No)+# is_interactive_signals_run short-circuits on origin, so an omitted one reads as+# pipeline-started and leaves an interactive-mode run with no ceiling.+def test_every_stamped_origin_is_an_interactive_signals_origin() -> None:+ assert set(INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN) <= set(INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS)++@pytest.mark.parametrize(("origin_product", "internal", "run_state", "application", "interactive"),[- # Inbox CTA: a person creates the task, so no pipeline stage is ever stamped.+ # Inbox CTA: a person creates the task; create_run stamps the interactive `inbox` stage.+ (Task.OriginProduct.SIGNAL_REPORT, False, {"ai_stage": "inbox"}, "signals", True),+ # A bare signal_report task (no report link) gets no stamp and stays interactive.(Task.OriginProduct.SIGNAL_REPORT, False, None, "signals", True),# Auto-started implementation: the pipeline stamps the run it started.(Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "implementation"}, "signals", False),@@ -127,8 +144,11 @@ def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> No(Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": ""}, "signals", True),(Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "research"}, "signals", False),(Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "custom_agent"}, "signals", False),+ (Task.OriginProduct.SIGNALS_CHAT, False, {"ai_stage": "chat"}, "signals", True),(Task.OriginProduct.SIGNALS_CHAT, False, None, "signals", True),(Task.OriginProduct.SIGNALS_SCOUT, True, {"ai_stage": "scout"}, "signals", False),+ # The interactive stamp never reaches a scheduled origin, and would not make it interactive.+ (Task.OriginProduct.SIGNALS_SCOUT, True, {"ai_stage": "inbox"}, "signals", False),(Task.OriginProduct.USER_CREATED, False, None, "array", False),],)diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 73456212de40..ca04f2e01b41 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -820,6 +820,33 @@ class TestFacadeReadsAndMappers(TestCase):new_run = task.runs.exclude(id=previous_run.id).get()self.assertEqual(new_run.state.get("self_driving_head_branch"), "posthog-self-driving/fix-abc123")+ def test_run_task_resume_of_a_pipeline_task_stays_unstamped(self):+ # The predecessor's stage is deliberately not carried forward: a stage makes the run+ # read as pipeline-started and drops it out of the interactive duration ceiling.+ from products.signals.backend.models import SignalReport++ # The report link is present so only `internal` can withhold the stamp here.+ report = SignalReport.objects.create(team=self.team)+ task = self._make_task(origin_product=Task.OriginProduct.SIGNAL_REPORT, signal_report=report, internal=True)+ previous_run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"ai_stage": "implementation"},+ )++ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={"mode": "interactive", "resume_from_run_id": str(previous_run.id)},+ )++ assert result is not None and result.error is None+ new_run = task.runs.exclude(id=previous_run.id).get()+ self.assertNotIn("ai_stage", new_run.state)+@parameterized.expand([# The inbox "Create PR" button sends no branch, so the team's configured base branch isdiff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 0834dea48bfc..f9abc9f00cae 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -234,6 +234,82 @@ class TestTask(TestCase):task_run = TaskRun.objects.get(id=run_id)self.assertNotIn("ai_stage", task_run.state)+ def test_create_run_stamps_inbox_on_a_report_linked_signal_report_task(self):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ task = Task.objects.create(+ team=self.team,+ title="Discuss report",+ description="From the Inbox",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ )++ run = task.create_run(mode="interactive")++ self.assertEqual(run.state["ai_stage"], "inbox")++ def test_create_run_leaves_a_bare_signal_report_task_unstamped(self):+ # The origin is client-settable; only the report link proves an Inbox run.+ task = Task.objects.create(+ team=self.team,+ title="Bare signal_report",+ description="No report link",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )++ run = task.create_run(mode="interactive")++ self.assertNotIn("ai_stage", run.state)++ def test_create_run_keeps_the_pipeline_stage_over_the_interactive_stamp(self):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ task = Task.objects.create(+ team=self.team,+ title="Auto-started implementation",+ description="Pipeline",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ )++ run = task.create_run(extra_state={"ai_stage": "implementation"})++ self.assertEqual(run.state["ai_stage"], "implementation")++ def test_create_run_leaves_a_pipeline_created_task_unstamped(self):+ # Stamping a pipeline-created task would move a rerun of self-driving work onto the+ # interactive cap.+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ task = Task.objects.create(+ team=self.team,+ title="Auto-started implementation",+ description="Pipeline",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ internal=True,+ )++ run = task.create_run(mode="interactive")++ self.assertNotIn("ai_stage", run.state)++ def test_create_run_stamps_chat_on_a_signals_chat_task(self):+ task = Task.objects.create(+ team=self.team,+ title="Suggest a scout",+ description="Chat",+ origin_product=Task.OriginProduct.SIGNALS_CHAT,+ )++ run = task.create_run(mode="interactive")++ self.assertEqual(run.state["ai_stage"], "chat")+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_and_run_omits_permission_mode_when_not_provided(self, mock_execute_workflow):user = User.objects.create(email="[email protected]")diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.pyindex 8e5e69bb08ae..cda3705343aa 100644--- a/products/tasks/backend/tests/test_presentation_serializers.py+++ b/products/tasks/backend/tests/test_presentation_serializers.py@@ -60,6 +60,10 @@ class TestTaskWriteSerializerOriginProduct(SimpleTestCase):[("image_builder", True),("signals_scout", True),+ # These two resolve mintable gateway products, so a forged origin would reach+ # internally funded inference under a per-run cap.+ ("signals_chat", True),+ ("scout_suggestions", True),("user_created", False),])