: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): pick the run's model from the mention text (#77250)
Vojta Bartoš887a2949ca50
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.pyindex 220a81131850..a6dfc9f910cb 100644--- a/posthog/temporal/ai/slack_app/__init__.py+++ b/posthog/temporal/ai/slack_app/__init__.py@@ -13,6 +13,7 @@ from posthog.temporal.ai.slack_app.activities import (cascade_posthog_code_repository_activity,classify_message_is_agent_directed,classify_posthog_code_task_needs_repo_activity,+ classify_slack_app_model_override_activity,classify_untagged_followup_activity,collect_posthog_code_thread_messages_activity,create_posthog_code_routing_rule_activity,@@ -46,6 +47,8 @@ from posthog.temporal.ai.slack_app.types import (PostHogSlackInboxOnboardingInputs,SlackAppMentionWorkflowInputs,SlackAppMessageReactionInput,+ SlackAppModelOverride,+ SlackAppModelOverrideInput,SlackRepoSelectionOutcome,)@@ -57,6 +60,7 @@ SLACK_APP_ACTIVITIES = [cascade_posthog_code_repository_activity,discover_posthog_code_repository_via_agent_activity,classify_posthog_code_task_needs_repo_activity,+ classify_slack_app_model_override_activity,enforce_posthog_code_billing_quota_activity,post_posthog_code_no_repos_activity,post_posthog_code_repo_picker_activity,@@ -90,11 +94,14 @@ __all__ = ["PostHogSlackInboxOnboardingInputs","SLACK_APP_ACTIVITIES","SlackAppMentionWorkflowInputs",+ "SlackAppModelOverride",+ "SlackAppModelOverrideInput","SlackRepoSelectionOutcome","block_posthog_code_task_if_no_personal_github_activity","cascade_posthog_code_repository_activity","classify_message_is_agent_directed","classify_posthog_code_task_needs_repo_activity",+ "classify_slack_app_model_override_activity","classify_untagged_followup_activity","collect_posthog_code_thread_messages_activity","create_posthog_code_routing_rule_activity",diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.pyindex 60e9bb59c368..503d963f9077 100644--- a/posthog/temporal/ai/slack_app/activities/__init__.py+++ b/posthog/temporal/ai/slack_app/activities/__init__.py@@ -3,6 +3,8 @@ from posthog.temporal.ai.slack_app.activities.classifiers import (CLASSIFIER_THREAD_HISTORY_MESSAGES,classify_message_is_agent_directed,classify_posthog_code_task_needs_repo_activity,+ classify_slack_app_model_override,+ classify_slack_app_model_override_activity,classify_task_needs_repo,classify_untagged_followup_activity,)@@ -51,6 +53,8 @@ __all__ = ["cascade_posthog_code_repository_activity","classify_message_is_agent_directed","classify_posthog_code_task_needs_repo_activity",+ "classify_slack_app_model_override",+ "classify_slack_app_model_override_activity","classify_task_needs_repo","classify_untagged_followup_activity","collect_posthog_code_thread_messages_activity",diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.pyindex 8949e11d47be..944701f75659 100644--- a/posthog/temporal/ai/slack_app/activities/classifiers.py+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py@@ -1,19 +1,47 @@import re-import jsonimport structlog+from openai.types.shared_params import ResponseFormatJSONSchema+from pydantic import ValidationErrorfrom temporalio import activityfrom posthog.llm.gateway_client import get_llm_client-from posthog.models.integration import SlackIntegration-from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs+from posthog.llm.semantic_enrichment import extract_json_object+from posthog.models.integration import Integration, SlackIntegration+from posthog.temporal.ai.slack_app.types import (+ PostHogCodeSlackMentionWorkflowInputs,+ SlackAppModelOverride,+ SlackAppModelOverrideInput,+)from posthog.temporal.common.utils import close_db_connections+from products.slack_app.backend.facade.run_preferences import (+ ModelChoice,+ available_model_choices,+ find_model_choice,+ is_slack_app_model_classifier_enabled,+)from products.slack_app.backend.models import SlackThreadTaskMappinglogger = structlog.get_logger(__name__)CLASSIFIER_THREAD_HISTORY_MESSAGES = 10+CLASSIFIER_MODEL = "claude-haiku-4-5-20251001"+# The override classifier runs on a reasoning model, which draws its reasoning from the+# same token budget as the reply. The reply itself is one short JSON object; the headroom+# is for the thinking in front of it, and a truncated turn reads as an unusable reply and+# falls back to saved preferences.+MODEL_OVERRIDE_CLASSIFIER_MODEL = "gpt-5.6-luna"+MODEL_OVERRIDE_MAX_TOKENS = 2048+# The gateway client defaults to a 600s read and two retries of its own, which is the+# right shape for a generation call and the wrong one here: this classifier gates task+# creation, and its answer is optional — any failure falls back to saved preferences. Left+# unbounded it never gets to fall back, because the activity's own 600s deadline expires+# first and fails the mention outright. Bounding the retries matters as much as the+# deadline: the activity is sync, so a thread Temporal has stopped waiting on keeps+# blocking until the client itself returns. Measured mean is ~1.7s per call.+MODEL_OVERRIDE_TIMEOUT_SECONDS = 10.0+MODEL_OVERRIDE_MAX_RETRIES = 1def classify_task_needs_repo(@@ -122,15 +150,12 @@ def classify_task_needs_repo(try:client = get_llm_client("slack_app_routing")response = client.chat.completions.create(- model="claude-haiku-4-5-20251001",+ model=CLASSIFIER_MODEL,messages=[{"role": "user", "content": prompt}],max_tokens=64,temperature=0,)- content = (response.choices[0].message.content or "").strip()- if content.startswith("```"):- content = content.strip("`").removeprefix("json").strip()- parsed = json.loads(content)+ parsed = extract_json_object(response.choices[0].message.content or "") or {}# Haiku occasionally stringifies the bool ({"needs_repo": "false"}).# bool("false") is True, which would flip the defensive bias — handle# strings explicitly and treat any other unexpected shape as False.@@ -215,15 +240,12 @@ def classify_message_is_agent_directed(try:client = get_llm_client("slack_app_routing")response = client.chat.completions.create(- model="claude-haiku-4-5-20251001",+ model=CLASSIFIER_MODEL,messages=[{"role": "user", "content": prompt}],max_tokens=64,temperature=0,)- content = (response.choices[0].message.content or "").strip()- if content.startswith("```"):- content = content.strip("`").removeprefix("json").strip()- parsed = json.loads(content)+ parsed = extract_json_object(response.choices[0].message.content or "") or {}return bool(parsed.get("agent_directed", False))except Exception:logger.exception("classify_message_is_agent_directed_failed")@@ -290,3 +312,171 @@ def classify_untagged_followup_activity(slack_user_id=slack_user_id,)return False+++def _model_override_response_format(choices: tuple[ModelChoice, ...]) -> ResponseFormatJSONSchema:+ """A strict JSON schema pinning the reply to the result shape.++ The `model` enum is the point: it removes the classifier's ability to name a model+ this workspace can't drive, which the prompt could only ask for and+ ``find_model_choice`` could only catch after the fact.++ `reasoning_effort` stays an unconstrained string. Which efforts are valid depends on+ the model the run finally lands on, not on the catalogue-wide union, so it is settled+ once where the preferences are resolved — constraining it here would move that+ decision to the wrong place.+ """+ return {+ "type": "json_schema",+ "json_schema": {+ "name": "slack_app_model_override",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {+ "model": {"type": ["string", "null"], "enum": [*(c.model for c in choices), None]},+ "reasoning_effort": {"type": ["string", "null"]},+ },+ "required": ["model", "reasoning_effort"],+ "additionalProperties": False,+ },+ },+ }+++def _render_model_catalogue(choices: tuple[ModelChoice, ...]) -> str:+ lines = []+ for choice in choices:+ efforts = ", ".join(choice.supported_efforts) if choice.supported_efforts else "no effort setting"+ lines.append(f"- {choice.model} — {choice.label} (efforts: {efforts})")+ return "\n".join(lines)+++def classify_slack_app_model_override(+ event_text: str,+ choices: tuple[ModelChoice, ...],+) -> SlackAppModelOverride | None:+ """Read a per-task model or reasoning-effort request out of a Slack mention.++ Returns ``None`` when the author asked for neither — which is the overwhelming+ majority of mentions, and the answer we fall back to on any parse, validation, or+ LLM failure. The cost of a miss is that the run uses the author's saved+ preferences, so every ambiguity resolves that way.++ The hard part is not spotting a model name; it is telling an instruction ("use+ fable for this") from subject matter ("add fable to the model picker"). The+ prompt is built around that distinction, and the schema restricts the answer to an+ id from ``choices``.++ Quality on that distinction is measured by the eval suite in+ ``products/slack_app/evals/eval_model_classifier.py`` — the unit tests around this+ function cover parsing and validation, not whether the prompt reads a sentence right.+ """+ prompt = (+ "You are routing a Slack message addressed to the PostHog agent. Decide whether "+ "the author asked for THIS task to run on a particular model or reasoning "+ "effort.\n\n"+ "Only these models can be selected — copy the id exactly as written:\n"+ f"{_render_model_catalogue(choices)}\n\n"+ "Name a model or effort only when the message instructs how to run this task:\n"+ ' - "use fable for this one", "run this on opus 5", "do this with max effort".\n'+ " - The instruction can sit alongside the actual request: 'use sonnet and fix "+ "the flaky checkout test'.\n\n"+ "Answer with nulls when a model or effort is merely part of the subject "+ "matter — this is the common mistake, so check for it:\n"+ ' - "add claude-fable-5 to our model picker" (a code change that names a model).\n'+ ' - "why is gpt-5 slower than opus in our evals?" (a question about models).\n'+ ' - "the opus rollout broke the dashboard" (a topic).\n'+ ' - "reasoning about this is hard" (the word, not a setting).\n\n'+ "Rules for the fields:\n"+ " - model: an id from the list above, or null if the author named no model (or "+ "named one that isn't listed).\n"+ " - reasoning_effort: only when the author explicitly asks for an effort level, "+ "and only a value listed for that model. Otherwise null.\n"+ " - An effort can be requested without a model, and a model without an effort.\n\n"+ "When you are unsure, answer with nulls — the author's saved default is the "+ "right thing to run.\n\n"+ f"Message: {event_text}\n\n"+ 'Answer with the two fields, e.g. {"model": "claude-fable-5", "reasoning_effort": '+ '"high"} or {"model": null, "reasoning_effort": null}'+ )++ try:+ client = get_llm_client("slack_app_routing").with_options(+ timeout=MODEL_OVERRIDE_TIMEOUT_SECONDS, max_retries=MODEL_OVERRIDE_MAX_RETRIES+ )+ response = client.chat.completions.create(+ model=MODEL_OVERRIDE_CLASSIFIER_MODEL,+ messages=[{"role": "user", "content": prompt}],+ max_tokens=MODEL_OVERRIDE_MAX_TOKENS,+ response_format=_model_override_response_format(choices),+ )+ # Tolerant parse on top of the schema on purpose: the gateway fronts several+ # providers and does not honour a response format identically on every route, so+ # a reply that arrives fenced still lands rather than failing the mention.+ parsed = extract_json_object(response.choices[0].message.content or "")+ # The reply has the same shape as the result, so it parses straight into it —+ # but the model is still the classifier's word, not ours, until checked against+ # the catalogue below.+ reply = SlackAppModelOverride.model_validate(parsed)+ except (ValidationError, ValueError):+ logger.info("slack_app_model_override_unusable_reply")+ return None+ except Exception:+ logger.exception("slack_app_model_override_classify_failed")+ return None++ choice = find_model_choice(reply.model, choices)+ if reply.model and choice is None:+ # The classifier was told to copy an id from the list; anything else is a+ # hallucination or a model we can't drive. Either way, don't act on it.+ logger.info("slack_app_model_override_unknown_model", requested_model=reply.model)++ # The effort rides through unchecked: which efforts a model supports depends on the+ # model the run finally lands on, so it is settled once, where the preferences are+ # resolved, rather than guessed against the catalogue-wide union here.+ if choice is None and not reply.reasoning_effort:+ return None+ return SlackAppModelOverride(model=choice.model if choice else None, reasoning_effort=reply.reasoning_effort)+++@close_db_connections+def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:+ """Resolve the model the mention asked for, or ``None`` to use saved preferences.++ Runs as its own activity rather than inside task creation so the choice is+ recorded in workflow history once: task creation retries, and re-running a+ classifier there could hand the second attempt a different model.++ Every mention behind the flag reaches the classifier. A keyword pre-filter would+ save the Haiku call on the majority that name no model, but it also decides — on+ a substring match — which phrasings can ever steer a run, and that judgement+ belongs to the model reading the sentence, not to a word list.+ """+ integration = Integration.objects.select_related("team").get(+ id=input.integration_id,+ kind="slack",+ integration_id=input.slack_team_id,+ )+ if not is_slack_app_model_classifier_enabled(integration):+ return None++ choices = available_model_choices()+ if not choices:+ # The gateway is the source of truth for what can run; with no catalogue we+ # cannot validate a request, and guessing is worse than doing nothing.+ logger.info("slack_app_model_override_empty_catalogue", integration_id=input.integration_id)+ return None++ override = classify_slack_app_model_override(input.event_text, choices)+ if override is None:+ return None++ logger.info(+ "slack_app_model_override_classified",+ integration_id=input.integration_id,+ model=override.model,+ reasoning_effort=override.reasoning_effort,+ )+ return overridediff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 37c8c286ca19..62c8f0cb57ef 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -16,7 +16,7 @@ from posthog.temporal.ai.slack_app.attachments import (prepare_slack_file_artifacts,)from posthog.temporal.ai.slack_app.helpers import block_if_team_over_quota, safe_react-from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs, SlackAppModelOverridefrom posthog.temporal.common.utils import close_db_connectionslogger = structlog.get_logger(__name__)@@ -31,11 +31,6 @@ _SLACK_RECOVERY_STRATEGY_CANCELLED = "cancelled_resume"_THREAD_CONTEXT_TAG = "slack_thread_context"_THREAD_CONTEXT_UPDATE_TAG = "slack_thread_context_update"_INITIATOR_PLACEHOLDER = "<original user message was here>"-# Default the Slack bot to Opus 5 when neither the user nor the workspace has-# pinned a model, instead of letting the agent server fall back to its own-# default. Kept together as a valid (runtime_adapter, model) pair.-_SLACK_DEFAULT_RUNTIME_ADAPTER = "claude"-_SLACK_DEFAULT_MODEL = "claude-opus-5"_SLACK_DELIVERY_CONSTRAINTS = """Slack delivery constraints:- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.@@ -522,6 +517,7 @@ def create_posthog_code_task_for_repo_activity(repository: str | None,repo_research_task_id: str | None = None,repo_research_run_id: str | None = None,+ model_override: SlackAppModelOverride | None = None,) -> None:from posthog.models.integration import Integration, SlackIntegration@@ -637,15 +633,9 @@ 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+ from products.slack_app.backend.facade.run_preferences import resolve_run_preferences- ai_prefs = resolve_ai_preferences(integration, slack_user_id)-- # `resolve_ai_preferences` guarantees runtime_adapter and model are set together,- # so falling back on both keeps the pair consistent — an explicit override wins,- # otherwise the Slack bot defaults to Opus 5.- runtime_adapter = ai_prefs.runtime_adapter or _SLACK_DEFAULT_RUNTIME_ADAPTER- model = ai_prefs.model or _SLACK_DEFAULT_MODEL+ run_prefs = resolve_run_preferences(integration, slack_user_id, override=model_override)# File into the creator's personal "#me" channel so the task surfaces in PostHog Desktop's# Spaces feed, which is strictly channel-scoped — a NULL-channel task shows up in no space.@@ -675,9 +665,9 @@ def create_posthog_code_task_for_repo_activity(start_workflow=False,posthog_mcp_scopes="full",initial_permission_mode="bypassPermissions",- runtime_adapter=runtime_adapter,- model=model,- reasoning_effort=ai_prefs.reasoning_effort,+ runtime_adapter=run_prefs.runtime_adapter,+ model=run_prefs.model,+ reasoning_effort=run_prefs.reasoning_effort,channel_id=personal_channel_id,)except Exception as e:diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.pyindex ce3839b76de8..6360e1a3ba7e 100644--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py@@ -9,9 +9,11 @@ from temporalio.common import RetryPolicyfrom posthog.temporal.ai.slack_app import (POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,PostHogCodeSlackMentionWorkflowInputs,+ SlackAppModelOverrideInput,block_posthog_code_task_if_no_personal_github_activity,cascade_posthog_code_repository_activity,classify_posthog_code_task_needs_repo_activity,+ classify_slack_app_model_override_activity,classify_untagged_followup_activity,collect_posthog_code_thread_messages_activity,create_posthog_code_task_for_repo_activity,@@ -30,8 +32,9 @@ from posthog.temporal.common.base import PostHogWorkflowPOSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS = 10 * 60POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15-# Temporal patch ID — an arbitrary string recorded in workflow history.+# Temporal patch IDs — arbitrary strings recorded in workflow history._PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS = "slack-file-only-followup-bypass-v1"+_PATCH_ID_MODEL_CLASSIFIER = "slack-app-model-classifier-v1"@workflow.defn(name="posthog-code-slack-mention-processing")@@ -305,6 +308,22 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):returnelif await _gate_on_personal_github(inputs, channel, thread_ts, user_id):return+ # Read a per-task model choice ("use fable for this one") out of the+ # mention. Runs here, past every gate that can still abandon the+ # mention, so the reply announcing the model only ever describes a task+ # that gets created. The feature flag is checked inside the activity —+ # branching the workflow on a flag would be non-deterministic on replay.+ model_override = None+ if workflow.patched(_PATCH_ID_MODEL_CLASSIFIER):+ model_override = await _execute_posthog_code_activity(+ classify_slack_app_model_override_activity,+ SlackAppModelOverrideInput(+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ event_text=event.get("text", ""),+ ),+ )+await _execute_posthog_code_activity(create_posthog_code_task_for_repo_activity,inputs,@@ -317,6 +336,7 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):repository,repo_research_task_id,repo_research_run_id,+ model_override,)except Exception as exc:workflow.logger.exception(diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.pyindex 27b0885ab112..6f7fd510e8e6 100644--- a/posthog/temporal/ai/slack_app/types.py+++ b/posthog/temporal/ai/slack_app/types.py@@ -107,6 +107,29 @@ class SlackAppMessageReactionInput(BaseModel):message_ts: str+class SlackAppModelOverrideInput(BaseModel):+ """Single-argument input for the model-override classifier activity."""++ integration_id: int+ slack_team_id: str+ event_text: str+++class SlackAppModelOverride(BaseModel):+ """A per-task model choice read out of the mention text.++ ``model`` is always a live catalogue id (the classifier picks from a list and+ the activity drops anything that isn't on it); ``reasoning_effort`` is a known+ effort value that still has to be checked against whichever model the task ends+ up on. Either field may be absent — "run this with max effort" names no model,+ "use fable" names no effort. The merge onto the resolved preferences happens at+ the point of use, in ``resolve_run_preferences``.+ """++ model: str | None = None+ reasoning_effort: str | None = None++@dataclassclass PostHogCodeSlackMentionCommandWorkflowInputs:event: dict[str, Any]diff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_model_override.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_model_override.ambrnew file mode 100644index 000000000000..c91e6699f21a--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_slack_app_model_override.ambr@@ -0,0 +1,32 @@+# serializer version: 1+# name: TestClassifySlackAppModelOverride.test_prompt_snapshot_matches+ '''+ You are routing a Slack message addressed to the PostHog agent. Decide whether the author asked for THIS task to run on a particular model or reasoning effort.++ Only these models can be selected — copy the id exactly as written:+ - claude-opus-5 — Claude Opus 5 (efforts: low, medium, high, max)+ - claude-fable-5 — Claude Fable 5 (efforts: low, medium, high)+ - gpt-5.6-sol — gpt-5.6-sol (efforts: low, medium, high, max)++ Name a model or effort only when the message instructs how to run this task:+ - "use fable for this one", "run this on opus 5", "do this with max effort".+ - The instruction can sit alongside the actual request: 'use sonnet and fix the flaky checkout test'.++ Answer with nulls when a model or effort is merely part of the subject matter — this is the common mistake, so check for it:+ - "add claude-fable-5 to our model picker" (a code change that names a model).+ - "why is gpt-5 slower than opus in our evals?" (a question about models).+ - "the opus rollout broke the dashboard" (a topic).+ - "reasoning about this is hard" (the word, not a setting).++ Rules for the fields:+ - model: an id from the list above, or null if the author named no model (or named one that isn't listed).+ - reasoning_effort: only when the author explicitly asks for an effort level, and only a value listed for that model. Otherwise null.+ - An effort can be requested without a model, and a model without an effort.++ When you are unsure, answer with nulls — the author's saved default is the right thing to run.++ Message: use fable for this one and fix the checkout test++ Answer with the two fields, e.g. {"model": "claude-fable-5", "reasoning_effort": "high"} or {"model": null, "reasoning_effort": null}+ '''+# ---diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_model_override.py b/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_model_override.pynew file mode 100644index 000000000000..1ee241a7abeb--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_model_override.py@@ -0,0 +1,159 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.ai.slack_app.activities.classifiers import classify_slack_app_model_override+from posthog.temporal.ai.slack_app.posthog_code_slack_mention import POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS++from products.slack_app.backend.services.model_catalogue import ModelChoice++CHOICES = (+ ModelChoice("claude", "claude-opus-5", "Claude Opus 5", ("low", "medium", "high", "max")),+ ModelChoice("claude", "claude-fable-5", "Claude Fable 5", ("low", "medium", "high")),+ ModelChoice("codex", "gpt-5.6-sol", "gpt-5.6-sol", ("low", "medium", "high", "max")),+)+++class TestClassifySlackAppModelOverride:+ @parameterized.expand(+ [+ (+ "model_and_effort",+ '{"model": "claude-fable-5", "reasoning_effort": "high"}',+ "claude-fable-5",+ "high",+ ),+ (+ "model_only",+ '{"model": "claude-fable-5", "reasoning_effort": null}',+ "claude-fable-5",+ None,+ ),+ # An effort can be asked for without naming a model; the model the run+ # already had stays, and the merge happens at the point of use.+ ("effort_only", '{"model": null, "reasoning_effort": "max"}', None, "max"),+ # Haiku replies are not reliably unfenced through the gateway.+ (+ "fenced_json",+ '```json\n{"model": "claude-fable-5", "reasoning_effort": null}\n```',+ "claude-fable-5",+ None,+ ),+ ("case_insensitive_id", '{"model": "Claude-Fable-5"}', "claude-fable-5", None),+ # An effort the chosen model can't do is dropped where the run's preferences+ # are resolved, not here, so it survives the classifier untouched.+ (+ "model_with_unsupported_effort",+ '{"model": "claude-fable-5", "reasoning_effort": "turbo"}',+ "claude-fable-5",+ "turbo",+ ),+ ]+ )+ def test_returns_requested_choice(self, _name, content, expected_model, expected_effort):+ override = self._classify("use fable for this", content)+ assert override is not None+ assert override.model == expected_model+ assert override.reasoning_effort == expected_effort++ @parameterized.expand(+ [+ # The common case: a mention that merely names a model is not an instruction,+ # and nulls are how the classifier says so.+ ("both_null", '{"model": null, "reasoning_effort": null}'),+ ("fields_missing", "{}"),+ # A model we can't drive is a hallucination or an unsupported ask; either+ # way the run must fall back to the resolved preferences.+ ("unknown_model", '{"model": "gemini-3-pro", "reasoning_effort": null}'),+ ("empty_reply", ""),+ ("prose_reply", "I think they want fable."),+ ("wrong_types", '{"model": 5, "reasoning_effort": []}'),+ ]+ )+ def test_returns_none(self, _name, content):+ assert self._classify("use fable for this", content) is None++ def test_llm_failure_falls_back_to_no_override(self):+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ side_effect=RuntimeError("boom"),+ ):+ assert classify_slack_app_model_override("use fable for this", CHOICES) is None++ def test_reply_is_pinned_to_the_live_catalogue(self):+ """The schema, not the prompt, is what stops the classifier naming a model this+ workspace can't drive. Asking for it in prose was the old guarantee and it only+ held as far as the model chose to cooperate; if the request stops carrying the+ enum, `find_model_choice` silently becomes the only thing standing between a+ hallucinated id and a dropped override.+ """+ fake_client = self._fake_client('{"model": null, "reasoning_effort": null}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=fake_client,+ ):+ classify_slack_app_model_override("use fable for this", CHOICES)++ kwargs = fake_client.chat.completions.create.call_args.kwargs+ schema = kwargs["response_format"]["json_schema"]+ assert schema["strict"] is True+ assert schema["schema"]["properties"]["model"]["enum"] == [+ "claude-opus-5",+ "claude-fable-5",+ "gpt-5.6-sol",+ None,+ ]+ # Which efforts a model supports depends on the model the run lands on, so the+ # effort is deliberately left open here and settled where preferences resolve.+ assert "enum" not in schema["schema"]["properties"]["reasoning_effort"]++ def test_call_is_bounded_so_a_slow_gateway_falls_back(self):+ # The gateway client's own defaults are a 600s read and two retries. Unbounded,+ # the activity's 600s deadline expires first, so the mention fails outright+ # instead of taking the fallback this classifier is built around.+ fake_client = self._fake_client('{"model": null, "reasoning_effort": null}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=fake_client,+ ):+ classify_slack_app_model_override("use fable for this", CHOICES)++ assert fake_client.with_options.called, "the classifier must bound the gateway client"+ options = fake_client.with_options.call_args.kwargs+ assert options["timeout"] < POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS+ assert options["max_retries"] * options["timeout"] < POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS++ def test_prompt_snapshot_matches(self, snapshot):+ """The prompt is the whole classifier — the catalogue it offers, the+ instruction-vs-subject-matter examples, and the reply contract. Pinning it means+ a reworded rule shows up as a reviewable diff in the ``.ambr`` snapshot rather+ than as a silent behaviour change. Update intentionally by re-running with+ ``--snapshot-update`` after auditing the diff.+ """+ assert self._render_prompt("use fable for this one and fix the checkout test") == snapshot++ def _render_prompt(self, text: str) -> str:+ fake_client = self._fake_client('{"model": null, "reasoning_effort": null}')+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=fake_client,+ ):+ classify_slack_app_model_override(text, CHOICES)+ return fake_client.chat.completions.create.call_args.kwargs["messages"][0]["content"]++ def _fake_client(self, content: str) -> MagicMock:+ response = MagicMock()+ response.choices = [MagicMock(message=MagicMock(content=content))]+ client = MagicMock()+ # `with_options` returns a configured copy, so the fake hands back itself to keep+ # one set of call records no matter how the call site bounds the client.+ client.with_options.return_value = client+ client.chat.completions.create.return_value = response+ return client++ def _classify(self, text: str, content: str):+ with patch(+ "posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client",+ return_value=self._fake_client(content),+ ):+ return classify_slack_app_model_override(text, CHOICES)diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py b/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.pynew file mode 100644index 000000000000..4480709fc54c--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py@@ -0,0 +1,83 @@+"""Gate tests for ``classify_slack_app_model_override_activity``.++The classifier's own prompt/parse behaviour is covered in+``posthog/temporal/tests/ai/test_classify_slack_app_model_override.py``. What+matters here is what guards it: the feature flag and an unreachable model+catalogue, each of which must produce "no override" without the LLM ever being+called.+"""++import pytest+from unittest.mock import patch++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.temporal.ai.slack_app.activities.classifiers import classify_slack_app_model_override_activity+from posthog.temporal.ai.slack_app.types import SlackAppModelOverride, SlackAppModelOverrideInput++from products.slack_app.backend.services.model_catalogue import ModelChoice++CATALOGUE = (ModelChoice("claude", "claude-fable-5", "Claude Fable 5", ("low", "medium", "high")),)++ACTIVITY_MODULE = "posthog.temporal.ai.slack_app.activities.classifiers"+++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_WS",+ sensitive_config={"access_token": "xoxb"},+ )+++def _input(integration: Integration, text: str) -> SlackAppModelOverrideInput:+ return SlackAppModelOverrideInput(+ integration_id=integration.id,+ slack_team_id=integration.integration_id or "",+ event_text=text,+ )+++class TestClassifySlackAppModelOverrideActivity:+ @pytest.mark.parametrize(+ "flag_on,catalogue",+ [+ (False, CATALOGUE),+ # The gateway is the source of truth for what can run; with no catalogue+ # there is nothing to validate a request against.+ (True, ()),+ ],+ )+ def test_gates_return_no_override_without_calling_the_llm(self, integration, flag_on, catalogue):+ with (+ patch(f"{ACTIVITY_MODULE}.is_slack_app_model_classifier_enabled", return_value=flag_on),+ patch(f"{ACTIVITY_MODULE}.available_model_choices", return_value=catalogue),+ patch(f"{ACTIVITY_MODULE}.classify_slack_app_model_override") as classify,+ ):+ result = classify_slack_app_model_override_activity(_input(integration, "use fable for this one"))+ assert result is None+ classify.assert_not_called()++ @pytest.mark.parametrize(+ "classified",+ [+ # No keyword gate stands in front of the classifier, so deciding a mention+ # carries no model instruction is the model's call, not a word list's.+ None,+ SlackAppModelOverride(model="claude-fable-5", reasoning_effort="high"),+ ],+ )+ def test_passes_the_mention_to_the_classifier_and_returns_its_verdict(self, integration, classified):+ with (+ patch(f"{ACTIVITY_MODULE}.is_slack_app_model_classifier_enabled", return_value=True),+ patch(f"{ACTIVITY_MODULE}.available_model_choices", return_value=CATALOGUE),+ patch(f"{ACTIVITY_MODULE}.classify_slack_app_model_override", return_value=classified) as classify,+ ):+ text = "fix the flaky checkout test"+ assert classify_slack_app_model_override_activity(_input(integration, text)) == classified+ classify.assert_called_once_with(text, CATALOGUE)diff --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 27473f2080cd..31cdbb8ad1a3 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@@ -19,6 +19,8 @@ from posthog.temporal.ai.slack_app.types import (PostHogCodeSlackMentionWorkflowInputs,SlackAppMentionWorkflowInputs,SlackAppMessageReactionInput,+ SlackAppModelOverride,+ SlackAppModelOverrideInput,SlackRepoSelectionOutcome,)@@ -28,9 +30,10 @@ def _message(*,event_id: str | None = None,untagged: bool = False,+ text: str = "fix the bug",) -> PostHogCodeSlackMentionWorkflowInputs:return PostHogCodeSlackMentionWorkflowInputs(- event={"channel": "C1", "ts": ts, "thread_ts": "100.0", "user": "U1", "text": "fix the bug"},+ event={"channel": "C1", "ts": ts, "thread_ts": "100.0", "user": "U1", "text": text},integration_id=1,slack_team_id="T1",slack_event_id=event_id,@@ -43,6 +46,10 @@ class _Recorder:def __init__(self) -> None:# (ts, repository) per create-task call, in execution order.self.created: list[tuple[str, str | None]] = []+ # ts -> model override the classifier returns; missing means no override.+ self.model_overrides: dict[str, SlackAppModelOverride] = {}+ # ts -> model override the create-task call actually received.+ self.created_with_override: dict[str, SlackAppModelOverride | None] = {}# ts per hourglass reaction (message queued behind another), in execution order.self.queued_marked: list[str] = []# ts per hourglass->eyes reaction swap, in execution order.@@ -159,6 +166,10 @@ def _fake_activities(rec: _Recorder) -> list:) -> bool:return False+ @activity.defn(name="classify_slack_app_model_override_activity")+ async def classify_model_override(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:+ return rec.model_overrides.get(input.event_text)+@activity.defn(name="create_posthog_code_task_for_repo_activity")async def create_task(inputs: PostHogCodeSlackMentionWorkflowInputs,@@ -171,8 +182,10 @@ def _fake_activities(rec: _Recorder) -> list:repository: str | None,repo_research_task_id: str | None = None,repo_research_run_id: str | None = None,+ model_override: SlackAppModelOverride | None = None,) -> None:ts = inputs.event["ts"]+ rec.created_with_override[ts] = model_overridereached = rec.create_reached.get(ts)if reached:reached.set()@@ -220,6 +233,7 @@ def _fake_activities(rec: _Recorder) -> list:post_picker,resolve_authorship,block_github,+ classify_model_override,create_task,picker_timeout,authorship_timeout,@@ -313,6 +327,27 @@ async def test_queued_messages_process_serially_in_arrival_order():assert rec.processing_marked == ["1.1", "1.2", "1.3"]+async 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")+ rec.model_overrides["use fable for this one"] = override+ rec.create_reached["1.1"] = asyncio.Event()+ rec.create_gates["1.1"] = asyncio.Event()++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", plain)+ await asyncio.wait_for(rec.create_reached["1.1"].wait(), timeout=30)+ await handle.signal(SlackAppMentionWorkflow.new_message, steered)+ 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}++@pytest.mark.asyncioasync def test_signal_with_start_on_running_workflow_signals_same_run():rec = _Recorder()diff --git a/products/posthog_ai/eval_harness/test/test_slack_app_scorers.py b/products/posthog_ai/eval_harness/test/test_slack_app_scorers.pynew file mode 100644index 000000000000..ddc8dbb389ce--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_slack_app_scorers.py@@ -0,0 +1,76 @@+from __future__ import annotations++from parameterized import parameterized++from products.slack_app.evals.model_classifier_scorers import EXPECTATION_KEY, ModelOverrideMatch, NoUnaskedOverride++ASKS_FOR_FABLE = {EXPECTATION_KEY: {"model": "claude-fable-5", "reasoning_effort": None}}+ASKS_FOR_NOTHING = {EXPECTATION_KEY: {"model": None, "reasoning_effort": None}}+++def _output(model: str | None = None, effort: str | None = None) -> dict:+ return {"override": {"model": model, "reasoning_effort": effort}}+++class TestModelOverrideMatch:+ @parameterized.expand(+ [+ ("both_fields_right", _output("claude-fable-5"), ASKS_FOR_FABLE, 1.0),+ # Right model, wrong effort is still not what the author asked for — scoring+ # the fields independently would report this as a half-success.+ (+ "right_model_wrong_effort",+ _output("claude-fable-5", "max"),+ ASKS_FOR_FABLE,+ 0.0,+ ),+ ("wrong_model", _output("claude-opus-5"), ASKS_FOR_FABLE, 0.0),+ ("missed_the_instruction", {"override": None}, ASKS_FOR_FABLE, 0.0),+ # A declined override and an explicit pair of nulls mean the same thing+ # downstream, so they must score the same.+ ("declined_reads_as_nulls", {"override": None}, ASKS_FOR_NOTHING, 1.0),+ ("nulls_read_as_declined", _output(), ASKS_FOR_NOTHING, 1.0),+ ]+ )+ def test_scores(self, _name, output, expected, want):+ assert ModelOverrideMatch().eval(output=output, expected=expected).score == want++ def test_classifier_error_is_a_failure_not_a_skip(self):+ score = ModelOverrideMatch().eval(output={"override": None, "error": "boom"}, expected=ASKS_FOR_FABLE)+ assert score.score == 0.0+++class TestNoUnaskedOverride:+ """The suite's headline metric, so its denominator has to be right.++ It reports a rate over mentions that name a model without asking for one. If it ever+ starts scoring the instruction cases too, the rate stays high for the wrong reason —+ diluted by cases that were never at risk of this failure.+ """++ @parameterized.expand(+ [+ ("invented_a_model", _output("claude-fable-5"), 0.0),+ ("invented_an_effort", _output(None, "max"), 0.0),+ ("left_it_alone", _output(), 1.0),+ ("declined", {"override": None}, 1.0),+ ]+ )+ def test_scores_subject_matter_cases(self, _name, output, want):+ assert NoUnaskedOverride().eval(output=output, expected=ASKS_FOR_NOTHING).score == want++ @parameterized.expand(+ [+ ("obeyed", _output("claude-fable-5")),+ ("missed", {"override": None}),+ ]+ )+ def test_skips_cases_that_ask_for_an_override(self, _name, output):+ assert NoUnaskedOverride().eval(output=output, expected=ASKS_FOR_FABLE).score is None++ def test_skips_on_classifier_error(self):+ """An erroring call returns no override, which looks like the safe answer — but+ counting it as one would let a wholly broken classifier post a perfect rate.+ """+ score = NoUnaskedOverride().eval(output={"override": None, "error": "boom"}, expected=ASKS_FOR_NOTHING)+ assert score.score is Nonediff --git a/products/slack_app/backend/facade/run_preferences.py b/products/slack_app/backend/facade/run_preferences.pynew file mode 100644index 000000000000..011825368062--- /dev/null+++ b/products/slack_app/backend/facade/run_preferences.py@@ -0,0 +1,19 @@+"""Facade re-exports for resolving which model a Slack-triggered run uses.++Cross-product callers (the Temporal activities under `posthog/temporal/`) import from+here rather than reaching into `services/`. Kept separate from `facade/slack_settings.py`+because that one is about stored per-(workspace, user) settings, while this is about the+catalogue those settings pick from and the precedence that resolves them for one run.+"""++from products.slack_app.backend.feature_flags import is_slack_app_model_classifier_enabled+from products.slack_app.backend.services.model_catalogue import ModelChoice, available_model_choices+from products.slack_app.backend.services.run_preferences import find_model_choice, resolve_run_preferences++__all__ = [+ "ModelChoice",+ "available_model_choices",+ "find_model_choice",+ "is_slack_app_model_classifier_enabled",+ "resolve_run_preferences",+]diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex d4f3a7c81210..b16e1f262373 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -35,6 +35,7 @@ SLACK_APP_ASSISTANT_FLAG = "slack-app-assistant"SLACK_APP_BOT_PRS_FLAG = "slack-app-bot-prs"SLACK_APP_LIVING_ARTIFACTS_FLAG = "slack-app-living-artifacts"SLACK_APP_CANVAS_FILE_ARTIFACTS_FLAG = "slack-app-canvas-file-artifacts"+SLACK_APP_MODEL_CLASSIFIER_FLAG = "slack-app-model-classifier"UNTAGGED_THREAD_FOLLOWUPS_FLAG = "posthog-slack-app-untagged-thread-followups"@@ -92,6 +93,32 @@ def is_slack_app_home_enabled(integration: Integration) -> bool:return False+def is_slack_app_model_classifier_enabled(integration: Integration) -> bool:+ """Gate for reading a one-off model choice out of the mention text ("use fable+ for this one") and running that task on it. Keyed on the Slack workspace ++ PostHog org, matching the other Slack-app gates.++ Independent of ``slack-app-home``: an override applies whether or not the+ workspace has opted into the settings tab."""+ try:+ return bool(+ posthoganalytics.feature_enabled(+ SLACK_APP_MODEL_CLASSIFIER_FLAG,+ f"slack_workspace:{integration.integration_id}",+ groups={"organization": str(integration.team.organization_id)},+ person_properties=_region_properties(),+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception(+ "slack_app_model_classifier_feature_flag_check_failed",+ integration_id=integration.id,+ )+ return False++def is_slack_app_agent_design_enabled(integration: Integration) -> bool:"""Gate for the agent-design plan-block streaming surface on Slack task runs.Keyed on the Slack workspace + PostHog org, matching ``is_slack_app_home_enabled``."""diff --git a/products/slack_app/backend/services/model_catalogue.py b/products/slack_app/backend/services/model_catalogue.pynew file mode 100644index 000000000000..78c44eff63da--- /dev/null+++ b/products/slack_app/backend/services/model_catalogue.py@@ -0,0 +1,191 @@+"""Which models a Slack-triggered run may use, and how to name them.++The catalogue is the live LLM-gateway model list for the `slack_app` product+(`llm_models`) intersected with the runtime adapters the tasks product knows how to+drive. Anything the gateway serves under a provider we can't route — bedrock, vertex —+is dropped rather than offered.++This is the single source for both consumers: the App Home picker renders it as a+Block Kit dropdown tree, and `model_override` matches a model named in a Slack mention+against it. Neither may hardcode a model list, and neither owns the display labels.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+++def _runtime_adapter_by_provider() -> dict[str, str]:+ """Gateway `owned_by` → tasks runtime adapter.++ Inverted from the tasks product's own adapter → provider mapping rather than+ written out here, so the two can never disagree about which runtime serves a+ provider. Providers with no adapter (bedrock, vertex) are simply absent, which is+ what drops their models from the catalogue.+ """+ # Deferred because `facade.run_config` re-exports from a module that imports the+ # tasks ORM, mcp_store, and sandbox config at import time; keeping that off the+ # slack_app import path is the reason, and the App Home tests' `sys.modules` swap+ # depends on it staying that way.+ from products.tasks.backend.facade.run_config import ( # noqa: PLC0415+ RuntimeAdapter,+ get_provider_for_runtime_adapter,+ )++ by_provider = {}+ for adapter in RuntimeAdapter:+ provider = get_provider_for_runtime_adapter(adapter)+ if provider is not None:+ by_provider[provider.value] = adapter.value+ return by_provider+++# 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)",+}++# Vendor initialisms that must not be title-cased into "Gpt".+_MODEL_ACRONYMS: dict[str, str] = {"gpt": "GPT", "glm": "GLM"}++REASONING_EFFORT_DISPLAY_NAMES: dict[str, str] = {+ "low": "Low",+ "medium": "Medium",+ "high": "High",+ "xhigh": "Extra high",+ "max": "Max",+ "ultracode": "Ultracode",+}+++@dataclass(frozen=True)+class ModelChoice:+ """One model a Slack run may use, with the efforts that model supports."""++ runtime_adapter: str+ model: str+ label: str+ supported_efforts: tuple[str, ...]+++def available_model_choices() -> tuple[ModelChoice, ...]:+ """Every model a Slack-triggered run may use.++ Empty when the gateway is unreachable — callers must treat that as "no choice to+ offer" rather than falling back to a hardcoded list, so a gateway outage can't+ route a run to a model the gateway would reject anyway.+ """+ from products.slack_app.backend.services.llm_models import list_slack_app_models # noqa: PLC0415+ from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts # noqa: PLC0415++ by_provider = _runtime_adapter_by_provider()+ choices = []+ for model in list_slack_app_models():+ runtime_adapter = by_provider.get(model.owned_by)+ if runtime_adapter is None:+ continue+ choices.append(+ ModelChoice(+ runtime_adapter=runtime_adapter,+ model=model.id,+ label=format_model_id(model.id),+ supported_efforts=tuple(e.value for e in get_supported_reasoning_efforts(runtime_adapter, model.id)),+ )+ )+ return tuple(choices)+++def runtime_adapter_for(model: str | None) -> str | None:+ """Which runtime drives this model, per the tasks catalogue.++ The adapter is a property of the model rather than an independent choice, so+ deriving it is what keeps a `(runtime_adapter, model)` pair from ever disagreeing.+ `None` for a model the tasks product has no runtime for.+ """+ from products.tasks.backend.facade.run_config import RuntimeAdapter, get_models_for_runtime_adapter # noqa: PLC0415++ if not model:+ return None+ normalized = model.strip().lower()+ for adapter in RuntimeAdapter:+ if any(known.lower() == normalized for known in get_models_for_runtime_adapter(adapter)):+ return adapter.value+ return None+++def filter_unsupported_effort(runtime_adapter: str | None, model: str | None, effort: str | None) -> str | None:+ """Drop an effort the given model doesn't support (e.g. a user saved `high` on a+ thinking model and then picked a non-thinking one).++ The single answer to "is this effort legal for this pair" — the stored-row resolver+ in `slack_settings` and the run resolver in `run_preferences` both route through it.+ """+ from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts # noqa: PLC0415++ if not effort:+ return None+ return effort if effort in {e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)} else None+++def format_model_id(model_id: str) -> str:+ """Turn a gateway model id into a display name: `Claude Opus 4.8`, `GPT-5.6 Sol`.++ Every family goes through the same rules — strip the provider prefix, glue a+ version onto a leading acronym, title-case the rest — so a new model is named+ without anyone touching a lookup table.+ """+ clean = model_id+ for provider in _runtime_adapter_by_provider():+ if clean.startswith(f"{provider}/"):+ clean = clean[len(provider) + 1 :]+ break++ # Collapse `4-8` into `4.8` so version components survive the dash split.+ words = re.split(r"[-_]", re.sub(r"(\d)-(\d)", r"\1.\2", clean))+ acronym = _MODEL_ACRONYMS.get(words[0].lower())+ if acronym is None:+ return " ".join(_titled(word) for word in words)+ # `gpt` + `5.6` reads as `GPT-5.6`, the way the vendor writes it, with any+ # remaining qualifier ("sol", "codex", "mini") as its own word.+ head = f"{acronym}-{words[1]}" if len(words) > 1 else acronym+ return " ".join([head, *(_titled(word) for word in words[2:])])+++def _titled(word: str) -> str:+ """Capitalise a name part, leaving bare version numbers alone."""+ if re.fullmatch(r"[0-9.]+", word):+ return word+ return word[:1].upper() + word[1:].lower()+++def label_for(value: str | None, mapping: dict[str, str]) -> str:+ """Display name for a stored value, falling back to the value itself."""+ if not value:+ return "—"+ return mapping.get(value, value)+++def describe_run_model(model: str | None, reasoning_effort: str | None) -> str:+ """Render the model a run is on, in one phrasing shared by the App Home card and+ the progress message in the Slack thread."""+ label = format_model_id(model) if model else "—"+ if not reasoning_effort:+ return f"*{label}*"+ return f"*{label}* · Reasoning: *{label_for(reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}*"+++__all__ = [+ "REASONING_EFFORT_DISPLAY_NAMES",+ "RUNTIME_ADAPTER_DISPLAY_NAMES",+ "ModelChoice",+ "available_model_choices",+ "describe_run_model",+ "filter_unsupported_effort",+ "format_model_id",+ "label_for",+ "runtime_adapter_for",+]diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.pynew file mode 100644index 000000000000..d64998742e40--- /dev/null+++ b/products/slack_app/backend/services/run_preferences.py@@ -0,0 +1,121 @@+"""Which model a Slack-triggered run actually uses.++One precedence chain, resolved in one place: a model named in the mention itself+("use fable for this one") beats the personal row, which beats the workspace row,+which falls back to the Slack default. `slack_settings` owns the personal-vs-workspace+half; this module owns the ends — the default underneath and the mention override on+top — so no caller has to assemble a triple by hand.++The triple is not three independent values. The runtime adapter follows from the+model, and which reasoning efforts exist depends on that pair, so every result is+built through `_coherent_preferences` rather than field by field. A model named in a+mention additionally has to be in the live catalogue (`model_catalogue`) — the same+set the App Home picker offers — so an override can never select something the picker+itself would refuse.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Protocol++from products.slack_app.backend.services.model_catalogue import (+ ModelChoice,+ available_model_choices,+ filter_unsupported_effort,+ runtime_adapter_for,+)+from products.slack_app.backend.services.slack_settings import AIPreferences, resolve_ai_preferences++if TYPE_CHECKING:+ from posthog.models.integration import Integration++# What a Slack run uses when neither the user nor the workspace has pinned a model.+# Chosen here rather than left to the agent server so the App Home card and the run+# itself agree on what "unset" means.+SLACK_DEFAULT_MODEL = "claude-opus-5"+++class ModelOverride(Protocol):+ """What a mention asked for. Structural so the Temporal payload satisfies it+ without this module importing anything from `posthog/temporal/`."""++ model: str | None+ reasoning_effort: str | None+++def _coherent_preferences(+ model: str | None,+ reasoning_effort: str | None,+ *,+ fallback_runtime_adapter: str | None,+) -> AIPreferences:+ """Assemble the one self-consistent triple for a model.++ The runtime adapter is derived rather than passed in, and an effort the pair+ doesn't support is dropped. `fallback_runtime_adapter` covers a model the tasks+ catalogue no longer lists, where a stored adapter is the best information left.+ """+ runtime_adapter = runtime_adapter_for(model) or fallback_runtime_adapter+ effort = filter_unsupported_effort(+ runtime_adapter, model, reasoning_effort.strip().lower() if reasoning_effort else None+ )+ return AIPreferences(runtime_adapter=runtime_adapter, model=model, reasoning_effort=effort)+++def resolve_run_preferences(+ integration: Integration,+ slack_user_id: str | None,+ *,+ override: ModelOverride | None = None,+) -> AIPreferences:+ """Resolve the full chain for one Slack-triggered run.++ A model named in the mention replaces the pair outright: an effort saved against+ the previous model must not ride along onto a different one. An effort named on its+ own applies to whichever model the run was already going to use. Either can be+ absent, and a request we can't honour — a model that isn't on offer, an effort the+ model doesn't support — leaves the run on its saved preferences.++ Note that `resolve_ai_preferences` yields nothing at all for a workspace that+ hasn't enabled `slack-app-home`, so there the chain is the Slack default plus+ whatever the mention asked for.+ """+ override_model = override.model if override else None+ override_effort = override.reasoning_effort if override else None++ if override_model:+ # Only a model named in the mention needs the catalogue, and the saved rows+ # can't influence the result, so neither is read on the other paths.+ choice = find_model_choice(override_model, available_model_choices())+ if choice is not None:+ return _coherent_preferences(choice.model, override_effort, fallback_runtime_adapter=choice.runtime_adapter)++ saved = resolve_ai_preferences(integration, slack_user_id)+ base = _coherent_preferences(+ saved.model or SLACK_DEFAULT_MODEL,+ saved.reasoning_effort,+ fallback_runtime_adapter=saved.runtime_adapter,+ )+ if not override_effort:+ return base++ # An effort this model can't do is dropped by `_coherent_preferences`; falling back+ # to `base` rather than to the stripped result means an impossible ask leaves the+ # run alone instead of quietly clearing the saved effort as well.+ requested = _coherent_preferences(base.model, override_effort, fallback_runtime_adapter=base.runtime_adapter)+ return requested if requested.reasoning_effort else base+++def find_model_choice(model: str | None, choices: tuple[ModelChoice, ...]) -> ModelChoice | None:+ """Match a requested model id against the catalogue, case-insensitively."""+ if not model:+ return None+ normalized = model.strip().lower()+ return next((c for c in choices if c.model.lower() == normalized), None)+++__all__ = [+ "SLACK_DEFAULT_MODEL",+ "find_model_choice",+ "resolve_run_preferences",+]diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex cfef901cb703..ad5f562f618a 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -32,6 +32,15 @@ from posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.feature_flags import is_slack_app_home_enabled, is_slack_app_oauth_enabledfrom products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.slack_app.backend.services.model_catalogue import (+ REASONING_EFFORT_DISPLAY_NAMES,+ RUNTIME_ADAPTER_DISPLAY_NAMES,+ available_model_choices,+ describe_run_model,+ format_model_id,+ label_for,+)+from products.slack_app.backend.services.run_preferences import SLACK_DEFAULT_MODELfrom products.slack_app.backend.services.slack_app_home_stats import (DEFAULT_STATS_WINDOW_DAYS,OUTCOME_CANCELLED,@@ -113,50 +122,6 @@ 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:@@ -179,48 +144,27 @@ class PickerAdapter: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()-+ """Group the model catalogue into the runtime → model → effort tree the modal's+ linked dropdowns render. Adapters with no available models are omitted entirely."""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+ for choice in available_model_choices():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)+ PickerEffort(value=e, label=label_for(e, REASONING_EFFORT_DISPLAY_NAMES)) for e in choice.supported_efforts)- by_adapter.setdefault(adapter_value, []).append(- PickerModel(value=gm.id, label=_format_model_id(gm.id, owned_by=gm.owned_by), supported_efforts=efforts)+ by_adapter.setdefault(choice.runtime_adapter, []).append(+ PickerModel(value=choice.model, label=choice.label, supported_efforts=efforts))return tuple(PickerAdapter(value=adapter_value,- label=RUNTIME_ADAPTER_DISPLAY_NAMES.get(adapter_value) or adapter_value,+ label=label_for(adapter_value, RUNTIME_ADAPTER_DISPLAY_NAMES),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():@@ -500,15 +444,6 @@ def _static_select(return element-def _provider_for_runtime_adapter(runtime_adapter: str | None) -> str:- """The gateway `owned_by` a runtime adapter implies — the inverse of- `_PROVIDER_TO_RUNTIME_ADAPTER`, so the two can't drift when an adapter is added."""- for provider, adapter in _PROVIDER_TO_RUNTIME_ADAPTER.items():- if adapter == runtime_adapter:- return provider- return "anthropic"--def _header_blocks() -> list[dict]:return [_section_title(@@ -521,8 +456,8 @@ 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 Slack bot defaults to Opus 5 (pinned in the task- creation activity); the user can still override it here.+ With nothing set the run falls back to the Slack default, named here from the+ same constant the run resolves against so the card can't drift from it."""header = _section_title("🤖 AI model",@@ -537,26 +472,28 @@ def _active_model_blocks(effective: AIPreferences, source: PreferenceSource) ->"type": "section","text": {"type": "mrkdwn",- "text": "Defaulting to Opus 5. Pick personal or workspace settings to override.",+ "text": (+ f"Defaulting to {format_model_id(SLACK_DEFAULT_MODEL)}. "+ "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 ""- )+ runtime_label = label_for(effective.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)return [header,{"type": "section","text": {"type": "mrkdwn",- "text": f"Currently running *{model_label}* · {runtime_label}{effort_part}",+ # Same phrasing as the notice a mention override posts, so the card and+ # the thread describe a run the same way.+ "text": (+ f"Currently running "+ f"{describe_run_model(effective.model, effective.reasoning_effort)} · {runtime_label}"+ ),},},source_blurb,@@ -1146,7 +1083,7 @@ def _bar(value: int, peak: int, width: int = _STATS_BAR_WIDTH) -> str:def _stats_model_label(usage: ModelUsage) -> str:"""Display label for a model, truncated so the bar column stays aligned."""- label = _format_model_id(usage.model, owned_by=_provider_for_runtime_adapter(usage.runtime_adapter))+ label = format_model_id(usage.model)return _truncate(label, _STATS_COLUMN_LABEL_CHARS)@@ -1174,13 +1111,12 @@ def _stats_footnote_blocks(state: StatsState) -> list[dict]:def _row_summary(row: SlackSettings | None) -> str:if not row or not row.runtime_adapter or not row.model:return "_(none)_"- owned_by = _provider_for_runtime_adapter(row.runtime_adapter)parts = [- f"*Model:* {_format_model_id(row.model, owned_by=owned_by)}",- f"*Runtime:* {_label(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",+ f"*Model:* {format_model_id(row.model)}",+ f"*Runtime:* {label_for(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",]if row.reasoning_effort:- parts.append(f"*Reasoning:* {_label(row.reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}")+ parts.append(f"*Reasoning:* {label_for(row.reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}")return " · ".join(parts)@@ -1263,7 +1199,7 @@ def render_edit_modal(if supported_efforts:effort_options = [{- "text": {"type": "plain_text", "text": _label(v, REASONING_EFFORT_DISPLAY_NAMES), "emoji": True},+ "text": {"type": "plain_text", "text": label_for(v, REASONING_EFFORT_DISPLAY_NAMES), "emoji": True},"value": v,}for v in supported_efforts@@ -2047,7 +1983,7 @@ def _resolve_project_state(.first())- def _label(c: Integration) -> str:+ def project_label(c: Integration) -> str:return f"{c.team.organization.name} · {c.team.name}"# Look up the workspace default's label against the full candidate list,@@ -2060,10 +1996,10 @@ def _resolve_project_state()workspace_team_label: str | None = Noneif workspace_team_id is not None:- workspace_team_label = next((_label(c) for c in candidates if c.team_id == workspace_team_id), None)+ workspace_team_label = next((project_label(c) for c in candidates if c.team_id == workspace_team_id), None)return ProjectState(- candidates=tuple(ProjectChoice(team_id=c.team_id, label=_label(c)) for c in accessible),+ candidates=tuple(ProjectChoice(team_id=c.team_id, label=project_label(c)) for c in accessible),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,diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pyindex c7048d20f738..31fa34322a06 100644--- a/products/slack_app/backend/services/slack_settings.py+++ b/products/slack_app/backend/services/slack_settings.py@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING, Anyfrom django.db.models import Qfrom products.slack_app.backend.feature_flags import is_slack_app_home_enabled+from products.slack_app.backend.services.model_catalogue import filter_unsupported_effortif TYPE_CHECKING:from posthog.models.integration import Integration@@ -105,7 +106,7 @@ def resolve_ai_preferences(integration: Integration, slack_user_id: str | None)model = chosen.get("model") or Nonereasoning_effort = chosen.get("reasoning_effort") or Noneif runtime_adapter and model and reasoning_effort:- reasoning_effort = _filter_unsupported_effort(runtime_adapter, model, reasoning_effort)+ reasoning_effort = filter_unsupported_effort(runtime_adapter, model, reasoning_effort)return AIPreferences(runtime_adapter=runtime_adapter,@@ -114,16 +115,6 @@ def resolve_ai_preferences(integration: Integration, slack_user_id: str | None))-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,diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex a8748c3adb37..816b0e9460f8 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -7,6 +7,7 @@ from slack_sdk import WebClientfrom posthog.models.integration import Integration, SlackIntegration+from products.slack_app.backend.services.model_catalogue import describe_run_modelfrom products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_barelogger = structlog.get_logger(__name__)@@ -288,13 +289,28 @@ class SlackThreadHandler:self,stage: str,task_url: str | None = None,+ model: str | None = None,+ reasoning_effort: str | None = None,) -> None:- """Post a new progress message or update the existing one."""+ """Post a new progress message or update the existing one.++ The model rides along as a context line rather than its own message: which+ model is running is a property of the task, and the thread already has one+ place that describes the task while it works.+ """text = f"*{PROGRESS_MESSAGE_MARKER}* :hourglass_flowing_sand:\nStage: {stage}"blocks: list[dict[str, Any]] = [{"type": "section", "text": {"type": "mrkdwn", "text": text}},]+ if model:+ blocks.append(+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": describe_run_model(model, reasoning_effort)}],+ }+ )+if task_url:blocks.append({diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.pynew file mode 100644index 000000000000..aa559d62a1b7--- /dev/null+++ b/products/slack_app/backend/tests/services/test_run_preferences.py@@ -0,0 +1,146 @@+from dataclasses import dataclass++import pytest+from unittest.mock import patch++from products.slack_app.backend.services import run_preferences+from products.slack_app.backend.services.model_catalogue import (+ ModelChoice,+ available_model_choices,+ describe_run_model,+ format_model_id,+)+from products.slack_app.backend.services.run_preferences import SLACK_DEFAULT_MODEL, resolve_run_preferences+from products.slack_app.backend.services.slack_settings import AIPreferences++# Real model ids: the resolver validates efforts against the tasks catalogue (the+# authority on what a model accepts), not against these tuples, so inventing ids here+# would make the fixture lie.+CATALOGUE = (+ ModelChoice("claude", "claude-sonnet-4-6", "Claude Sonnet 4.6", ("low", "medium", "high")),+ ModelChoice("claude", "claude-fable-5", "Claude Fable 5", ("low", "medium", "high", "xhigh", "max")),+ ModelChoice("claude", "moonshotai/kimi-k3", "Moonshotai Kimi K3", ()),+ ModelChoice("codex", "gpt-5.6-sol", "gpt-5.6-sol", ("low", "medium", "high", "xhigh", "max")),+)++SAVED = AIPreferences(runtime_adapter="claude", model="claude-sonnet-4-6", reasoning_effort="medium")+++def catalogue():+ with patch.object(run_preferences, "available_model_choices", return_value=CATALOGUE):+ yield+++@dataclass+class _Override:+ """Stands in for the Temporal payload the activity returns."""++ model: str | None = None+ reasoning_effort: str | None = None+++def _resolve(saved: AIPreferences, override_model=None, override_effort=None):+ """Resolve with `resolve_ai_preferences` stubbed, so these stay unit tests over the+ precedence rules rather than over the settings rows."""+ with patch.object(run_preferences, "resolve_ai_preferences", return_value=saved):+ return resolve_run_preferences(+ integration=None, # type: ignore[arg-type]+ slack_user_id="U1",+ override=_Override(model=override_model, reasoning_effort=override_effort),+ )+++class TestResolveRunPreferences:+ @pytest.mark.parametrize(+ "override_model,override_effort,expected",+ [+ # A model named in the mention replaces the pair outright — the effort saved+ # against the previous model must not ride along onto a different one.+ ("claude-fable-5", None, AIPreferences("claude", "claude-fable-5", None)),+ # An effort on its own applies to whatever model the run was already using.+ (None, "high", AIPreferences("claude", "claude-sonnet-4-6", "high")),+ ("claude-fable-5", "high", AIPreferences("claude", "claude-fable-5", "high")),+ # Crossing runtimes derives the adapter from the model, never from the request.+ ("gpt-5.6-sol", None, AIPreferences("codex", "gpt-5.6-sol", None)),+ ("CLAUDE-Fable-5", None, AIPreferences("claude", "claude-fable-5", None)),+ # Nothing on offer matches, so the run keeps its saved preferences.+ ("gemini-3-pro", None, SAVED),+ (None, None, SAVED),+ # `xhigh` is real for Fable but not for Sonnet 4.6, so it is dropped.+ ("claude-sonnet-4-6", "xhigh", AIPreferences("claude", "claude-sonnet-4-6", None)),+ # A model that exposes no effort setting at all takes none.+ ("moonshotai/kimi-k3", "high", AIPreferences("claude", "moonshotai/kimi-k3", None)),+ # An effort this model can't do leaves the run alone — including the effort+ # it already had, which an impossible ask must not clear.+ (None, "xhigh", SAVED),+ ],+ )+ def test_mention_override_precedence(self, catalogue, override_model, override_effort, expected):+ assert _resolve(SAVED, override_model, override_effort) == expected++ def test_falls_back_to_the_slack_default_when_nothing_is_saved(self, catalogue):+ """An unset workspace must still get a pinned model, not whatever the agent+ server would otherwise choose."""+ assert _resolve(AIPreferences()) == AIPreferences("claude", SLACK_DEFAULT_MODEL, None)++ def test_override_applies_on_top_of_the_default(self, catalogue):+ resolved = _resolve(AIPreferences(), override_model="claude-fable-5")+ assert resolved == AIPreferences("claude", "claude-fable-5", None)++ def test_derives_the_adapter_for_a_saved_model(self, catalogue):+ """A stored `(runtime_adapter, model)` pair that disagrees resolves to the+ adapter the model actually runs on."""+ saved = AIPreferences(runtime_adapter="codex", model="claude-fable-5", reasoning_effort=None)+ assert _resolve(saved).runtime_adapter == "claude"+++class TestDescribeRunModel:+ @pytest.mark.parametrize(+ "model,reasoning_effort,expected",+ [+ ("claude-fable-5", "high", "*Claude Fable 5* · Reasoning: *High*"),+ ("claude-fable-5", None, "*Claude Fable 5*"),+ ("claude-opus-5", "ultracode", "*Claude Opus 5* · Reasoning: *Ultracode*"),+ ],+ )+ def test_renders_the_shared_phrasing(self, model, reasoning_effort, expected):+ assert describe_run_model(model, reasoning_effort) == expected+++class TestFormatModelId:+ @pytest.mark.parametrize(+ "model_id,expected",+ [+ ("claude-opus-5", "Claude Opus 5"),+ # A dashed version survives the split as one component.+ ("claude-sonnet-4-6", "Claude Sonnet 4.6"),+ # Vendor initialisms keep their casing and stay glued to the version, so+ # the picker reads "GPT-5.6 Sol" rather than "Gpt 5.6 Sol".+ ("gpt-5.2", "GPT-5.2"),+ ("gpt-5.6-sol", "GPT-5.6 Sol"),+ ("gpt-5.3-codex", "GPT-5.3 Codex"),+ ("gpt-5-mini", "GPT-5 Mini"),+ # A provider-prefixed id drops the prefix before naming.+ ("openai/gpt-5.5", "GPT-5.5"),+ ],+ )+ def test_names_every_family_without_a_lookup_table(self, model_id, expected):+ assert format_model_id(model_id) == expected+++class TestAvailableModelChoices:+ def test_drops_providers_we_cannot_route(self):+ """The gateway serves models under providers the tasks product has no runtime+ for; offering one would produce a run the gateway rejects."""+ from products.slack_app.backend.services.llm_models import GatewayModel++ gateway = (+ GatewayModel(id="claude-fable-5", owned_by="anthropic", context_window=200000),+ GatewayModel(id="titan-express", owned_by="bedrock", context_window=8000),+ )+ with patch(+ "products.slack_app.backend.services.llm_models.list_slack_app_models",+ return_value=gateway,+ ):+ assert [c.model for c in available_model_choices()] == ["claude-fable-5"]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 1e6ea42c8d02..11374e875abb 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@@ -150,6 +150,25 @@ def _stub_picker_facade():return Nonereturn f"Effort '{effort}' not supported on {model}."+ # The catalogue derives the gateway-provider → adapter mapping and the adapter for+ # a given model from the tasks product rather than restating them, so the stub has+ # to answer both.+ providers_by_adapter = {"claude": "anthropic", "codex": "openai"}+ models_by_adapter = {+ "claude": ("claude-opus-4-7", "claude-sonnet-4-6"),+ "codex": ("gpt-5", "gpt-5.5"),+ }++ def _adapter_value(adapter):+ return adapter.value if hasattr(adapter, "value") else adapter++ def fake_get_provider(adapter):+ provider = providers_by_adapter.get(_adapter_value(adapter))+ return _Adapter(provider) if provider else None++ def fake_get_models(adapter):+ return models_by_adapter.get(_adapter_value(adapter), ())+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@@ -158,6 +177,8 @@ def _stub_picker_facade():fake.RuntimeAdapter = _RuntimeAdapter()fake.get_supported_reasoning_efforts = fake_get_supportedfake.get_reasoning_effort_error = fake_get_error+ fake.get_provider_for_runtime_adapter = fake_get_provider+ fake.get_models_for_runtime_adapter = fake_get_modelsfake.PUBLIC_REASONING_EFFORTS = public_efforts@dataclass(frozen=True)diff --git a/products/slack_app/evals/__init__.py b/products/slack_app/evals/__init__.pyindex e69de29bb2d1..cd6bf0e4d16f 100644--- a/products/slack_app/evals/__init__.py+++ b/products/slack_app/evals/__init__.py@@ -0,0 +1 @@+"""Eval suites for the Slack app."""diff --git a/products/slack_app/evals/eval_model_classifier.py b/products/slack_app/evals/eval_model_classifier.pynew file mode 100644index 000000000000..13195173a05a--- /dev/null+++ b/products/slack_app/evals/eval_model_classifier.py@@ -0,0 +1,172 @@+"""Does the model-override classifier read a Slack mention the way a person would?++The unit tests around `classify_slack_app_model_override` feed it canned replies: they+cover parsing, validation, and the catalogue check, and would pass unchanged if the+prompt were replaced with the word "hello". This suite covers the part they can't —+whether the model, reading a real sentence, can tell an instruction about how to run the+task from a task that merely mentions a model.++That distinction is the whole classifier, and it fails asymmetrically: see+`NoUnaskedOverride` in `scorers.py` for why the false-positive rate is the number to+watch rather than overall accuracy.++Public rather than private: the point of the suite is comparing a baseline against a+later prompt or model change, and that history lives in Braintrust keyed on+`experiment_name` — a private run leaves local logs to diff by hand. Every prompt below+is synthetic, so there is no customer text to keep off the wire.++To run:+ hogli evals eval_model_classifier+ hogli evals eval_model_classifier --eval names_model_in_code_change+"""++from __future__ import annotations++import asyncio++from posthog.temporal.ai.slack_app.activities import classifiers++from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval+from products.slack_app.backend.services.model_catalogue import ModelChoice+from products.slack_app.evals.model_classifier_scorers import EXPECTATION_KEY, ModelOverrideMatch, NoUnaskedOverride++SUITE_KIND = SuiteKind.ONE_SHOT++# Frozen rather than `available_model_choices()`: the live catalogue tracks whatever the+# gateway currently serves, so scores would move when a model ships or is retired, for+# reasons that have nothing to do with the prompt. Refresh deliberately, and expect the+# baseline to step when you do.+CHOICES: tuple[ModelChoice, ...] = (+ ModelChoice("claude", "claude-opus-5", "Claude Opus 5", ("low", "medium", "high", "xhigh", "max")),+ ModelChoice("claude", "claude-fable-5", "Claude Fable 5", ("low", "medium", "high", "xhigh", "max")),+ ModelChoice("claude", "claude-sonnet-5", "Claude Sonnet 5", ("low", "medium", "high", "xhigh", "max")),+ ModelChoice("codex", "gpt-5.6-luna", "GPT-5.6 Luna", ("low", "medium", "high", "xhigh", "max")),+ ModelChoice("codex", "gpt-5.6-sol", "GPT-5.6 Sol", ("low", "medium", "high", "xhigh", "max")),+)+++def _asks(model: str | None = None, reasoning_effort: str | None = None) -> dict:+ return {EXPECTATION_KEY: {"model": model, "reasoning_effort": reasoning_effort}}+++# Deliberately not the prompt's own few-shot examples. Reusing those would measure+# whether the model can copy a list it was just handed, which tells us nothing about the+# sentences people actually send.+INSTRUCTION_CASES = [+ BaseEvalCase(+ name="plain_model_instruction",+ prompt="@PostHog use opus 5 for this — the retention query is returning empty buckets",+ expected=_asks(model="claude-opus-5"),+ ),+ BaseEvalCase(+ name="instruction_after_the_ask",+ prompt="@PostHog can you look into why the billing webhook retries twice? run it on fable please",+ expected=_asks(model="claude-fable-5"),+ ),+ BaseEvalCase(+ name="effort_without_model",+ prompt="@PostHog this one's gnarly, give it max effort — the session replay index is corrupt somehow",+ expected=_asks(reasoning_effort="max"),+ ),+ BaseEvalCase(+ name="model_and_effort",+ prompt="@PostHog run this on sonnet 5 with low effort, it's a one-line copy change in the nav",+ expected=_asks(model="claude-sonnet-5", reasoning_effort="low"),+ ),+ BaseEvalCase(+ name="colloquial_model_name",+ prompt="@PostHog do this one with luna: add a loading state to the cohort picker",+ expected=_asks(model="gpt-5.6-luna"),+ ),+ BaseEvalCase(+ name="instruction_with_model_also_as_subject",+ prompt=(+ "@PostHog use fable for this one. The task: our model picker is missing gpt-5.6-sol, add it to the dropdown"+ ),+ expected=_asks(model="claude-fable-5"),+ ),+]++# The expensive direction. Each of these names a model, and the right answer is to do+# nothing with it.+SUBJECT_MATTER_CASES = [+ BaseEvalCase(+ name="names_model_in_code_change",+ prompt="@PostHog add gpt-5.6-luna to the model picker in settings, it's missing from the dropdown",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="question_comparing_models",+ prompt="@PostHog why is opus 5 slower than sonnet 5 on our eval suite? dig into the traces",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="model_as_incident_topic",+ prompt="@PostHog the fable rollout broke the usage dashboard last night, can you find what changed",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="effort_as_english",+ prompt="@PostHog reasoning about this caching bug is hard, can you take a look at the invalidation logic",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="model_in_config_file",+ prompt="@PostHog our CLASSIFIER_MODEL constant still says claude-haiku-4-5, update it and the tests",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="model_in_error_message",+ prompt='@PostHog users are seeing "model gpt-5.6-sol is not available" on the tasks page, fix the fallback',+ expected=_asks(),+ ),+ BaseEvalCase(+ name="past_tense_report",+ prompt="@PostHog I ran this on opus 5 yesterday and it missed the race condition, try again",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="effort_as_product_copy",+ prompt="@PostHog the effort selector tooltip says 'max effort' but the value sent is xhigh, fix the label",+ expected=_asks(),+ ),+ BaseEvalCase(+ name="no_model_mentioned",+ prompt="@PostHog the checkout funnel drops 40% between steps 2 and 3, can you work out why",+ expected=_asks(),+ ),+]+++async def eval_model_classifier(ctx: EvalContext) -> None:+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ # Recorded on every case so an experiment says which model produced its scores —+ # otherwise two runs of the same suite are indistinguishable in the history, which+ # is exactly what you go to the history to compare.+ classifier_model = classifiers.MODEL_OVERRIDE_CLASSIFIER_MODEL+ try:+ # Sync, and blocking on the gateway — keep it off the event loop so cases+ # still run concurrently under the harness's limiter.+ override = await asyncio.to_thread(classifiers.classify_slack_app_model_override, case.prompt, CHOICES)+ except Exception as error:+ return {+ "classifier_model": classifier_model,+ "override": None,+ "error": f"{type(error).__name__}: {error}",+ }+ return {+ "classifier_model": classifier_model,+ "override": override.model_dump() if override else None,+ "last_message": f"{classifier_model}: {override.model_dump() if override else None}",+ }++ await OneShotPublicEval(+ experiment_name="slack-app-model-classifier",+ cases=[*INSTRUCTION_CASES, *SUBJECT_MATTER_CASES],+ scorers=[ModelOverrideMatch(), NoUnaskedOverride()],+ task=task,+ ctx=ctx,+ )diff --git a/products/slack_app/evals/model_classifier_scorers.py b/products/slack_app/evals/model_classifier_scorers.pynew file mode 100644index 000000000000..f9dd0e3d2ddc--- /dev/null+++ b/products/slack_app/evals/model_classifier_scorers.py@@ -0,0 +1,87 @@+"""Scorers for the Slack model-override classifier suite."""++from __future__ import annotations++from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer++# Both scorers read the same expectation: one case states the answer once, and the+# false-positive scorer derives "this case asks for nothing" from it rather than+# carrying a second, separately-maintained flag that could disagree.+EXPECTATION_KEY = "model_override_match"+++def _reads(output: dict | None) -> tuple[str | None, str | None]:+ """The classifier's answer as a `(model, reasoning_effort)` pair.++ A `None` override — the classifier declining to steer the run — reads the same as an+ explicit pair of nulls, because that is what it means downstream.+ """+ override = (output or {}).get("override") or {}+ return override.get("model"), override.get("reasoning_effort")+++class ModelOverrideMatch(Scorer):+ """Did the classifier read the mention the way a person would?++ Scores both fields at once: a run launched on the right model at the wrong effort is+ still not what the author asked for.+ """++ def _name(self) -> str:+ return EXPECTATION_KEY++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ if output and output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})++ want = (expected or {}).get(EXPECTATION_KEY)+ if want is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})++ got_model, got_effort = _reads(output)+ want_model, want_effort = want.get("model"), want.get("reasoning_effort")+ matched = got_model == want_model and got_effort == want_effort+ return Score(+ name=self._name(),+ score=1.0 if matched else 0.0,+ metadata={+ "expected_model": want_model,+ "actual_model": got_model,+ "expected_effort": want_effort,+ "actual_effort": got_effort,+ },+ )+++class NoUnaskedOverride(Scorer):+ """The failure that actually costs the user something.++ The two error directions are not symmetric. Missing a real instruction falls back to+ the author's saved preferences — they notice and rephrase. Inventing an instruction+ out of subject matter silently moves someone's run onto a model they never chose, and+ nothing in the thread says so.++ Skips (`None`) on cases that do ask for something, so the score reads as a rate over+ the mentions that merely *mention* a model.+ """++ def _name(self) -> str:+ return "no_unasked_override"++ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:+ want = (expected or {}).get(EXPECTATION_KEY) or {}+ if want.get("model") or want.get("reasoning_effort"):+ return Score(name=self._name(), score=None, metadata={"reason": "Case asks for an override"})++ if output and output.get("error"):+ # An erroring call yields no override, which is the safe answer here — but+ # scoring it as a pass would hide a broken classifier behind a good rate.+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})++ got_model, got_effort = _reads(output)+ invented = got_model is not None or got_effort is not None+ return Score(+ name=self._name(),+ score=0.0 if invented else 1.0,+ metadata={"actual_model": got_model, "actual_effort": got_effort},+ )diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.pyindex 8ac8ebebd95f..3ef7be8fada5 100644--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py@@ -106,6 +106,10 @@ def _viewer_has_posthog_code_access(viewer: User | None) -> bool:def post_slack_update(input: PostSlackUpdateInput) -> None:"""Post Slack update based on current task run state. Idempotent."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler++ # Deferred with the model import below: `facade.run_config` re-exports from+ # `process_task.utils`, whose import graph reaches back to this module.+ from products.tasks.backend.facade.run_config import parse_run_statefrom products.tasks.backend.models import TaskRuntry:@@ -158,7 +162,13 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:handler.update_reaction("eyes")returnstage = _get_stage_from_status(task_run.status, task_run.stage)- handler.post_or_update_progress(stage, task_url)+ run_state = parse_run_state(task_run.state)+ handler.post_or_update_progress(+ stage,+ task_url,+ model=run_state.model,+ reasoning_effort=run_state.reasoning_effort,+ )except Exception:logger.exception("post_slack_update_failed", run_id=input.run_id)diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 99752eb2786e..9ba88756718f 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -215,7 +215,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {),"slack_app_routing": ProductConfig(allowed_application_ids=None,- allowed_models=frozenset({"claude-haiku-4-5"}),+ allowed_models=frozenset({"claude-haiku-4-5", "gpt-5.6-luna"}),allow_api_keys=True,credit_bucket=CreditBucket.AI_CREDITS,),