: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(slack-app): bill codex slack tasks to the user's own plan (#120128)
posthog[bot]4c8271c11789
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex ab124651712b..be129747b703 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -4191,16 +4191,22 @@ def post_thread_join_prompt(owner_slack_user_id: str,joiner_slack_user_id: str,opens_thread: bool,+ plan_name: str | None = None,) -> None:"""Ask the thread creator whether someone else may join their thread.``opens_thread`` says that approving lets anyone join the thread, not only this person.+ ``plan_name`` names the creator's plan when the thread's task runs on it, so the creator+ knows that people who join spend it.The whole event is stashed behind a one-off token, so letting them join sends the originalmessage rather than a reconstruction of it. The person who asked hears that the creator wasasked, so their message does not seem lost. While a prompt for this person waits, theirnext messages post no new prompt, so a chatty joiner cannot flood the creator."""+ plan_note = (+ f"This task runs on your {plan_name}, so messages from people who join use it too. " if plan_name else ""+ )pending_key = _thread_join_pending_key(integration.id, channel, thread_ts, joiner_slack_user_id)if not cache.add(pending_key, True, timeout=THREAD_JOIN_PROMPT_MAX_AGE_SECONDS):return@@ -4258,7 +4264,7 @@ def post_thread_join_prompt("elements": [{"type": "mrkdwn",- "text": f"In the {home_tab_label} you can choose who joins your threads.",+ "text": f"{plan_note}In the {home_tab_label} you can choose who joins your threads.",}],},diff --git a/products/slack_app/backend/facade/run_preferences.py b/products/slack_app/backend/facade/run_preferences.pyindex f0915aa338c0..01f3cd90a680 100644--- a/products/slack_app/backend/facade/run_preferences.py+++ b/products/slack_app/backend/facade/run_preferences.py@@ -19,6 +19,7 @@ from products.slack_app.backend.services.model_router import (from products.slack_app.backend.services.run_preferences import (LiveRunModelChange,find_model_choice,+ resolve_effective_runtime_adapter,resolve_live_run_override,resolve_run_preferences,)@@ -33,6 +34,7 @@ __all__ = ["find_model_choice","group_by_runtime","model_router_options",+ "resolve_effective_runtime_adapter","resolve_live_run_override","resolve_run_preferences",]diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex f9246ecf1c50..c92a01aa054a 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -49,6 +49,7 @@ SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_CHART_LINKS_FLAG = "slack-app-chart-links"SLACK_APP_FORKING_FLAG = "slack-app-forking"SLACK_APP_MULTIPLAYER_APPROVALS_FLAG = "slack-app-multiplayer-approvals"+SLACK_APP_BYOS_FLAG = "slack-app-byos"SLACK_APP_UNPROMPTED_ANSWERS_FLAG = "slack-app-unprompted-answers"@@ -153,6 +154,27 @@ def is_slack_app_multiplayer_approvals_enabled(integration: Integration, distinc)+def is_slack_app_byos_enabled(integration: Integration, distinct_id: str | None, *, adapter: str = "codex") -> bool:+ """Gate for Slack runs that bill to the user's own plan.++ Depends on the tasks rollout flag for that plan, which is checked first. A Slack run+ marked for a plan whose rollout is off fails when it starts, so Slack must never mark one.+ ``distinct_id`` is the PostHog user whose plan the run would use.+ """+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — keeps tasks off this import path++ if not tasks_facade.own_subscription_cloud_enabled(+ adapter, distinct_id=distinct_id, organization_id=str(integration.team.organization_id)+ ):+ return False+ return _workspace_flag_enabled(+ SLACK_APP_BYOS_FLAG,+ integration,+ failure_log_key="slack_app_byos_feature_flag_check_failed",+ distinct_id=distinct_id,+ )++def is_slack_app_unprompted_answers_enabled(integration: Integration) -> bool:"""Gate for answering top-level channel messages nobody tagged the app in.diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.pyindex 616f96c5ec10..09c1585332cb 100644--- a/products/slack_app/backend/services/run_preferences.py+++ b/products/slack_app/backend/services/run_preferences.py@@ -62,6 +62,19 @@ def _central_run_default(team_id: int, user_id: int | None) -> ResolvedAIRunConfreturn resolved+def resolve_effective_runtime_adapter(runtime_adapter: str | None, *, team_id: int, user_id: int | None) -> str | None:+ """The runtime adapter a new run will use.++ `resolve_run_preferences` leaves the triple empty when a central default exists, and+ `create_run` fills it in later. A caller that must know the runtime before the run+ exists (to choose its billing) reads the same default here.+ """+ if runtime_adapter:+ return runtime_adapter+ central_default = _central_run_default(team_id, user_id)+ return central_default.runtime_adapter if central_default else None++def _coherent_preferences(model: str | None,reasoning_effort: str | None,diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex cdd61755d3c4..8b4cacbcc74f 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -34,6 +34,7 @@ from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.feature_flags import (+ is_slack_app_byos_enabled,is_slack_app_multiplayer_approvals_enabled,is_slack_app_oauth_enabled,is_slack_app_unprompted_answers_enabled,@@ -423,6 +424,14 @@ class GitHubState:settings_url: str | None = None+@dataclass(frozen=True)+class OwnPlanState:+ """Whether the Codex tasks this viewer starts from Slack bill to their ChatGPT plan."""++ connected: bool+ settings_url: str++@dataclass(frozen=True)class RunDefaultsState:"""The central PostHog default a Slack run resolves to; only a model named in@@ -458,6 +467,7 @@ def render_home_view(untagged_question_mode: UntaggedFollowupMode | None = None,channel_welcome_mode: ChannelWelcomeMode | None = None,auto_model_choice: bool | None = None,+ own_plan: OwnPlanState | None = None,thread_join_mode: ThreadJoinMode | None = None,has_project_access: bool = True,account_settings_url: str | None = None,@@ -499,6 +509,9 @@ def render_home_view(# `None` means no PostHog user is linked to this viewer.if auto_model_choice is not None:blocks.extend(_auto_model_choice_blocks(auto_model_choice))+ # A connected plan is described under Multiplayer, because people who join spend it too.+ if own_plan is not None and not own_plan.connected:+ blocks.extend(_own_plan_blocks(own_plan))# Section 4 — thread follow-ups: whether replies other people leave in the# threads you started reach PostHog on their own.@@ -506,10 +519,11 @@ def render_home_view(blocks.append({"type": "divider"})blocks.extend(_untagged_followups_section_blocks(untagged_followup_mode))- # Section 4a — multiplayer: who may join the threads you started.- if thread_join_mode is not None:+ # Section 4a — multiplayer: who may join the threads you started, and whose plan pays.+ uses_own_plan = bool(own_plan and own_plan.connected)+ if thread_join_mode is not None or uses_own_plan:blocks.append({"type": "divider"})- blocks.extend(_multiplayer_section_blocks(thread_join_mode))+ blocks.extend(_multiplayer_section_blocks(thread_join_mode, uses_own_plan=uses_own_plan))# Section 4b — channel questions. `None` means the flag is off for this workspace.if untagged_question_mode is not None:@@ -971,6 +985,15 @@ def _auto_model_choice_blocks(enabled: bool) -> list[dict]:]+def _own_plan_blocks(state: OwnPlanState) -> list[dict]:+ """The prompt to connect a ChatGPT plan, for a viewer who has not connected one."""+ text = f"<{state.settings_url}|Connect your ChatGPT plan> in PostHog to use it for Codex tasks you start here."+ return [+ _subsection_label("ChatGPT plan"),+ {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]},+ ]++UNTAGGED_FOLLOWUP_MODE_LABELS: dict[str, str] = {UntaggedFollowupMode.AUTO: "Pick them up automatically",UntaggedFollowupMode.ASK: "Ask them first",@@ -1040,18 +1063,36 @@ def _untagged_questions_section_blocks(mode: UntaggedFollowupMode) -> list[dict])-def _multiplayer_section_blocks(mode: ThreadJoinMode) -> list[dict]:- """Picker for what happens when someone else tags PostHog in a thread you started."""- select = _static_select(- action_id=ACTION_SET_THREAD_JOIN_MODE,- placeholder="Choose who can join",- pairs=ThreadJoinMode.choices,- selected=mode.value,- )- return [+def _multiplayer_section_blocks(mode: ThreadJoinMode | None, *, uses_own_plan: bool) -> list[dict]:+ """Who may join the threads you started, and whose plan pays when they do.++ ``mode`` is `None` when the join setting is not offered to this viewer.+ """+ blocks: list[dict] = [_section_title("👥 Multiplayer", "What I do when someone else tags @PostHog in a thread you started."),- {"type": "actions", "elements": [select]},]+ if mode is not None:+ select = _static_select(+ action_id=ACTION_SET_THREAD_JOIN_MODE,+ placeholder="Choose who can join",+ pairs=ThreadJoinMode.choices,+ selected=mode.value,+ )+ blocks.append({"type": "actions", "elements": [select]})+ if uses_own_plan:+ blocks.append(_subsection_label("ChatGPT plan"))+ blocks.append(+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": "Codex tasks you start here use your ChatGPT plan, also when other people join your thread.",+ }+ ],+ }+ )+ return blocksCHANNEL_WELCOME_MODE_LABELS: dict[str, str] = {@@ -2227,6 +2268,8 @@ def _build_home_view(selected_status=view_state.selected_status,page=view_state.tasks_page,)+ home_user = _resolve_home_user(integration, slack_user_id)+ own_plan = _resolve_own_plan_state(integration, slack_user_id, home_user, accessible=accessible)stats_state = _resolve_stats_state(integration,accessible=accessible,@@ -2250,13 +2293,12 @@ def _build_home_view(),channel_welcome_mode=resolve_channel_welcome_mode(integration.integration_id) if is_admin else None,auto_model_choice=(- resolve_auto_model_choice(integration.integration_id, slack_user_id)- if _auto_model_choice_offered(integration, slack_user_id)- else None+ resolve_auto_model_choice(integration.integration_id, slack_user_id) if home_user is not None else None),+ own_plan=own_plan,thread_join_mode=(resolve_thread_join_mode(integration, slack_user_id)- if _thread_join_offered(integration, _resolve_home_user(integration, slack_user_id))+ if _thread_join_offered(integration, home_user)else None),has_project_access=bool(accessible),@@ -2510,6 +2552,29 @@ def _thread_join_offered(integration: Integration, home_user: User | None) -> boreturn home_user is not None and is_slack_app_multiplayer_approvals_enabled(integration, home_user.distinct_id)+def _resolve_own_plan_state(+ integration: Integration, slack_user_id: str, home_user: User | None, *, accessible: list[Integration]+) -> OwnPlanState | None:+ """The ChatGPT plan card for this viewer, or `None` when the card is not offered."""+ from products.slack_app.backend.services.slack_messages import ai_subscriptions_url # noqa: PLC0415+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415++ if home_user is None:+ return None+ try:+ target = _routed_project_integration(integration, slack_user_id, accessible=accessible)+ if target is None or not is_slack_app_byos_enabled(target, home_user.distinct_id):+ return None+ return OwnPlanState(+ connected=tasks_facade.can_bill_plan_unattended(home_user, "codex"),+ settings_url=ai_subscriptions_url(target.team_id),+ )+ except Exception:+ # The card is optional; a lookup failure must not cost the whole Home tab.+ logger.exception("slack_app_home_own_plan_resolution_failed", slack_user_id=slack_user_id)+ return None++def _auto_model_choice_offered(integration: Integration, slack_user_id: str) -> bool:return _resolve_home_user(integration, slack_user_id) is not Nonediff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 27a79547b7ac..890fe8f3020d 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -708,6 +708,8 @@ class RunFooter:# The project the thread's task belongs to, so a reader can tell which project's# data the answer was drawn from.project: str | None = None+ # Whose plan pays for the run, for example "Your ChatGPT plan". Absent on PostHog credits.+ plan: str | None = Nonedef has_content(self) -> bool:"""Whether this would render as anything.@@ -717,7 +719,7 @@ class RunFooter:keeps meaning "None-coalesce" and cannot silently discard a partial instance.The ids are not part of the answer — they say nothing on their own."""- return any((self.task_url, self.model, self.project))+ return any((self.task_url, self.model, self.project, self.plan))def _project_name(team_id: int, *, integration_id: int | None, created_by_id: int | None) -> str | None:@@ -764,6 +766,36 @@ def _project_name(team_id: int, *, integration_id: int | None, created_by_id: inreturn team.name if team else None+_SLACK_USER_ID = re.compile(r"[UW][A-Z0-9]+")+++def _plan_label(state: dict[str, Any] | None, *, task_id: Any, integration_id: int | None) -> str | None:+ """Whose plan pays for the run, or `None` on PostHog credits.++ The person who sent the turn reads "Your". When someone who joined the thread sent it, the+ reply mentions the thread creator, so everyone reading can see and reach whose plan pays.+ """+ from products.slack_app.backend.models import SlackThreadTaskMapping # noqa: PLC0415+ from products.tasks.backend.facade.api import get_run_plan # noqa: PLC0415++ plan = get_run_plan(state)+ if plan is None:+ return None+ if plan.owner_user_id is not None and plan.owner_user_id == (state or {}).get("slack_actor_user_id"):+ return f"Your {plan.plan_name}"+ if integration_id is None:+ return plan.plan_name+ owner_slack_user_id = (+ SlackThreadTaskMapping.objects.filter(integration_id=integration_id, task_id=task_id)+ .values_list("mentioning_slack_user_id", flat=True)+ .first()+ )+ # The id goes into the footer's mrkdwn unescaped, so only a well-formed one becomes a mention.+ if not owner_slack_user_id or not _SLACK_USER_ID.fullmatch(owner_slack_user_id):+ return plan.plan_name+ return f"<@{owner_slack_user_id}>'s {plan.plan_name}"++def load_run_footer(run_id: str | UUID | None, *, integration_id: int | None) -> RunFooter:"""Describe a run for the footer.@@ -800,6 +832,7 @@ def load_run_footer(run_id: str | UUID | None, *, integration_id: int | None) ->integration_id=integration_id,created_by_id=run.created_by_id,),+ plan=_plan_label(run.state, task_id=run.task_id, integration_id=integration_id),)except Exception:logger.exception("slack_app_run_footer_load_failed", run_id=str(run_id))@@ -807,7 +840,8 @@ def load_run_footer(run_id: str | UUID | None, *, integration_id: int | None) ->def _run_context_segments(footer: RunFooter) -> list[str]:- """What the run is, as footer segments: the model, then the project it answered from.+ """What the run is, as footer segments: the model, the plan that pays for it, then the+ project it answered from.Shared by the reply footer and the progress message so the two cannot describe onerun differently, and so the escaping below has a single home.@@ -815,6 +849,8 @@ def _run_context_segments(footer: RunFooter) -> list[str]:segments: list[str] = []if footer.model:segments.append(describe_run_model(footer.model, footer.reasoning_effort))+ if footer.plan:+ segments.append(footer.plan)if footer.project:# A project name is tenant text in a `mrkdwn` block, so `<!channel>` broadcasts# and `<url|label>` renders a link the reader reads as the bot's. Escaped here@@ -997,6 +1033,11 @@ def personal_integrations_url(team_id: int) -> str:return _public_url(f"/project/{team_id}/settings/user-personal-integrations")+def ai_subscriptions_url(team_id: int) -> str:+ """Where someone connects their own ChatGPT plan for Codex tasks."""+ return _public_url(f"/project/{team_id}/settings/environment-ai-subscriptions")++def project_web_url(team_id: int) -> str:"""Absolute ``/project/<id>`` base for links into this project's PostHog app."""return _public_url(f"/project/{team_id}")diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.pyindex 10ecbf339a7d..db8448121564 100644--- a/products/slack_app/backend/temporal/activities/task_creation.py+++ b/products/slack_app/backend/temporal/activities/task_creation.py@@ -71,6 +71,25 @@ def _slack_actor_state_updates(*, user_id: int, slack_user_id: str) -> dict[str,return tasks_facade.slack_actor_state_updates(user_id=user_id, slack_user_id=slack_user_id)+def _own_plan_state(integration: Any, user: Any, *, runtime_adapter: str | None) -> dict[str, Any]:+ """The run-state keys that bill a new run to this user's own plan, or none to keep PostHog credits.++ The caller passes the thread creator, whose plan pays for every turn in the thread.+ A failed check keeps the run on credits rather than blocking the mention.+ """+ from products.slack_app.backend.feature_flags import is_slack_app_byos_enabled # noqa: PLC0415+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415++ try:+ state: dict[str, Any] = tasks_facade.unattended_model_access_state(user, runtime_adapter=runtime_adapter)+ # The flag is a network call, so the local plan checks run first.+ if state and is_slack_app_byos_enabled(integration, user.distinct_id, adapter=str(runtime_adapter)):+ return state+ except Exception:+ logger.exception("slack_app_own_plan_resolution_failed", user_id=user.id)+ return {}++def _strip_context_tag(text: str) -> str:return re.sub(rf"</?\s*{_THREAD_CONTEXT_TAG}\s*/?>", "", text, flags=re.IGNORECASE)@@ -578,6 +597,7 @@ def create_posthog_code_task_for_repo_activity(model_override: SlackAppModelOverride | None = None,) -> None:from posthog.models.integration import Integration, SlackIntegration+ from posthog.models.user import Userfrom products.signals.backend.facade import api as signals_facadefrom products.slack_app.backend.models import SlackThreadTaskMapping@@ -716,9 +736,21 @@ def create_posthog_code_task_for_repo_activity(# PR tooling enabled so an explicit follow-up can clone a repo and publish.allow_pr_creation = True- from products.slack_app.backend.facade.run_preferences import resolve_run_preferences+ from products.slack_app.backend.facade.run_preferences import (+ resolve_effective_runtime_adapter,+ resolve_run_preferences,+ )run_prefs = resolve_run_preferences(override=model_override, team_id=integration.team_id, user_id=user_id)+ own_plan_state: dict[str, Any] = {}+ if mentioner := User.objects.filter(id=user_id, is_active=True).first():+ own_plan_state = _own_plan_state(+ integration,+ mentioner,+ runtime_adapter=resolve_effective_runtime_adapter(+ run_prefs.runtime_adapter, team_id=integration.team_id, user_id=user_id+ ),+ )# File into the creator's personal "#me" channel so the task surfaces in PostHog Desktop's# Spaces feed, which is strictly channel-scoped — a NULL-channel task shows up in no space.@@ -752,6 +784,7 @@ def create_posthog_code_task_for_repo_activity(model=run_prefs.model,reasoning_effort=run_prefs.reasoning_effort,channel_id=personal_channel_id,+ extra_run_state=own_plan_state,)except Exception as e:logger.exception(@@ -775,6 +808,7 @@ def create_posthog_code_task_for_repo_activity(logger.info("posthog_code_task_created",team_id=integration.team_id,+ uses_own_plan=bool(own_plan_state),repository=repository,channel=channel,thread_ts=thread_ts,@@ -1008,6 +1042,7 @@ def forward_posthog_code_followup_activity(owner_slack_user_id=mapping.mentioning_slack_user_id,joiner_slack_user_id=slack_user_id,opens_thread=join == ThreadJoinDecision.ASK_FOR_THREAD,+ plan_name=plan.plan_name if (plan := tasks_facade.get_run_plan(task_run.state)) else None,)return True@@ -1158,6 +1193,9 @@ def forward_posthog_code_followup_activity(message_id=_slack_followup_message_id(channel, user_message_ts, thread_ts),actor_slack_user_id=slack_user_id,person_message=person_message,+ # The join check above applied the thread creator's choice about who may join, and a+ # run on a plan bills the creator's plan whoever sends the turn.+ plan_owner_consented=True,)if signal_result is not True:logger.warning(@@ -1419,6 +1457,7 @@ def _resume_task_with_new_run(model_override: SlackAppModelOverride | None = None,) -> bool:"""Create a new run on the same task when a follow-up arrives after the previous run completed."""+ from products.slack_app.backend.facade.run_preferences import resolve_effective_runtime_adapterfrom products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415decode_slack_event_text,labeled_mentions_to_display_names,@@ -1483,6 +1522,16 @@ def _resume_task_with_new_run(# carried over, like the keys above: a preference changed since the previous run is# picked up too.extra_state.update(_run_preference_state(model_override, team_id=mapping.task.team_id, user_id=run_actor.id))+ # The thread creator's plan, whoever replies: the creator chose who may join their thread.+ # `create_run` resolves the defaults for the replying user, so the runtime is read for them too.+ own_plan_state = _own_plan_state(+ integration,+ created_by,+ runtime_adapter=resolve_effective_runtime_adapter(+ extra_state.get("runtime_adapter"), team_id=mapping.task.team_id, user_id=run_actor.id+ ),+ )+ extra_state.update(own_plan_state)extra_state.update(tasks_facade.get_resume_snapshot_carry_state(previous_state))extra_state["resume_from_run_id"] = str(previous_run.id)@@ -1516,7 +1565,11 @@ def _resume_task_with_new_run(# its gated-model entitlement check inside `create_run` must run against whoever# launches this follow-up.new_run = tasks_facade.create_run(- mapping.task_id, mode="interactive", extra_state=extra_state, acting_user_id=run_actor.id+ mapping.task_id,+ mode="interactive",+ extra_state=extra_state,+ acting_user_id=run_actor.id,+ subscription_owner_id=created_by.id if own_plan_state else None,)except Exception:logger.exception(diff --git a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.pyindex f79a8852c3ac..a3fe1b4adc6d 100644--- a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py+++ b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py@@ -5,12 +5,15 @@ from uuid import uuid4import pytestfrom unittest.mock import patch-from django.test import SimpleTestCase+from django.apps import apps+from django.test import SimpleTestCase, TestCasefrom parameterized import parameterized+from posthog.models import Organization, Team, Userfrom posthog.models.integration import Integration+from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.services.slack_messages import (RunFooter,load_run_footer,@@ -55,6 +58,12 @@ class TestRunFooter(SimpleTestCase):None,"Project: *<!channel> & <https://evil/|View on web>*",),+ (+ "plan_follows_the_model",+ RunFooter(model="claude-opus-5", plan="Your ChatGPT plan", project="Fernwood staging"),+ None,+ "*Claude Opus 5* · Your ChatGPT plan · Project: *Fernwood staging*",+ ),("configure_only",RunFooter(),@@ -98,11 +107,86 @@ class TestLoadRunFooter(SimpleTestCase):assert f"/tasks/{task_id}" in (footer.task_url or "")assert footer.model == "claude-opus-5"+ @parameterized.expand(+ [+ ("posthog_credits", {}, None),+ (+ "the_owner_is_speaking",+ {+ "runtime_adapter": "codex",+ "codex_model_access": "own-subscription",+ "codex_subscription_user_id": 7,+ "slack_actor_user_id": 7,+ },+ "Your ChatGPT plan",+ ),+ (+ "no_known_speaker",+ {"runtime_adapter": "codex", "codex_model_access": "own-subscription", "codex_subscription_user_id": 7},+ "ChatGPT plan",+ ),+ ]+ )+ @patch("products.tasks.backend.facade.api.get_task_run")+ def test_names_the_plan_that_pays_for_the_run(+ self, _name: str, state: dict, expected: str | None, mock_get_run+ ) -> None:+ mock_get_run.return_value = SimpleNamespace(+ id=uuid4(), task_id=uuid4(), team_id=1, state=state, created_by_id=None+ )++ assert load_run_footer("run-1", integration_id=None).plan == expected+@patch("products.tasks.backend.facade.api.get_task_run", side_effect=RuntimeError("db down"))def test_a_failure_to_describe_the_run_costs_the_footer_not_the_answer(self, _mock_get_run) -> None:assert load_run_footer("run-1", integration_id=None) == RunFooter()+class TestLoadRunFooterJoinedThread(TestCase):+ @parameterized.expand(+ [+ ("well_formed_id", "U0CREATOR1", "<@U0CREATOR1>'s ChatGPT plan"),+ # The id lands in mrkdwn unescaped, so anything else must not become markup.+ ("malformed_id", "U1> <!channel", "ChatGPT plan"),+ ]+ )+ @patch("products.tasks.backend.facade.api.get_task_run")+ def test_a_joiners_reply_mentions_the_creator_whose_plan_pays(+ self, _name: str, creator_slack_user_id: str, expected: str, mock_get_run+ ) -> None:+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="team")+ creator = User.objects.create(email="[email protected]")+ integration = Integration.objects.create(team=team, kind="slack", integration_id="T1", config={})+ Task = apps.get_model("tasks", "Task")+ task = Task.objects.create(+ team=team, title="t", description="d", origin_product=Task.OriginProduct.SLACK, created_by=creator+ )+ SlackThreadTaskMapping.objects.create(+ team=team,+ integration=integration,+ slack_workspace_id="T1",+ channel="C1",+ thread_ts="1.0",+ task=task,+ task_run=apps.get_model("tasks", "TaskRun").objects.create(task=task, team=team),+ mentioning_slack_user_id=creator_slack_user_id,+ )+ mock_get_run.return_value = SimpleNamespace(+ id=uuid4(),+ task_id=task.id,+ team_id=team.id,+ created_by_id=None,+ state={+ "runtime_adapter": "codex",+ "codex_model_access": "own-subscription",+ "codex_subscription_user_id": creator.id,+ "slack_actor_user_id": creator.id + 1,+ },+ )++ assert load_run_footer("run-1", integration_id=integration.id).plan == expected++class TestViewerHasCodeAccess(SimpleTestCase):def _integration(self) -> Integration:organization = SimpleNamespace(id="org-1")diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex 97ca35ada545..521e964f8919 100644--- a/products/slack_app/backend/tests/services/test_slack_app_home.py+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py@@ -62,6 +62,7 @@ from products.slack_app.backend.services.slack_app_home import (AccountState,GitHubAccount,GitHubState,+ OwnPlanState,ProjectChoice,ProjectState,RunDefaultsState,@@ -478,9 +479,26 @@ class TestRenderHomeView:untagged_question_mode=UntaggedFollowupMode.ASK,channel_welcome_mode=ChannelWelcomeMode.CHANNEL,auto_model_choice=auto_model_choice,+ own_plan=OwnPlanState(connected=True, settings_url="https://app.example.com/settings"),thread_join_mode=ThreadJoinMode.ASK_PER_THREAD,)+ @pytest.mark.parametrize(+ "connected, in_multiplayer, connect_link",+ [(True, True, False), (False, False, True)],+ )+ def test_a_connected_plan_is_described_under_multiplayer(self, connected, in_multiplayer, connect_link):+ # People who join spend the creator's plan, so the plan belongs with who may join.+ view = render_home_view(+ is_admin=False,+ own_plan=OwnPlanState(connected=connected, settings_url="https://app.example.com/settings"),+ )+ text = _all_text(view)++ assert ("Multiplayer" in text) is in_multiplayer+ assert ("use your ChatGPT plan, also when other people join your thread" in text) is in_multiplayer+ assert ("Connect your ChatGPT plan" in text) is connect_link+def test_every_control_the_tab_renders_is_routable(self):# The interactivity endpoint claims region ownership and dispatches off# HOME_ACTION_IDS, so a control missing from it renders as a button that@@ -1278,6 +1296,24 @@ class TestHandleAppHomeOpened:assert (ACTION_SET_THREAD_JOIN_MODE in _action_ids(view)) is flag_on_for_viewerassert ("Multiplayer" in _all_text(view)) is flag_on_for_viewer+ def test_join_picker_shows_without_the_plan_card(self, slack_integration, mock_slack_client, flag_on, admin_user):+ # Who may join a thread is not a plan feature, so closing the BYOS gate must not hide it.+ opener = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)+ SlackUserProfileCache.objects.create(integration=slack_integration, slack_user_id="U001", email=opener.email)++ with (+ patch("products.slack_app.backend.services.slack_app_home.is_slack_app_byos_enabled", return_value=False),+ patch(+ "products.slack_app.backend.services.slack_app_home.is_slack_app_multiplayer_approvals_enabled",+ return_value=True,+ ),+ ):+ handle_app_home_opened({"user": "U001"}, SLACK_WORKSPACE_ID, integration=slack_integration)++ view = mock_slack_client.views_publish.call_args.kwargs["view"]+ assert ACTION_SET_THREAD_JOIN_MODE in _action_ids(view)+ assert "ChatGPT plan" not in _all_text(view)+def _github_row(self, user: User, login: str) -> UserIntegration:return UserIntegration.objects.create(user=user,diff --git a/products/slack_app/backend/tests/test_feature_flags.py b/products/slack_app/backend/tests/test_feature_flags.pyindex 3aec5f884e23..83e62cae0ec3 100644--- a/products/slack_app/backend/tests/test_feature_flags.py+++ b/products/slack_app/backend/tests/test_feature_flags.py@@ -60,3 +60,20 @@ def test_user_keyed_gate_resolves_against_the_acting_user(assert feature_enabled.call_args.args[1] == expected_identityassert feature_enabled.call_args.kwargs["person_properties"] == {"region": "DEV"}assert feature_enabled.call_args.kwargs["groups"] == {"organization": str(org.id)}+++ ("plan_rollout_on", "slack_flag_on", "expected"),+ [(True, True, True), (False, True, False), (True, False, False)],+ ids=["both on", "plan rollout off", "slack flag off"],+)+def test_byos_gate_depends_on_the_plan_rollout_flag(workspace_integration, plan_rollout_on, slack_flag_on, expected):+ # A Slack run marked for a plan whose rollout is off fails when it starts, so the Slack+ # flag alone must never open the gate.+ def feature_enabled(key, *args, **kwargs):+ if key == feature_flags.SLACK_APP_BYOS_FLAG:+ return slack_flag_on+ return plan_rollout_on++ with patch("posthoganalytics.feature_enabled", side_effect=feature_enabled):+ assert feature_flags.is_slack_app_byos_enabled(workspace_integration, "user-1") is expecteddiff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex 3ce3c5ab7996..0a155be6b048 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -1,3 +1,4 @@+from contextlib import AbstractContextManager, nullcontextfrom types import SimpleNamespacefrom unittest import TestCase as UnitTestCase@@ -32,6 +33,7 @@ from products.slack_app.backend.temporal import ()from products.slack_app.backend.temporal.activities.task_creation import _build_terminal_recovery_promptfrom products.slack_app.backend.temporal.helpers import safe_react+from products.tasks.backend.facade import ai_run_defaultsdef _make_inputs(@@ -209,6 +211,49 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):bot_id_patcher.start()self.addCleanup(bot_id_patcher.stop)+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")+ @patch("posthog.models.integration.SlackIntegration")+ def test_a_codex_model_from_the_saved_default_bills_the_mentioners_plan(+ self, mock_slack_cls, mock_execute_workflow+ ):+ # Slack leaves the triple empty when a saved default exists, so the runtime is only+ # known once `create_run` applies that default.+ ai_run_defaults.update_user_ai_run_preferences(+ self.team.id, self.user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None+ )+ mock_slack_instance = MagicMock()+ mock_slack_instance.client.chat_getPermalink.return_value = {+ "ok": True,+ "permalink": "https://slack.example.com/t",+ }+ mock_slack_cls.return_value = mock_slack_instance++ inputs = _make_inputs(self.integration.id, self.user.id)+ with (+ patch(+ "products.tasks.backend.facade.api.unattended_model_access_state",+ side_effect=lambda user, runtime_adapter: (+ {"codex_model_access": "own-subscription"} if runtime_adapter == "codex" else {}+ ),+ ),+ patch("products.slack_app.backend.feature_flags.is_slack_app_byos_enabled", return_value=True),+ ):+ create_posthog_code_task_for_repo_activity(+ inputs,+ "C123",+ "1234.5678",+ "U_ALICE",+ self.user.id,+ inputs.event,+ [SlackThreadMessage(user="U_ALICE", text="fix the tests")],+ None,+ )++ state = self.Task.objects.get(team=self.team).latest_run.state+ assert state["runtime_adapter"] == "codex"+ assert state["codex_model_access"] == "own-subscription"+ assert state["codex_subscription_user_id"] == self.user.id+@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_task_starts_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):@@ -1234,6 +1279,68 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert ({"channel": "C123", "timestamp": "1234.5679", "name": "eyes"} in removed) is not deliveredif prompted:assert mock_prompt.call_args.kwargs["opens_thread"] is (mode in (None, ThreadJoinMode.ASK_PER_THREAD))+ if delivered:+ # A run on the creator's plan takes the joiner's turn on that plan.+ assert mock_signal.call_args.kwargs["plan_owner_consented"] is True++ @parameterized.expand(+ [+ ("model_pinned_in_the_reply", True),+ # Slack leaves the triple empty when a saved default exists, so the runtime is only+ # known once `create_run` applies that default.+ ("model_from_the_saved_default", False),+ ]+ )+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")+ @patch("products.slack_app.backend.api.resolve_slack_user")+ @patch("posthog.models.integration.SlackIntegration")+ def test_a_joiner_resumes_the_task_on_the_thread_creators_plan(+ self, _name, pinned, mock_slack_cls, mock_resolve, mock_execute_workflow+ ):+ self.task_run.status = self.TaskRun.Status.COMPLETED+ self.task_run.save()+ self._create_mapping(mentioning_user="U_ALICE")+ bob = User.objects.create(email="[email protected]", first_name="Bob")+ mock_slack_cls.return_value = MagicMock()+ mock_resolve.return_value = SlackUserContext(user=bob, slack_email="[email protected]")+ preference_patch: AbstractContextManager[object]+ if pinned:+ preference_patch = patch(+ "products.slack_app.backend.temporal.activities.task_creation._run_preference_state",+ return_value={"runtime_adapter": "codex", "model": "gpt-5.5", "provider": "openai"},+ )+ else:+ ai_run_defaults.update_user_ai_run_preferences(+ self.team.id, bob.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None+ )+ preference_patch = nullcontext()++ with (+ preference_patch,+ patch(+ "products.tasks.backend.facade.api.unattended_model_access_state",+ side_effect=lambda user, runtime_adapter: (+ {"codex_model_access": "own-subscription"}+ if user == self.user and runtime_adapter == "codex"+ else {}+ ),+ ),+ patch("products.slack_app.backend.feature_flags.is_slack_app_byos_enabled", return_value=True),+ ):+ forward_posthog_code_followup_activity(+ inputs=_make_inputs(self.integration.id, self.user.id),+ channel="C123",+ thread_ts="1234.5678",+ slack_user_id="U_BOB",+ event_text="<@BOT> fix the tests",+ user_message_ts="1234.5679",+ )++ new_run = self.TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"])+ assert new_run.state["runtime_adapter"] == "codex"+ assert new_run.state["codex_model_access"] == "own-subscription"+ assert new_run.state["codex_subscription_user_id"] == self.user.id+ assert new_run.state["slack_actor_user_id"] == bob.id@patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.models.integration.SlackIntegration")diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex ba5d4b928685..c254623ab106 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -223,6 +223,10 @@ RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"BENJAMIN_FEATURE_FLAG = "task-cloud-run-benjamin-plus"CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-claude-own-subscription-cloud"CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-codex-own-subscription-cloud"+OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAGS: dict[str, str] = {+ "claude": CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ "codex": CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+}# The plan name a person reads when a subscription run is refused. Every layer that gates,# refuses, or explains one of these runs takes the name from here.SUBSCRIPTION_PLAN_NAMES: dict[str, str] = {"claude": "Claude plan", "codex": "ChatGPT plan"}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 3569bb3930c0..dfb8c7142375 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -104,6 +104,7 @@ from products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_tokenfrom products.tasks.backend.feature_flags import (get_model_access_error,+ own_subscription_cloud_enabled as own_subscription_cloud_enabled,pi_cloud_runtime_enabled,run_stream_presence_gated,)@@ -142,6 +143,10 @@ from products.tasks.backend.logic.services.space_setup import (build_space_setup_prompt,space_setup_task_title,)+from products.tasks.backend.logic.services.unattended_plan import (+ can_bill_plan_unattended as can_bill_plan_unattended,+ unattended_model_access_state as unattended_model_access_state,+)from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_runfrom products.tasks.backend.logic.stream.backlog import TaskRunStreamBacklogIndexfrom products.tasks.backend.mentions import resolve_mentioned_user_ids@@ -259,6 +264,10 @@ __all__ = ["task_run_model_outside_gateway_pin","ensure_task_run_session","ensure_subscription_owner",+ "get_run_plan",+ "own_subscription_cloud_enabled",+ "can_bill_plan_unattended",+ "unattended_model_access_state","beacon_task_presence","bootstrap_task_run","SANDBOX_REPOSITORIES_ROOT",@@ -2243,14 +2252,22 @@ def create_run(extra_state: dict | None = None,branch: str | None = None,acting_user_id: int | None = None,+ subscription_owner_id: int | None = None,) -> contracts.TaskRunDTO:"""Create a new run for an existing task (e.g. resuming an interactive sandbox session).``acting_user_id`` attributes the run to the user whose AI run preferences should applywhen ``extra_state`` pins no runtime selection; it falls back to the task's creator.+ ``subscription_owner_id`` names whose plan the run bills to, when that is not the acting user."""task = Task.objects.get(id=task_id)- run = task.create_run(mode=mode, extra_state=extra_state, branch=branch, acting_user_id=acting_user_id)+ run = task.create_run(+ mode=mode,+ extra_state=extra_state,+ branch=branch,+ acting_user_id=acting_user_id,+ subscription_owner_id=subscription_owner_id,+ )return _task_run_to_dto(run, task=task)@@ -4098,6 +4115,17 @@ def _delete_task_session_object(task_session_id: UUID, object_storage_key: str))+def get_run_plan(state: dict[str, Any] | None) -> contracts.RunPlan | None:+ """The plan a run bills to, or `None` for a run on PostHog credits."""+ try:+ access = resolve_model_access(state or {})+ except InvalidModelAccess:+ return None+ if access.adapter is None:+ return None+ return contracts.RunPlan(plan_name=SUBSCRIPTION_PLAN_NAMES[access.adapter], owner_user_id=access.owner_id)++def ensure_subscription_owner(state: dict[str, Any] | None, actor_user_id: int | None) -> None:"""Refuse anyone but the owner of the plan a run bills to. A run on PostHog credits allows everyone."""run_state = state or {}@@ -5759,9 +5787,14 @@ def signal_task_run_user_message(steer: bool = False,rpc_timeout: timedelta | None = None,workflow_id: str | None = None,+ plan_owner_consented: bool = False,) -> bool | None:"""Queue a user_message follow-up signal on the run's workflow.+ ``plan_owner_consented`` lets someone other than the plan owner message a run on the owner's+ plan. Only a caller that collected the owner's consent may set it, such as the Slack app,+ where the thread creator chooses who may join their threads.+Returns ``True`` on success, ``False`` when the target workflow is gone(completed or evicted — a terminal outcome), ``None`` when the run isn'tfound. Transient signalling failures propagate so a calling Temporal@@ -5780,7 +5813,8 @@ def signal_task_run_user_message(run = _get_visible_run(run_id, task_id, team_id)if run is None:return None- ensure_subscription_owner(run.state, actor_user_id)+ if not plan_owner_consented:+ ensure_subscription_owner(run.state, actor_user_id)if run.is_terminal or (run.state or {}).get("cancel_requested_at"):if not run.is_terminal:raise RuntimeError("Task run is still stopping. Try again shortly.")diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex c0836fc3c713..9bd7aab234a0 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -1145,3 +1145,11 @@ class SandboxRunStarter:parent_task_id: UUIDparent_run_id: UUID+++@dataclass(frozen=True, kw_only=True)+class RunPlan:+ """The user plan a run bills to in place of PostHog credits."""++ plan_name: str+ owner_user_id: int | Nonediff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex 00a861362fa4..e71fdbc7b983 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -11,6 +11,7 @@ from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,MCP_EXEC_SKILLS_FEATURE_FLAG,+ OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAGS,PI_CLOUD_RUNTIME_FEATURE_FLAG,get_required_model_flag,)@@ -71,6 +72,29 @@ def is_dev_stack_image_bake_enabled() -> bool:return False+def own_subscription_cloud_enabled(adapter: str, *, distinct_id: str | None, organization_id: str) -> bool:+ """Whether a cloud run may bill to its owner's plan for this adapter; fail-closed when evaluation fails.++ `distinct_id` is the plan owner's, not the id of whoever started the run.+ """+ if not distinct_id:+ return False+ try:+ return bool(+ posthoganalytics.feature_enabled(+ OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAGS[adapter],+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("own_subscription_cloud_flag_check_failed", extra={"adapter": adapter})+ return False++def pi_cloud_runtime_enabled(team: "Team", user: "User") -> bool:"""Whether this user may run the Pi harness in the cloud; fail-closed when evaluation fails.diff --git a/products/tasks/backend/logic/services/tests/test_unattended_plan.py b/products/tasks/backend/logic/services/tests/test_unattended_plan.pynew file mode 100644index 000000000000..ead7fdc17bd7--- /dev/null+++ b/products/tasks/backend/logic/services/tests/test_unattended_plan.py@@ -0,0 +1,28 @@+import pytest++from posthog.models import User+from posthog.models.user_integration import UserIntegration++from products.tasks.backend.logic.services.unattended_plan import unattended_model_access_state+++class TestUnattendedModelAccessState:+ @pytest.mark.parametrize(+ "runtime_adapter,status,expected",+ [+ ("codex", "connected", {"codex_model_access": "own-subscription"}),+ ("codex", "reauth_required", {}),+ ("codex", None, {}),+ ("claude", "connected", {}),+ (None, "connected", {}),+ ],+ )+ def test_only_a_connected_plan_matching_the_harness_bills_the_run(self, runtime_adapter, status, expected):+ user = User.objects.create(email="[email protected]")+ if status is not None:+ UserIntegration.objects.create(+ user=user, kind=UserIntegration.IntegrationKind.CODEX, integration_id="acct", config={"status": status}+ )++ assert unattended_model_access_state(user, runtime_adapter=runtime_adapter) == expecteddiff --git a/products/tasks/backend/logic/services/unattended_plan.py b/products/tasks/backend/logic/services/unattended_plan.pynew file mode 100644index 000000000000..2ac070aebd01--- /dev/null+++ b/products/tasks/backend/logic/services/unattended_plan.py@@ -0,0 +1,41 @@+"""Whether a run that no client starts, such as one from the Slack app, can bill to the user's own plan.++Desktop and the web composer send `{adapter}_model_access` with every run they create. A surface+with no client in the loop has no such choice to send, so a connected plan counts as the opt-in.+The caller checks the plan's rollout flag (`own_subscription_cloud_enabled`) first, because a run+marked for a plan whose rollout is off fails when it starts instead of falling back to credits.+"""++from typing import cast, get_args++from posthog.models.integration.codex import CodexUserIntegration+from posthog.models.user import User++from products.tasks.backend.logic.model_access import SubscriptionAdapter+++def can_bill_plan_unattended(user: User, adapter: SubscriptionAdapter) -> bool:+ """Whether the user's plan for this adapter can pay for a run while the user is not at a client.++ A Claude plan cannot, because PostHog stores no Claude token: the owner's Desktop must answer+ the token request each time an agent session starts. A ChatGPT plan can, because PostHog+ holds the token and refreshes it for the sandbox.+ """+ if adapter != "codex":+ return False+ integration = CodexUserIntegration.for_user(user.id)+ return integration is not None and integration.is_connected()+++def unattended_model_access_state(user: User, *, runtime_adapter: str | None) -> dict[str, str]:+ """The run-state keys that put a new run on the user's plan, or none to keep it on PostHog credits.++ The plan must match the run's harness, because `resolve_model_access` refuses a ChatGPT plan+ on a Claude run. `Task.create_run` then records the plan owner.+ """+ if runtime_adapter not in get_args(SubscriptionAdapter):+ return {}+ adapter = cast(SubscriptionAdapter, runtime_adapter)+ if not can_bill_plan_unattended(user, adapter):+ return {}+ return {f"{adapter}_model_access": "own-subscription"}diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 4effd99e6513..bf0ff8818381 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -816,6 +816,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):acting_user_id: int | None = None,scheduled_at: datetime | None = None,startup_requested_at: datetime | None = None,+ subscription_owner_id: int | None = None,) -> "TaskRun":startup_requested_at = startup_requested_at or django_timezone.now()if scheduled_at is not None and django_timezone.is_naive(scheduled_at):@@ -899,7 +900,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):task._apply_ai_run_defaults(state, acting_user_id)model_access = resolve_model_access(state)if model_access.adapter is not None:- state[f"{model_access.adapter}_subscription_user_id"] = acting_user_id or task.created_by_id+ state[f"{model_access.adapter}_subscription_user_id"] = (+ subscription_owner_id or acting_user_id or task.created_by_id+ )if task.ownership_version is not None:state[TASK_OWNERSHIP_VERSION_STATE_KEY] = task.ownership_versiondiff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 60adb4544b53..e1019e4552ed 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -20,8 +20,6 @@ from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_PEER_MESSAGING_FEATURE_FLAG,BENJAMIN_FEATURE_FLAG,- CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,- CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,CODEX_SUBSCRIPTION_EGRESS_DOMAINS,DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,DEV_STACK_IMAGE_NAME,@@ -49,6 +47,7 @@ from products.tasks.backend.exceptions import (TaskRunNotReadyError,)from products.tasks.backend.facade.api import ensure_task_run_session+from products.tasks.backend.feature_flags import own_subscription_cloud_enabledfrom products.tasks.backend.logic.model_access import ModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.agent_instructions import agent_instructions_state_updatefrom products.tasks.backend.logic.services.agentsh import (@@ -478,19 +477,16 @@ def _is_rtk_enabled(@frozenclass _SubscriptionAdapter:- flag: strruntime_name: strsettings_name: str_SUBSCRIPTION_ADAPTERS: dict[str, _SubscriptionAdapter] = {"claude": _SubscriptionAdapter(- flag=CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,runtime_name="Claude",settings_name="Claude subscription settings",),"codex": _SubscriptionAdapter(- flag=CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,runtime_name="Codex",settings_name="ChatGPT subscription settings",),@@ -519,22 +515,7 @@ def _ensure_subscription_allowed(cause=ValueError(f"Subscription requested for a non-{spec.runtime_name} runtime"),capture=False,)- try:- enabled = bool(- distinct_id- and posthoganalytics.feature_enabled(- spec.flag,- distinct_id=distinct_id,- groups={"organization": organization_id},- group_properties={"organization": {"id": organization_id}},- only_evaluate_locally=False,- send_feature_flag_events=False,- )- )- except Exception as e:- log_with_activity_context(f"{adapter}_own_subscription_flag_check_failed", run_id=run_id, error=str(e))- enabled = False- if not enabled:+ if not own_subscription_cloud_enabled(adapter, distinct_id=distinct_id, organization_id=organization_id):raise ProcessTaskFatalError(f"Using your {plan_name} for cloud tasks is unavailable. Try again later, "f'or open {spec.settings_name} and turn off "Cloud tasks" to use PostHog credits.',