: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): add per-user and per-workspace AI preferences (#66025)
Vojta Bartošd2bb15986574
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.pyindex 0937fd964db3..f0c825290ec6 100644--- a/posthog/llm/gateway_client.py+++ b/posthog/llm/gateway_client.py@@ -10,6 +10,7 @@ Product = Literal["llm_gateway","posthog_code","background_agents",+ "slack_app","slack_app_routing","wizard","django",diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex b2fb44c49e07..db114c01ab59 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -410,6 +410,10 @@ 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.slack_settings import resolve_ai_preferences++ ai_prefs = resolve_ai_preferences(integration, slack_user_id)+# 1. Create task + run WITHOUT starting the workflowtry:created = tasks_facade.create_and_run_task(@@ -426,6 +430,9 @@ def create_posthog_code_task_for_repo_activity(start_workflow=False,posthog_mcp_scopes="full",initial_permission_mode="bypassPermissions",+ runtime_adapter=ai_prefs.runtime_adapter,+ model=ai_prefs.model,+ reasoning_effort=ai_prefs.reasoning_effort,)except Exception as e:logger.exception(diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 6cb630802fc5..fc90ee577226 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -63,12 +63,20 @@ from products.slack_app.backend.services.integration_resolver import (user_resolution_failure_reply,)from products.slack_app.backend.services.slack_app_home import (+ ACTION_EDIT_PERSONAL,+ ACTION_EDIT_WORKSPACE,+ ACTION_RESET_PERSONAL,ACTION_RESET_PROJECT_PERSONAL,ACTION_SET_PROJECT_PERSONAL,ACTION_SET_PROJECT_WORKSPACE,ACTION_UNLINK_ACCOUNT,+ EDIT_MODAL_PERSONAL_CALLBACK_ID,+ EDIT_MODAL_WORKSPACE_CALLBACK_ID,+ MODAL_ACTION_MODEL,+ MODAL_ACTION_RUNTIME_ADAPTER,+ handle_ai_preferences_block_action as _handle_ai_preferences_block_action,handle_app_home_opened as _handle_app_home_opened,- handle_home_block_action as _handle_home_block_action,+ handle_app_home_view_submission as _handle_app_home_view_submission,)from products.slack_app.backend.services.slack_user_info import (get_cached_bot_user_id,@@ -2564,27 +2572,36 @@ def _extract_context_token(payload: dict) -> str:return payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("context_token", "")-_HOME_TAB_ACTION_IDS = frozenset(+_AI_PREFERENCES_ACTION_IDS = frozenset({+ ACTION_EDIT_PERSONAL,+ ACTION_EDIT_WORKSPACE,+ ACTION_RESET_PERSONAL,ACTION_RESET_PROJECT_PERSONAL,ACTION_SET_PROJECT_PERSONAL,ACTION_SET_PROJECT_WORKSPACE,ACTION_UNLINK_ACCOUNT,+ MODAL_ACTION_RUNTIME_ADAPTER,+ MODAL_ACTION_MODEL,})+_AI_PREFERENCES_CALLBACK_IDS = frozenset({EDIT_MODAL_PERSONAL_CALLBACK_ID, EDIT_MODAL_WORKSPACE_CALLBACK_ID})-def _is_home_tab_interactivity(payload: dict, payload_type: str) -> bool:- """Return True if this payload is a Home tab block_actions interaction.+def _is_ai_preferences_interactivity(payload: dict, payload_type: str) -> bool:+ """Return True if this payload is a Slack App Home AI-settings interaction.- Home-tab buttons carry no per-row hint — they're workspace-scoped, not- tied to a specific task or repo. The cross-region router uses this to- claim locality based on the workspace integration alone rather than- dropping the click.+ AI-settings buttons (Edit/Reset on the Home tab, runtime/model dispatch+ re-renders inside the modal) and modal submissions carry no per-row hint —+ the picker is workspace-scoped, not tied to a specific task or repo. The+ cross-region router uses this to claim locality based on the workspace+ integration alone rather than dropping the click."""+ if payload_type == "view_submission":+ return payload.get("view", {}).get("callback_id", "") in _AI_PREFERENCES_CALLBACK_IDSif payload_type == "block_actions":for action in payload.get("actions", []) or ():- if action.get("action_id", "") in _HOME_TAB_ACTION_IDS:+ if action.get("action_id", "") in _AI_PREFERENCES_ACTION_IDS:return Truereturn False@@ -3283,11 +3300,12 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:kind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,).exists()- elif slack_team_id and _is_home_tab_interactivity(payload, payload_type):- # App Home routing/account actions carry no per-row hint — the button- # is tied to the workspace, not a specific picker context. Claim- # locality based on the workspace integration alone; if we own *any*- # Integration for this Slack team, the click is ours to handle.+ elif slack_team_id and _is_ai_preferences_interactivity(payload, payload_type):+ # App Home AI-settings actions (Edit/Reset/Save) and the modal+ # re-render dispatched_actions carry no per-row hint — the button is+ # tied to the workspace, not a specific picker context. Claim locality+ # based on the workspace integration alone; if we own *any* Integration+ # for this Slack team, the click is ours to handle.local = Integration.objects.filter(kind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,@@ -3364,6 +3382,9 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:if payload_type == "block_suggestion":return _handle_repo_picker_options(payload)+ if payload_type == "view_submission":+ return _handle_app_home_view_submission(payload)+if payload_type == "block_actions":actions = payload.get("actions", [])for action in actions:@@ -3388,7 +3409,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return inbox_interactivity.handle_inbox_sources(payload)if action_id == onboarding.INBOX_AI_APPROVAL_ACTION_ID:return inbox_interactivity.handle_inbox_ai_approval(payload)- if action_id in _HOME_TAB_ACTION_IDS:- return _handle_home_block_action(payload, action)+ if action_id in _AI_PREFERENCES_ACTION_IDS:+ return _handle_ai_preferences_block_action(payload, action)return HttpResponse(status=200)diff --git a/products/slack_app/backend/facade/slack_settings.py b/products/slack_app/backend/facade/slack_settings.pynew file mode 100644index 000000000000..180f130b4e39--- /dev/null+++ b/products/slack_app/backend/facade/slack_settings.py@@ -0,0 +1,20 @@+"""Facade re-exports for the Slack-app per-(workspace, user) settings subsystem.++Cross-product callers (e.g. Temporal activities under `posthog/temporal/`)+import from here rather than reaching into `services/`. Mirrors the layering+in `products/tasks/backend/facade/`.+"""++from products.slack_app.backend.feature_flags import SLACK_APP_HOME_FLAG+from products.slack_app.backend.services.slack_settings import (+ AIPreferences,+ resolve_ai_preferences,+ validate_ai_preferences,+)++__all__ = [+ "SLACK_APP_HOME_FLAG",+ "AIPreferences",+ "resolve_ai_preferences",+ "validate_ai_preferences",+]diff --git a/products/slack_app/backend/migrations/0009_slacksettings_ai_settings.py b/products/slack_app/backend/migrations/0009_slacksettings_ai_settings.pynew file mode 100644index 000000000000..bfc5ede2b820--- /dev/null+++ b/products/slack_app/backend/migrations/0009_slacksettings_ai_settings.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0008_slackthreadtaskmapping_last_forwarded_ts"),+ ]++ operations = [+ migrations.AddField(+ model_name="slacksettings",+ name="ai_preferences",+ field=models.JSONField(blank=True, null=True),+ ),+ ]diff --git a/products/slack_app/backend/migrations/0010_slacksettings_default_integration_nullable.py b/products/slack_app/backend/migrations/0010_slacksettings_default_integration_nullable.pynew file mode 100644index 000000000000..0724eccc239f--- /dev/null+++ b/products/slack_app/backend/migrations/0010_slacksettings_default_integration_nullable.py@@ -0,0 +1,23 @@+import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "0001_initial"),+ ("slack_app", "0009_slacksettings_ai_settings"),+ ]++ operations = [+ migrations.AlterField(+ model_name="slacksettings",+ name="default_integration",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="slack_settings_as_default",+ to="posthog.integration",+ ),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex f4dffaf92d5d..db318ea2fb40 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_slackthreadtaskmapping_last_forwarded_ts+0010_slacksettings_default_integration_nullablediff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 4092e1d6be74..90eda2c314b7 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -92,13 +92,19 @@ class SlackSettings(UUIDModel):resolution time."""+ # Nullable so a personal row can carry AI preferences while inheriting the+ # workspace routing default.default_integration = models.ForeignKey("posthog.Integration",on_delete=models.CASCADE,related_name="slack_settings_as_default",+ null=True,+ blank=True,)slack_workspace_id = models.CharField(max_length=64)slack_user_id = models.CharField(max_length=64, null=True, blank=True)+ # Keys mirror the task-run request serializer.+ ai_preferences = models.JSONField(blank=True, null=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)@@ -123,6 +129,18 @@ class SlackSettings(UUIDModel):target = self.default_integration_id if self.default_integration_id else "(inherit)"return f"{self.slack_workspace_id} / {who} → integration {target}"+ @property+ def runtime_adapter(self) -> str | None:+ return (self.ai_preferences or {}).get("runtime_adapter")++ @property+ def model(self) -> str | None:+ return (self.ai_preferences or {}).get("model")++ @property+ def reasoning_effort(self) -> str | None:+ return (self.ai_preferences or {}).get("reasoning_effort")+class SlackChannel(UUIDModel):"""Per-(Slack workspace, Slack channel) state.diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex a13732af6e8d..6752c7cadcca 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -130,6 +130,7 @@ def resolve_from_candidates(defaults = list(SlackSettings.objects.filter(slack_workspace_id=slack_team_id).filter(Q(slack_user_id=slack_user_id) | Q(slack_user_id__isnull=True))+ .exclude(default_integration__isnull=True).select_related("default_integration","default_integration__team",@@ -138,16 +139,19 @@ def resolve_from_candidates()defaults.sort(key=lambda d: d.slack_user_id is None)for default in defaults:- if accessible_team_ids is not None and default.default_integration.team_id not in accessible_team_ids:+ target = default.default_integration+ if target is None:+ continue+ if accessible_team_ids is not None and target.team_id not in accessible_team_ids:continue# Refuse a stale default whose target is no longer in the candidate# set — e.g. the integration's kind was changed away from the one# we were asked to resolve, or it was deleted+recreated. The user# can overwrite the row at any time with `@PostHog project <id>`.- if default.default_integration.id not in candidate_ids:+ if target.id not in candidate_ids:continuesource: ResolutionSource = "user_default" if default.slack_user_id else "workspace_default"- return ResolutionResult(integration=default.default_integration, source=source, candidates=accessible)+ return ResolutionResult(integration=target, source=source, candidates=accessible)if len(accessible) == 1:return ResolutionResult(integration=accessible[0], source="sole_candidate", candidates=accessible)diff --git a/products/slack_app/backend/services/llm_models.py b/products/slack_app/backend/services/llm_models.pynew file mode 100644index 000000000000..7e2a78ff0113--- /dev/null+++ b/products/slack_app/backend/services/llm_models.py@@ -0,0 +1,62 @@+"""Slack-app view of the models the LLM gateway exposes for `slack_app`.++The gateway is the source of truth — hardcoding the list here would mean a+Slack-side PR every time it changes. Cached via Django's shared cache so the+Home tab publish never blocks on a gateway round-trip; the fetch timeout is+capped at 3s because it sits on the Slack interactivity hot path (trigger_id+expires after ~3s), and failures are negatively cached for 30s so a broken+gateway can't make every interaction wait the full timeout.+"""++from __future__ import annotations++from dataclasses import dataclass++from django.core.cache import cache++import structlog++from posthog.llm.gateway_client import get_llm_client++logger = structlog.get_logger(__name__)++_CACHE_KEY = "slack_app:llm_gateway_models"+_CACHE_TTL_SECONDS = 30 * 60+_NEGATIVE_CACHE_TTL_SECONDS = 30+_FETCH_TIMEOUT_SECONDS = 3.0+++@dataclass(frozen=True)+class GatewayModel:+ id: str+ owned_by: str+ context_window: int+++def list_slack_app_models() -> tuple[GatewayModel, ...]:+ """Return the model list the `slack_app` gateway product exposes.++ Returns an empty tuple on any error. The empty result is briefly cached+ so subsequent interactions during an outage fail fast.+ """+ cached = cache.get(_CACHE_KEY)+ if cached is not None:+ return cached++ try:+ page = get_llm_client(product="slack_app").with_options(timeout=_FETCH_TIMEOUT_SECONDS).models.list()+ except Exception:+ logger.exception("slack_app_llm_gateway_models_fetch_failed")+ cache.set(_CACHE_KEY, (), timeout=_NEGATIVE_CACHE_TTL_SECONDS)+ return ()++ models = tuple(+ GatewayModel(+ id=m.id,+ owned_by=getattr(m, "owned_by", ""),+ context_window=getattr(m, "context_window", 0),+ )+ for m in page.data+ )+ cache.set(_CACHE_KEY, models, timeout=_CACHE_TTL_SECONDS)+ return modelsdiff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex b86d0b6af7ba..1c3f3f5f89cc 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -1,22 +1,25 @@-"""App Home tab renderer + interactivity handlers for the PostHog Slack app.--The Home tab is the user-facing control panel for the integration. This-first iteration carries two cards — project routing (which PostHog project-@PostHog mentions land in) and account linking (Sign-in-with-Slack). The-layout leaves room for additional cards as they come online.--All Block Kit payloads are built as plain dicts here so they can be-unit-tested without any Slack client. The event/interactivity handlers in-`products/slack_app/backend/api.py` are the ones that actually call-`views.publish` / `views.open`.+"""App Home tab + edit modal renderers for the PostHog Slack app.++The Home tab is the user-facing control panel for the integration. For this+first iteration it carries one card — the AI preferences picker that feeds+Slack-triggered task runs — but the layout leaves room for additional cards+(notifications, account linking, activity feed) as they come online. Each card+follows the same pattern: a one-line "effective" summary, an admin-aware edit+control, and an optional explainer of where the effective value came from.++All Block Kit payloads (views, modals) are built as plain dicts here so they+can be unit-tested without any Slack client. The event/interactivity handlers+in `products/slack_app/backend/api.py` are the ones that actually call+`views.publish` / `views.open` / `views.update`."""from __future__ import annotationsfrom dataclasses import dataclass-from typing import Any+from typing import Any, Literal-from django.http import HttpResponse+from django.core.exceptions import ValidationError+from django.http import HttpResponse, JsonResponseimport structlog@@ -27,18 +30,201 @@ from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.feature_flags import is_slack_app_home_enabled, slack_oauth_link_enabledfrom products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.slack_app.backend.services.slack_settings import (+ AIPreferences,+ build_ai_preferences_payload,+ resolve_ai_preferences,+ validate_ai_preferences,+)from products.slack_app.backend.services.slack_user_info import is_slack_workspace_adminfrom products.slack_app.backend.services.slack_user_oauth import build_invite_url, find_linked_posthog_userlogger = structlog.get_logger(__name__)+# Block / action / callback identifiers. Centralised so the interactivity+# handler in api.py and the renderers here cannot drift apart.HOME_CALLBACK_ID = "slack_app_home"+ACTION_EDIT_PERSONAL = "slack_app_home:edit_personal"+ACTION_EDIT_WORKSPACE = "slack_app_home:edit_workspace"+ACTION_RESET_PERSONAL = "slack_app_home:reset_personal"ACTION_UNLINK_ACCOUNT = "slack_app_home:unlink_account"ACTION_SET_PROJECT_PERSONAL = "slack_app_home:set_project_personal"ACTION_SET_PROJECT_WORKSPACE = "slack_app_home:set_project_workspace"ACTION_RESET_PROJECT_PERSONAL = "slack_app_home:reset_project_personal"+EDIT_MODAL_PERSONAL_CALLBACK_ID = "slack_app_ai_prefs:personal"+EDIT_MODAL_WORKSPACE_CALLBACK_ID = "slack_app_ai_prefs:workspace"++MODAL_ACTION_RUNTIME_ADAPTER = "ai_prefs:runtime_adapter"+MODAL_ACTION_MODEL = "ai_prefs:model"+MODAL_ACTION_REASONING_EFFORT = "ai_prefs:reasoning_effort"++MODAL_BLOCK_RUNTIME_ADAPTER = "block_runtime_adapter"+MODAL_BLOCK_MODEL = "block_model"+MODAL_BLOCK_REASONING_EFFORT = "block_reasoning_effort"++EditScope = Literal["personal", "workspace"]++# Runtime + effort labels are UI strings with no tasks-product equivalent.+# Model display labels are computed from the model id on the fly via+# `_format_model_id` so we never have to hand-maintain a model→label map.+RUNTIME_ADAPTER_DISPLAY_NAMES: dict[str, str] = {+ "claude": "Claude (Anthropic)",+ "codex": "Codex (OpenAI)",+}++REASONING_EFFORT_DISPLAY_NAMES: dict[str, str] = {+ "low": "Low",+ "medium": "Medium",+ "high": "High",+ "xhigh": "Extra high",+ "max": "Max",+}++# Gateway `owned_by` → tasks RuntimeAdapter value. Other providers+# (bedrock, vertex…) get dropped from the picker.+_PROVIDER_TO_RUNTIME_ADAPTER: dict[str, str] = {+ "anthropic": "claude",+ "openai": "codex",+}++_PROVIDER_PREFIXES = ("anthropic/", "openai/")+++def _format_model_id(model_id: str, *, owned_by: str) -> str:+ """OpenAI ids stay lowercase; Claude ids become `Claude Opus 4.8` etc."""+ clean = model_id+ for prefix in _PROVIDER_PREFIXES:+ if clean.startswith(prefix):+ clean = clean[len(prefix) :]+ break+ if owned_by == "openai":+ return clean.lower()+ import re as _re++ # Collapse `4-8` into `4.8` so version components survive the dash split.+ clean = _re.sub(r"(\d)-(\d)", r"\1.\2", clean)+ return " ".join(+ word if _re.fullmatch(r"[0-9.]+", word) else word[:1].upper() + word[1:].lower()+ for word in _re.split(r"[-_]", clean)+ )+++@dataclass(frozen=True)+class PickerEffort:+ value: str+ label: str+++@dataclass(frozen=True)+class PickerModel:+ value: str+ label: str+ supported_efforts: tuple[PickerEffort, ...]+++@dataclass(frozen=True)+class PickerAdapter:+ value: str+ label: str+ models: tuple[PickerModel, ...]+++def get_picker_choices() -> tuple[PickerAdapter, ...]:+ """Build the picker tree from the live LLM-gateway model list.++ Models come from `slack_app` product on the gateway (cached). Per-model+ effort support and adapter grouping come from the tasks facade. Display+ labels are local UI strings.++ Adapters with no available models are omitted entirely.+ """+ from products.slack_app.backend.services.llm_models import list_slack_app_models+ from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts++ gateway_models = list_slack_app_models()++ by_adapter: dict[str, list[PickerModel]] = {}+ for gm in gateway_models:+ adapter_value = _PROVIDER_TO_RUNTIME_ADAPTER.get(gm.owned_by)+ if adapter_value is None:+ continue+ efforts = tuple(+ PickerEffort(value=e.value, label=REASONING_EFFORT_DISPLAY_NAMES.get(e.value) or e.value)+ for e in get_supported_reasoning_efforts(adapter_value, gm.id)+ )+ by_adapter.setdefault(adapter_value, []).append(+ PickerModel(value=gm.id, label=_format_model_id(gm.id, owned_by=gm.owned_by), supported_efforts=efforts)+ )++ return tuple(+ PickerAdapter(+ value=adapter_value,+ label=RUNTIME_ADAPTER_DISPLAY_NAMES.get(adapter_value) or adapter_value,+ models=tuple(models),+ )+ for adapter_value, models in by_adapter.items()+ )+++def _label(value: str | None, mapping: dict[str, str]) -> str:+ if not value:+ return "—"+ return mapping.get(value, value)+++def _models_for(runtime_adapter: str) -> tuple[tuple[str, str], ...]:+ """Return `(value, label)` pairs for the modal's model dropdown."""+ for adapter in get_picker_choices():+ if adapter.value == runtime_adapter:+ return tuple((m.value, m.label) for m in adapter.models)+ return ()+++def _runtime_adapter_options() -> tuple[tuple[str, str], ...]:+ """Return `(value, label)` pairs for the modal's runtime dropdown."""+ return tuple((a.value, a.label) for a in get_picker_choices())+++@dataclass(frozen=True)+class PreferenceSource:+ """Which row contributed the effective `(runtime_adapter, model)` pair.++ Used to render the "Source: …" line on the active-model card so the+ precedence (personal → workspace → unset) is visible at a glance.+ """++ label: str++ @classmethod+ def personal(cls) -> PreferenceSource:+ return cls(label="Your personal override")++ @classmethod+ def workspace(cls) -> PreferenceSource:+ return cls(label="Workspace default")++ @classmethod+ def unset(cls) -> PreferenceSource:+ return cls(label="System default")+++def resolve_source(+ user_row: SlackSettings | None,+ workspace_row: SlackSettings | None,+) -> PreferenceSource:+ """Return where the effective pair came from.++ Mirrors the same atomic-pair rule the resolver uses: a row only "sources"+ the pair when both halves are set on it.+ """+ if user_row and user_row.runtime_adapter and user_row.model:+ return PreferenceSource.personal()+ if workspace_row and workspace_row.runtime_adapter and workspace_row.model:+ return PreferenceSource.workspace()+ return PreferenceSource.unset()+@dataclass(frozen=True)class ProjectChoice:@@ -69,7 +255,12 @@ class ProjectState:@dataclass(frozen=True)class AccountState:- """Inputs the renderer needs to draw the optional account-link card."""+ """Inputs the renderer needs to draw the optional account-link card.++ Carries no business logic — the handler computes whether the flag is on+ and whether the Slack user is currently linked, and hands the result+ here so the renderer stays a pure function.+ """enabled: bool = Falselinked_email: str | None = None@@ -78,19 +269,36 @@ class AccountState:def render_home_view(*,+ effective: AIPreferences,+ user_row: SlackSettings | None,+ workspace_row: SlackSettings | None,is_admin: bool,account_state: AccountState | None = None,project_state: ProjectState | None = None,) -> dict:"""Render the Block Kit payload for `views.publish` on the App Home tab."""+ source = resolve_source(user_row, workspace_row)blocks: list[dict] = []+blocks.extend(_header_blocks())+ # Section 1 — project routing. Personal pick on top; admins get an+ # editable workspace default below, others see it as read-only context.if project_state and project_state.has_anything_to_show:blocks.append({"type": "divider"})blocks.extend(_project_section_blocks(project_state, is_admin=is_admin))+ # Section 2 — AI model settings: which model handles those mentions.+ # Headline shows the effective triple (and its source); personal /+ # workspace controls underneath mirror the project routing layout.+ blocks.append({"type": "divider"})+ blocks.extend(_active_model_blocks(effective, source))+ blocks.extend(_personal_section_blocks(user_row))+ blocks.extend(_workspace_section_blocks(workspace_row, is_admin=is_admin))++ # Section 3 — account linking: tucked at the end because it's a setup+ # step you do once, not a knob you tune. Flag-gated.if account_state and account_state.enabled:blocks.append({"type": "divider"})blocks.extend(_account_section_blocks(account_state))@@ -122,6 +330,51 @@ def _header_blocks() -> list[dict]:]+def _active_model_blocks(effective: AIPreferences, source: PreferenceSource) -> list[dict]:+ """Headline that shows which model is actually running, and why.++ When nothing is set the agent-server picks its own default — we don't+ know which one, so don't lie. Just say so and let the user override.+ """+ header = _section_title(+ "AI model",+ "Which Claude / Codex configuration handles your @PostHog mentions.",+ )+ source_blurb = {"type": "context", "elements": [{"type": "mrkdwn", "text": f"Source: {source.label}"}]}++ if effective.is_empty:+ return [+ header,+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "Inheriting PostHog Code's default — pick personal or workspace settings to override.",+ },+ },+ source_blurb,+ ]++ runtime_label = _label(effective.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)+ model_label = _format_model_id(effective.model, owned_by="") if effective.model else "—"+ effort_part = (+ f" · Reasoning: *{_label(effective.reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}*"+ if effective.reasoning_effort+ else ""+ )+ return [+ header,+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": f"Currently running *{model_label}* · {runtime_label}{effort_part}",+ },+ },+ source_blurb,+ ]++def _project_section_blocks(state: ProjectState, *, is_admin: bool) -> list[dict]:"""Render the project-routing card.@@ -251,28 +504,270 @@ def _account_section_blocks(account_state: AccountState) -> list[dict]:return blocks-def _footer_blocks() -> list[dict]:+def _personal_section_blocks(user_row: SlackSettings | None) -> list[dict]:+ """Personal AI override sub-card. Always editable by the user themselves."""++ has_override = bool(user_row and user_row.runtime_adapter and user_row.model)+ summary = _row_summary(user_row) if has_override else "_No personal override — inheriting the workspace default._"++ actions: list[dict] = [+ {+ "type": "button",+ "action_id": ACTION_EDIT_PERSONAL,+ "text": {"type": "plain_text", "text": "Edit my settings", "emoji": True},+ }+ ]+ if has_override:+ actions.append(+ {+ "type": "button",+ "action_id": ACTION_RESET_PERSONAL,+ "style": "danger",+ "text": {"type": "plain_text", "text": "Reset to workspace default", "emoji": True},+ "confirm": {+ "title": {"type": "plain_text", "text": "Clear your override?"},+ "text": {+ "type": "mrkdwn",+ "text": "You'll inherit the workspace default until you set new personal preferences.",+ },+ "confirm": {"type": "plain_text", "text": "Reset"},+ "deny": {"type": "plain_text", "text": "Cancel"},+ },+ }+ )+return [+ _subsection_label("Your override"),+ {"type": "section", "text": {"type": "mrkdwn", "text": summary}},+ {"type": "actions", "elements": actions},+ ]+++def _workspace_section_blocks(+ workspace_row: SlackSettings | None,+ *,+ is_admin: bool,+) -> list[dict]:+ """Workspace AI default sub-card — admin-only; non-admins don't see it."""++ if not is_admin:+ return []++ has_default = bool(workspace_row and workspace_row.runtime_adapter and workspace_row.model)+ summary = (+ _row_summary(workspace_row)+ if has_default+ else "_No workspace default set — falls back to PostHog's system default._"+ )+ blocks: list[dict] = [+ _subsection_label("Workspace default"),+ {"type": "section", "text": {"type": "mrkdwn", "text": summary}},{- "type": "context",+ "type": "actions","elements": [- {"type": "mrkdwn", "text": "Mention @PostHog in any channel to get started."},+ {+ "type": "button",+ "action_id": ACTION_EDIT_WORKSPACE,+ "text": {"type": "plain_text", "text": "Edit workspace default", "emoji": True},+ }],+ },+ ]+ return blocks+++def _footer_blocks() -> list[dict]:+ return []+++def _row_summary(row: SlackSettings | None) -> str:+ if not row or not row.runtime_adapter or not row.model:+ return "_(none)_"+ owned_by = "openai" if row.runtime_adapter == "codex" else "anthropic"+ parts = [+ f"*Model:* {_format_model_id(row.model, owned_by=owned_by)}",+ f"*Runtime:* {_label(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",+ ]+ if row.reasoning_effort:+ parts.append(f"*Reasoning:* {_label(row.reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}")+ return " · ".join(parts)+++# ---------------------------------------------------------------------------+# Edit modal+# ---------------------------------------------------------------------------+++def render_edit_modal(+ *,+ scope: EditScope,+ current: AIPreferences,+ supported_efforts: list[str] | None = None,+) -> dict:+ """Build the Block Kit modal payload for personal or workspace editing.++ `supported_efforts` lets the caller pre-compute which efforts are valid for+ the currently selected model (using+ `products.tasks.backend.temporal.process_task.utils.get_supported_reasoning_efforts`).+ When `None`, the effort block is omitted entirely; the modal re-renders via+ `block_actions` on runtime_adapter / model change to fill it in.+ """++ callback_id = EDIT_MODAL_PERSONAL_CALLBACK_ID if scope == "personal" else EDIT_MODAL_WORKSPACE_CALLBACK_ID+ # Slack caps modal titles at 24 characters; longer ones get rejected with+ # `invalid_arguments` on `views.open`.+ title = "Personal AI preferences" if scope == "personal" else "Workspace AI preferences"++ runtime_pairs = _runtime_adapter_options()+ runtime_options = [+ {+ "text": {"type": "plain_text", "text": label, "emoji": True},+ "value": value,+ }+ for value, label in runtime_pairs+ ]+ runtime_element: dict[str, Any] = {+ "type": "static_select",+ "action_id": MODAL_ACTION_RUNTIME_ADAPTER,+ "placeholder": {"type": "plain_text", "text": "Pick a runtime"},+ "options": runtime_options,+ }+ if current.runtime_adapter and any(v == current.runtime_adapter for v, _ in runtime_pairs):+ runtime_element["initial_option"] = next(o for o in runtime_options if o["value"] == current.runtime_adapter)+ runtime_block: dict[str, Any] = {+ "type": "input",+ "block_id": MODAL_BLOCK_RUNTIME_ADAPTER,+ "label": {"type": "plain_text", "text": "Runtime"},+ "dispatch_action": True,+ "element": runtime_element,+ }++ model_block: dict[str, Any] | None = None+ if current.runtime_adapter:+ model_options = [+ {+ "text": {"type": "plain_text", "text": label, "emoji": True},+ "value": value,+ }+ for value, label in _models_for(current.runtime_adapter)+ ]+ if model_options:+ model_element: dict[str, Any] = {+ "type": "static_select",+ "action_id": MODAL_ACTION_MODEL,+ "placeholder": {"type": "plain_text", "text": "Pick a model"},+ "options": model_options,+ }+ if current.model and any(o["value"] == current.model for o in model_options):+ model_element["initial_option"] = next(o for o in model_options if o["value"] == current.model)+ model_block = {+ "type": "input",+ "block_id": MODAL_BLOCK_MODEL,+ "label": {"type": "plain_text", "text": "Model"},+ "dispatch_action": True,+ "element": model_element,+ }++ effort_block: dict[str, Any] | None = None+ if supported_efforts:+ effort_options = [+ {+ "text": {"type": "plain_text", "text": _label(v, REASONING_EFFORT_DISPLAY_NAMES), "emoji": True},+ "value": v,+ }+ for v in supported_efforts+ ]+ effort_element: dict[str, Any] = {+ "type": "static_select",+ "action_id": MODAL_ACTION_REASONING_EFFORT,+ "placeholder": {"type": "plain_text", "text": "Pick an effort (optional)"},+ "options": effort_options,+ }+ if current.reasoning_effort and current.reasoning_effort in supported_efforts:+ effort_element["initial_option"] = next(o for o in effort_options if o["value"] == current.reasoning_effort)+ effort_block = {+ "type": "input",+ "block_id": MODAL_BLOCK_REASONING_EFFORT,+ "label": {"type": "plain_text", "text": "Reasoning effort"},+ "optional": True,+ "element": effort_element,}++ blocks = [+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": (+ "Pick the runtime and model that should handle PostHog Slack requests for you."+ if scope == "personal"+ else "Set the default runtime and model for everyone in this Slack workspace."+ ),+ }+ ],+ },+ runtime_block,]+ if model_block:+ blocks.append(model_block)+ if effort_block:+ blocks.append(effort_block)++ return {+ "type": "modal",+ "callback_id": callback_id,+ "title": {"type": "plain_text", "text": title, "emoji": True},+ "submit": {"type": "plain_text", "text": "Save"},+ "close": {"type": "plain_text", "text": "Cancel"},+ "blocks": blocks,+ }+++def parse_modal_submission(view: dict) -> tuple[str | None, str | None, str | None]:+ """Pull `(runtime_adapter, model, reasoning_effort)` out of a Slack view_submission payload.++ Returns `(None, None, None)` for any block the user didn't fill in. The+ caller validates the triple via `validate_ai_preferences`.+ """++ state = view.get("state", {}).get("values", {})++ runtime_adapter = _selected_value(state, MODAL_BLOCK_RUNTIME_ADAPTER, MODAL_ACTION_RUNTIME_ADAPTER)+ model = _selected_value(state, MODAL_BLOCK_MODEL, MODAL_ACTION_MODEL)+ reasoning_effort = _selected_value(state, MODAL_BLOCK_REASONING_EFFORT, MODAL_ACTION_REASONING_EFFORT)+ return runtime_adapter, model, reasoning_effort+++def _selected_value(state: dict, block_id: str, action_id: str) -> str | None:+ block = state.get(block_id, {})+ action = block.get(action_id, {})+ selected = action.get("selected_option")+ if isinstance(selected, dict):+ return selected.get("value")+ return None# ---------------------------------------------------------------------------# Event + interactivity handlers# ---------------------------------------------------------------------------+#+# Public entry points are re-exported from `api.py` under matching `_handle_*`+# names so the dispatchers there can call them with minimal extra wiring.+#+# Concurrency model: each Slack interactivity request is short-lived (<3s SLA),+# so all writes use plain Django ORM calls inside the request thread. The+# resolver is read at task-creation time inside the Temporal workflow, not+# here.def handle_app_home_opened(event: dict, slack_team_id: str) -> None:"""Publish the Home tab for the user who just opened it.- Gated by the slack-app-home flag — when off the publish is skipped so- installs without the manifest changes (and workspaces that haven't- opted in) keep getting Slack's default blank Home tab.+ Gated by the slack-app-home flag — when off, the publish is skipped so+ installs without the manifest changes (and workspaces that haven't opted+ in) keep getting Slack's default blank Home tab instead of seeing an+ interactive UI for a feature that doesn't fire downstream."""slack_user_id = event.get("user")@@ -286,12 +781,18 @@ def handle_app_home_opened(event: dict, slack_team_id: str) -> None:if not is_slack_app_home_enabled(integration):return+ effective = resolve_ai_preferences(integration, slack_user_id)+ user_row, workspace_row = _load_rows(integration, slack_user_id)+slack = SlackIntegration(integration)is_admin = _is_admin(slack, integration, slack_user_id)account_state = _resolve_account_state(integration, slack_user_id)project_state = _resolve_project_state(integration, slack_user_id)view = render_home_view(+ effective=effective,+ user_row=user_row,+ workspace_row=workspace_row,is_admin=is_admin,account_state=account_state,project_state=project_state,@@ -306,23 +807,41 @@ def handle_app_home_opened(event: dict, slack_team_id: str) -> None:)-def handle_home_block_action(payload: dict, action: dict) -> HttpResponse:- """Dispatch a `block_actions` payload originating from the Home tab."""+def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResponse:+ """Dispatch a `block_actions` payload originating from the Home tab or modal."""action_id = action.get("action_id")slack_team_id = (payload.get("team") or {}).get("id", "")slack_user_id = (payload.get("user") or {}).get("id", "")+ trigger_id = payload.get("trigger_id")integration = _get_slack_integration(slack_team_id)if integration is None:return HttpResponse(status=200)- # The flag is the kill-switch for the whole feature — writes must- # respect it too, otherwise a flipped-off flag silently accumulates- # rows that the resolver will ignore.+ # The flag is the kill-switch for the whole feature — writes and modal+ # opens must respect it too, otherwise a flipped-off flag silently+ # accumulates rows that the resolver will ignore.if not is_slack_app_home_enabled(integration):return HttpResponse(status=200)+ if action_id == ACTION_EDIT_PERSONAL and trigger_id:+ _open_edit_modal(integration, slack_user_id, scope="personal", trigger_id=trigger_id)+ return HttpResponse(status=200)++ if action_id == ACTION_EDIT_WORKSPACE and trigger_id:+ slack = SlackIntegration(integration)+ if not _is_admin(slack, integration, slack_user_id):+ _post_ephemeral_admin_only(slack, payload)+ return HttpResponse(status=200)+ _open_edit_modal(integration, slack_user_id, scope="workspace", trigger_id=trigger_id)+ return HttpResponse(status=200)++ if action_id == ACTION_RESET_PERSONAL:+ _clear_personal_override(integration, slack_user_id)+ _republish_home(integration, slack_user_id)+ return HttpResponse(status=200)+if action_id == ACTION_SET_PROJECT_PERSONAL:_apply_project_pick(integration, slack_user_id=slack_user_id, action=action, scope="personal")_republish_home(integration, slack_user_id)@@ -351,15 +870,70 @@ def handle_home_block_action(payload: dict, action: dict) -> HttpResponse:_republish_home(integration, slack_user_id)return HttpResponse(status=200)+ if action_id in (MODAL_ACTION_RUNTIME_ADAPTER, MODAL_ACTION_MODEL):+ # Modal re-render: a runtime / model change updates which downstream+ # blocks (model list, effort options) are valid. Push an updated view.+ return _update_modal_after_input_change(payload)+return HttpResponse(status=200)+def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonResponse:+ """Handle the Save click on the personal or workspace edit modal."""++ view = payload.get("view", {})+ callback_id = view.get("callback_id")+ if callback_id not in (EDIT_MODAL_PERSONAL_CALLBACK_ID, EDIT_MODAL_WORKSPACE_CALLBACK_ID):+ return HttpResponse(status=200)++ slack_team_id = (payload.get("team") or {}).get("id", "")+ slack_user_id = (payload.get("user") or {}).get("id", "")++ integration = _get_slack_integration(slack_team_id)+ if integration is None:+ return _modal_error_response("This Slack workspace is no longer connected to PostHog.")++ if not is_slack_app_home_enabled(integration):+ return _modal_error_response("AI preferences are not available for this workspace right now.")++ runtime_adapter, model, reasoning_effort = parse_modal_submission(view)++ try:+ validate_ai_preferences(runtime_adapter, model, reasoning_effort)+ except ValidationError as exc:+ return _modal_error_response(_first_validation_message(exc))++ if callback_id == EDIT_MODAL_PERSONAL_CALLBACK_ID:+ _write_row(+ integration,+ slack_user_id=slack_user_id,+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,+ )+ else:+ slack = SlackIntegration(integration)+ if not _is_admin(slack, integration, slack_user_id):+ return _modal_error_response("Only Slack workspace admins can change the workspace default.")+ _write_row(+ integration,+ slack_user_id=None,+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,+ )++ _republish_home(integration, slack_user_id)+ return JsonResponse({"response_action": "clear"})++# ---------------------------------------------------------------------------# Handler internals# ---------------------------------------------------------------------------def _get_slack_integration(slack_team_id: str) -> Integration | None:+if not slack_team_id:return Nonereturn (@@ -369,7 +943,31 @@ def _get_slack_integration(slack_team_id: str) -> Integration | None:)+def _load_rows(integration: Integration, slack_user_id: str) -> tuple[SlackSettings | None, SlackSettings | None]:++ user_row = SlackSettings.objects.filter(+ slack_workspace_id=integration.integration_id,+ slack_user_id=slack_user_id,+ ).first()+ workspace_row = SlackSettings.objects.filter(+ slack_workspace_id=integration.integration_id,+ slack_user_id__isnull=True,+ ).first()+ return user_row, workspace_row+++def _row_to_settings(row: SlackSettings | None) -> AIPreferences:+ if row is None:+ return AIPreferences()+ return AIPreferences(+ runtime_adapter=row.runtime_adapter,+ model=row.model,+ reasoning_effort=row.reasoning_effort,+ )++def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:+try:return is_slack_workspace_admin(slack, integration, slack_user_id)except Exception:@@ -381,20 +979,148 @@ def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id:return False-def _clear_project_personal(integration: Integration, slack_user_id: str) -> None:- """Clear the personal routing override."""+def _open_edit_modal(integration: Integration, slack_user_id: str, *, scope: EditScope, trigger_id: str) -> None:+ user_row, workspace_row = _load_rows(integration, slack_user_id)+ current = _row_to_settings(user_row if scope == "personal" else workspace_row)+ supported = _supported_efforts(current.runtime_adapter, current.model)+ slack = SlackIntegration(integration)++ # No models available (gateway down / misconfigured) — opening a modal+ # with an empty dropdown crashes Slack's validation. Show an info modal+ # instead so the user gets a clear message and doesn't see a silent+ # no-op click.+ if not _runtime_adapter_options():+ view = _render_unavailable_modal()+ else:+ view = render_edit_modal(scope=scope, current=current, supported_efforts=supported)++ try:+ slack.client.views_open(trigger_id=trigger_id, view=view)+ except Exception:+ logger.exception(+ "slack_app_home_open_modal_failed",+ slack_user_id=slack_user_id,+ scope=scope,+ )+++def _render_unavailable_modal() -> dict:+ return {+ "type": "modal",+ "title": {"type": "plain_text", "text": "AI preferences", "emoji": True},+ "close": {"type": "plain_text", "text": "Close"},+ "blocks": [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "Couldn't load the model list right now. Try again in a minute — if it keeps failing, ping the team.",+ },+ }+ ],+ }+++def _update_modal_after_input_change(payload: dict) -> HttpResponse:+ """Re-render the modal in response to a runtime_adapter or model change.++ Reads the in-flight state from `payload["view"]`, derives the new supported+ efforts (changes when the model changes), and pushes the updated view via+ `views.update`. Nothing is persisted here — the user still has to Save to+ commit.+ """++ view = payload.get("view", {})+ callback_id = view.get("callback_id")+ if callback_id not in (EDIT_MODAL_PERSONAL_CALLBACK_ID, EDIT_MODAL_WORKSPACE_CALLBACK_ID):+ return HttpResponse(status=200)++ runtime_adapter, model, reasoning_effort = parse_modal_submission(view)+ current = AIPreferences(runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort)+ supported = _supported_efforts(runtime_adapter, model)++ scope: EditScope = "personal" if callback_id == EDIT_MODAL_PERSONAL_CALLBACK_ID else "workspace"+ updated_view = render_edit_modal(scope=scope, current=current, supported_efforts=supported)++ slack_team_id = (payload.get("team") or {}).get("id", "")+ integration = _get_slack_integration(slack_team_id)+ if integration is None:+ return HttpResponse(status=200)++ slack = SlackIntegration(integration)+ try:+ slack.client.views_update(view_id=view.get("id"), hash=view.get("hash"), view=updated_view)+ except Exception:+ logger.exception("slack_app_home_modal_update_failed")+ return HttpResponse(status=200)+++def _supported_efforts(runtime_adapter: str | None, model: str | None) -> list[str] | None:+ if not runtime_adapter or not model:+ return None+ from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts++ return [e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)] or None+++def _write_row(+ integration: Integration,+ *,+ slack_user_id: str | None,+ runtime_adapter: str | None,+ model: str | None,+ reasoning_effort: str | None,+) -> None:+ """Upsert a SlackSettings row with the given AI preferences.++ `default_integration` is left untouched on existing rows so saving AI+ preferences doesn't accidentally overwrite the user's routing pick.+ """++ payload = build_ai_preferences_payload(runtime_adapter, model, reasoning_effort)+ SlackSettings.objects.update_or_create(+ slack_workspace_id=integration.integration_id,+ slack_user_id=slack_user_id,+ defaults={"ai_preferences": payload or None},+ )+++def _clear_personal_override(integration: Integration, slack_user_id: str) -> None:+ """Clear just the AI fields on the user's row. Leaves routing alone."""+SlackSettings.objects.filter(slack_workspace_id=integration.integration_id,slack_user_id=slack_user_id,- ).delete()+ ).update(ai_preferences=None)+++def _clear_project_personal(integration: Integration, slack_user_id: str) -> None:+ """Clear the personal routing override; drop the row if no AI overrides remain."""++ row = SlackSettings.objects.filter(+ slack_workspace_id=integration.integration_id,+ slack_user_id=slack_user_id,+ ).first()+ if row is None:+ return+ if not row.ai_preferences:+ row.delete()+ return+ row.default_integration = None+ row.save(update_fields=["default_integration", "updated_at"])def _republish_home(integration: Integration, slack_user_id: str) -> None:+ user_row, workspace_row = _load_rows(integration, slack_user_id)+ effective = resolve_ai_preferences(integration, slack_user_id)slack = SlackIntegration(integration)is_admin = _is_admin(slack, integration, slack_user_id)account_state = _resolve_account_state(integration, slack_user_id)project_state = _resolve_project_state(integration, slack_user_id)view = render_home_view(+ effective=effective,+ user_row=user_row,+ workspace_row=workspace_row,is_admin=is_admin,account_state=account_state,project_state=project_state,@@ -471,8 +1197,10 @@ def _resolve_project_state(integration: Integration, slack_user_id: str) -> Proj# Look up the workspace default's label against the full candidate list,# not `accessible`, so a default pointing at an inaccessible project still# surfaces in the UI.+ # Guard on the FK object (not the *_id field) so mypy narrows+ # `default_integration` from `Integration | None` to `Integration`.workspace_team_id = (- workspace_row.default_integration.team_id if workspace_row and workspace_row.default_integration_id else None+ workspace_row.default_integration.team_id if workspace_row and workspace_row.default_integration else None)workspace_team_label: str | None = Noneif workspace_team_id is not None:@@ -480,9 +1208,7 @@ def _resolve_project_state(integration: Integration, slack_user_id: str) -> Projreturn ProjectState(candidates=tuple(ProjectChoice(team_id=c.team_id, label=_label(c)) for c in accessible),- personal_team_id=(- user_row.default_integration.team_id if user_row and user_row.default_integration_id else None- ),+ personal_team_id=(user_row.default_integration.team_id if user_row and user_row.default_integration else None),workspace_team_id=workspace_team_id,workspace_team_label=workspace_team_label,)@@ -582,8 +1308,38 @@ def _workspace_org_ids(slack_team_id: str) -> set:)+def _modal_error_response(message: str) -> JsonResponse:+ """Slack-format response: keep the modal open and surface an error.++ Slack expects `response_action=errors` with a `block_id`-keyed errors map.+ We attach the error to the runtime block so it's visible without scrolling.+ """++ return JsonResponse(+ {+ "response_action": "errors",+ "errors": {MODAL_BLOCK_RUNTIME_ADAPTER: message[:200]},+ }+ )+++def _first_validation_message(exc: Exception) -> str:+ messages = getattr(exc, "messages", None)+ if messages:+ return messages[0]+ return "Settings could not be saved."++def _post_ephemeral_admin_only(slack: SlackIntegration, payload: dict) -> None:- """Tell a non-admin that workspace edits are gated."""+ """Tell a non-admin that workspace edits are gated.++ The Home tab Edit button is already rendered admin-only, so reaching this+ path means the user came in via a stale view or a hand-crafted payload.+ App Home block_actions payloads carry no `channel`/`container.channel_id`+ (the Home tab isn't channel-bound), so fall back to a direct message to+ the user — `chat_postMessage(channel=<user id>)` opens the IM if it does+ not already exist.+ """slack_user_id = (payload.get("user") or {}).get("id", "")if not slack_user_id:returndiff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pynew file mode 100644index 000000000000..c7048d20f738--- /dev/null+++ b/products/slack_app/backend/services/slack_settings.py@@ -0,0 +1,193 @@+"""Read/write helpers for per-(Slack workspace, Slack user) settings backed+by `models.SlackSettings`. Currently exposes AI-preference resolution; future+per-user / per-workspace knobs belong here too.++Key names mirror the task-run request serializer+(`products/tasks/backend/presentation/serializers.py`) so the resolver output+can be handed to the task layer with zero translation.++Resolution: whole-triple swap, not field-by-field merge. If the user row+carries the atomic `(runtime_adapter, model)` pair, the user's entire+preference object takes over (including its absent `reasoning_effort`);+otherwise we fall back wholesale to the workspace default. A field-by-field+merge would blend mismatched configurations — for example, surfacing a+workspace `reasoning_effort` of `low` alongside the user's non-thinking+model — which is never what the user picked. `reasoning_effort` is still+dropped if the resolved model doesn't support it, so a stale effort from+a previous model choice can't silently stick. Unset keys stay `None` so the+task layer applies its own defaults rather than duplicating them here.++Gated by the `slack-app-home` feature flag: when off the resolver returns+the empty object, preserving pre-Home-tab behaviour for workspaces that+haven't opted in.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING, Any++from django.db.models import Q++from products.slack_app.backend.feature_flags import is_slack_app_home_enabled++if TYPE_CHECKING:+ from posthog.models.integration import Integration+++@dataclass(frozen=True)+class AIPreferences:+ """Resolved AI preferences for a single (workspace, slack_user_id) lookup.++ Field names match the task-run request serializer so callers can splat this+ straight into the task creation payload.+ """++ runtime_adapter: str | None = None+ model: str | None = None+ reasoning_effort: str | None = None++ @property+ def is_empty(self) -> bool:+ return self.runtime_adapter is None and self.model is None and self.reasoning_effort is None+++_EMPTY = AIPreferences()+++def resolve_ai_preferences(integration: Integration, slack_user_id: str | None) -> AIPreferences:+ """Resolve the effective AI preferences for a Slack user in a workspace.++ Whole-triple swap: if the user row carries the atomic `(runtime_adapter,+ model)` pair, the user's preference object wins outright; otherwise the+ workspace row wins outright. We never blend the two. `reasoning_effort`+ is dropped if the resolved model doesn't support it.+ """++ if not is_slack_app_home_enabled(integration):+ return _EMPTY++ from products.slack_app.backend.models import SlackSettings++ slack_workspace_id = integration.integration_id+ # SQL `IN (..., NULL)` does not match NULL rows, so the workspace-wide row+ # (slack_user_id IS NULL) needs its own arm in the filter.+ user_row_filter = Q(slack_user_id=slack_user_id) if slack_user_id else Q(pk__in=[])+ rows = list(+ SlackSettings.objects.filter(+ Q(slack_workspace_id=slack_workspace_id) & (Q(slack_user_id__isnull=True) | user_row_filter)+ ).values("slack_user_id", "ai_preferences")+ )+ # Pulled into local dicts so mypy can give them a definite type — the+ # JSONField returns `Any | None` per row, and a `next(...) or {}` expression+ # ends up as a wider union mypy refuses to narrow.+ user_prefs: dict[str, Any] = {}+ workspace_prefs: dict[str, Any] = {}+ for r in rows:+ payload = r["ai_preferences"] or {}+ if r["slack_user_id"] is None:+ workspace_prefs = payload+ elif slack_user_id is not None and r["slack_user_id"] == slack_user_id:+ user_prefs = payload++ # `validate_ai_preferences` enforces that `runtime_adapter` and `model` are+ # set together, so the presence of either one is a faithful signal that+ # this row has been explicitly configured. Pick the whole triple from+ # whichever row sourced the pair.+ if user_prefs.get("runtime_adapter") and user_prefs.get("model"):+ chosen = user_prefs+ elif workspace_prefs.get("runtime_adapter") and workspace_prefs.get("model"):+ chosen = workspace_prefs+ else:+ chosen = {}++ runtime_adapter = chosen.get("runtime_adapter") or None+ model = chosen.get("model") or None+ reasoning_effort = chosen.get("reasoning_effort") or None+ if runtime_adapter and model and reasoning_effort:+ reasoning_effort = _filter_unsupported_effort(runtime_adapter, model, reasoning_effort)++ return AIPreferences(+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,+ )+++def _filter_unsupported_effort(runtime_adapter: str, model: str, effort: str) -> str | None:+ """Drop a stored effort the resolved model no longer supports (e.g. user+ saved `high` on a thinking model and then picked a non-thinking one)."""++ from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts++ supported = {e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)}+ return effort if effort in supported else None+++def build_ai_preferences_payload(+ runtime_adapter: str | None,+ model: str | None,+ reasoning_effort: str | None,+) -> dict[str, str]:+ """Pack the triple into the JSON shape stored on `SlackSettings.ai_preferences`.++ Drops keys whose value is `None` so callers can distinguish "intentionally+ cleared" (key absent) from "set to falsy value".+ """+ payload = {+ "runtime_adapter": runtime_adapter,+ "model": model,+ "reasoning_effort": reasoning_effort,+ }+ return {k: v for k, v in payload.items() if v}+++def validate_ai_preferences(+ runtime_adapter: str | None,+ model: str | None,+ reasoning_effort: str | None,+) -> None:+ """Validate the `(runtime_adapter, model, reasoning_effort)` triple.++ Raises `django.core.exceptions.ValidationError` if the triple is internally+ inconsistent. Call this from the write path so half-set rows never reach+ the DB.+ """+ from django.core.exceptions import ValidationError++ from products.tasks.backend.facade.run_config import (+ PUBLIC_REASONING_EFFORTS,+ RuntimeAdapter,+ get_reasoning_effort_error,+ )++ if (runtime_adapter is None) != (model is None):+ raise ValidationError(+ "runtime_adapter and model must be set together — set both to override the default, or both to null to inherit."+ )++ if runtime_adapter is not None:+ valid_adapters = {a.value for a in RuntimeAdapter}+ if runtime_adapter not in valid_adapters:+ raise ValidationError(+ f"Unknown runtime_adapter '{runtime_adapter}'. Valid: {', '.join(sorted(valid_adapters))}."+ )++ if reasoning_effort is not None:+ valid_efforts = {e.value for e in PUBLIC_REASONING_EFFORTS}+ if reasoning_effort not in valid_efforts:+ raise ValidationError(+ f"Unknown reasoning_effort '{reasoning_effort}'. Valid: {', '.join(sorted(valid_efforts))}."+ )++ error = get_reasoning_effort_error(runtime_adapter, model, reasoning_effort)+ if error:+ raise ValidationError(error)+++__all__ = [+ "AIPreferences",+ "build_ai_preferences_payload",+ "resolve_ai_preferences",+ "validate_ai_preferences",+]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 6aa23ab6965b..c6ba72af03ee 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@@ -1,11 +1,20 @@-"""Tests for the App Home tab (project routing + OAuth account linking).+"""Tests for the App Home tab + AI preferences modal.-Block Kit renderer tests run as pure functions on dicts; handler tests-exercise the real Django flow with the Slack API client mocked out.+Combines the pure renderer tests (Block Kit dict shapes) with the end-to-end+handler tests (real Django flow, Slack client mocked). One shared autouse+fixture stubs the tasks-facade + LLM-gateway-models modules so the test env's+`SANDBOX_PROVIDER=docker` + `DEBUG=False` combination doesn't trigger an+eager docker-sandbox load on import."""from __future__ import annotations+import sys+import json+from dataclasses import dataclass+from types import ModuleType+from typing import Any+import pytestfrom unittest.mock import MagicMock, patch@@ -15,17 +24,28 @@ from posthog.models.team.team import Teamfrom products.slack_app.backend.models import SlackSettingsfrom products.slack_app.backend.services.slack_app_home import (+ ACTION_EDIT_PERSONAL,+ ACTION_EDIT_WORKSPACE,+ ACTION_RESET_PERSONAL,ACTION_RESET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_WORKSPACE,- ACTION_UNLINK_ACCOUNT,- AccountState,- ProjectChoice,- ProjectState,+ EDIT_MODAL_PERSONAL_CALLBACK_ID,+ EDIT_MODAL_WORKSPACE_CALLBACK_ID,+ MODAL_ACTION_MODEL,+ MODAL_ACTION_REASONING_EFFORT,+ MODAL_ACTION_RUNTIME_ADAPTER,+ MODAL_BLOCK_MODEL,+ MODAL_BLOCK_REASONING_EFFORT,+ MODAL_BLOCK_RUNTIME_ADAPTER,+ PreferenceSource,+ handle_ai_preferences_block_action,handle_app_home_opened,- handle_home_block_action,+ handle_app_home_view_submission,+ parse_modal_submission,+ render_edit_modal,render_home_view,+ resolve_source,)+from products.slack_app.backend.services.slack_settings import AIPreferencesSLACK_WORKSPACE_ID = "T_HOME"@@ -84,11 +104,121 @@ def non_admin_user():yield[email protected](autouse=True)+def _stub_picker_facade():+ """Stub `tasks.facade.run_config` and the LLM-gateway model fetch.++ The tasks facade pulls in `tasks.temporal` on import, which the test env+ can't satisfy. The gateway fetch would hit a real network. Both get+ replaced with deterministic in-memory fakes covering every model the+ renderer and handler tests reference.+ """++ class _Effort:+ def __init__(self, value):+ self.value = value++ class _Adapter:+ def __init__(self, value):+ self.value = value++ class _RuntimeAdapter:+ CLAUDE = _Adapter("claude")+ CODEX = _Adapter("codex")++ def __iter__(self):+ return iter([self.CLAUDE, self.CODEX])++ supported_by_model = {+ ("claude", "claude-opus-4-7"): ("low", "medium", "high", "xhigh", "max"),+ ("claude", "claude-sonnet-4-6"): ("low", "medium", "high"),+ ("codex", "gpt-5"): ("low", "medium", "high"),+ ("codex", "gpt-5.5"): ("low", "medium", "high", "xhigh"),+ }+ public_efforts = tuple(_Effort(v) for v in ("low", "medium", "high", "xhigh", "max"))++ def fake_get_supported(adapter, model):+ adapter_value = adapter.value if hasattr(adapter, "value") else adapter+ return tuple(_Effort(v) for v in supported_by_model.get((adapter_value, model), ()))++ def fake_get_error(adapter, model, effort):+ if adapter is None or model is None or effort is None:+ return None+ if effort in supported_by_model.get((adapter, model), ()):+ return None+ return f"Effort '{effort}' not supported on {model}."++ facade_name = "products.tasks.backend.facade.run_config"+ # `Any` annotation so mypy accepts the stub-attribute assignments below —+ # the stdlib `ModuleType` rejects them outright, and ruff B010 reverts any+ # `setattr` workaround back to attribute syntax.+ fake: Any = ModuleType(facade_name)+ fake.RuntimeAdapter = _RuntimeAdapter()+ fake.get_supported_reasoning_efforts = fake_get_supported+ fake.get_reasoning_effort_error = fake_get_error+ fake.PUBLIC_REASONING_EFFORTS = public_efforts++ @dataclass(frozen=True)+ class _GatewayModel:+ id: str+ owned_by: str+ context_window: int = 200_000++ gateway_models = (+ _GatewayModel(id="claude-opus-4-7", owned_by="anthropic"),+ _GatewayModel(id="claude-sonnet-4-6", owned_by="anthropic"),+ _GatewayModel(id="gpt-5", owned_by="openai"),+ _GatewayModel(id="gpt-5.5", owned_by="openai"),+ )+ llm_models_name = "products.slack_app.backend.services.llm_models"+ fake_llm_models: Any = ModuleType(llm_models_name)+ fake_llm_models.list_slack_app_models = lambda: gateway_models+ fake_llm_models.GatewayModel = _GatewayModel++ saved_facade = sys.modules.get(facade_name)+ saved_llm = sys.modules.get(llm_models_name)+ sys.modules[facade_name] = fake+ sys.modules[llm_models_name] = fake_llm_models+ try:+ yield+ finally:+ if saved_facade is None:+ sys.modules.pop(facade_name, None)+ else:+ sys.modules[facade_name] = saved_facade+ if saved_llm is None:+ sys.modules.pop(llm_models_name, None)+ else:+ sys.modules[llm_models_name] = saved_llm++# ----------------------------------------------------------------------------# Helpers+# Renderer helpers# ---------------------------------------------------------------------------+@dataclass+class _Row:+ """Duck-type stand-in for a SlackSettings row — keeps the renderer tests+ off the database. Declared at module scope (instead of inside the helper+ below) so mypy can resolve the dataclass-generated attribute types."""++ runtime_adapter: str | None = None+ model: str | None = None+ reasoning_effort: str | None = None+++def _make_row(+ *,+ runtime_adapter: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,+) -> Any:+ # Returned as Any so call sites that pass this to render_home_view /+ # resolve_source (which expect a real `SlackSettings`) don't trip mypy.+ return _Row(runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort)++def _action_ids(view: dict) -> list[str]:out: list[str] = []for block in view["blocks"]:@@ -98,7 +228,12 @@ def _action_ids(view: dict) -> list[str]:return out+def _block_ids(view: dict) -> list[str]:+ return [b.get("block_id") for b in view["blocks"] if b.get("block_id")]++def _all_text(view: dict) -> str:+ """Flatten all `text` fields for substring assertions."""out: list[str] = []def walk(node):@@ -115,95 +250,222 @@ def _all_text(view: dict) -> str:return " ".join(out)-def _block_action_payload(*, action_id: str, slack_user_id: str, channel: str | None = None) -> dict:+def _build_submission(*, runtime_adapter=None, model=None, effort=None) -> dict:+ state: dict = {}+ if runtime_adapter:+ state[MODAL_BLOCK_RUNTIME_ADAPTER] = {+ MODAL_ACTION_RUNTIME_ADAPTER: {"selected_option": {"value": runtime_adapter}}+ }+ if model:+ state[MODAL_BLOCK_MODEL] = {MODAL_ACTION_MODEL: {"selected_option": {"value": model}}}+ if effort:+ state[MODAL_BLOCK_REASONING_EFFORT] = {MODAL_ACTION_REASONING_EFFORT: {"selected_option": {"value": effort}}}+ return {"state": {"values": state}}+++# ---------------------------------------------------------------------------+# Handler helpers+# ---------------------------------------------------------------------------+++def _block_action_payload(+ *,+ action_id: str,+ slack_user_id: str,+ trigger_id: str | None = None,+ channel: str | None = None,+) -> dict:return {"type": "block_actions","team": {"id": SLACK_WORKSPACE_ID},"user": {"id": slack_user_id},+ "trigger_id": trigger_id,"channel": {"id": channel} if channel else None,"actions": [{"action_id": action_id}],}+def _view_submission_payload(+ *,+ callback_id: str,+ slack_user_id: str,+ runtime_adapter: str | None,+ model: str | None,+ effort: str | None,+) -> dict:+ state: dict = {}+ if runtime_adapter:+ state[MODAL_BLOCK_RUNTIME_ADAPTER] = {+ MODAL_ACTION_RUNTIME_ADAPTER: {"selected_option": {"value": runtime_adapter}}+ }+ if model:+ state[MODAL_BLOCK_MODEL] = {MODAL_ACTION_MODEL: {"selected_option": {"value": model}}}+ if effort:+ state[MODAL_BLOCK_REASONING_EFFORT] = {"ai_prefs:reasoning_effort": {"selected_option": {"value": effort}}}+ return {+ "type": "view_submission",+ "team": {"id": SLACK_WORKSPACE_ID},+ "user": {"id": slack_user_id},+ "view": {+ "id": "V1",+ "hash": "H1",+ "callback_id": callback_id,+ "state": {"values": state},+ },+ }++# ---------------------------------------------------------------------------# Renderer tests# ---------------------------------------------------------------------------class TestRenderHomeView:- def test_renders_home_type(self):- view = render_home_view(is_admin=False)+ def test_empty_state_renders_buttons_and_no_reset(self):+ view = render_home_view(+ effective=AIPreferences(),+ user_row=None,+ workspace_row=None,+ is_admin=False,+ )assert view["type"] == "home"-- def test_hides_project_section_when_no_candidates_and_no_default(self):- view = render_home_view(is_admin=False, project_state=ProjectState())- assert "Project routing" not in _all_text(view)-- def test_shows_personal_picker_when_candidates_present(self):- state = ProjectState(- candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),+ ids = _action_ids(view)+ # Personal edit always present; reset hidden when no override; non-admin+ # doesn't see the workspace edit button.+ assert ACTION_EDIT_PERSONAL in ids+ assert ACTION_RESET_PERSONAL not in ids+ assert ACTION_EDIT_WORKSPACE not in ids++ def test_admin_sees_workspace_edit_button(self):+ view = render_home_view(+ effective=AIPreferences(),+ user_row=None,+ workspace_row=None,+ is_admin=True,)- view = render_home_view(is_admin=False, project_state=state)- assert ACTION_SET_PROJECT_PERSONAL in _action_ids(view)- assert "Project routing" in _all_text(view)-- def test_personal_pick_renders_reset_button(self):- state = ProjectState(- candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),- personal_team_id=1,+ assert ACTION_EDIT_WORKSPACE in _action_ids(view)++ def test_personal_override_renders_reset_button(self):+ view = render_home_view(+ effective=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ user_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ workspace_row=None,+ is_admin=False,)- view = render_home_view(is_admin=False, project_state=state)- assert ACTION_RESET_PROJECT_PERSONAL in _action_ids(view)-- def test_workspace_default_shows_to_non_admin_as_read_only(self):- # Non-admin doesn't get the workspace picker but sees what's set.- state = ProjectState(- candidates=(ProjectChoice(team_id=1, label="Org · A"),),- workspace_team_id=1,- workspace_team_label="Org · A",+ assert ACTION_RESET_PERSONAL in _action_ids(view)++ def test_active_model_summary_mentions_model_label(self):+ view = render_home_view(+ effective=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ user_row=None,+ workspace_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ is_admin=True,)- view = render_home_view(is_admin=False, project_state=state)- assert ACTION_SET_PROJECT_WORKSPACE not in _action_ids(view)+ text_blob = " ".join(block["text"]["text"] for block in view["blocks"] if block.get("type") == "section")+ # Friendly label rather than raw model id; source attribution visible.+ assert "Claude Opus 4.7" in text_blobassert "Workspace default" in _all_text(view)- assert "Org · A" in _all_text(view)- def test_admin_sees_workspace_picker(self):- state = ProjectState(- candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),- )- view = render_home_view(is_admin=True, project_state=state)- assert ACTION_SET_PROJECT_WORKSPACE in _action_ids(view)-- def test_admin_no_access_footnote_when_default_is_inaccessible(self):- # workspace_team_id is set but not in candidates → admin sees footnote.- state = ProjectState(- candidates=(ProjectChoice(team_id=1, label="Org · A"),),- workspace_team_id=42,- workspace_team_label="Other Org · Secret",+ def test_source_resolution_is_atomic(self):+ # User has only `reasoning_effort` set (no pair). Source should fall+ # through to the workspace's complete pair.+ assert (+ resolve_source(+ _make_row(reasoning_effort="medium"),+ _make_row(runtime_adapter="claude", model="claude-opus-4-7"),+ )+ == PreferenceSource.workspace())- view = render_home_view(is_admin=True, project_state=state)- assert "no access" in _all_text(view)- assert "Other Org · Secret" in _all_text(view)- def test_account_section_hidden_when_disabled(self):- view = render_home_view(is_admin=False, account_state=AccountState(enabled=False))- assert "Linked PostHog account" not in _all_text(view)- assert "Connect to PostHog" not in _all_text(view)+ def test_source_unset_when_neither_row_has_pair(self):+ assert resolve_source(None, None) == PreferenceSource.unset()+ assert resolve_source(_make_row(reasoning_effort="high"), None) == PreferenceSource.unset()- def test_account_section_linked_shows_email_and_disconnect(self):- view = render_home_view(- is_admin=False,- account_state=AccountState(enabled=True, linked_email="[email protected]"),- )- assert "[email protected]" in _all_text(view)- assert ACTION_UNLINK_ACCOUNT in _action_ids(view)- def test_account_section_unlinked_shows_connect_button(self):- view = render_home_view(- is_admin=False,- account_state=AccountState(enabled=True, linked_email=None, link_url="https://example/auth"),+class TestRenderEditModal:+ @pytest.mark.parametrize(+ "scope,callback_id",+ [+ ("personal", EDIT_MODAL_PERSONAL_CALLBACK_ID),+ ("workspace", EDIT_MODAL_WORKSPACE_CALLBACK_ID),+ ],+ )+ def test_callback_id_matches_scope(self, scope, callback_id):+ view = render_edit_modal(scope=scope, current=AIPreferences())+ assert view["callback_id"] == callback_id++ def test_no_runtime_means_no_model_or_effort_blocks(self):+ view = render_edit_modal(scope="personal", current=AIPreferences())+ ids = _block_ids(view)+ assert MODAL_BLOCK_RUNTIME_ADAPTER in ids+ assert MODAL_BLOCK_MODEL not in ids+ assert MODAL_BLOCK_REASONING_EFFORT not in ids++ def test_runtime_picked_unlocks_model_block(self):+ view = render_edit_modal(scope="personal", current=AIPreferences(runtime_adapter="claude"))+ ids = _block_ids(view)+ assert MODAL_BLOCK_MODEL in ids+ # Effort block needs both the model and a non-empty supported list.+ assert MODAL_BLOCK_REASONING_EFFORT not in ids++ def test_model_options_match_runtime(self):+ view = render_edit_modal(scope="personal", current=AIPreferences(runtime_adapter="codex"))+ model_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_MODEL)+ option_values = [o["value"] for o in model_block["element"]["options"]]+ # Codex models only — assert via prefix to stay resilient as the facade+ # adds new Codex ids.+ assert option_values+ assert all(v.startswith("gpt-") for v in option_values)++ def test_effort_block_renders_only_when_supported_efforts_provided(self):+ view = render_edit_modal(+ scope="personal",+ current=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7"),+ supported_efforts=["low", "medium", "high"],+ )+ block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_REASONING_EFFORT)+ assert block["optional"] is True+ values = [o["value"] for o in block["element"]["options"]]+ assert values == ["low", "medium", "high"]++ def test_initial_options_reflect_current_values(self):+ view = render_edit_modal(+ scope="workspace",+ current=AIPreferences(+ runtime_adapter="claude",+ model="claude-opus-4-7",+ reasoning_effort="high",+ ),+ supported_efforts=["low", "medium", "high"],)- assert "Connect to PostHog" in _all_text(view)+ runtime_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_RUNTIME_ADAPTER)+ model_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_MODEL)+ effort_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_REASONING_EFFORT)+ assert runtime_block["element"]["initial_option"]["value"] == "claude"+ assert model_block["element"]["initial_option"]["value"] == "claude-opus-4-7"+ assert effort_block["element"]["initial_option"]["value"] == "high"++ def test_dispatch_action_set_on_runtime_and_model(self):+ view = render_edit_modal(scope="personal", current=AIPreferences(runtime_adapter="claude"))+ runtime_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_RUNTIME_ADAPTER)+ model_block = next(b for b in view["blocks"] if b.get("block_id") == MODAL_BLOCK_MODEL)+ # dispatch_action triggers a block_actions payload so the modal can+ # re-render with downstream options matching the new selection.+ assert runtime_block["dispatch_action"] is True+ assert model_block["dispatch_action"] is True+++class TestParseModalSubmission:+ def test_all_three_picked(self):+ view = _build_submission(runtime_adapter="claude", model="claude-opus-4-7", effort="high")+ assert parse_modal_submission(view) == ("claude", "claude-opus-4-7", "high")++ def test_no_state_returns_all_none(self):+ assert parse_modal_submission({}) == (None, None, None)++ def test_partial_state_returns_partial_tuple(self):+ view = _build_submission(runtime_adapter="claude")+ assert parse_modal_submission(view) == ("claude", None, None)# ---------------------------------------------------------------------------@@ -233,35 +495,169 @@ class TestHandleAppHomeOpened:# ---------------------------------------------------------------------------+class TestEditPersonalAction:+ def test_opens_modal(self, slack_integration, mock_slack_client, flag_on, admin_user):+ payload = _block_action_payload(+ action_id=ACTION_EDIT_PERSONAL,+ slack_user_id="U001",+ trigger_id="trig.1",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])+ assert mock_slack_client.views_open.called+ view = mock_slack_client.views_open.call_args.kwargs["view"]+ assert view["callback_id"] == EDIT_MODAL_PERSONAL_CALLBACK_ID+++class TestEditWorkspaceAdminGate:+ def test_admin_opens_modal(self, slack_integration, mock_slack_client, flag_on, admin_user):+ payload = _block_action_payload(+ action_id=ACTION_EDIT_WORKSPACE,+ slack_user_id="U001",+ trigger_id="trig.2",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])+ assert mock_slack_client.views_open.called++ def test_non_admin_blocked(self, slack_integration, mock_slack_client, flag_on, non_admin_user):+ payload = _block_action_payload(+ action_id=ACTION_EDIT_WORKSPACE,+ slack_user_id="U001",+ trigger_id="trig.3",+ channel="C1",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])+ # Non-admin gets an ephemeral notice rather than the modal.+ assert not mock_slack_client.views_open.called+ assert mock_slack_client.chat_postEphemeral.called or mock_slack_client.chat_postMessage.called+++class TestResetPersonal:+ def test_clears_ai_fields_and_republishes(self, slack_integration, mock_slack_client, flag_on, admin_user):+ SlackSettings.objects.create(+ default_integration=slack_integration,+ slack_workspace_id=SLACK_WORKSPACE_ID,+ slack_user_id="U001",+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )+ payload = _block_action_payload(+ action_id=ACTION_RESET_PERSONAL,+ slack_user_id="U001",+ trigger_id="trig.4",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])++ row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")+ assert row.runtime_adapter is None+ assert row.model is None+ assert row.reasoning_effort is None+ assert mock_slack_client.views_publish.called++class TestResetProjectPersonal:- def test_drops_row_when_reset(self, slack_integration, mock_slack_client, flag_on, admin_user):+ def test_clears_routing_only_when_ai_preferences_present(+ self, slack_integration, mock_slack_client, flag_on, admin_user+ ):+ # Mixed row → reset clears routing, AI fields stay.SlackSettings.objects.create(default_integration=slack_integration,slack_workspace_id=SLACK_WORKSPACE_ID,+ slack_user_id="U001",+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )+ payload = _block_action_payload(+ action_id=ACTION_RESET_PROJECT_PERSONAL,+ slack_user_id="U001",+ trigger_id="trig.5",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])++ row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")+ assert row.default_integration_id is None+ assert row.runtime_adapter == "claude"+ assert row.model == "claude-opus-4-7"+ assert row.reasoning_effort == "high"+ assert mock_slack_client.views_publish.called++ def test_deletes_row_when_no_ai_preferences_remain(self, slack_integration, mock_slack_client, flag_on, admin_user):+ # Routing-only row → reset drops it so the resolver falls back to+ # the workspace default cleanly.+ SlackSettings.objects.create(+ default_integration=slack_integration,+ slack_workspace_id=SLACK_WORKSPACE_ID,+ slack_user_id="U002",+ )+ payload = _block_action_payload(+ action_id=ACTION_RESET_PROJECT_PERSONAL,slack_user_id="U002",+ trigger_id="trig.6",)- payload = _block_action_payload(action_id=ACTION_RESET_PROJECT_PERSONAL, slack_user_id="U002")- handle_home_block_action(payload, payload["actions"][0])+ handle_ai_preferences_block_action(payload, payload["actions"][0])assert not SlackSettings.objects.filter(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U002").exists()assert mock_slack_client.views_publish.calleddef test_no_row_is_a_noop(self, slack_integration, mock_slack_client, flag_on, admin_user):- payload = _block_action_payload(action_id=ACTION_RESET_PROJECT_PERSONAL, slack_user_id="U003")- handle_home_block_action(payload, payload["actions"][0])+ payload = _block_action_payload(+ action_id=ACTION_RESET_PROJECT_PERSONAL,+ slack_user_id="U003",+ trigger_id="trig.7",+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])# Nothing to clear — still republish so the view stays in sync.assert mock_slack_client.views_publish.called-class TestSetWorkspaceProjectAdminGate:+# ---------------------------------------------------------------------------+# Handler tests — view_submission+# ---------------------------------------------------------------------------+++class TestPersonalSubmit:+ def test_writes_row_and_republishes(self, slack_integration, mock_slack_client, flag_on, admin_user):+ payload = _view_submission_payload(+ callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,+ slack_user_id="U001",+ runtime_adapter="claude",+ model="claude-opus-4-7",+ effort="high",+ )+ response = handle_app_home_view_submission(payload)+ assert response.status_code == 200+ assert json.loads(response.content) == {"response_action": "clear"}++ row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")+ assert row.runtime_adapter == "claude"+ assert row.model == "claude-opus-4-7"+ assert row.reasoning_effort == "high"+ assert mock_slack_client.views_publish.called++ def test_invalid_pair_keeps_modal_open_with_error(self, slack_integration, mock_slack_client, flag_on):+ # `xhigh` isn't supported on claude-sonnet-4-6 — validate_ai_preferences rejects.+ payload = _view_submission_payload(+ callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,+ slack_user_id="U001",+ runtime_adapter="claude",+ model="claude-sonnet-4-6",+ effort="xhigh",+ )+ response = handle_app_home_view_submission(payload)+ body = json.loads(response.content)+ assert body["response_action"] == "errors"+ assert MODAL_BLOCK_RUNTIME_ADAPTER in body["errors"]+ # Modal left open: no row written, no publish.+ assert not SlackSettings.objects.filter(slack_user_id="U001").exists()+++class TestWorkspaceSubmitAdminGate:def test_non_admin_blocked(self, slack_integration, mock_slack_client, flag_on, non_admin_user):- payload = _block_action_payload(- action_id=ACTION_SET_PROJECT_WORKSPACE,+ payload = _view_submission_payload(+ callback_id=EDIT_MODAL_WORKSPACE_CALLBACK_ID,slack_user_id="U_NONADMIN",- channel="C1",+ runtime_adapter="claude",+ model="claude-opus-4-7",+ effort="high",)- # Payload doesn't pick a team, but the admin gate should short-circuit first.- handle_home_block_action(payload, payload["actions"][0])+ response = handle_app_home_view_submission(payload)+ body = json.loads(response.content)+ assert body["response_action"] == "errors"assert not SlackSettings.objects.filter(slack_user_id__isnull=True).exists()- # Non-admin notice goes via ephemeral or DM.- assert mock_slack_client.chat_postEphemeral.called or mock_slack_client.chat_postMessage.calleddiff --git a/products/slack_app/backend/tests/services/test_slack_settings.py b/products/slack_app/backend/tests/services/test_slack_settings.pynew file mode 100644index 000000000000..8caebe7aaffa--- /dev/null+++ b/products/slack_app/backend/tests/services/test_slack_settings.py@@ -0,0 +1,338 @@+from typing import Any++import pytest+from unittest.mock import patch++from django.core.exceptions import ValidationError++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.feature_flags import SLACK_APP_HOME_FLAG+from products.slack_app.backend.models import SlackSettings+from products.slack_app.backend.services.slack_settings import (+ AIPreferences,+ resolve_ai_preferences,+ validate_ai_preferences,+)+++def slack_setup(db):+ organization = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=organization, name="Team")+ integration = Integration.objects.create(+ team=team,+ kind="slack",+ integration_id="T_WS",+ sensitive_config={"access_token": "xoxb"},+ )+ return integration+++def flag_on():+ """Flip the slack-app-home flag on for the duration of a test."""+ with patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=True,+ ) as mock:+ yield mock+++def flag_off():+ with patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=False,+ ) as mock:+ yield mock++[email protected](autouse=True)+def _stub_task_runtime_helpers():+ """Replace the lazy tasks-facade imports with a minimal stub.++ Slack handler code imports `products.tasks.backend.facade.run_config`,+ which re-exports from `products.tasks.backend.temporal.process_task.utils`.+ Loading either pulls in `tasks.backend.temporal.__init__.py`, which+ eagerly loads the docker sandbox class. The test env sets+ `SANDBOX_PROVIDER=docker` alongside `DEBUG=False` — a combination the+ sandbox module rejects at import time. Production runs+ `SANDBOX_PROVIDER=modal`, so the real lazy import path works there.+ Stubbing the facade module here keeps these tests focused on resolver+ logic without dragging the tasks-temporal import chain in.+ """+ supported_by_model = {+ ("claude", "claude-opus-4-7"): {"low", "medium", "high", "xhigh", "max"},+ ("claude", "claude-sonnet-4-6"): {"low", "medium", "high"},+ ("codex", "gpt-5.5"): {"low", "medium", "high", "xhigh"},+ ("codex", "gpt-5"): {"low", "medium", "high"},+ }++ class _Effort:+ def __init__(self, value: str):+ self.value = value++ def fake_get_supported(adapter, model):+ return tuple(_Effort(v) for v in supported_by_model.get((adapter, model), set()))++ def fake_get_error(adapter, model, effort):+ if adapter is None or model is None or effort is None:+ return None+ supported = supported_by_model.get((adapter, model), set())+ if effort in supported:+ return None+ return f"Reasoning effort '{effort}' is not supported for {adapter}/{model}."++ class _Adapter:+ def __init__(self, value):+ self.value = value++ class _RuntimeAdapter:+ CLAUDE = _Adapter("claude")+ CODEX = _Adapter("codex")++ def __iter__(self):+ return iter([self.CLAUDE, self.CODEX])++ class _PublicEffort:+ def __init__(self, value):+ self.value = value++ public_efforts = (+ _PublicEffort("low"),+ _PublicEffort("medium"),+ _PublicEffort("high"),+ _PublicEffort("xhigh"),+ _PublicEffort("max"),+ )++ import sys+ from types import ModuleType++ module_name = "products.tasks.backend.facade.run_config"+ # `Any` annotation so mypy accepts the stub-attribute assignments below —+ # the stdlib `ModuleType` rejects them, and ruff B010 reverts any+ # `setattr` workaround back to attribute syntax.+ fake: Any = ModuleType(module_name)+ fake.get_supported_reasoning_efforts = fake_get_supported+ fake.get_reasoning_effort_error = fake_get_error+ fake.RuntimeAdapter = _RuntimeAdapter()+ fake.PUBLIC_REASONING_EFFORTS = public_efforts++ saved = sys.modules.get(module_name)+ sys.modules[module_name] = fake+ try:+ yield+ finally:+ if saved is None:+ sys.modules.pop(module_name, None)+ else:+ sys.modules[module_name] = saved+++class TestResolveAIPreferences:+ @pytest.mark.parametrize(+ "user_row,workspace_row,expected",+ [+ pytest.param(+ None,+ None,+ AIPreferences(),+ id="no-rows-returns-empty",+ ),+ pytest.param(+ None,+ {"runtime_adapter": "claude", "model": "claude-opus-4-7", "effort": "high"},+ AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ id="workspace-only-applies",+ ),+ pytest.param(+ {"runtime_adapter": "codex", "model": "gpt-5.5", "effort": "high"},+ None,+ AIPreferences(runtime_adapter="codex", model="gpt-5.5", reasoning_effort="high"),+ id="user-only-applies",+ ),+ pytest.param(+ {"runtime_adapter": "claude", "model": "claude-opus-4-7", "effort": "high"},+ {"runtime_adapter": "codex", "model": "gpt-5.5", "effort": "low"},+ AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),+ id="user-overrides-workspace",+ ),+ ],+ )+ def test_resolution_table(self, slack_setup, flag_on, user_row, workspace_row, expected):+ integration = slack_setup+ if user_row:+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ ai_preferences={+ "runtime_adapter": user_row["runtime_adapter"],+ "model": user_row["model"],+ "reasoning_effort": user_row["effort"],+ },+ )+ if workspace_row:+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ ai_preferences={+ "runtime_adapter": workspace_row["runtime_adapter"],+ "model": workspace_row["model"],+ "reasoning_effort": workspace_row["effort"],+ },+ )+ assert resolve_ai_preferences(integration, "U001") == expected++ def test_user_row_with_no_pair_yields_workspace_triple_intact(self, slack_setup, flag_on):+ """A user row without the atomic `(runtime_adapter, model)` pair is+ treated as "no personal preference", so the workspace row wins+ wholesale — including its own `reasoning_effort`. The user's+ orphaned effort never leaks into the resolved triple."""+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ # Orphan effort with no pair — shouldn't reach the DB through the+ # normal write path, but the resolver still has to defend against+ # it (direct writes, older data, schema drift).+ ai_preferences={"reasoning_effort": "medium"},+ )+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )++ assert resolve_ai_preferences(integration, "U001") == AIPreferences(+ runtime_adapter="claude",+ model="claude-opus-4-7",+ reasoning_effort="high",+ )++ def test_user_pair_without_effort_does_not_inherit_workspace_effort(self, slack_setup, flag_on):+ """If the user explicitly picks a pair without a reasoning effort,+ the resolver must not silently graft the workspace's effort onto+ it. Whole-triple swap: user's absent effort stays absent."""+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7"},+ )+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "low"},+ )++ assert resolve_ai_preferences(integration, "U001") == AIPreferences(+ runtime_adapter="claude",+ model="claude-opus-4-7",+ reasoning_effort=None,+ )++ def test_unsupported_effort_dropped_when_model_does_not_support_it(self, slack_setup, flag_on):+ """If a row stores an effort the resolved model can't honour (e.g.+ the model definition changed since the effort was saved), the+ resolver drops it rather than letting it leak through to the task+ layer."""+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ # `xhigh` isn't in `supported_by_model` for sonnet-4-6, so the+ # runtime drop must clear it.+ ai_preferences={+ "runtime_adapter": "claude",+ "model": "claude-sonnet-4-6",+ "reasoning_effort": "xhigh",+ },+ )+ result = resolve_ai_preferences(integration, "U001")+ assert result.runtime_adapter == "claude"+ assert result.model == "claude-sonnet-4-6"+ assert result.reasoning_effort is None++ def test_user_id_none_uses_workspace_row_only(self, slack_setup, flag_on):+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )+ result = resolve_ai_preferences(integration, None)+ assert result == AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high")++ def test_flag_off_returns_empty_even_with_rows_present(self, slack_setup, flag_off):+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )+ assert resolve_ai_preferences(integration, "U001") == AIPreferences()++ def test_flag_check_failure_fails_closed(self, slack_setup):+ integration = slack_setup+ SlackSettings.objects.create(+ default_integration=integration,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},+ )+ with patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("boom"),+ ):+ assert resolve_ai_preferences(integration, "U001") == AIPreferences()+++class TestValidateAIPreferences:+ def test_all_none_is_valid(self):+ validate_ai_preferences(None, None, None)++ def test_full_triple_is_valid(self):+ validate_ai_preferences("claude", "claude-opus-4-7", "high")++ def test_pair_without_effort_is_valid(self):+ validate_ai_preferences("claude", "claude-opus-4-7", None)++ @pytest.mark.parametrize(+ "runtime_adapter,model",+ [+ ("claude", None),+ (None, "claude-opus-4-7"),+ ],+ )+ def test_half_set_pair_rejected(self, runtime_adapter, model):+ with pytest.raises(ValidationError, match="must be set together"):+ validate_ai_preferences(runtime_adapter, model, None)++ def test_unknown_runtime_adapter_rejected(self):+ with pytest.raises(ValidationError, match="Unknown runtime_adapter"):+ validate_ai_preferences("nonsense", "claude-opus-4-7", None)++ def test_unknown_reasoning_effort_rejected(self):+ with pytest.raises(ValidationError, match="Unknown reasoning_effort"):+ validate_ai_preferences("claude", "claude-opus-4-7", "ultra")++ def test_effort_unsupported_by_model_rejected(self):+ with pytest.raises(ValidationError, match="not supported"):+ validate_ai_preferences("claude", "claude-sonnet-4-6", "xhigh")++ def test_flag_constant_is_stable(self):+ # Sanity: the flag name is what we documented and rolled out with.+ assert SLACK_APP_HOME_FLAG == "slack-app-home"diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex 1dd1c2961e6b..a40dd2d8191b 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -248,6 +248,31 @@ class TestResolveIntegration:assert result.source == "sole_candidate"assert result.integration == self.integration_b+ def test_null_user_default_falls_through_to_workspace(self):+ # A null personal row exists because the user reset their project+ # routing back to workspace default. The resolver must skip it and+ # use the workspace-wide row.+ SlackSettings.objects.create(+ default_integration=None,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=None,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "workspace_default"+ assert result.integration == self.integration_a+def test_user_default_wins_over_workspace_default(self):SlackSettings.objects.create(default_integration=self.integration_a,diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.pyindex a6b04d670cdc..4ef284f2c998 100644--- a/products/tasks/backend/facade/run_config.py+++ b/products/tasks/backend/facade/run_config.py@@ -24,8 +24,10 @@ from products.tasks.backend.temporal.process_task.utils import (RunSource,RunState,RuntimeAdapter,+ get_models_for_runtime_adapter,get_provider_for_runtime_adapter,get_reasoning_effort_error,+ get_supported_reasoning_efforts,parse_run_state,)@@ -41,7 +43,9 @@ __all__ = ["RunSource","RunState","RuntimeAdapter",+ "get_models_for_runtime_adapter","get_provider_for_runtime_adapter","get_reasoning_effort_error",+ "get_supported_reasoning_efforts","parse_run_state",]diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex dcf79d071246..7ac2965a238e 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -336,8 +336,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):internal: bool = False,output_schema: type[BaseModel] | dict | None = None,interaction_origin: str | None = None,- model: str | None = None,runtime_adapter: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,initial_permission_mode: str | None = None,sandbox_resources: "SandboxResources | None" = None,sandbox_timeout_seconds: int | None = None,@@ -461,6 +462,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):if initial_permission_mode is None and runtime_adapter == RuntimeAdapter.CODEX.value:initial_permission_mode = "auto"+ if reasoning_effort:+ extra_state["reasoning_effort"] = reasoning_effort+# Forwarded to the in-sandbox agent and lifted onto its $ai_generation traces as an# `ai_stage` property (see TaskProcessingContext / agent-server configureEnvironment).if ai_stage:@@ -555,8 +559,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):internal: bool = False,output_schema: type[BaseModel] | dict | None = None,interaction_origin: str | None = None,- model: str | None = None,runtime_adapter: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,initial_permission_mode: str | None = None,sandbox_resources: "SandboxResources | None" = None,sandbox_timeout_seconds: int | None = None,@@ -580,8 +585,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):internal=internal,output_schema=output_schema,interaction_origin=interaction_origin,- model=model,runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,initial_permission_mode=initial_permission_mode,sandbox_resources=sandbox_resources,sandbox_timeout_seconds=sandbox_timeout_seconds,diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex fd38dc310df0..da789dd98b91 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -128,6 +128,29 @@ CODEX_XHIGH_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = ()CODEX_XHIGH_REASONING_MODELS: frozenset[str] = frozenset({"gpt-5.5"})+# Canonical list of Codex models. The runtime technically accepts any+# `gpt-*` identifier passed through, but only models on this list are+# considered tested and surfaced in pickers. Extend when a new Codex model+# ships.+CODEX_MODELS: tuple[str, ...] = ("gpt-5", "gpt-5.5")+++def get_models_for_runtime_adapter(runtime_adapter: RuntimeAdapter | str | None) -> tuple[str, ...]:+ """Return the canonical model identifiers the given runtime adapter exposes.++ Empty tuple if the adapter is unknown. Mirrors `get_supported_reasoning_efforts`+ in spirit — small pure helper that callers can rely on when composing+ runtime/model picker UIs at the consumer layer.+ """+ if runtime_adapter is None:+ return ()+ adapter_value = runtime_adapter.value if isinstance(runtime_adapter, RuntimeAdapter) else runtime_adapter+ if adapter_value == RuntimeAdapter.CLAUDE.value:+ return tuple(CLAUDE_REASONING_EFFORTS_BY_MODEL.keys())+ if adapter_value == RuntimeAdapter.CODEX.value:+ return CODEX_MODELS+ return ()+def get_provider_for_runtime_adapter(runtime_adapter: RuntimeAdapter | str | None,@@ -212,6 +235,9 @@ def parse_run_state(state: dict[str, Any] | None) -> RunState:return RunState.model_validate(state or {})+# TTL for the per-run GitHub user token cache. Kept for backward-compat with callers+# (notably the PostHog Code CLI) that still pass ``github_user_token`` on the run request.+# The server-side identity flow should be preferred going forward.GITHUB_USER_TOKEN_CACHE_TTL_SECONDS = 6 * 60 * 60# Minimum interval between MCP token refreshes pushed to a live sandbox. The@@ -528,12 +554,6 @@ def user_github_integration_is_usable(user_github_integration: UserGitHubIntegra)-# TTL for the per-run GitHub user token cache. Kept for backward-compat with callers-# (notably the PostHog Code CLI) that still pass ``github_user_token`` on the run request.-# The server-side identity flow should be preferred going forward.-GITHUB_USER_TOKEN_CACHE_TTL_SECONDS = 6 * 60 * 60--def _github_user_token_cache_key(run_id: str) -> str:return f"task-run-github-user-token:{run_id}"diff --git a/tach.toml b/tach.tomlindex b401fd3bb657..aec210107b3f 100644--- a/tach.toml+++ b/tach.toml@@ -596,6 +596,7 @@ depends_on = ["products.dashboards","products.product_analytics","products.signals",+ "products.tasks",]layer = "modules"