Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): read credentials, MCP tools and billing from the profile (#126066)

Charles Vien7680cc504966
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 11cd9073f09c..06a4c5aff0ea 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -252,3 +252,40 @@ BK_MCP_SCOPE = "business_knowledge:read"
# It reads the project to find its organization, and the business knowledge tools sit behind a flag
# targeted by organization, so without project:read the search tool is hidden.
BK_MCP_SCOPES = [BK_MCP_SCOPE, "user:read", "project:read"]
+
+DOCS_SEARCH_TOOL = "docs-search"
+# Read tools the token's scopes unlock but the answer never needs. Knowledge content can carry
+# injected instructions, so hide anything that reads the asker's own data.
+BK_HIDDEN_TOOLS = (
+ DOCS_SEARCH_TOOL,
+ "user-get",
+ "user-home-settings-get",
+ "llma-personal-spend",
+ "reminder-get",
+ "reminders-list",
+ "project-get",
+ "mcp-connections-list",
+ "mcp-connection-tools-list",
+ "tasks-list",
+ "tasks-retrieve",
+ "tasks-runs-list",
+ "tasks-runs-retrieve",
+ "tasks-runs-session-logs-retrieve",
+ "tasks-artifacts-list",
+ "tasks-config-list",
+ "tasks-me-config-list",
+ "tasks-models-retrieve",
+ "channel-list",
+ "channel-retrieve",
+ "channel-instructions-retrieve",
+ "inbox-reports-list",
+ "inbox-reports-retrieve",
+ "inbox-report-artefacts-list",
+ "inbox-report-artefacts-retrieve",
+ "inbox-report-checks-list",
+ "inbox-report-checks-retrieve",
+ "inbox-source-configs-list",
+ "inbox-source-configs-retrieve",
+ "task-context-wiki-channel-resolve",
+ "task-context-wiki-page-retrieve",
+)
diff --git a/products/business_knowledge/backend/sandbox.py b/products/business_knowledge/backend/sandbox.py
index 89d1d5d6d2c3..ae0fa6d54287 100644
--- a/products/business_knowledge/backend/sandbox.py
+++ b/products/business_knowledge/backend/sandbox.py
@@ -19,7 +19,7 @@ from products.tasks.backend.facade.contracts import CreatedTaskDTO, TaskRunDTO
from products.tasks.backend.facade.profiles import TaskRunOptions
from . import task_profiles
-from .constants import BK_MCP_SCOPES
+from .constants import BK_MCP_SCOPES, DOCS_SEARCH_TOOL
from .github_repos import repository_tools_enabled
from .logic import KnowledgeSearchResult, get_always_on_context
@@ -33,43 +33,7 @@ BK_SEARCH_TOOL = "business-knowledge-documents-search"
BK_WINDOW_TOOL = "business-knowledge-document-window-retrieve"
BK_REPO_SEARCH_TOOL = "business-knowledge-repositories-search"
BK_REPO_FILE_TOOL = "business-knowledge-repositories-file-retrieve"
-DOCS_SEARCH_TOOL = "docs-search"
BK_DISPLAY_TOOLS = frozenset({BK_SEARCH_TOOL, BK_WINDOW_TOOL, BK_REPO_SEARCH_TOOL, BK_REPO_FILE_TOOL})
-# Read tools the token's scopes unlock but the answer never needs. Knowledge content can carry
-# injected instructions, so hide anything that reads the asker's own data.
-BK_HIDDEN_TOOLS = [
- DOCS_SEARCH_TOOL,
- "user-get",
- "user-home-settings-get",
- "llma-personal-spend",
- "reminder-get",
- "reminders-list",
- "project-get",
- "mcp-connections-list",
- "mcp-connection-tools-list",
- "tasks-list",
- "tasks-retrieve",
- "tasks-runs-list",
- "tasks-runs-retrieve",
- "tasks-runs-session-logs-retrieve",
- "tasks-artifacts-list",
- "tasks-config-list",
- "tasks-me-config-list",
- "tasks-models-retrieve",
- "channel-list",
- "channel-retrieve",
- "channel-instructions-retrieve",
- "inbox-reports-list",
- "inbox-reports-retrieve",
- "inbox-report-artefacts-list",
- "inbox-report-artefacts-retrieve",
- "inbox-report-checks-list",
- "inbox-report-checks-retrieve",
- "inbox-source-configs-list",
- "inbox-source-configs-retrieve",
- "task-context-wiki-channel-resolve",
- "task-context-wiki-page-retrieve",
-]
_RECOGNIZED_TOOLS = BK_DISPLAY_TOOLS | {DOCS_SEARCH_TOOL}
# A follow-up run is a new process. These pins live on the previous run, not on the task.
_RESUMED_RUN_STATE_KEYS = (
@@ -278,7 +242,7 @@ def start_sandbox_run(
output_schema=SandboxAnswer.model_json_schema(),
),
extra_run_state={
- "mcp_exclude_tools": BK_HIDDEN_TOOLS,
+ "mcp_exclude_tools": list(task_profiles.BUSINESS_KNOWLEDGE.mcp_exclude_tools),
"config_snapshot": {"connectors": {"mcp_installation_ids": []}},
},
)
diff --git a/products/business_knowledge/backend/task_profiles.py b/products/business_knowledge/backend/task_profiles.py
index 7e2fa00718db..b91bfe25288c 100644
--- a/products/business_knowledge/backend/task_profiles.py
+++ b/products/business_knowledge/backend/task_profiles.py
@@ -11,7 +11,7 @@ from products.tasks.backend.facade.profiles import (
register_task_profiles,
)
-from .constants import BK_MCP_SCOPES, MAX_OPEN_RUNS_PER_OWNER
+from .constants import BK_HIDDEN_TOOLS, BK_MCP_SCOPES, MAX_OPEN_RUNS_PER_OWNER
BUSINESS_KNOWLEDGE = TaskProfile(
key="business_knowledge",
@@ -34,6 +34,7 @@ BUSINESS_KNOWLEDGE = TaskProfile(
mcp_agent=None,
mcp_scopes=BK_MCP_SCOPES,
mcp_store_servers=False,
+ mcp_exclude_tools=BK_HIDDEN_TOOLS,
oauth_app=OAuthApp.ARRAY,
github_resolution=GithubResolution.WITH_REPOSITORY,
user_authorable_prs=False,
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index fb9713a7931a..7a86eff7e6c4 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -16,6 +16,7 @@ from django.db.models import Q
import structlog
from products.mcp_store.backend.agents import (
+ BuiltInAgentKey,
built_in_agent_key_for_task_origin,
create_gateway_agent_token,
credential_owner_eligible,
@@ -440,6 +441,8 @@ def resolve_installations_for_sandbox(
include_personal: bool = False,
task_origin: str | None = None,
task_agent_key: str | None = None,
+ has_profile: bool = False,
+ profile_agent_key: BuiltInAgentKey | None = None,
credential_owner_id: int | None = None,
allowed_installation_ids: list[str] | None = None,
allowed_gateway_server_ids: list[str] | None = None,
@@ -457,7 +460,10 @@ def resolve_installations_for_sandbox(
on every call, so an offboarded owner's grants stop mounting even though
the grant rows persist. Origin alone is not
trusted: the persisted task agent key must match the origin mapping. A
- mapped origin without that marker gets no MCP Store installations. Built-in agent
+ mapped origin without that marker gets no MCP Store installations.
+ When ``has_profile`` is True, ``profile_agent_key`` replaces the origin
+ mapping: a profiled task resolves as the agent its profile names, or as a
+ member task when the profile names none, whatever its origin. Built-in agent
handling is gated per team on the `mcp-gateway` rollout flag; teams
without it resolve mapped origins like unmapped tasks. Unmapped origins
retain the legacy member behavior and optionally include the user's
@@ -491,7 +497,7 @@ def resolve_installations_for_sandbox(
"template", "gateway_server"
)
- mapped_agent_key = built_in_agent_key_for_task_origin(task_origin or "")
+ mapped_agent_key = profile_agent_key if has_profile else built_in_agent_key_for_task_origin(task_origin or "")
if mapped_agent_key is not None and not is_builtin_agent_enforcement_enabled(team_id):
# Rollout gate: until the gateway ships for this team, built-in
# agent origins keep the legacy member resolution below.
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index 0caba7b1ffb1..b8c7565d7f7a 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -478,6 +478,27 @@ class TestGetInstallationsForSandbox(BaseTest):
)
assert mismatched_results == []
+ profiled_results = resolve_installations_for_sandbox(
+ self.team.id,
+ user_id=self.user.id,
+ include_personal=True,
+ task_origin="user_created",
+ task_agent_key="support",
+ has_profile=True,
+ profile_agent_key="support",
+ credential_owner_id=self.user.id,
+ ).mounted
+ assert [result.id for result in profiled_results] == [str(personal.id)]
+
+ profiled_member_results = resolve_installations_for_sandbox(
+ self.team.id,
+ user_id=self.user.id,
+ include_personal=True,
+ task_origin="support_reply",
+ has_profile=True,
+ ).mounted
+ assert {result.name for result in profiled_member_results} == {"Personal", "Ungranted"}
+
def test_built_in_agent_only_gets_the_run_credential_owner_s_grants(self) -> None:
account = self._support_agent()
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 518774d2f97a..c4c59fc9576c 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -213,6 +213,7 @@ from products.tasks.backend.task_sources import apply_task_source
from products.tasks.backend.visibility import (
PRODUCT_PRIVATE_ORIGIN_PRODUCTS,
TEAM_READABLE_ORIGIN_PRODUCTS,
+ readable_without_channel,
scout_trial_visibility_q,
task_control_q,
task_run_visibility_q,
@@ -2082,7 +2083,7 @@ def create_and_run_task(
team, report_id=signal_report_id, stage="task_create", enabled=free_trial_enabled
)
channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else None
- if channel is None and not internal and origin_product not in TEAM_READABLE_ORIGIN_PRODUCTS:
+ if channel is None and not internal and not readable_without_channel(origin_product, profile):
channel = _ensure_personal_channel(team.id, user_id)[0]
task = Task.create_and_run(
team=team,
@@ -2328,7 +2329,7 @@ def create_task_without_run(
if channel is None:
channel = (
None
- if origin.origin_product in TEAM_READABLE_ORIGIN_PRODUCTS
+ if readable_without_channel(origin.origin_product, profile)
else _ensure_personal_channel(team.id, user_id)[0]
)
task = Task.create_without_run(
@@ -8466,6 +8467,21 @@ def update_task(
validated_data["repositories"] = [validated_data["repository"]] if validated_data["repository"] else []
else:
validated_data.pop("repository")
+ profile = task.stored_profile
+ changes_github_access = not validated_data.keys().isdisjoint(
+ {"repository", "repositories", "github_integration", "github_user_integration"}
+ )
+ if (
+ profile is not None
+ and changes_github_access
+ and not Task.attaches_github(
+ task.origin_product, profile, has_repository=bool(validated_data.get("repository", task.repository))
+ )
+ ):
+ validated_data.pop("github_integration", None)
+ validated_data.pop("github_user_integration", None)
+ task.github_integration = None
+ task.github_user_integration = None
if "title" in validated_data and "title_manually_set" not in validated_data:
validated_data["title_manually_set"] = True
if "archived" in validated_data and validated_data["archived"] != task.archived:
diff --git a/products/tasks/backend/facade/profiles.py b/products/tasks/backend/facade/profiles.py
index 94a0d875e747..aab048fca04f 100644
--- a/products/tasks/backend/facade/profiles.py
+++ b/products/tasks/backend/facade/profiles.py
@@ -167,6 +167,7 @@ class TaskProfile:
# True installs the team's MCP store servers in the sandbox. False installs none, personal
# servers included.
mcp_store_servers: bool
+ mcp_exclude_tools: tuple[str, ...]
# The OAuth application that mints the sandbox's PostHog tokens. The LLM gateway pins billing
# products per application, so a token from a shared application is valid for every product on
# it. A product with its own billing needs its own application.
@@ -302,10 +303,14 @@ _ORIGIN_SCOPED_FIELDS = (
"warm",
)
+MAX_MCP_EXCLUDE_TOOLS = 32
+
_profiles: dict[str, TaskProfile] = {}
def register_task_profile(profile: TaskProfile) -> None:
+ if len(profile.mcp_exclude_tools) > MAX_MCP_EXCLUDE_TOOLS:
+ raise TaskProfileError(f"Task profile {profile.key!r} hides more than {MAX_MCP_EXCLUDE_TOOLS} MCP tools")
existing = _profiles.get(profile.key)
if existing is not None and existing != profile:
raise TaskProfileError(f"Task profile {profile.key!r} is already registered with different values")
diff --git a/products/tasks/backend/logic/services/compute_quota.py b/products/tasks/backend/logic/services/compute_quota.py
index c3554992954a..bcd6241f6f0b 100644
--- a/products/tasks/backend/logic/services/compute_quota.py
+++ b/products/tasks/backend/logic/services/compute_quota.py
@@ -6,6 +6,7 @@ from django.conf import settings
from posthog.models import Team, User
from products.tasks.backend.facade.contracts import ComputeQuotaDenialReason
+from products.tasks.backend.facade.profiles import TaskProfile
from products.tasks.backend.metrics import observe_compute_quota_check
from products.tasks.backend.models import Task, TaskClientProvenance
@@ -30,12 +31,18 @@ def task_creator_is_staff(task: Task) -> bool:
def is_task_billable_compute(task: Task) -> bool:
- return is_billable_compute(origin_product=task.origin_product, client_provenance=task.client_provenance)
+ return is_billable_compute(
+ origin_product=task.origin_product, client_provenance=task.client_provenance, profile=task.stored_profile
+ )
-def is_billable_compute(*, origin_product: str | None, client_provenance: str | None) -> bool:
+def is_billable_compute(
+ *, origin_product: str | None, client_provenance: str | None, profile: TaskProfile | None = None
+) -> bool:
if client_provenance not in POSTHOG_CODE_CLIENT_PROVENANCES:
return False
+ if profile is not None:
+ return profile.bills_compute
return origin_product in (Task.OriginProduct.USER_CREATED, Task.OriginProduct.SPACE_SETUP)
diff --git a/products/tasks/backend/logic/services/tests/test_compute_quota.py b/products/tasks/backend/logic/services/tests/test_compute_quota.py
index 54b74936a765..39b66eab4d6d 100644
--- a/products/tasks/backend/logic/services/tests/test_compute_quota.py
+++ b/products/tasks/backend/logic/services/tests/test_compute_quota.py
@@ -1,3 +1,5 @@
+from dataclasses import replace
+
import pytest
from unittest.mock import patch
@@ -5,6 +7,7 @@ from django.test import override_settings
from posthog.models import Organization, Team, User
+from products.tasks.backend.facade.profiles import get_task_profile
from products.tasks.backend.logic.services.compute_quota import (
ComputeQuotaDenialReason,
get_compute_quota_denial_reason,
@@ -103,3 +106,17 @@ class TestComputeQuota:
def test_unknown_origin_is_ineligible(self):
assert not is_billable_compute(origin_product=None, client_provenance=TaskClientProvenance.POSTHOG_DESKTOP)
+
+ @pytest.mark.parametrize(
+ "bills_compute,provenance,billable",
+ [
+ (True, TaskClientProvenance.POSTHOG_DESKTOP, True),
+ (False, TaskClientProvenance.POSTHOG_DESKTOP, False),
+ (True, None, False),
+ ],
+ )
+ def test_profiled_task_bills_compute_by_its_profile(self, bills_compute, provenance, billable):
+ profile = replace(get_task_profile("business_knowledge"), key="test.billing", bills_compute=bills_compute)
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ assert is_task_billable_compute(self.task(profile=profile.key, client_provenance=provenance)) is billable
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index b693ebc0688e..2177487f50a8 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -533,6 +533,17 @@ def observe_github_webhook_task_run_lookup(*, scoped: bool) -> None:
GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL.labels(scoped="true" if scoped else "false").inc()
+MCP_EXCLUDE_TOOLS_OVER_CAP_TOTAL = Counter(
+ "posthog_tasks_mcp_exclude_tools_over_cap_total",
+ "Profiled runs refused because the profile and the run together hide more MCP tools than the sandbox cap",
+ labelnames=["profile"],
+)
+
+
+def observe_mcp_exclude_tools_over_cap(*, profile: str) -> None:
+ MCP_EXCLUDE_TOOLS_OVER_CAP_TOTAL.labels(profile=profile).inc()
+
+
def _metric_label(value: object | None) -> str:
if value is None:
return "unknown"
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index f89a0af3b3ac..5eb441c51726 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -54,6 +54,7 @@ from products.tasks.backend.dev_stack_image_models import (
)
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.facade.profiles import (
+ GithubResolution,
PrAuthorship,
TaskProfile,
TaskProfileError,
@@ -708,9 +709,15 @@ class Task(Taggable, DeletedMetaFields, models.Model):
return self.origin_product == Task.OriginProduct.POSTHOG_AI
return profile.user_authorable_prs and profile.default_pr_authorship == PrAuthorship.BOT
+ @staticmethod
+ def mcp_agent_key_for(origin_product: str, profile: TaskProfile | None) -> MCPBuiltInAgentKey | None:
+ if profile is not None:
+ return cast("MCPBuiltInAgentKey | None", profile.mcp_agent)
+ return MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(origin_product)
+
@property
def mcp_builtin_agent_key(self) -> MCPBuiltInAgentKey | None:
- expected_key = MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(self.origin_product)
+ expected_key = Task.mcp_agent_key_for(self.origin_product, self.stored_profile)
marker = (self.state or {}).get(MCP_BUILT_IN_AGENT_STATE_KEY)
return expected_key if marker == expected_key else None
@@ -1308,6 +1315,14 @@ class Task(Taggable, DeletedMetaFields, models.Model):
Task.OriginProduct.SIGNALS_SCOUT,
)
+ @staticmethod
+ def attaches_github(origin_product: str, profile: TaskProfile | None, *, has_repository: bool) -> bool:
+ if profile is None:
+ return Task._github_resolution_allowed(origin_product, has_repository=has_repository)
+ if profile.github_resolution == GithubResolution.WITH_REPOSITORY:
+ return has_repository
+ return profile.github_resolution == GithubResolution.ALWAYS
+
@staticmethod
def _build_task(
*,
@@ -1392,7 +1407,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
user_github_integration_is_usable,
)
- github_resolution_allowed = Task._github_resolution_allowed(origin_product, has_repository=bool(repository))
+ github_resolution_allowed = Task.attaches_github(origin_product, profile, has_repository=bool(repository))
github_integration = None
if github_resolution_allowed:
github_integration = next(
@@ -1455,9 +1470,11 @@ class Task(Taggable, DeletedMetaFields, models.Model):
if sandbox_env is None:
raise ValueError(f"Invalid sandbox_environment_id: {sandbox_environment_id}")
- expected_agent_key = MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(origin_product)
+ expected_agent_key = Task.mcp_agent_key_for(origin_product, profile)
if mcp_builtin_agent_key is not None and mcp_builtin_agent_key != expected_agent_key:
raise ValueError(f"Agent key {mcp_builtin_agent_key!r} does not match task origin {origin_product!r}")
+ if profile is not None:
+ mcp_builtin_agent_key = expected_agent_key
initial_state: dict[str, Any] = {}
if mcp_builtin_agent_key:
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 69a008a589be..14dc38f6878e 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -77,14 +77,17 @@ INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS = frozenset(
def _oauth_application_for_task(task: Task, state: dict[str, Any] | None) -> SandboxOAuthApplication:
- # A metrics import bills the `posthog_ai` gateway product, which accepts only this application.
- if task.origin_product in (Task.OriginProduct.POSTHOG_AI, Task.OriginProduct.METRICS_IMPORT):
- return "posthog_ai"
if (
task.origin_product in (Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT)
and (state or {}).get("billing_product") == "posthog_ai"
):
return "posthog_ai"
+ profile = task.stored_profile
+ if profile is not None:
+ return cast(SandboxOAuthApplication, profile.oauth_app.value)
+ # A metrics import bills the `posthog_ai` gateway product, which accepts only this application.
+ if task.origin_product in (Task.OriginProduct.POSTHOG_AI, Task.OriginProduct.METRICS_IMPORT):
+ return "posthog_ai"
if task.origin_product in SIGNALS_ORIGIN_PRODUCTS:
return "signals"
return "array"
@@ -212,12 +215,9 @@ def create_oauth_access_token(
"application": _oauth_application_for_task(task, run_state),
"sandbox_task_id": task.id,
}
- if task.origin_product in {
- Task.OriginProduct.SIGNALS_SCOUT,
- Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
- Task.OriginProduct.SUPPORT_REPLY,
- Task.OriginProduct.WORKFLOW,
- } and is_builtin_agent_enforcement_enabled(task.team_id):
+ if Task.mcp_agent_key_for(task.origin_product, task.stored_profile) is not None and (
+ is_builtin_agent_enforcement_enabled(task.team_id)
+ ):
# This scope only removes access to the human MCP Store surface. Add it
# even when a legacy task lacks trusted provenance so an old spoofed
# origin fails closed instead of inheriting its creator's connections.
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index bf205a024d58..60c1bf732bbf 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -49,11 +49,12 @@ from products.tasks.backend.temporal.process_task.utils import (
get_sandbox_ph_mcp_configs,
get_task_run_credential_user,
get_user_mcp_server_configs,
+ include_personal_mcp_for_task,
is_slack_interaction_state,
loop_mcp_installation_allowlist,
mark_sandbox_github_identity,
mark_sandbox_mcp_session,
- mcp_exclude_tools_from_state,
+ mcp_exclude_tools_for_task,
record_delivered_message,
sandbox_identity_scope,
unmounted_mcp_installations_log_fields,
@@ -631,13 +632,13 @@ def _refresh_sandbox_mcp(
slack_reply_context=(state or {}).get("slack_reply_context") is True,
task_id=str(task_run.task_id),
origin_product=task_run.task.origin_product,
- exclude_tools=mcp_exclude_tools_from_state(state),
+ exclude_tools=mcp_exclude_tools_for_task(task_run.task, state),
)
user_mcp = get_user_mcp_server_configs(
token=access_token,
team_id=task_run.team_id,
user_id=actor_user.id,
- include_personal=not task_run.task.internal,
+ include_personal=include_personal_mcp_for_task(task_run.task),
interaction_origin=(state or {}).get("interaction_origin"),
slack_reply_context=(state or {}).get("slack_reply_context") is True,
allowed_installation_ids=loop_mcp_installation_allowlist(state),
@@ -645,6 +646,7 @@ def _refresh_sandbox_mcp(
task_agent_key=task_run.task.mcp_builtin_agent_key,
credential_owner_id=task_run.task.mcp_credential_owner_id,
allowed_gateway_server_ids=task_run.task.mcp_gateway_server_allowlist,
+ profile=task_run.task.stored_profile,
)
if user_mcp.configs:
mcp_configs = mcp_configs + user_mcp.configs
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index a1caf13874e0..adfe25e6ec00 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -78,9 +78,10 @@ from products.tasks.backend.temporal.process_task.utils import (
get_sandbox_ph_mcp_configs,
get_task_run_credential_user,
get_user_mcp_server_configs,
+ include_personal_mcp_for_task,
loop_mcp_installation_allowlist,
mark_sandbox_mcp_session,
- mcp_exclude_tools_from_state,
+ mcp_exclude_tools_for_task,
unmounted_mcp_installations_log_fields,
unmounted_mcp_installations_notice,
)
@@ -424,17 +425,6 @@ def _report_unmounted_mcp_installations(ctx: TaskProcessingContext, unmounted: S
emit_agent_log(ctx.run_id, "warn", notice)
-def _include_personal_mcp_for_task(task: Task) -> bool:
- """Whether a run may pull the task creator's *personal* MCP installations.
-
- Internal/autonomous runs (support reply, signals) must never pull a
- resolved member's personal creds. Agent-specific grant filtering happens
- in the MCP Store facade.
- User-initiated Code runs get shared + the creator's personal installs.
- """
- return not task.internal
-
-
def _start_protected_base_branch_lookup(
ctx: TaskProcessingContext,
) -> tuple[ThreadPoolExecutor, Future[str | None]] | None:
@@ -533,9 +523,9 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
slack_reply_context=ctx.slack_reply_context,
task_id=str(ctx.task_id),
origin_product=task.origin_product,
- exclude_tools=mcp_exclude_tools_from_state(ctx.state),
+ exclude_tools=mcp_exclude_tools_for_task(task, ctx.state),
)
- include_personal = _include_personal_mcp_for_task(task)
+ include_personal = include_personal_mcp_for_task(task)
user_mcp = get_user_mcp_server_configs(
token=access_token,
team_id=ctx.team_id,
@@ -548,6 +538,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
task_agent_key=task.mcp_builtin_agent_key,
credential_owner_id=task.mcp_credential_owner_id,
allowed_gateway_server_ids=task.mcp_gateway_server_allowlist,
+ profile=task.stored_profile,
)
if user_mcp.configs:
mcp_configs = mcp_configs + user_mcp.configs
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 4a32345ad14f..3c6f6b767a52 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -27,7 +27,6 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
_agentsh_domains_for,
_emit_agent_server_log_tail,
_ensure_repository_on_disk,
- _include_personal_mcp_for_task,
_invoke_start_agent_server,
_launch_agent_shadow,
_LaunchParams,
@@ -709,21 +708,6 @@ def _mock_github_integration(mocker, pr_base: str | None):
return integration
- "internal,expected",
- [
- # Internal/autonomous runs (support reply, signals) get shared team
- # connections only — never a resolved member's personal MCP creds.
- (True, False),
- # User-initiated Code runs get shared + the creator's personal installs.
- (False, True),
- ],
-)
-def test_include_personal_mcp_for_task(mocker, internal, expected) -> None:
- task = mocker.Mock(internal=internal)
- assert _include_personal_mcp_for_task(task) is expected
-
-
def test_prepare_launch_retries_task_read_and_keeps_db_drop_identity(mocker) -> None:
task_get = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"
@@ -747,7 +731,7 @@ def test_prepare_launch_retries_task_read_and_keeps_db_drop_identity(mocker) ->
],
)
def test_prepare_launch_relabels_only_non_transient_token_errors(mocker, raised, expected) -> None:
- task = mocker.Mock(internal=True, created_by_id=None, team_id=1)
+ task = mocker.Mock(internal=True, stored_profile=None, created_by_id=None, team_id=1)
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"
).return_value.get.return_value = task
@@ -814,6 +798,7 @@ def _mock_prepare_launch_dependencies(mocker) -> None:
prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"
task = mocker.Mock(
internal=True,
+ stored_profile=None,
runtime="claude",
origin_product=None,
mcp_builtin_agent_key=None,
@@ -1182,6 +1167,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(
created_by_id=None,
team_id=1,
internal=True,
+ stored_profile=None,
origin_product="support_reply",
mcp_builtin_agent_key="support",
mcp_credential_owner_id=17,
@@ -1253,6 +1239,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(
task_agent_key="support",
credential_owner_id=17,
allowed_gateway_server_ids=["srv-1"],
+ profile=None,
)
sandbox.start_agent_server.assert_called_once()
sandbox.wait_for_agent_server_ready.assert_not_called()
@@ -1279,6 +1266,7 @@ async def test_start_agent_server_forwards_imported_and_relayed_mcp_servers(mock
created_by_id=None,
team_id=1,
internal=False,
+ stored_profile=None,
origin_product="user_created",
mcp_builtin_agent_key=None,
mcp_credential_owner_id=None,
@@ -1338,6 +1326,7 @@ async def test_start_agent_server_passes_initial_permission_mode(mocker) -> None
created_by_id=None,
team_id=1,
internal=False,
+ stored_profile=None,
origin_product="user_created",
mcp_builtin_agent_key=None,
mcp_credential_owner_id=None,
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index ac70d6c69aed..dbbb4d2ae14d 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -76,6 +76,7 @@ def _make_task_run_mock(team_id: int = 7, created_by_id: int | None = 42, state:
task.created_by_id = created_by_id
task.team_id = team_id
task.internal = False
+ task.stored_profile = None
task.origin_product = "user_created"
task.mcp_builtin_agent_key = None
task.mcp_credential_owner_id = None
@@ -153,6 +154,7 @@ class TestRefreshSandboxMcp:
task_agent_key="support",
credential_owner_id=99,
allowed_gateway_server_ids=["srv-9"],
+ profile=None,
)
mock_send_refresh.assert_called_once()
_, kwargs = mock_send_refresh.call_args
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 0ae72baab0ee..461315b4eca6 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -1,9 +1,13 @@
+from dataclasses import replace
+
+import pytest
import time_machine
from unittest.mock import MagicMock, call, patch
from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
+from prometheus_client import REGISTRY
from posthog.egress.limiter.policies import Priority
from posthog.models import Integration, Organization, Team
@@ -14,7 +18,8 @@ from posthog.models.user_integration import UserGitHubIntegration, UserIntegrati
from products.mcp_store.backend.facade.contracts import ActiveInstallation, SandboxInstallations
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, RESUME_SNAPSHOT_KIND
-from products.tasks.backend.exceptions import CredentialUnavailableError
+from products.tasks.backend.exceptions import CredentialUnavailableError, ProcessTaskFatalError
+from products.tasks.backend.facade.profiles import TaskProfile, get_task_profile
from products.tasks.backend.models import Task
from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.temporal.process_task.utils import (
@@ -39,9 +44,11 @@ from products.tasks.backend.temporal.process_task.utils import (
get_task_run_credential_user,
get_user_github_integration,
get_user_mcp_server_configs,
+ include_personal_mcp_for_task,
is_bot_authorship_fallback,
is_caller_token_run,
loop_mcp_installation_allowlist,
+ mcp_exclude_tools_for_task,
mcp_exclude_tools_from_state,
mcp_exec_skills_env_vars,
parse_run_state,
@@ -49,6 +56,8 @@ from products.tasks.backend.temporal.process_task.utils import (
upgrade_run_to_user_authorship,
)
+BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")
+
class TestRuntimeModelCapabilities(SimpleTestCase):
def test_glm_5_3_supports_claude_reasoning_efforts(self) -> None:
@@ -419,6 +428,50 @@ class TestMcpExcludeTools(SimpleTestCase):
assert mcp_exclude_tools_from_state({"mcp_exclude_tools": "docs-search"}) == []
assert mcp_exclude_tools_from_state(None) == []
+ @parameterized.expand(
+ [
+ ("no_profile", None, ["docs-search"], ["docs-search"]),
+ ("profile_only", ("user-get",), None, ["user-get"]),
+ ("profile_and_run", ("user-get",), ["docs-search", "user-get"], ["user-get", "docs-search"]),
+ ("profile_hides_nothing", (), ["docs-search"], ["docs-search"]),
+ ]
+ )
+ def test_mcp_exclude_tools_for_task_adds_the_run_to_the_profile(
+ self, _name: str, profile_tools: tuple[str, ...] | None, run_tools: list[str] | None, expected: list[str]
+ ) -> None:
+ task = MagicMock()
+ task.stored_profile = (
+ None if profile_tools is None else replace(BUSINESS_KNOWLEDGE, mcp_exclude_tools=profile_tools)
+ )
+ state = None if run_tools is None else {"mcp_exclude_tools": run_tools}
+ assert mcp_exclude_tools_for_task(task, state) == expected
+
+ @parameterized.expand(
+ [
+ ("profile_and_run_fill_the_cap", 31, 1, False),
+ ("run_overflows_the_cap", 31, 2, True),
+ ("run_alone_overflows_the_cap", 0, 34, True),
+ ]
+ )
+ def test_mcp_exclude_tools_for_task_refuses_a_run_past_the_cap(
+ self, _name: str, profile_count: int, run_count: int, refused: bool
+ ) -> None:
+ profile_tools = tuple(f"profile-{i}" for i in range(profile_count))
+ run_tools = [f"run-{i}" for i in range(run_count)]
+ task = MagicMock()
+ task.stored_profile = replace(BUSINESS_KNOWLEDGE, mcp_exclude_tools=profile_tools)
+ labels = {"profile": BUSINESS_KNOWLEDGE.key}
+ before = REGISTRY.get_sample_value("posthog_tasks_mcp_exclude_tools_over_cap_total", labels) or 0
+
+ if refused:
+ with pytest.raises(ProcessTaskFatalError):
+ mcp_exclude_tools_for_task(task, {"mcp_exclude_tools": run_tools})
+ else:
+ assert mcp_exclude_tools_for_task(task, {"mcp_exclude_tools": run_tools}) == [*profile_tools, *run_tools]
+
+ after = REGISTRY.get_sample_value("posthog_tasks_mcp_exclude_tools_over_cap_total", labels) or 0
+ assert after - before == (1 if refused else 0)
+
class TestMcpServerConfigToDict(SimpleTestCase):
def test_description_is_serialized_for_the_sandbox(self) -> None:
@@ -481,22 +534,41 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
{"name": "x-posthog-mcp-consumer", "value": consumer},
]
- @parameterized.expand([(None, True), ("account_audit", False)])
+ @parameterized.expand(
+ [
+ ("no_profile", None, None, True),
+ ("account_audit", "account_audit", None, False),
+ ("profile_without_store_servers", None, BUSINESS_KNOWLEDGE, False),
+ (
+ "profile_agent",
+ None,
+ replace(BUSINESS_KNOWLEDGE, key="test.support", mcp_store_servers=True, mcp_agent="support"),
+ True,
+ ),
+ ]
+ )
@patch(MOCK_API_URL)
@patch(MOCK_FACADE)
def test_builds_configs_from_facade_results(
- self, origin_product: str | None, mounts_store: bool, mock_facade, mock_api_url
+ self,
+ _name: str,
+ origin_product: str | None,
+ profile: TaskProfile | None,
+ mounts_store: bool,
+ mock_facade,
+ mock_api_url,
) -> None:
mock_api_url.return_value = self.API_BASE
installation = self._make_installation()
mock_facade.return_value = SandboxInstallations(mounted=(installation,))
configs = get_user_mcp_server_configs(
- self.TOKEN, self.TEAM_ID, self.USER_ID, origin_product=origin_product
+ self.TOKEN, self.TEAM_ID, self.USER_ID, origin_product=origin_product, profile=profile
).configs
if not mounts_store:
assert configs == []
+ mock_facade.assert_not_called()
return
mock_facade.assert_called_once_with(
@@ -508,6 +580,8 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
credential_owner_id=None,
allowed_installation_ids=None,
allowed_gateway_server_ids=None,
+ has_profile=profile is not None,
+ profile_agent_key=profile.mcp_agent if profile is not None else None,
)
assert configs == [
McpServerConfig(
@@ -638,6 +712,8 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
credential_owner_id=self.CREDENTIAL_OWNER_ID,
allowed_installation_ids=None,
allowed_gateway_server_ids=["server-1"],
+ has_profile=False,
+ profile_agent_key=None,
)
assert configs == [
McpServerConfig(
@@ -652,6 +728,19 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
]
assert all(header["name"] != "X-PostHog-Task-Id" for header in configs[0].headers)
+ @parameterized.expand(
+ [
+ ("internal", True, None, False),
+ ("user_created", False, None, True),
+ ("profile_without_personal_mcp", False, BUSINESS_KNOWLEDGE, False),
+ ]
+ )
+ def test_include_personal_mcp_for_task(
+ self, _name: str, internal: bool, profile: TaskProfile | None, expected: bool
+ ) -> None:
+ task = MagicMock(internal=internal, stored_profile=profile)
+ assert include_personal_mcp_for_task(task) is expected
+
@parameterized.expand([(True,), (False,)])
@patch(MOCK_API_URL)
@patch(MOCK_FACADE)
@@ -670,6 +759,8 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
credential_owner_id=None,
allowed_installation_ids=None,
allowed_gateway_server_ids=None,
+ has_profile=False,
+ profile_agent_key=None,
)
@patch(MOCK_API_URL)
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index a62b0b4b93fe..f47c58fce7c9 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -5,7 +5,7 @@ import logging
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from enum import StrEnum
-from typing import TYPE_CHECKING, Any, Literal, Optional
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -51,7 +51,7 @@ from products.tasks.backend.exceptions import (
ProcessTaskTransientError,
)
from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
-from products.tasks.backend.facade.profiles import TaskProfile
+from products.tasks.backend.facade.profiles import MAX_MCP_EXCLUDE_TOOLS, TaskProfile
from products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled
from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access
from products.tasks.backend.logic.services.desktop_gateway_token import (
@@ -77,6 +77,7 @@ from products.tasks.backend.logic.services.run_actor import (
loop_owner_eligible_for_credentials,
)
from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
+from products.tasks.backend.metrics import observe_mcp_exclude_tools_over_cap
from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.temporal.process_task.ai_gateway_token import (
AI_GATEWAY_TOKEN_MINTS,
@@ -96,7 +97,7 @@ if TYPE_CHECKING:
from posthog.models.user import User
from products.slack_app.backend.models import SlackThreadTaskMapping
- from products.tasks.backend.models import Task, TaskRun
+ from products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
TaskProcessingContext,
)
@@ -600,6 +601,20 @@ def unmounted_mcp_installations_log_fields(unmounted: Sequence[UnmountedInstalla
]
+def include_personal_mcp_for_task(task: Task) -> bool:
+ """Whether a run may pull the task creator's *personal* MCP installations.
+
+ Internal/autonomous runs (support reply, signals) must never pull a
+ resolved member's personal creds. Agent-specific grant filtering happens
+ in the MCP Store facade.
+ User-initiated Code runs get shared + the creator's personal installs.
+ """
+ profile = task.stored_profile
+ if profile is not None:
+ return profile.personal_mcp
+ return not task.internal
+
+
def get_user_mcp_server_configs(
token: str,
team_id: int,
@@ -613,6 +628,7 @@ def get_user_mcp_server_configs(
task_agent_key: str | None = None,
credential_owner_id: int | None = None,
allowed_gateway_server_ids: list[str] | None = None,
+ profile: TaskProfile | None = None,
) -> UserMcpServerConfigs:
"""Fetch MCP Store installations for sandbox use and return configs.
@@ -646,10 +662,15 @@ def get_user_mcp_server_configs(
``unmounted`` carries the installations the run reached but left out, with the reason.
+ A task whose stored ``profile`` turns off ``mcp_store_servers`` gets no Store installations,
+ and the profile's ``mcp_agent`` replaces the origin mapping.
+
Returns no configs on errors (non-fatal).
"""
if origin_product == "account_audit":
return UserMcpServerConfigs(configs=[])
+ if profile is not None and not profile.mcp_store_servers:
+ return UserMcpServerConfigs(configs=[])
resolution = resolve_installations_for_sandbox(
team_id,
@@ -657,6 +678,8 @@ def get_user_mcp_server_configs(
include_personal=include_personal,
task_origin=origin_product,
task_agent_key=task_agent_key,
+ has_profile=profile is not None,
+ profile_agent_key=cast("MCPBuiltInAgentKey | None", profile.mcp_agent) if profile is not None else None,
credential_owner_id=credential_owner_id,
allowed_installation_ids=allowed_installation_ids,
allowed_gateway_server_ids=allowed_gateway_server_ids,
@@ -829,12 +852,9 @@ POSTHOG_MCP_DESCRIPTION = (
)
_MCP_EXCLUDE_TOOL_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
-_MAX_MCP_EXCLUDE_TOOLS = 32
-def sanitize_mcp_exclude_tools(names: Sequence[str] | None) -> list[str]:
- if not names:
- return []
+def _unique_mcp_exclude_tools(names: Iterable[str]) -> list[str]:
seen: set[str] = set()
cleaned: list[str] = []
for name in names:
@@ -843,16 +863,44 @@ def sanitize_mcp_exclude_tools(names: Sequence[str] | None) -> list[str]:
continue
seen.add(token)
cleaned.append(token)
- if len(cleaned) >= _MAX_MCP_EXCLUDE_TOOLS:
- break
return cleaned
-def mcp_exclude_tools_from_state(state: dict[str, Any] | None) -> list[str]:
+def sanitize_mcp_exclude_tools(names: Sequence[str] | None) -> list[str]:
+ if not names:
+ return []
+ return _unique_mcp_exclude_tools(names)[:MAX_MCP_EXCLUDE_TOOLS]
+
+
+def _mcp_exclude_tool_names_in_state(state: dict[str, Any] | None) -> list[str]:
raw = (state or {}).get("mcp_exclude_tools")
if not isinstance(raw, list):
return []
- return sanitize_mcp_exclude_tools([name for name in raw if isinstance(name, str)])
+ return [name for name in raw if isinstance(name, str)]
+
+
+def mcp_exclude_tools_from_state(state: dict[str, Any] | None) -> list[str]:
+ return sanitize_mcp_exclude_tools(_mcp_exclude_tool_names_in_state(state))
+
+
+def mcp_exclude_tools_for_task(task: Task, state: dict[str, Any] | None) -> list[str]:
+ profile = task.stored_profile
+ if profile is None:
+ return mcp_exclude_tools_from_state(state)
+ excluded = _unique_mcp_exclude_tools([*profile.mcp_exclude_tools, *_mcp_exclude_tool_names_in_state(state)])
+ if len(excluded) > MAX_MCP_EXCLUDE_TOOLS:
+ over_cap = excluded[MAX_MCP_EXCLUDE_TOOLS:]
+ logger.warning(
+ "task_mcp_exclude_tools_over_cap",
+ extra={"task_id": str(task.id), "profile": profile.key, "over_cap_tools": over_cap},
+ )
+ observe_mcp_exclude_tools_over_cap(profile=profile.key)
+ raise ProcessTaskFatalError(
+ "The task hides more MCP tools than the sandbox can hide",
+ {"task_id": str(task.id), "profile": profile.key, "excluded_tool_count": len(excluded)},
+ cause=ValueError(f"{len(excluded)} hidden MCP tools exceed the limit of {MAX_MCP_EXCLUDE_TOOLS}"),
+ )
+ return excluded
def get_sandbox_ph_mcp_configs(
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 34dc51e4e8b4..4b6cc8fb7d47 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -1,3 +1,4 @@
+from dataclasses import replace
from datetime import timedelta
import pytest
@@ -11,6 +12,7 @@ from posthog.models.user import User
from posthog.temporal.oauth import RESEARCH_WITHHELD_SCOPES, PosthogMcpScopes, resolve_scopes
from products.tasks.backend.exceptions import TaskInvalidStateError
+from products.tasks.backend.facade.profiles import OAuthApp, get_task_profile
from products.tasks.backend.models import (
INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN,
TASK_OWNERSHIP_VERSION_STATE_KEY,
@@ -44,6 +46,7 @@ def test_built_in_agent_origins_use_restricted_oauth_scope(
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=origin_product,
)
@@ -79,6 +82,7 @@ def test_posthog_ai_task_keeps_member_token_and_posthog_ai_oauth_application(
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=origin,
)
@@ -96,6 +100,52 @@ def test_posthog_ai_task_keeps_member_token_and_posthog_ai_oauth_application(
)
+ "origin_product,state,profile_fields,application,restricted",
+ [
+ (Task.OriginProduct.POSTHOG_AI, {}, {}, "array", False),
+ (Task.OriginProduct.SIGNAL_REPORT, {"billing_product": "posthog_ai"}, {}, "posthog_ai", False),
+ (
+ Task.OriginProduct.USER_CREATED,
+ {},
+ {"oauth_app": OAuthApp.SIGNALS, "mcp_agent": "support"},
+ "signals",
+ True,
+ ),
+ ],
+)
+@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=True)
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_profiled_task_takes_its_oauth_application_and_agent_scope_from_the_profile(
+ mock_create: MagicMock,
+ mock_enforcement: MagicMock,
+ origin_product: Task.OriginProduct,
+ state: dict[str, str],
+ profile_fields: dict,
+ application: str,
+ restricted: bool,
+) -> None:
+ task = MagicMock(
+ id="task-id",
+ created_by=MagicMock(),
+ team_id=123,
+ origin_product=origin_product,
+ stored_profile=replace(get_task_profile("business_knowledge"), **profile_fields),
+ )
+
+ assert create_oauth_access_token(task, run_state=state) == "token"
+
+ expected = {"include_mcp_builtin_agent_scope": True} if restricted else {}
+ mock_create.assert_called_once_with(
+ task.created_by,
+ 123,
+ scopes="read_only",
+ application=application,
+ sandbox_task_id=task.id,
+ **expected,
+ )
+
+
@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)
@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
def test_built_in_agent_origin_keeps_member_token_until_gateway_flag_rollout(
@@ -105,6 +155,7 @@ def test_built_in_agent_origin_keeps_member_token_until_gateway_flag_rollout(
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=Task.OriginProduct.SUPPORT_REPLY,
)
@@ -134,6 +185,7 @@ def test_array_task_mints_only_slack_runs_with_the_slack_provenance_marker(
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=origin_product,
)
@@ -194,6 +246,7 @@ def test_signals_origins_mint_under_the_signals_app_and_mark_only_user_started_r
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=origin_product,
internal=internal,
@@ -258,6 +311,7 @@ def test_oauth_token_can_disable_task_creator_fallback() -> None:
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=Task.OriginProduct.USER_CREATED,
)
@@ -461,6 +515,7 @@ def test_subscription_run_withholds_the_gateway_scope(mock_create: MagicMock, ad
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=Task.OriginProduct.USER_CREATED,
)
@@ -475,6 +530,7 @@ def test_gateway_billed_run_keeps_the_gateway_scope(mock_create: MagicMock) -> N
task = MagicMock(
id="task-id",
created_by=MagicMock(),
+ stored_profile=None,
team_id=123,
origin_product=Task.OriginProduct.USER_CREATED,
)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index bbe5d2db56ea..dcfc86326a04 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -68,7 +68,13 @@ from products.tasks.backend.facade import (
api as tasks_facade,
contracts as tasks_contracts,
)
-from products.tasks.backend.facade.profiles import NetworkAccess, NetworkPolicy, TaskProfile, get_task_profile
+from products.tasks.backend.facade.profiles import (
+ GithubResolution,
+ NetworkAccess,
+ NetworkPolicy,
+ TaskProfile,
+ get_task_profile,
+)
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
from products.tasks.backend.logic.services.ai_run_defaults import update_team_ai_run_preferences
@@ -17690,6 +17696,70 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(task.repositories, [])
self.assertTrue(tasks_facade.task_exempt_from_code_access(task.id, self.team.id))
+ @parameterized.expand(
+ [
+ ("never_refuses_a_later_attachment", GithubResolution.NEVER, None, False, "attach", False),
+ (
+ "with_repository_drops_both_when_the_repo_goes",
+ GithubResolution.WITH_REPOSITORY,
+ "a/b",
+ True,
+ "unset",
+ False,
+ ),
+ (
+ "with_repository_keeps_both_while_the_repo_stays",
+ GithubResolution.WITH_REPOSITORY,
+ "a/b",
+ True,
+ "title",
+ True,
+ ),
+ (
+ "with_repository_keeps_a_repo_less_attachment_on_a_title_edit",
+ GithubResolution.WITH_REPOSITORY,
+ None,
+ True,
+ "title",
+ True,
+ ),
+ ("always_takes_a_later_attachment", GithubResolution.ALWAYS, None, False, "attach", True),
+ ]
+ )
+ def test_update_follows_the_profile_github_resolution(
+ self,
+ _name,
+ resolution: GithubResolution,
+ repository: str | None,
+ preattached: bool,
+ change: str,
+ attached: bool,
+ ):
+ profile = replace(BUSINESS_KNOWLEDGE, key="test.github", github_resolution=resolution)
+ integration = Integration.objects.create(team=self.team, kind="github", config={})
+ task = self.create_task()
+ task.profile = profile.key
+ if preattached:
+ task.github_integration = integration
+ if repository is not None:
+ task.repository = repository
+ task.repositories = [repository]
+ task.github_user_integration = _grant_user_github_access(self.user)
+ task.save()
+ payload = {
+ "attach": {"github_integration": integration.id},
+ "unset": {"repositories": []},
+ "title": {"title": "Renamed"},
+ }[change]
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/", payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ task.refresh_from_db()
+ self.assertEqual(task.github_integration_id is not None, attached)
+ self.assertEqual(task.github_user_integration_id is not None, attached and repository is not None)
+
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_start_without_code_access_returns_403(self, mock_gate):
self.set_tasks_feature_flag(False)
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 6ad69b175421..c268be7bc253 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -1,6 +1,7 @@
import json
import importlib
import threading
+from dataclasses import replace
from datetime import datetime, timedelta
from typing import Any, ClassVar
from uuid import UUID, uuid4
@@ -30,6 +31,7 @@ from products.tasks.backend.facade import (
)
from products.tasks.backend.facade.access import PostHogAIAccessDecision
from products.tasks.backend.facade.profiles import (
+ Read,
Repository,
SourceKind,
TaskProfileError,
@@ -2054,6 +2056,33 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertEqual(task.channel.channel_type, Channel.ChannelType.PERSONAL)
self.assertEqual(task.channel.created_by_id, self.user.id)
+ @parameterized.expand(
+ [
+ ("with_run_team_readable", True, Read.TEAM, False),
+ ("with_run_creator_readable", True, Read.CREATOR, True),
+ ("without_run_team_readable", False, Read.TEAM, False),
+ ("without_run_creator_readable", False, Read.CREATOR, True),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_profiled_task_files_a_personal_channel_by_its_profile_read(
+ self, _name, with_run: bool, read: Read, expect_personal: bool, _mock_workflow
+ ):
+ profile = replace(
+ get_task_profile("business_knowledge"), key="test.listed", listed=True, read_without_channel=read
+ )
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ if with_run:
+ task_id = facade.create_and_run_task(
+ team=self.team, title="Profiled", description="desc", user_id=self.user.id, profile=profile
+ ).task_id
+ else:
+ task_id = facade.create_task_without_run(team=self.team, user_id=self.user.id, profile=profile)
+
+ channel = Task.objects.select_related("channel").get(id=task_id).channel
+ self.assertEqual(channel is not None and channel.channel_type == Channel.ChannelType.PERSONAL, expect_personal)
+
@parameterized.expand(
[
("public", lambda self: self._make_channel().id, True),
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 91c8d142b278..82594c3a2f41 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -25,6 +25,7 @@ from posthog.storage import object_storage
from products.tasks.backend.facade.profiles import (
GithubAccess,
+ GithubResolution,
PrAuthorship,
Repository,
SourceKind,
@@ -42,6 +43,7 @@ from products.tasks.backend.models import (
MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY,
TASK_OWNERSHIP_VERSION_STATE_KEY,
TASK_RUN_FINISH_REPORT_STATE_KEY,
+ MCPBuiltInAgentKey,
SandboxEnvironment,
SandboxSnapshot,
Task,
@@ -56,8 +58,15 @@ BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")
SOURCE_ID = uuid.UUID("5ab01f4d-5b1e-4990-9802-4f8792a76759")
FLOW_SOURCE = TaskSource(kind=SourceKind.HOG_FLOW, id=str(SOURCE_ID))
REPORT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.report", source_kind=SourceKind.SIGNAL_REPORT)
-POSTHOG_AI_BOT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.posthog_ai_bot", origin_product="posthog_ai")
+POSTHOG_AI_BOT_PROFILE = replace(
+ BUSINESS_KNOWLEDGE,
+ key="test.posthog_ai_bot",
+ origin_product="posthog_ai",
+ github_resolution=GithubResolution.ALWAYS,
+)
PI_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.pi", runtimes=("pi",))
+NO_GITHUB_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.no_github", github_resolution=GithubResolution.NEVER)
+SUPPORT_AGENT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.support_agent", mcp_agent="support")
# Far enough back that any bump is unambiguously forward, and stable so a test can assert the
# clock did *not* move.
@@ -668,24 +677,34 @@ class TestTask(TestCase):
@parameterized.expand(
[
- (Task.OriginProduct.SIGNALS_CHAT, False),
- (Task.OriginProduct.SIGNAL_REPORT, False),
- (Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, False),
- (Task.OriginProduct.AUTORESEARCH, False),
- (Task.OriginProduct.ACCOUNT_AUDIT, False),
- (Task.OriginProduct.WORKFLOW, False),
- (Task.OriginProduct.SUPPORT_REPLY, False),
- (Task.OriginProduct.TASK_ANALYSIS, False),
- (Task.OriginProduct.SPACE_SETUP, False),
- (Task.OriginProduct.USER_CREATED, True),
- (Task.OriginProduct.SLACK, True),
- (Task.OriginProduct.IMAGE_BUILDER, True),
- (Task.OriginProduct.SIGNALS_SCOUT, True),
+ (Task.OriginProduct.SIGNALS_CHAT, None, False),
+ (Task.OriginProduct.SIGNAL_REPORT, None, False),
+ (Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, None, False),
+ (Task.OriginProduct.AUTORESEARCH, None, False),
+ (Task.OriginProduct.ACCOUNT_AUDIT, None, False),
+ (Task.OriginProduct.WORKFLOW, None, False),
+ (Task.OriginProduct.SUPPORT_REPLY, None, False),
+ (Task.OriginProduct.TASK_ANALYSIS, None, False),
+ (Task.OriginProduct.SPACE_SETUP, None, False),
+ (Task.OriginProduct.USER_CREATED, None, True),
+ (Task.OriginProduct.SLACK, None, True),
+ (Task.OriginProduct.IMAGE_BUILDER, None, True),
+ (Task.OriginProduct.SIGNALS_SCOUT, None, True),
+ (None, NO_GITHUB_PROFILE, False),
+ (
+ None,
+ replace(
+ BUSINESS_KNOWLEDGE,
+ key="test.github_with_repository",
+ github_resolution=GithubResolution.WITH_REPOSITORY,
+ ),
+ False,
+ ),
]
)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_attaches_github_to_a_repo_less_task_only_for_opted_in_origins(
- self, origin_product, attaches_github, mock_execute_workflow
+ self, origin_product, profile, attaches_github, mock_execute_workflow
):
user = User.objects.create(email="[email protected]")
integration = Integration.objects.create(team=self.team, kind="github", config={})
@@ -695,7 +714,7 @@ class TestTask(TestCase):
team=self.team,
title="Repo-less task",
description="No repository",
- origin_product=origin_product,
+ **({"profile": profile} if profile else {"origin_product": origin_product}),
user_id=user.id,
)
@@ -741,6 +760,31 @@ class TestTask(TestCase):
state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state
self.assertEqual((task.runtime, state.get("sandbox_template")), expected)
+ @parameterized.expand([("caller_passes_the_key", "support"), ("caller_passes_none", None)])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_and_run_takes_the_agent_key_from_the_profile(
+ self, _name: str, passed_key: MCPBuiltInAgentKey | None, _mock_execute_workflow
+ ):
+ user = User.objects.create(email="[email protected]")
+
+ with (
+ patch.dict(
+ "products.tasks.backend.facade.profiles._profiles",
+ {SUPPORT_AGENT_PROFILE.key: SUPPORT_AGENT_PROFILE},
+ ),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Agent task",
+ description="Runs as the support agent",
+ profile=SUPPORT_AGENT_PROFILE,
+ user_id=user.id,
+ mcp_builtin_agent_key=passed_key,
+ )
+
+ self.assertEqual(task.mcp_builtin_agent_key, "support")
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_keeps_the_previous_template_and_refuses_a_forbidden_one(self, mock_execute_workflow):
user = User.objects.create(email="[email protected]")
diff --git a/products/tasks/backend/tests/test_profile_parity.py b/products/tasks/backend/tests/test_profile_parity.py
index 8aca863596bb..9b78217bd702 100644
--- a/products/tasks/backend/tests/test_profile_parity.py
+++ b/products/tasks/backend/tests/test_profile_parity.py
@@ -26,9 +26,12 @@ from products.tasks.backend.presentation.views.api import (
)
from products.tasks.backend.temporal.oauth import _oauth_application_for_task
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
-from products.tasks.backend.temporal.process_task.activities.start_agent_server import _include_personal_mcp_for_task
from products.tasks.backend.temporal.process_task.ai_gateway_token import resolve_sandbox_ai_product
-from products.tasks.backend.temporal.process_task.utils import USER_AUTHORABLE_ORIGIN_PRODUCTS, get_pr_authorship_mode
+from products.tasks.backend.temporal.process_task.utils import (
+ USER_AUTHORABLE_ORIGIN_PRODUCTS,
+ get_pr_authorship_mode,
+ include_personal_mcp_for_task,
+)
from products.tasks.backend.visibility import (
PRODUCT_PRIVATE_ORIGIN_PRODUCTS,
TEAM_READABLE_ORIGIN_PRODUCTS,
@@ -131,7 +134,7 @@ class TestTaskProfilesMatchMaster(SimpleTestCase):
@parameterized.expand(PROFILES)
def test_personal_mcp_matches_master(self, _key: str, profile: TaskProfile) -> None:
- self.assertEqual(profile.personal_mcp, _include_personal_mcp_for_task(_task(profile)))
+ self.assertEqual(profile.personal_mcp, include_personal_mcp_for_task(_task(profile)))
@parameterized.expand(PROFILES)
def test_inherit_user_defaults_matches_master(self, _key: str, profile: TaskProfile) -> None:
diff --git a/products/tasks/backend/tests/test_profiles.py b/products/tasks/backend/tests/test_profiles.py
index dee9ee8d9b8e..431ddf90386e 100644
--- a/products/tasks/backend/tests/test_profiles.py
+++ b/products/tasks/backend/tests/test_profiles.py
@@ -29,9 +29,10 @@ class TestTaskProfileRegistry(SimpleTestCase):
[
("read_without_channel", {"read_without_channel": Read.TEAM}),
("idle_minutes", {"idle_minutes": 5}),
+ ("too_many_hidden_mcp_tools", {"mcp_exclude_tools": tuple(f"tool-{i}" for i in range(33))}),
]
)
- def test_rejects_a_profile_that_disagrees_with_its_origin(self, _name: str, overrides: dict) -> None:
+ def test_rejects_an_invalid_profile(self, _name: str, overrides: dict) -> None:
conflicting = replace(BUSINESS_KNOWLEDGE, key="test.conflicting", **overrides)
with self.assertRaises(TaskProfileError):
diff --git a/products/tasks/backend/tests/test_visibility.py b/products/tasks/backend/tests/test_visibility.py
index 9e9ba7f5b963..f599b0bae6f4 100644
--- a/products/tasks/backend/tests/test_visibility.py
+++ b/products/tasks/backend/tests/test_visibility.py
@@ -1,11 +1,15 @@
+from dataclasses import replace
+
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.models import Team
+from posthog.models import Team, User
+from products.tasks.backend.facade.profiles import DrivePolicy, Read, get_task_profile
from products.tasks.backend.models import Channel, Task, TaskRun
from products.tasks.backend.visibility import task_control_q, task_run_visibility_q, task_visibility_q
@@ -50,3 +54,98 @@ class TestChildEnvironmentVisibility(BaseTest):
assert channel.team_id == self.team.id
assert list(Task.objects.filter(team_id=env_team.id).filter(visibility_q(self.user.id, env_team.id))) == [task]
+
+
+VISIBLE_PROFILE = replace(get_task_profile("business_knowledge"), key="test.visibility", api_visible=True)
+
+
+class TestVisibilityFollowsOriginProfiles(BaseTest):
+ @parameterized.expand(
+ [
+ ("read_kept_without_profile", Task, task_visibility_q, Task.OriginProduct.EXPERIMENTS, None, True),
+ (
+ "read_dropped_by_creator_profile",
+ Task,
+ task_visibility_q,
+ Task.OriginProduct.EXPERIMENTS,
+ {"read_without_channel": Read.CREATOR},
+ False,
+ ),
+ ("read_absent_without_profile", Task, task_visibility_q, Task.OriginProduct.USER_CREATED, None, False),
+ (
+ "read_added_by_team_profile",
+ Task,
+ task_visibility_q,
+ Task.OriginProduct.USER_CREATED,
+ {"read_without_channel": Read.TEAM},
+ True,
+ ),
+ (
+ "run_read_added_by_team_profile",
+ TaskRun,
+ task_run_visibility_q,
+ Task.OriginProduct.USER_CREATED,
+ {"read_without_channel": Read.TEAM},
+ True,
+ ),
+ (
+ "run_read_dropped_by_creator_profile",
+ TaskRun,
+ task_run_visibility_q,
+ Task.OriginProduct.EXPERIMENTS,
+ {"read_without_channel": Read.CREATOR},
+ False,
+ ),
+ ("drive_kept_without_profile", Task, task_control_q, Task.OriginProduct.SIGNAL_REPORT, None, True),
+ (
+ "drive_dropped_by_owner_profile",
+ Task,
+ task_control_q,
+ Task.OriginProduct.SIGNAL_REPORT,
+ {"drive": DrivePolicy.OWNER},
+ False,
+ ),
+ (
+ "drive_added_by_audience_profile",
+ Task,
+ task_control_q,
+ Task.OriginProduct.USER_CREATED,
+ {"drive": DrivePolicy.AUDIENCE},
+ True,
+ ),
+ (
+ "read_hidden_by_private_profile",
+ Task,
+ task_visibility_q,
+ Task.OriginProduct.SIGNAL_REPORT,
+ {"read_without_channel": Read.TEAM, "api_visible": False},
+ False,
+ ),
+ (
+ "run_hidden_by_private_profile",
+ TaskRun,
+ task_run_visibility_q,
+ Task.OriginProduct.SIGNAL_REPORT,
+ {"read_without_channel": Read.TEAM, "api_visible": False},
+ False,
+ ),
+ ]
+ )
+ def test_unfiled_task_from_another_user_follows_its_origin_profile(
+ self, _name, model, visibility_q, origin_product, overrides, expected
+ ) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ task = Task.objects.create(
+ team=self.team, created_by=other_user, title="t", description="d", origin_product=origin_product
+ )
+ TaskRun.objects.create(team=self.team, task=task)
+ profiles = (
+ {}
+ if overrides is None
+ else {VISIBLE_PROFILE.key: replace(VISIBLE_PROFILE, origin_product=origin_product, **overrides)}
+ )
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", profiles):
+ visible = model.objects.filter(team_id=self.team.id).filter(visibility_q(self.user.id, self.team.id))
+
+ assert visible.exists() is expected
diff --git a/products/tasks/backend/visibility.py b/products/tasks/backend/visibility.py
index 7b10af6e0690..ddd871939cd6 100644
--- a/products/tasks/backend/visibility.py
+++ b/products/tasks/backend/visibility.py
@@ -5,6 +5,7 @@ posthog.api.file_system.registrations, which loads at django.setup()) don't pull
tasks API surface. Its module-scope imports reach jsonschema and the modal SDK.
"""
+from collections.abc import Callable, Sequence
from typing import cast
from django.db.models import BooleanField, OuterRef, Q, Subquery, Value
@@ -12,6 +13,7 @@ from django.db.models.functions import Coalesce
from posthog.models.team import Team
+from products.tasks.backend.facade.profiles import DrivePolicy, Read, TaskProfile, task_profiles
from products.tasks.backend.models import Channel, Task
# These origins predate channels and remain team-scoped while their tasks have no channel.
@@ -40,6 +42,30 @@ PRODUCT_PRIVATE_ORIGIN_PRODUCTS = [
]
+def readable_without_channel(origin_product: str, profile: TaskProfile | None) -> bool:
+ if profile is not None:
+ return profile.read_without_channel == Read.TEAM
+ return origin_product in TEAM_READABLE_ORIGIN_PRODUCTS
+
+
+def _origins_by_profile(master_origins: Sequence[str], matches: Callable[[TaskProfile], bool]) -> list[str]:
+ profiled = {profile.origin_product: matches(profile) for profile in task_profiles()}
+ kept = [origin for origin in master_origins if profiled.get(origin, True)]
+ return kept + [origin for origin, match in profiled.items() if match and origin not in master_origins]
+
+
+def _team_controlled_origins() -> list[str]:
+ return _origins_by_profile(TEAM_VISIBLE_ORIGIN_PRODUCTS, lambda profile: profile.drive == DrivePolicy.AUDIENCE)
+
+
+def _team_readable_origins() -> list[str]:
+ return _origins_by_profile(TEAM_READABLE_ORIGIN_PRODUCTS, lambda profile: profile.read_without_channel == Read.TEAM)
+
+
+def _product_private_origins() -> list[str]:
+ return _origins_by_profile(PRODUCT_PRIVATE_ORIGIN_PRODUCTS, lambda profile: not profile.api_visible)
+
+
def _creator_q(user_id: int | None) -> Q:
return Q(pk__in=[]) if user_id is None else Q(created_by_id=user_id)
@@ -68,12 +94,10 @@ def task_control_q(user_id: int | None, team_id: int | None = None) -> Q:
"""
channeled_q = Q(channel_id__isnull=False) & _visible_channel_q(user_id, team_id) & _creator_q(user_id)
legacy_q = Q(channel_id__isnull=True) & (
- _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_VISIBLE_ORIGIN_PRODUCTS)
+ _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=_team_controlled_origins())
)
return (
- (channeled_q | legacy_q)
- & scout_trial_visibility_q(user_id)
- & ~Q(origin_product__in=PRODUCT_PRIVATE_ORIGIN_PRODUCTS)
+ (channeled_q | legacy_q) & scout_trial_visibility_q(user_id) & ~Q(origin_product__in=_product_private_origins())
)
@@ -85,12 +109,10 @@ def task_visibility_q(user_id: int | None, team_id: int | None = None) -> Q:
"""
channeled_q = Q(channel_id__isnull=False) & _visible_channel_q(user_id, team_id)
legacy_q = Q(channel_id__isnull=True) & (
- _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_READABLE_ORIGIN_PRODUCTS)
+ _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=_team_readable_origins())
)
return (
- (channeled_q | legacy_q)
- & scout_trial_visibility_q(user_id)
- & ~Q(origin_product__in=PRODUCT_PRIVATE_ORIGIN_PRODUCTS)
+ (channeled_q | legacy_q) & scout_trial_visibility_q(user_id) & ~Q(origin_product__in=_product_private_origins())
)
@@ -100,9 +122,9 @@ def task_run_visibility_q(user_id: int | None, team_id: int | None = None) -> Q:
legacy_q = Q(task__channel_id__isnull=True) & (
(Q(task__pk__in=[]) if user_id is None else Q(task__created_by_id=user_id))
| Q(task__created_by__isnull=True)
- | Q(task__origin_product__in=TEAM_READABLE_ORIGIN_PRODUCTS)
+ | Q(task__origin_product__in=_team_readable_origins())
)
trial_visibility = ~Task.scout_experiment_q(relation="task")
if user_id is not None:
trial_visibility |= Q(task__created_by_id=user_id)
- return (channeled_q | legacy_q) & trial_visibility & ~Q(task__origin_product__in=PRODUCT_PRIVATE_ORIGIN_PRODUCTS)
+ return (channeled_q | legacy_q) & trial_visibility & ~Q(task__origin_product__in=_product_private_origins())