: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 jev model router for new slack tasks (#113359)
Vojta Bartoš4505aa5919cd
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.pyindex a3e1f43bafeb..6fe8dd083441 100644--- a/posthog/temporal/ai/slack_app/__init__.py+++ b/posthog/temporal/ai/slack_app/__init__.py@@ -14,6 +14,7 @@ from posthog.temporal.ai.slack_app.activities import (classify_message_is_agent_directed,classify_posthog_code_task_needs_repo_activity,classify_slack_app_model_override_activity,+ classify_slack_app_model_router_activity,classify_slack_app_project_route_activity,classify_untagged_followup_activity,collect_posthog_code_thread_messages_activity,@@ -47,6 +48,7 @@ from posthog.temporal.ai.slack_app.types import (SlackAppMessageReactionInput,SlackAppModelOverride,SlackAppModelOverrideInput,+ SlackAppModelRouterInput,SlackAppProjectRoute,SlackAppProjectRouteInput,SlackRepoSelectionOutcome,@@ -63,6 +65,7 @@ SLACK_APP_ACTIVITIES = [classify_posthog_code_task_needs_repo_activity,classify_slack_app_model_override_activity,classify_slack_app_project_route_activity,+ classify_slack_app_model_router_activity,enforce_posthog_code_billing_quota_activity,post_posthog_code_no_repos_activity,post_posthog_code_repo_picker_activity,@@ -95,6 +98,7 @@ __all__ = ["SlackAppMentionWorkflowInputs","SlackAppModelOverride","SlackAppModelOverrideInput",+ "SlackAppModelRouterInput","SlackAppProjectRoute","SlackAppProjectRouteInput","SlackRepoSelectionOutcome",@@ -121,5 +125,6 @@ __all__ = ["post_posthog_code_repo_picker_activity","request_untagged_followup_confirmation_activity","resolve_posthog_code_slack_command_user_activity",+ "classify_slack_app_model_router_activity","run_posthog_slack_inbox_onboarding_activity",]diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.pyindex 7da66c185780..55dd136687ee 100644--- a/posthog/temporal/ai/slack_app/activities/__init__.py+++ b/posthog/temporal/ai/slack_app/activities/__init__.py@@ -23,6 +23,7 @@ from posthog.temporal.ai.slack_app.activities.messaging import (post_posthog_code_repo_picker_activity,request_untagged_followup_confirmation_activity,)+from posthog.temporal.ai.slack_app.activities.model_router import classify_slack_app_model_router_activityfrom posthog.temporal.ai.slack_app.activities.onboarding import (run_posthog_slack_inbox_onboarding,run_posthog_slack_inbox_onboarding_activity,@@ -74,6 +75,7 @@ __all__ = ["process_slack_app_fork_thread_activity","request_untagged_followup_confirmation_activity","resolve_posthog_code_slack_command_user_activity",+ "classify_slack_app_model_router_activity","run_posthog_slack_inbox_onboarding","run_posthog_slack_inbox_onboarding_activity",]diff --git a/posthog/temporal/ai/slack_app/activities/model_router.py b/posthog/temporal/ai/slack_app/activities/model_router.pynew file mode 100644index 000000000000..e6d1bce2fe36--- /dev/null+++ b/posthog/temporal/ai/slack_app/activities/model_router.py@@ -0,0 +1,132 @@+"""Automatic model choice for a new Slack task.++It runs only for the first message of a thread, because a follow-up joins a sandbox that+already runs and cannot change its runtime.+"""++import structlog+from temporalio import activity++from posthog.llm.managed_decision_model import DEFAULT_DECISION_MODEL+from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion+from posthog.llm.system_one_client import GATEWAY_MAX_CHOICE_OPTIONS, build_system_one_client+from posthog.models.integration import Integration+from posthog.models.user import User+from posthog.temporal.ai.slack_app.activities.classifiers import CLASSIFIER_PROPERTY, _thread_trace_id+from posthog.temporal.ai.slack_app.types import SlackAppModelOverride, SlackAppModelRouterInput+from posthog.temporal.common.utils import close_db_connections++from products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.facade.run_preferences import (+ MODEL_ROUTER_INSTRUCTIONS,+ ModelRouterOption,+ model_router_options,+)+from products.slack_app.backend.feature_flags import is_slack_app_model_router_enabled+from products.slack_app.backend.services.slack_settings import resolve_auto_model_choice++logger = structlog.get_logger(__name__)++MODEL_ROUTER_DECISION_MODEL = DEFAULT_DECISION_MODEL+# The router is on the path to the first reply in the thread, so a slow answer costs more+# than a missed one. A miss leaves the run on the default it already had.+MODEL_ROUTER_TIMEOUT_SECONDS = 5.0++_QUESTION_ID = "model"+++def classify_slack_app_model_router(+ event_text: str,+ options: tuple[ModelRouterOption, ...],+ *,+ team_id: int,+ repository: str | None,+ distinct_id: str | None,+ trace_id: str | None = None,+) -> ModelRouterOption | None:+ options = options[:GATEWAY_MAX_CHOICE_OPTIONS]+ if len(options) < 2:+ return None+ by_key = {option.model: option for option in options}++ # No TypeSafe fallback: the request is customer text, and TypeSafe is a third party.+ client = build_system_one_client(+ model=MODEL_ROUTER_DECISION_MODEL,+ ai_product="slack_app_routing",+ team_id=team_id,+ distinct_id=distinct_id,+ trace_id=trace_id,+ properties={CLASSIFIER_PROPERTY: "slack_model_router"},+ timeout=MODEL_ROUTER_TIMEOUT_SECONDS,+ )+ result = client.decide(+ state={"request": event_text, "repository": repository},+ questions={+ _QUESTION_ID: ChoiceQuestion(+ instructions=MODEL_ROUTER_INSTRUCTIONS,+ criteria={key: option.description for key, option in by_key.items()},+ )+ },+ )+ answer = result.answers.get(_QUESTION_ID)+ if not isinstance(answer, ChoiceAnswer) or answer.choice not in by_key:+ logger.warning("slack_app_model_router_unexpected_answer")+ return None+ logger.info("slack_app_model_router_answer", choice=answer.choice, confidence=answer.confidence)+ return by_key[answer.choice]+++@close_db_connections+def classify_slack_app_model_router_activity(input: SlackAppModelRouterInput) -> SlackAppModelOverride | None:+ """A model named in the mention always wins, because the author asked for it. The router+ picks only a model: the effort comes from the mention, else from the stored default when+ the router picks that default's model, else the model's own default.+ """+ override = input.model_override+ if (override is not None and override.model) or not input.event_text.strip():+ return override+ if not resolve_auto_model_choice(input.slack_team_id, input.slack_user_id):+ return override++ integration = Integration.objects.select_related("team").get(+ id=input.integration_id,+ kind="slack",+ integration_id=input.slack_team_id,+ )+ user = User.objects.filter(id=input.user_id).first()+ if user is None or not is_slack_app_model_router_enabled(integration, distinct_id=user.distinct_id):+ return override++ options: tuple[ModelRouterOption, ...] = ()+ try:+ options = model_router_options(team_id=integration.team_id, user_id=user.id, distinct_id=user.distinct_id)+ picked = classify_slack_app_model_router(+ input.event_text,+ options,+ team_id=integration.team_id,+ repository=input.repository,+ distinct_id=user.distinct_id,+ trace_id=_thread_trace_id(input.slack_team_id, input.thread_ts),+ )+ except Exception:+ logger.exception("slack_app_model_router_failed")+ picked = None++ capture_slack_event(+ integration,+ "slack app model routed",+ slack_user_id=input.slack_user_id,+ posthog_user=user,+ routed=picked is not None,+ model=picked.model if picked else None,+ option_count=len(options),+ has_repository=input.repository is not None,+ )+ if picked is None:+ return override++ return SlackAppModelOverride(+ model=picked.model,+ reasoning_effort=(override.reasoning_effort if override else None) or picked.reasoning_effort,+ )diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.pyindex bbd261a4dd25..f1b140d410cf 100644--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py@@ -12,10 +12,12 @@ from posthog.temporal.ai.slack_app import (PostHogCodeSlackMentionWorkflowInputs,SlackAppModelOverride,SlackAppModelOverrideInput,+ SlackAppModelRouterInput,SlackAppProjectRouteInput,cascade_posthog_code_repository_activity,classify_posthog_code_task_needs_repo_activity,classify_slack_app_model_override_activity,+ classify_slack_app_model_router_activity,classify_slack_app_project_route_activity,classify_untagged_followup_activity,collect_posthog_code_thread_messages_activity,@@ -44,6 +46,7 @@ _PATCH_ID_FOLLOWUP_MODEL_CLASSIFIER = "slack-app-followup-model-classifier-v1"_PATCH_ID_PROJECT_ROUTE_CLASSIFIER = "slack-app-project-route-classifier-v1"_PATCH_ID_PROJECT_ROUTE_QUOTA = "slack-app-project-route-quota-v1"_PATCH_ID_UNTAGGED_FOLLOWUP_CONFIRMATION = "slack-untagged-followup-confirmation-v1"+_PATCH_ID_MODEL_ROUTER = "slack-app-model-router-v1"@workflow.defn(name="posthog-code-slack-mention-processing")@@ -306,6 +309,22 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):returnrepository = self._selected_repo+ # After repo selection, so the repository can inform the pick.+ if workflow.patched(_PATCH_ID_MODEL_ROUTER):+ model_override = await _execute_posthog_code_activity(+ classify_slack_app_model_router_activity,+ SlackAppModelRouterInput(+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ slack_user_id=slack_user_id,+ user_id=user_id,+ event_text=event.get("text", ""),+ thread_ts=thread_ts,+ repository=repository,+ model_override=model_override,+ ),+ )+await _execute_posthog_code_activity(create_posthog_code_task_for_repo_activity,inputs,diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.pyindex 23758130ec3b..864eaed16ed2 100644--- a/posthog/temporal/ai/slack_app/types.py+++ b/posthog/temporal/ai/slack_app/types.py@@ -165,6 +165,17 @@ class SlackAppModelOverride(BaseModel):reasoning_effort: str | None = None+class SlackAppModelRouterInput(BaseModel):+ integration_id: int+ slack_team_id: str+ slack_user_id: str+ user_id: int+ event_text: str+ thread_ts: str | None = None+ repository: str | None = None+ model_override: SlackAppModelOverride | None = None++class SlackAppProjectRouteInput(BaseModel):"""Single-argument input for the project-route classifier activity.diff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_model_router_activity.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_model_router_activity.ambrnew file mode 100644index 000000000000..08bd62e6a319--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_model_router_activity.ambr@@ -0,0 +1,42 @@+# serializer version: 1+# name: TestRouteSlackAppModelActivity.test_request_to_the_decision_model_matches_snapshot+ dict({+ 'question': dict({+ 'criteria': dict({+ 'claude-opus-5-5': 'Claude Opus 5.5. Runtime: Claude (Anthropic). Model: A strong model for deep work. Good for large or unclear code changes, hard bugs, and research across many files. Cost per token compared to Claude Sonnet 5: 2×. Step 2 of 2 on the Claude (Anthropic) scale from fastest to smartest.',+ 'claude-sonnet-5-5': 'Claude Sonnet 5.5. Runtime: Claude (Anthropic). Model: A balanced model. Good for most code changes, bug fixes with a clear cause, and PostHog data questions. Cost per token compared to Claude Sonnet 5: 1×. Step 1 of 2 on the Claude (Anthropic) scale from fastest to smartest.',+ 'gpt-6-luna': 'GPT-6 Luna. Runtime: Codex (OpenAI). Model: A light and very cheap model. Good for short answers, lookups, summaries and very small edits. Not good for changes across many files. Cost per token compared to Claude Sonnet 5: 0.05×. Step 1 of 2 on the Codex (OpenAI) scale from fastest to smartest.',+ 'gpt-6-sol': "GPT-6 Sol. Runtime: Codex (OpenAI). Model: A general coding model. Good for most code changes and debugging. Cost per token compared to Claude Sonnet 5: 1×. Step 2 of 2 on the Codex (OpenAI) scale from fastest to smartest. This is the user's personal default.",+ }),+ 'instructions': dict({+ 'cost': 'Each option shows its cost per token compared to a baseline model.',+ 'goal': 'Pick the cheapest option that will most likely finish the task correctly on the first try. A failed run costs more than a smarter option, because the user must wait and ask again.',+ 'input': 'state.request is the Slack message that starts the task. state.repository is the code repository the task works in, or null when the task works without code.',+ 'pick_a_faster_option_when': list([+ 'The request asks a direct question with a short answer, for example a count, a definition or a link.',+ 'The request asks for one PostHog query, one insight or a summary of data.',+ 'The request asks for a small, clear edit, for example a typo, a copy change or a version bump.',+ 'state.repository is null and the request does not ask for code.',+ ]),+ 'pick_a_smarter_option_when': list([+ 'The request asks for a new feature, a refactor, or a change across many files.',+ 'The request asks to find the cause of a bug, a flaky test, a crash or a performance problem.',+ 'The request is unclear, and the agent must research the code or the data to know what to do.',+ 'The request asks for a design, a plan or a careful review.',+ ]),+ 'rules': list([+ 'Judge the work that the request needs, not the length of the message. A short message can ask for hard work.',+ 'Stay on the runtime of the default option. Change the runtime only when the other runtime has a clearly better option for this request.',+ 'Pick the top step of a scale only when the request is clearly one of the hardest tasks.',+ "When two options fit equally well, pick the user's personal default, then the project default, then the default for Slack tasks.",+ ]),+ 'task': 'Pick the model for a new task that the PostHog agent runs. The agent can change code in a repository, open pull requests, query PostHog data and change PostHog settings.',+ }),+ 'type': 'choice',+ }),+ 'state': dict({+ 'repository': 'posthog/posthog',+ 'request': 'fix the flaky checkout test',+ }),+ })+# ---diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_model_router_activity.py b/posthog/temporal/tests/ai/slack_app/activities/test_model_router_activity.pynew file mode 100644index 000000000000..10c4c5d5c12b--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/test_model_router_activity.py@@ -0,0 +1,194 @@+from collections.abc import Mapping+from contextlib import nullcontext+from dataclasses import dataclass++import pytest+from unittest.mock import MagicMock, patch++from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, SystemOneResult+from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.temporal.ai.slack_app.activities.model_router import classify_slack_app_model_router_activity+from posthog.temporal.ai.slack_app.types import SlackAppModelOverride, SlackAppModelRouterInput++from products.slack_app.backend.models import SlackSettings+from products.slack_app.backend.services.model_catalogue import ModelChoice+from products.slack_app.backend.services.model_router import PERSONAL_DEFAULT_NOTE+from products.tasks.backend.facade.ai_run_defaults import update_user_ai_run_preferences++MODULE = "posthog.temporal.ai.slack_app.activities.model_router"+OPTIONS_MODULE = "products.slack_app.backend.services.model_router"+FLAG = "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled"+SLACK_USER_ID = "U_ROUTER"++_EFFORTS = ("low", "medium", "high", "xhigh", "max")+# A fixed catalogue and ladder, so the snapshot moves when the router's own text changes+# and not each time the catalog prices or ships a model.+CHOICES = (+ ModelChoice("claude", "claude-sonnet-5-5", "Claude Sonnet 5.5", _EFFORTS, "1×"),+ ModelChoice("claude", "claude-opus-5-5", "Claude Opus 5.5", _EFFORTS, "2×"),+ ModelChoice("codex", "gpt-6-luna", "GPT-6 Luna", _EFFORTS, "0.05×"),+ ModelChoice("codex", "gpt-6-sol", "GPT-6 Sol", _EFFORTS, "1×"),+)+++@dataclass(frozen=True)+class _Notch:+ model: str+ effort: str+++LADDER = {+ "claude": (_Notch("claude-sonnet-5-5", "medium"), _Notch("claude-opus-5-5", "xhigh")),+ "codex": (_Notch("gpt-6-luna", "low"), _Notch("gpt-6-sol", "high")),+}+++def integration(db):+ organization = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=organization, name="Team")+ return Integration.objects.create(+ team=team,+ kind="slack",+ integration_id="T_ROUTER",+ sensitive_config={"access_token": "xoxb"},+ )+++def user(integration):+ return User.objects.create_and_join(integration.team.organization, "[email protected]", None)+++def _input(+ integration: Integration, user: User, override: SlackAppModelOverride | None = None+) -> SlackAppModelRouterInput:+ return SlackAppModelRouterInput(+ integration_id=integration.id,+ slack_team_id=integration.integration_id or "",+ slack_user_id=SLACK_USER_ID,+ user_id=user.id,+ event_text="fix the flaky checkout test",+ thread_ts="1700000000.000100",+ repository="posthog/posthog",+ model_override=override,+ )+++def _opt_in(integration: Integration) -> None:+ SlackSettings.objects.create(+ slack_workspace_id=integration.integration_id, slack_user_id=SLACK_USER_ID, auto_model_choice=True+ )+++def _client_picking(model: str | None = None) -> MagicMock:+ def decide(*, state: object, questions: Mapping[str, ChoiceQuestion]) -> SystemOneResult:+ criteria = questions["model"].criteria+ choice = model or next(+ key for key, description in criteria.items() if PERSONAL_DEFAULT_NOTE in str(description)+ )+ return SystemOneResult(+ model="jev",+ answers={"model": ChoiceAnswer(choice=choice, confidence=0.9, probabilities={choice: 0.9})},+ input_tokens=None,+ )++ client = MagicMock()+ client.decide.side_effect = decide+ return client+++class TestRouteSlackAppModelActivity:+ @pytest.mark.parametrize(+ "opted_in,flag_enabled,override",+ [+ (True, True, SlackAppModelOverride(model="gpt-6-sol", reasoning_effort=None)),+ (False, True, None),+ (True, False, None),+ ],+ ids=["model_named_in_mention", "not_opted_in", "flag_off"],+ )+ def test_ineligible_mention_keeps_its_override_without_asking_the_router(+ self, integration, user, opted_in, flag_enabled, override+ ):+ if opted_in:+ _opt_in(integration)+ with (+ patch(FLAG, return_value=flag_enabled),+ patch(f"{MODULE}.build_system_one_client") as build_client,+ patch(f"{MODULE}.capture_slack_event"),+ ):+ result = classify_slack_app_model_router_activity(_input(integration, user, override))++ assert result == override+ build_client.assert_not_called()++ @pytest.mark.parametrize(+ "picked,override,expected",+ [+ (None, None, SlackAppModelOverride(model="gpt-6-sol", reasoning_effort="high")),+ (+ None,+ SlackAppModelOverride(model=None, reasoning_effort="low"),+ SlackAppModelOverride(model="gpt-6-sol", reasoning_effort="low"),+ ),+ ("claude-opus-5-5", None, SlackAppModelOverride(model="claude-opus-5-5", reasoning_effort=None)),+ ],+ ids=["picks_personal_default", "effort_named_in_mention", "picks_ladder_model"],+ )+ def test_routed_mention_runs_on_the_picked_model(self, integration, user, picked, override, expected):+ _opt_in(integration)+ update_user_ai_run_preferences(+ integration.team_id, user.id, runtime_adapter="codex", model="gpt-6-sol", reasoning_effort="high"+ )+ with (+ patch(FLAG, return_value=True),+ patch(f"{MODULE}.build_system_one_client", return_value=_client_picking(picked)),+ patch(f"{MODULE}.capture_slack_event"),+ ):+ result = classify_slack_app_model_router_activity(_input(integration, user, override))++ assert result == expected++ @pytest.mark.parametrize("failing", ["decision_model", "option_building"])+ def test_router_failure_keeps_the_mention_on_its_default(self, integration, user, failing):+ _opt_in(integration)+ client = MagicMock()+ client.decide.side_effect = TimeoutError()+ broken_options = (+ patch(f"{MODULE}.model_router_options", side_effect=RuntimeError())+ if failing == "option_building"+ else nullcontext()+ )+ with (+ patch(FLAG, return_value=True),+ patch(f"{MODULE}.build_system_one_client", return_value=client),+ patch(f"{MODULE}.capture_slack_event"),+ broken_options,+ ):+ result = classify_slack_app_model_router_activity(_input(integration, user))++ assert result is None++ def test_request_to_the_decision_model_matches_snapshot(self, integration, user, snapshot):+ _opt_in(integration)+ update_user_ai_run_preferences(+ integration.team_id, user.id, runtime_adapter="codex", model="gpt-6-sol", reasoning_effort="high"+ )+ client = _client_picking()+ with (+ patch(FLAG, return_value=True),+ patch("products.tasks.backend.facade.run_config.get_model_access_error", return_value=None),+ patch(f"{OPTIONS_MODULE}.available_model_choices", return_value=CHOICES),+ patch(f"{OPTIONS_MODULE}.offered_model_choices", return_value=CHOICES),+ patch(f"{OPTIONS_MODULE}.CAPABILITY_LADDER_BY_RUNTIME_ADAPTER", LADDER),+ patch(f"{MODULE}.build_system_one_client", return_value=client),+ patch(f"{MODULE}.capture_slack_event"),+ ):+ classify_slack_app_model_router_activity(_input(integration, user))++ request = client.decide.call_args.kwargs+ assert {"state": request["state"], "question": request["questions"]["model"].to_json()} == snapshotdiff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.pyindex fe373eb7243d..a8cc43199581 100644--- a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py@@ -21,6 +21,7 @@ from posthog.temporal.ai.slack_app.types import (SlackAppMessageReactionInput,SlackAppModelOverride,SlackAppModelOverrideInput,+ SlackAppModelRouterInput,SlackAppProjectRoute,SlackAppProjectRouteInput,SlackRepoSelectionOutcome,@@ -52,6 +53,9 @@ class _Recorder:self.created: list[tuple[str, str | None]] = []# ts -> model override the classifier returns; missing means no override.self.model_overrides: dict[str, SlackAppModelOverride] = {}+ # event text -> what the model router returns; missing means it passes the override through.+ self.routed_overrides: dict[str, SlackAppModelOverride] = {}+ self.router_inputs: list[SlackAppModelRouterInput] = []# ts -> model override the create-task call actually received.self.created_with_override: dict[str, SlackAppModelOverride | None] = {}# event text -> project route the classifier returns; missing means no route.@@ -207,6 +211,11 @@ def _fake_activities(rec: _Recorder) -> list:async def classify_project_route(input: SlackAppProjectRouteInput) -> SlackAppProjectRoute | None:return rec.project_routes.get(input.event_text)+ @activity.defn(name="classify_slack_app_model_router_activity")+ async def route_model(input: SlackAppModelRouterInput) -> SlackAppModelOverride | None:+ rec.router_inputs.append(input)+ return rec.routed_overrides.get(input.event_text, input.model_override)+@activity.defn(name="create_posthog_code_task_for_repo_activity")async def create_task(inputs: PostHogCodeSlackMentionWorkflowInputs,@@ -263,6 +272,7 @@ def _fake_activities(rec: _Recorder) -> list:block_github,classify_model_override,classify_project_route,+ route_model,create_task,picker_timeout,internal_error,@@ -356,12 +366,12 @@ async def test_queued_messages_process_serially_in_arrival_order():@pytest.mark.asyncioasync def test_model_override_reaches_task_creation():- """A mention that names a model steers only its own task; the next one in the- same thread goes back to the resolved preferences."""rec = _Recorder()plain, steered = _message("1.1"), _message("1.2", text="use fable for this one")override = SlackAppModelOverride(model="claude-fable-5", reasoning_effort="high")+ routed = SlackAppModelOverride(model="gpt-6-sol", reasoning_effort="low")rec.model_overrides["use fable for this one"] = override+ rec.routed_overrides["fix the bug"] = routedrec.create_reached["1.1"] = asyncio.Event()rec.create_gates["1.1"] = asyncio.Event()@@ -372,7 +382,11 @@ async def test_model_override_reaches_task_creation():rec.create_gates["1.1"].set()await asyncio.wait_for(handle.result(), timeout=30)- assert rec.created_with_override == {"1.1": None, "1.2": override}+ assert rec.created_with_override == {"1.1": routed, "1.2": override}+ assert [(i.model_override, i.repository) for i in rec.router_inputs] == [+ (None, "org/auto-repo"),+ (override, "org/auto-repo"),+ ]@pytest.mark.asyncio@@ -417,6 +431,7 @@ async def test_model_override_reaches_a_followup_without_creating_a_task():assert rec.forwarded_with_override == {"1.1": override}assert rec.created == []+ assert rec.router_inputs == []@pytest.mark.asynciodiff --git a/products/slack_app/backend/facade/run_preferences.py b/products/slack_app/backend/facade/run_preferences.pyindex 1cb96f8f5f68..f0915aa338c0 100644--- a/products/slack_app/backend/facade/run_preferences.py+++ b/products/slack_app/backend/facade/run_preferences.py@@ -11,6 +11,11 @@ from products.slack_app.backend.services.model_catalogue import (describe_run_model,group_by_runtime,)+from products.slack_app.backend.services.model_router import (+ MODEL_ROUTER_INSTRUCTIONS,+ ModelRouterOption,+ model_router_options,+)from products.slack_app.backend.services.run_preferences import (LiveRunModelChange,find_model_choice,@@ -19,12 +24,15 @@ from products.slack_app.backend.services.run_preferences import ()__all__ = [+ "MODEL_ROUTER_INSTRUCTIONS","LiveRunModelChange","ModelChoice",+ "ModelRouterOption","available_model_choices","describe_run_model","find_model_choice","group_by_runtime",+ "model_router_options","resolve_live_run_override","resolve_run_preferences",]diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex fa71a20e1d86..a294a9f96dac 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -48,6 +48,7 @@ logger = structlog.get_logger(__name__)SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_FORKING_FLAG = "slack-app-forking"SLACK_APP_PROJECT_PICKER_FLAG = "slack-app-project-picker"+SLACK_APP_MODEL_ROUTER_FLAG = "slack-app-model-router"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -137,6 +138,16 @@ def is_slack_app_project_picker_enabled(integration: Integration, distinct_id: s)+def is_slack_app_model_router_enabled(integration: Integration, distinct_id: str | None = None) -> bool:+ """Gate for the App Home "Use auto model choice" toggle. The router also needs the toggle on."""+ return _workspace_flag_enabled(+ SLACK_APP_MODEL_ROUTER_FLAG,+ integration,+ failure_log_key="slack_app_model_router_feature_flag_check_failed",+ distinct_id=distinct_id,+ )++def is_slack_app_assistant_enabled(integration: Integration) -> bool:"""Gate for the DM assistant: the install must hold the scopes the DM surfacecalls — ``im:history`` in particular, without which the assistant would answerdiff --git a/products/slack_app/backend/migrations/0020_slacksettings_auto_model_choice.py b/products/slack_app/backend/migrations/0020_slacksettings_auto_model_choice.pynew file mode 100644index 000000000000..1e7c119bd8f6--- /dev/null+++ b/products/slack_app/backend/migrations/0020_slacksettings_auto_model_choice.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.18 on 2026-10-07 17:26++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0019_slacksettings_channel_welcome_mode"),+ ]++ operations = [+ migrations.AddField(+ model_name="slacksettings",+ name="auto_model_choice",+ field=models.BooleanField(+ blank=True,+ help_text="Let PostHog pick the model for each new task this user starts from Slack.",+ null=True,+ ),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 09c698641220..e36f82e9ade6 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0019_slacksettings_channel_welcome_mode+0020_slacksettings_auto_model_choicediff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 74a9b807bb28..d1c18b029d72 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -190,6 +190,12 @@ class SlackSettings(UUIDModel):choices=ChannelWelcomeMode.choices,help_text="Where the greeting goes when someone adds the app to a channel in this workspace.",)+ # Only read on a personal row. NULL means the user never turned it on, which resolves to off.+ auto_model_choice = models.BooleanField(+ null=True,+ blank=True,+ help_text="Let PostHog pick the model for each new task this user starts from Slack.",+ )created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/slack_app/backend/services/model_catalogue.py b/products/slack_app/backend/services/model_catalogue.pyindex 14a199896019..e55ce9562bd7 100644--- a/products/slack_app/backend/services/model_catalogue.py+++ b/products/slack_app/backend/services/model_catalogue.py@@ -13,6 +13,7 @@ against it. Neither may hardcode a model list.from __future__ import annotationsfrom products.tasks.backend.facade.model_catalogue import (+ CAPABILITY_LADDER_BY_RUNTIME_ADAPTER,COST_BASELINE_MODEL,REASONING_EFFORT_DISPLAY_NAMES,RUNTIME_ADAPTER_DISPLAY_NAMES,@@ -23,6 +24,7 @@ from products.tasks.backend.facade.model_catalogue import (filter_unsupported_effort,group_by_runtime,label_for,+ normalize_model_id,offered_model_choices,runtime_adapter_for,)@@ -52,6 +54,7 @@ def describe_run_model(model: str | None, reasoning_effort: str | None) -> str:__all__ = [+ "CAPABILITY_LADDER_BY_RUNTIME_ADAPTER","COST_BASELINE_MODEL","REASONING_EFFORT_DISPLAY_NAMES","RUNTIME_ADAPTER_DISPLAY_NAMES",@@ -64,5 +67,6 @@ __all__ = ["display_name_for_model","group_by_runtime","label_for",+ "normalize_model_id","runtime_adapter_for",]diff --git a/products/slack_app/backend/services/model_router.py b/products/slack_app/backend/services/model_router.pynew file mode 100644index 000000000000..11a7fb4efef2--- /dev/null+++ b/products/slack_app/backend/services/model_router.py@@ -0,0 +1,227 @@+"""The options the automatic model choice picks from for a new Slack task.++The router picks a model, not a reasoning effort: nothing in the first message tells how+hard the task will turn out to be. The options are the models on the capability ladder plus+the stored defaults, and not every model in the catalog, because a System One choice question+takes at most 16 options on the gateway. The decision model reads only the option text and+scores each option against its own text, so the model notes sit in each option and not once+in the instructions.+"""++from __future__ import annotations++from dataclasses import dataclass+from functools import cache++from posthog.llm.system_one import JsonValue++from products.slack_app.backend.services.model_catalogue import (+ CAPABILITY_LADDER_BY_RUNTIME_ADAPTER,+ COST_BASELINE_MODEL,+ RUNTIME_ADAPTER_DISPLAY_NAMES,+ ModelChoice,+ available_model_choices,+ display_name_for_model,+ filter_unsupported_effort,+ label_for,+ normalize_model_id,+ offered_model_choices,+)+from products.slack_app.backend.services.run_preferences import SLACK_DEFAULT_MODEL, find_model_choice++PERSONAL_DEFAULT_NOTE = "This is the user's personal default."+PROJECT_DEFAULT_NOTE = "This is the project default."+SLACK_DEFAULT_NOTE = "This is the default for Slack tasks in this project."++_LUNA_NOTE = (+ "A light and very cheap model. Good for short answers, lookups, summaries and very small edits. "+ "Not good for changes across many files."+)+_SOL_NOTE = "A general coding model. Good for most code changes and debugging."++# Keyed by id prefix, so a new version of a family gets its note without an edit. A model on+# the capability ladder must match one, or the router picks it blind.+_MODEL_NOTES: dict[str, str] = {+ "claude-sonnet": (+ "A balanced model. Good for most code changes, bug fixes with a clear cause, and PostHog data questions."+ ),+ "claude-opus": (+ "A strong model for deep work. Good for large or unclear code changes, hard bugs, "+ "and research across many files."+ ),+ "claude-fable": (+ "The most capable Claude model. Good only for the hardest problems, for example a design change "+ "across many systems or a subtle data or concurrency bug."+ ),+ "gpt-6-astra": "The most capable OpenAI model. Good only for the hardest problems.",+ "gpt-6-luna": _LUNA_NOTE,+ "gpt-5.6-luna": _LUNA_NOTE,+ "gpt-5.6-terra": "A mid-size model. Good for normal code changes with a clear goal.",+ "gpt-6-sol": _SOL_NOTE,+ "gpt-6.1-sol": _SOL_NOTE,+ "gpt-5.6-sol": _SOL_NOTE,+}++# User text stays in `state`. The instructions only name its fields, so the request cannot+# become an instruction.+MODEL_ROUTER_INSTRUCTIONS: dict[str, JsonValue] = {+ "task": (+ "Pick the model for a new task that the PostHog agent runs. "+ "The agent can change code in a repository, open pull requests, query PostHog data and change PostHog settings."+ ),+ "input": (+ "state.request is the Slack message that starts the task. "+ "state.repository is the code repository the task works in, or null when the task works without code."+ ),+ "goal": (+ "Pick the cheapest option that will most likely finish the task correctly on the first try. "+ "A failed run costs more than a smarter option, because the user must wait and ask again."+ ),+ "cost": "Each option shows its cost per token compared to a baseline model.",+ "pick_a_smarter_option_when": [+ "The request asks for a new feature, a refactor, or a change across many files.",+ "The request asks to find the cause of a bug, a flaky test, a crash or a performance problem.",+ "The request is unclear, and the agent must research the code or the data to know what to do.",+ "The request asks for a design, a plan or a careful review.",+ ],+ "pick_a_faster_option_when": [+ "The request asks a direct question with a short answer, for example a count, a definition or a link.",+ "The request asks for one PostHog query, one insight or a summary of data.",+ "The request asks for a small, clear edit, for example a typo, a copy change or a version bump.",+ "state.repository is null and the request does not ask for code.",+ ],+ "rules": [+ "Judge the work that the request needs, not the length of the message. A short message can ask for hard work.",+ "Stay on the runtime of the default option. Change the runtime only when the other runtime has "+ "a clearly better option for this request.",+ "Pick the top step of a scale only when the request is clearly one of the hardest tasks.",+ "When two options fit equally well, pick the user's personal default, then the project default, "+ "then the default for Slack tasks.",+ ],+}+++@dataclass(frozen=True)+class ModelRouterOption:+ model: str+ # The effort saved with a stored default of this model, so picking that default keeps it.+ # The decision model never sees or picks it.+ reasoning_effort: str | None+ description: str+++@dataclass(frozen=True)+class _Candidate:+ choice: ModelChoice+ reasoning_effort: str | None+ ladder_note: str | None = None+ notes: tuple[str, ...] = ()+++def _stored_default(+ preferences: dict[str, str], choices: tuple[ModelChoice, ...]+) -> tuple[ModelChoice, str | None] | None:+ """`None` when no Slack run can use the preference, because Slack runs only on ACP."""+ if preferences.get("runtime") not in (None, "", "acp"):+ return None+ model = preferences.get("model")+ choice = find_model_choice(normalize_model_id(model) if model else None, choices)+ if choice is None:+ return None+ return choice, filter_unsupported_effort(choice.runtime_adapter, choice.model, preferences.get("reasoning_effort"))+++def _model_note(model: str) -> str | None:+ return next((note for prefix, note in _MODEL_NOTES.items() if model.startswith(prefix)), None)+++def _describe(candidate: _Candidate) -> str:+ choice = candidate.choice+ parts = [+ f"{display_name_for_model(choice.model)}.",+ f"Runtime: {label_for(choice.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}.",+ ]+ if model_note := _model_note(choice.model):+ parts.append(f"Model: {model_note}")+ if choice.cost_multiplier:+ parts.append(+ f"Cost per token compared to {display_name_for_model(COST_BASELINE_MODEL)}: {choice.cost_multiplier}."+ )+ if candidate.ladder_note:+ parts.append(candidate.ladder_note)+ parts.extend(candidate.notes)+ return " ".join(parts)+++def model_router_options(+ *,+ team_id: int,+ user_id: int | None,+ distinct_id: str | None,+) -> tuple[ModelRouterOption, ...]:+ """Leaves out models the viewer may not use, so task creation never refuses the pick."""+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path+ ai_run_defaults,+ )+ from products.tasks.backend.facade.run_config import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path+ get_model_access_error,+ )++ catalog = available_model_choices()+ offered = offered_model_choices()++ @cache+ def allowed(model: str) -> bool:+ return get_model_access_error(model, distinct_id=distinct_id) is None++ candidates: dict[str, _Candidate] = {}++ def add(+ choice: ModelChoice, effort: str | None, *, ladder_note: str | None = None, note: str | None = None+ ) -> None:+ existing = candidates.get(choice.model) or _Candidate(choice=choice, reasoning_effort=effort)+ candidates[choice.model] = _Candidate(+ choice=choice,+ reasoning_effort=existing.reasoning_effort,+ ladder_note=existing.ladder_note or ladder_note,+ notes=(*existing.notes, note) if note else existing.notes,+ )++ # A stored default may name a retired model. The person chose it, so it stays an option.+ if user_id is not None:+ personal = _stored_default(ai_run_defaults.get_user_ai_run_preferences(team_id, user_id), catalog)+ if personal is not None and allowed(personal[0].model):+ add(*personal, note=PERSONAL_DEFAULT_NOTE)+ project = _stored_default(ai_run_defaults.get_team_ai_run_preferences(team_id), catalog)+ if project is not None and allowed(project[0].model):+ add(*project, note=PROJECT_DEFAULT_NOTE)+ # Without a usable stored default the run falls to Slack's own, and the tie-break needs to see it.+ if not candidates and (slack_default := find_model_choice(SLACK_DEFAULT_MODEL, catalog)) is not None:+ add(slack_default, None, note=SLACK_DEFAULT_NOTE)++ for runtime_adapter, ladder in CAPABILITY_LADDER_BY_RUNTIME_ADAPTER.items():+ runtime_label = label_for(runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)+ # The ladder repeats a model at several efforts. The router picks only the model.+ models = list(dict.fromkeys(notch.model for notch in ladder))+ for index, model in enumerate(models, start=1):+ choice = find_model_choice(model, offered)+ if choice is None:+ continue+ add(+ choice,+ None,+ ladder_note=f"Step {index} of {len(models)} on the {runtime_label} scale from fastest to smartest.",+ )++ return tuple(+ ModelRouterOption(model=c.choice.model, reasoning_effort=c.reasoning_effort, description=_describe(c))+ for c in candidates.values()+ if allowed(c.choice.model)+ )+++__all__ = [+ "MODEL_ROUTER_INSTRUCTIONS",+ "ModelRouterOption",+ "model_router_options",+]diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex acf2a2f704e2..1b50f94e6d71 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -33,7 +33,7 @@ from posthog.models.user_integration import UserIntegrationfrom posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.analytics import capture_slack_event-from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.feature_flags import is_slack_app_model_router_enabled, is_slack_app_oauth_enabledfrom products.slack_app.backend.models import (ChannelWelcomeMode,SlackSettings,@@ -70,8 +70,10 @@ from products.slack_app.backend.services.slack_app_home_stats import ()from products.slack_app.backend.services.slack_settings import (AIPreferences,+ resolve_auto_model_choice,resolve_channel_welcome_mode,resolve_untagged_followup_mode,+ set_auto_model_choice,set_channel_welcome_mode,)from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin@@ -100,6 +102,7 @@ ACTION_STATS_WINDOW = "slack_app_home:stats_window"ACTION_STATS_REFRESH = "slack_app_home:stats_refresh"ACTION_SET_UNTAGGED_FOLLOWUP_MODE = "slack_app_home:set_untagged_followup_mode"ACTION_SET_CHANNEL_WELCOME_MODE = "slack_app_home:set_channel_welcome_mode"+ACTION_SET_AUTO_MODEL_CHOICE = "slack_app_home:set_auto_model_choice"# URL buttons: Slack opens the link itself and posts a block_actions payload we# only ack — the ids exist so the clicks still reach the usage-analytics capture.ACTION_GITHUB_SETTINGS = "slack_app_home:github_settings"@@ -126,6 +129,7 @@ HOME_ACTION_IDS: frozenset[str] = frozenset(ACTION_STATS_REFRESH,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,ACTION_SET_CHANNEL_WELCOME_MODE,+ ACTION_SET_AUTO_MODEL_CHOICE,ACTION_GITHUB_SETTINGS,ACTION_CONNECT_ACCOUNT,}@@ -438,6 +442,7 @@ def render_home_view(stats_state: StatsState | None = None,untagged_followup_mode: UntaggedFollowupMode | None = None,channel_welcome_mode: ChannelWelcomeMode | None = None,+ auto_model_choice: bool | None = None,has_project_access: bool = True,account_settings_url: str | None = None,) -> dict:@@ -475,6 +480,9 @@ def render_home_view(blocks.append({"type": "divider"})blocks.extend(_active_model_blocks(run_defaults))blocks.extend(_personal_section_blocks(run_defaults))+ # `None` means the `slack-app-model-router` flag is off for this viewer.+ if auto_model_choice is not None:+ blocks.extend(_auto_model_choice_blocks(auto_model_choice))# Section 4 — thread follow-ups: whether replies other people leave in the# threads you started reach PostHog on their own.@@ -901,6 +909,42 @@ def _personal_section_blocks(run_defaults: RunDefaultsState) -> list[dict]:]+AUTO_MODEL_CHOICE_VALUE = "on"+++def _auto_model_choice_blocks(enabled: bool) -> list[dict]:+ option = {+ "text": {"type": "mrkdwn", "text": "*Use auto model choice*"},+ # Slack caps an option description at 75 characters and rejects the whole+ # `views.publish` call over it, so the caveats go in the context line below.+ "description": {+ "type": "mrkdwn",+ "text": "PostHog picks the model for each new task you start.",+ },+ "value": AUTO_MODEL_CHOICE_VALUE,+ }+ checkbox: dict[str, Any] = {+ "type": "checkboxes",+ "action_id": ACTION_SET_AUTO_MODEL_CHOICE,+ "options": [option],+ }+ if enabled:+ checkbox["initial_options"] = [option]+ return [+ _subsection_label("Auto model choice"),+ {"type": "actions", "elements": [checkbox]},+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": "A model you name in your message still wins, and follow-ups keep the model of their task.",+ }+ ],+ },+ ]++UNTAGGED_FOLLOWUP_MODE_LABELS: dict[str, str] = {UntaggedFollowupMode.AUTO: "Pick them up automatically",UntaggedFollowupMode.ASK: "Ask them first",@@ -1656,6 +1700,19 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResporepublish()return HttpResponse(status=200)+ if action_id == ACTION_SET_AUTO_MODEL_CHOICE:+ # A stale view must not turn the router on for someone the flag no longer covers.+ if _auto_model_choice_offered(integration, slack_user_id):+ enabled = any(+ option.get("value") == AUTO_MODEL_CHOICE_VALUE for option in action.get("selected_options") or []+ )+ set_auto_model_choice(integration.integration_id, slack_user_id, enabled)+ capture_slack_event(+ integration, "slack app auto model choice toggled", slack_user_id=slack_user_id, enabled=enabled+ )+ republish()+ return HttpResponse(status=200)+if action_id == ACTION_SET_CHANNEL_WELCOME_MODE:slack = SlackIntegration(integration)if not _is_admin(slack, integration, slack_user_id):@@ -2035,7 +2092,7 @@ def _clear_project_personal(integration: Integration, slack_user_id: str) -> Non).first()if row is None:return- if not row.untagged_followup_mode:+ if not row.untagged_followup_mode and not row.auto_model_choice:row.delete()returnrow.default_integration = None@@ -2097,6 +2154,11 @@ def _build_home_view(stats_state=stats_state,untagged_followup_mode=resolve_untagged_followup_mode(integration, slack_user_id),channel_welcome_mode=resolve_channel_welcome_mode(integration.integration_id) if is_admin else None,+ auto_model_choice=(+ resolve_auto_model_choice(integration.integration_id, slack_user_id)+ if _auto_model_choice_offered(integration, slack_user_id)+ else None+ ),has_project_access=bool(accessible),# The same settings page the GitHub card deep-links to.account_settings_url=github_state.settings_url,@@ -2344,6 +2406,13 @@ def _resolve_run_defaults_state()+def _auto_model_choice_offered(integration: Integration, slack_user_id: str) -> bool:+ home_user = _resolve_home_user(integration, slack_user_id)+ if home_user is None:+ return False+ return is_slack_app_model_router_enabled(integration, distinct_id=home_user.distinct_id)++def _resolve_account_state(integration: Integration, slack_user_id: str) -> AccountState:slack_team_id = integration.integration_idif not is_slack_app_oauth_enabled(integration):diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pyindex 93bf68b50a8c..7b6cdc4bdf82 100644--- a/products/slack_app/backend/services/slack_settings.py+++ b/products/slack_app/backend/services/slack_settings.py@@ -1,6 +1,6 @@"""Read helpers for per-(Slack workspace, Slack user) settings backed by-`models.SlackSettings` (today: the untagged follow-up mode and the channel-welcome mode), plus the shared+`models.SlackSettings` (today: the untagged follow-up mode, the channel+welcome mode and the automatic model choice), plus the sharedAI-triple value object.Model preferences themselves live in the central tasks config@@ -97,9 +97,34 @@ def set_channel_welcome_mode(slack_workspace_id: str, mode: ChannelWelcomeMode))+def resolve_auto_model_choice(slack_workspace_id: str, slack_user_id: str | None) -> bool:+ if not slack_user_id:+ return False++ from products.slack_app.backend.models import SlackSettings++ return bool(+ SlackSettings.objects.filter(slack_workspace_id=slack_workspace_id, slack_user_id=slack_user_id)+ .values_list("auto_model_choice", flat=True)+ .first()+ )+++def set_auto_model_choice(slack_workspace_id: str, slack_user_id: str, enabled: bool) -> None:+ from products.slack_app.backend.models import SlackSettings++ SlackSettings.objects.update_or_create(+ slack_workspace_id=slack_workspace_id,+ slack_user_id=slack_user_id,+ defaults={"auto_model_choice": enabled},+ )++__all__ = ["AIPreferences",+ "resolve_auto_model_choice","resolve_channel_welcome_mode",+ "set_auto_model_choice","set_channel_welcome_mode","resolve_untagged_followup_mode",]diff --git a/products/slack_app/backend/tests/services/test_model_router.py b/products/slack_app/backend/tests/services/test_model_router.pynew file mode 100644index 000000000000..b9a556501119--- /dev/null+++ b/products/slack_app/backend/tests/services/test_model_router.py@@ -0,0 +1,66 @@+import pytest+from unittest.mock import patch++from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.slack_app.backend.services.model_router import (+ PERSONAL_DEFAULT_NOTE,+ SLACK_DEFAULT_NOTE,+ model_router_options,+)+from products.slack_app.backend.services.run_preferences import SLACK_DEFAULT_MODEL+from products.tasks.backend.facade.ai_run_defaults import update_user_ai_run_preferences+from products.tasks.backend.facade.model_catalogue import CAPABILITY_LADDER_BY_RUNTIME_ADAPTER++ACCESS_ERROR = "products.tasks.backend.facade.run_config.get_model_access_error"+++def team(db):+ organization = Organization.objects.create(name="Org")+ return Team.objects.create(organization=organization, name="Team")+++class TestModelRouterOptions:+ def test_options_leave_out_a_model_the_viewer_may_not_use(self, team):+ with patch(+ ACCESS_ERROR,+ side_effect=lambda model, distinct_id: "gated" if model.startswith("claude-") else None,+ ):+ options = model_router_options(team_id=team.id, user_id=None, distinct_id="viewer")++ assert options+ assert not [option for option in options if option.model.startswith("claude-")]+ assert len({option.model for option in options}) == len(options)++ def test_every_ladder_option_says_what_its_model_is_good_for(self, team):+ with patch(ACCESS_ERROR, return_value=None):+ options = model_router_options(team_id=team.id, user_id=None, distinct_id="viewer")++ ladder = {notch.model for notches in CAPABILITY_LADDER_BY_RUNTIME_ADAPTER.values() for notch in notches}+ unexplained = [+ option.model for option in options if option.model in ladder and "Model: " not in option.description+ ]+ assert unexplained == []++ @pytest.mark.parametrize(+ "stored_model,gated_model,expected_default,expected_note",+ [+ ("openai/gpt-6-sol", None, "gpt-6-sol", PERSONAL_DEFAULT_NOTE),+ ("gpt-6-sol", "gpt-6-sol", SLACK_DEFAULT_MODEL, SLACK_DEFAULT_NOTE),+ ],+ ids=["provider_qualified_default", "gated_default_falls_to_slack_default"],+ )+ def test_marks_the_default_the_run_would_use(+ self, team, stored_model, gated_model, expected_default, expected_note+ ):+ user = User.objects.create_and_join(team.organization, "[email protected]", None)+ update_user_ai_run_preferences(+ team.id, user.id, runtime_adapter="codex", model=stored_model, reasoning_effort=None+ )+ with patch(ACCESS_ERROR, side_effect=lambda model, distinct_id: "gated" if model == gated_model else None):+ options = model_router_options(team_id=team.id, user_id=user.id, distinct_id="viewer")++ assert [option.model for option in options if expected_note in option.description] == [expected_default]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 94f415d96dea..4bfd58c1b1d0 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@@ -39,6 +39,7 @@ from products.slack_app.backend.services.slack_app_home import (ACTION_EDIT_PERSONAL,ACTION_RESET_PERSONAL,ACTION_RESET_PROJECT_PERSONAL,+ ACTION_SET_AUTO_MODEL_CHOICE,ACTION_SET_CHANNEL_WELCOME_MODE,ACTION_SET_PROJECT_WORKSPACE,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,@@ -46,6 +47,7 @@ from products.slack_app.backend.services.slack_app_home import (ACTION_TASKS_PAGE_NEXT,ACTION_TASKS_PAGE_PREV,ACTION_UNLINK_ACCOUNT,+ AUTO_MODEL_CHOICE_VALUE,BLOCK_TASKS_CONTROLS,EDIT_MODAL_PERSONAL_CALLBACK_ID,HOME_ACTION_IDS,@@ -284,6 +286,23 @@ def _find_block(view: dict, block_prefix: str) -> dict | None:return None+def _option_objects(view: dict) -> list[dict]:+ out: list[dict] = []++ def walk(node):+ if isinstance(node, dict):+ for key, value in node.items():+ if key in ("options", "initial_options") and isinstance(value, list):+ out.extend(option for option in value if isinstance(option, dict))+ walk(value)+ elif isinstance(node, list):+ for item in node:+ walk(item)++ walk(view["blocks"])+ return out++def _all_text(view: dict) -> str:"""Flatten all `text` fields for substring assertions."""out: list[str] = []@@ -421,11 +440,8 @@ class TestRenderHomeView:assert "Claude Opus 4.7" in text_blobassert "Your PostHog default" in _all_text(view)- def test_every_control_the_tab_renders_is_routable(self):- # The interactivity endpoint claims region ownership and dispatches off- # HOME_ACTION_IDS, so a control missing from it renders as a button that- # silently does nothing. Render every card at once and check the whole set.- view = render_home_view(+ def _every_card_view(self, *, auto_model_choice: bool = False) -> dict:+ return render_home_view(is_admin=True,run_defaults=RunDefaultsState(model="claude-opus-4-7", runtime_adapter="claude", source="user"),account_state=AccountState(enabled=True, link_url="https://app/link"),@@ -458,13 +474,36 @@ class TestRenderHomeView:stats_state=StatsState(tasks_started=4, tasks_with_pr=2, tasks_merged=1, active_people=2),untagged_followup_mode=UntaggedFollowupMode.AUTO,channel_welcome_mode=ChannelWelcomeMode.CHANNEL,+ auto_model_choice=auto_model_choice,)+ def test_every_control_the_tab_renders_is_routable(self):+ # The interactivity endpoint claims region ownership and dispatches off+ # HOME_ACTION_IDS, so a control missing from it renders as a button that+ # silently does nothing. Render every card at once and check the whole set.+ view = self._every_card_view()+# Equality both ways: an unroutable control fails on the left, and a card that# stopped rendering fails on the right instead of passing a subset check trivially.# Unlink only renders once an account is linked, which this fixture deliberately isn't.assert set(_action_ids(view)) == HOME_ACTION_IDS - {ACTION_UNLINK_ACCOUNT}+ @pytest.mark.parametrize("auto_model_choice", [False, True])+ def test_every_option_stays_within_the_limits_slack_enforces(self, auto_model_choice):+ # `views.publish` validates the whole payload, so one over-long label or+ # description costs the entire tab: Slack returns `invalid_arguments` and the+ # viewer keeps whatever was published last. Checked options carry a second copy+ # of the option object under `initial_options`, hence both renders.+ view = self._every_card_view(auto_model_choice=auto_model_choice)++ oversized = [+ (option["value"], field, len(option[field]["text"]))+ for option in _option_objects(view)+ for field, limit in (("text", 75), ("description", 75))+ if field in option and len(option[field]["text"]) > limit+ ]+ assert oversized == []+class TestThreadFollowupsCard:def _view(self, mode) -> dict:@@ -524,6 +563,47 @@ class TestThreadFollowupsPicker:assert mock_slack_client.views_publish.called+class TestAutoModelChoiceToggle:+ def _toggle(self, checked: bool) -> dict:+ selected = [{"value": AUTO_MODEL_CHOICE_VALUE}] if checked else []+ return {+ "type": "block_actions",+ "team": {"id": SLACK_WORKSPACE_ID},+ "user": {"id": "U001"},+ "actions": [{"action_id": ACTION_SET_AUTO_MODEL_CHOICE, "selected_options": selected}],+ }++ @pytest.mark.parametrize(+ "flag_enabled,checked,expected",+ [+ (True, True, True),+ (True, False, False),+ # A view rendered before the flag turned off must not opt anyone in.+ (False, True, None),+ ],+ )+ def test_toggle_is_stored_for_the_clicking_user_only_while_the_flag_is_on(+ self, slack_integration, mock_slack_client, flag_enabled, checked, expected+ ):+ User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)+ SlackUserProfileCache.objects.create(+ integration=slack_integration, slack_user_id="U001", email="[email protected]"+ )+ payload = self._toggle(checked)+ with (+ patch(+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=flag_enabled,+ ),+ patch("products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin", return_value=False),+ ):+ handle_ai_preferences_block_action(payload, payload["actions"][0])++ row = SlackSettings.objects.filter(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001").first()+ assert (row.auto_model_choice if row else None) == expected+ assert mock_slack_client.views_publish.called++class TestChannelWelcomePicker:def test_card_is_hidden_from_non_admins(self):view = render_home_view(is_admin=False, channel_welcome_mode=ChannelWelcomeMode.CHANNEL)@@ -1300,15 +1380,20 @@ class TestResetPersonal:class TestResetProjectPersonal:+ @pytest.mark.parametrize(+ "other_settings",+ [{"untagged_followup_mode": UntaggedFollowupMode.AUTO}, {"auto_model_choice": True}],+ ids=["followup_mode", "auto_model_choice"],+ )def test_clears_routing_only_when_other_settings_present(- self, slack_integration, mock_slack_client, flag_on, admin_user+ self, slack_integration, mock_slack_client, flag_on, admin_user, other_settings):- # Mixed row → reset clears routing, the follow-up mode stays.+ # Mixed row → reset clears routing, the other setting stays.SlackSettings.objects.create(default_integration=slack_integration,slack_workspace_id=SLACK_WORKSPACE_ID,slack_user_id="U001",- untagged_followup_mode=UntaggedFollowupMode.AUTO,+ **other_settings,)payload = _block_action_payload(action_id=ACTION_RESET_PROJECT_PERSONAL,@@ -1319,7 +1404,7 @@ class TestResetProjectPersonal:row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")assert row.default_integration_id is None- assert row.untagged_followup_mode == UntaggedFollowupMode.AUTO+ assert {field: getattr(row, field) for field in other_settings} == other_settingsassert mock_slack_client.views_publish.calleddef test_deletes_row_when_no_other_settings_remain(self, slack_integration, mock_slack_client, flag_on, admin_user):diff --git a/products/tasks/backend/facade/model_catalogue.py b/products/tasks/backend/facade/model_catalogue.pyindex 25ae490fd977..59817ac99062 100644--- a/products/tasks/backend/facade/model_catalogue.py+++ b/products/tasks/backend/facade/model_catalogue.py@@ -24,8 +24,10 @@ from products.tasks.backend.logic.services.model_catalogue import (offered_model_choices,runtime_adapter_for,)+from products.tasks.backend.model_catalog import CAPABILITY_LADDER_BY_RUNTIME_ADAPTER, normalize_model_id__all__ = [+ "CAPABILITY_LADDER_BY_RUNTIME_ADAPTER","COST_BASELINE_MODEL","REASONING_EFFORT_DISPLAY_NAMES","RUNTIME_ADAPTER_DISPLAY_NAMES",@@ -39,6 +41,7 @@ __all__ = ["filter_unsupported_effort","group_by_runtime","label_for",+ "normalize_model_id","offered_model_choices","runtime_adapter_for",]