: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): switch the model from a follow-up (#81078)
Vojta Bartoš1c4b2d66648c
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.pyindex 90f411334505..ddb50a3772a9 100644--- a/posthog/temporal/ai/slack_app/activities/classifiers.py+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py@@ -528,17 +528,23 @@ def classify_slack_app_model_override(@activity.defn@close_db_connectionsdef classify_slack_app_model_override_activity(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:- """Resolve the model the mention asked for, or ``None`` to use saved preferences.+ """Resolve the model a message 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.+ Runs as its own activity rather than inside the activity that consumes it so the+ choice is recorded in workflow history once: both task creation and follow-up+ forwarding retry, and re-running a classifier there could hand the second attempt a+ different model than the first one announced. The workflow calls it once, above the+ point where the mention and follow-up paths diverge.- Every mention behind the flag reaches the classifier. A keyword pre-filter would+ Every message behind the flag reaches the classifier. A keyword pre-filter wouldsave the Haiku call on the majority that name no model, but it also decides — ona substring match — which phrasings can ever steer a run, and that judgement- belongs to the model reading the sentence, not to a word list.+ belongs to the model reading the sentence, not to a word list. Blank text is not+ that judgement: there is no sentence to read."""+ if not input.event_text.strip():+ return None+integration = Integration.objects.select_related("team").get(id=input.integration_id,kind="slack",@@ -551,7 +557,7 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInputif 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)+ logger.info("slack_app_model_override_empty_catalogue", integration_id=integration.id)return Noneoverride = classify_slack_app_model_override(input.event_text, choices)@@ -560,7 +566,7 @@ def classify_slack_app_model_override_activity(input: SlackAppModelOverrideInputlogger.info("slack_app_model_override_classified",- integration_id=input.integration_id,+ integration_id=integration.id,model=override.model,reasoning_effort=override.reasoning_effort,)diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 60750ca01d66..1139a6302f56 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -19,7 +19,7 @@ from posthog.temporal.ai.slack_app.helpers import block_if_team_over_quota, safefrom posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs, SlackAppModelOverridefrom posthog.temporal.common.utils import close_db_connections-from products.slack_app.backend.services.slack_messages import post_slack_thread_reply+from products.slack_app.backend.services.slack_messages import context_block, post_slack_thread_replylogger = structlog.get_logger(__name__)@@ -766,11 +766,17 @@ def forward_posthog_code_followup_activity(slack_user_id: str,event_text: str,user_message_ts: str | None,+ model_override: SlackAppModelOverride | None = None,) -> bool:"""Forward a follow-up message to the running agent if a mapping exists.Returns True if the message was handled (forwarded or rejected), False ifno mapping exists and the caller should continue with the normal new-task flow.++ ``model_override`` is classified by the workflow, above the point where the+ follow-up and new-task paths diverge, so a retry of this activity reuses the model+ the first attempt announced. It defaults to ``None`` for histories recorded before+ the workflow classified this early, which simply leave the run on its own model."""from posthog.models.integration import Integration, SlackIntegration@@ -861,6 +867,7 @@ def forward_posthog_code_followup_activity(user_message_ts,actor_user=actor_user,user_text_prefix=followup_user_text_prefix,+ model_override=model_override,)from products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415@@ -937,6 +944,18 @@ def forward_posthog_code_followup_activity(or user_text)+ # Switch the running agent before the message is queued, so the turn this reply+ # opens is the first one on the model it asked for.+ _apply_followup_model_override(+ slack,+ channel,+ thread_ts,+ task_run=task_run,+ task_id=mapping.task_id,+ override=model_override,+ actor_user=actor_user,+ )+# Queue on the workflow so delivery is ordered with the web path. The# deterministic message id keeps redelivery idempotent.signal_result = tasks_facade.signal_task_run_user_message(@@ -1004,6 +1023,121 @@ def forward_posthog_code_followup_activity(return True+def _apply_followup_model_override(+ slack: Any,+ channel: str,+ thread_ts: str,+ *,+ task_run: Any,+ task_id: Any,+ override: SlackAppModelOverride | None,+ actor_user: Any | None,+) -> None:+ """Move a running agent onto the model and effort a follow-up asked for.++ The harness is fixed once a sandbox starts, so a model belonging to the other+ runtime is answered rather than attempted: that one needs a new task. A switch that+ lands says nothing, because the footer under the next reply reads the model back out+ of the run's state. A failure to apply leaves the run on what it was already using+ rather than derailing the follow-up.+ """+ from products.slack_app.backend.facade.run_preferences import describe_run_model, resolve_live_run_override+ from products.tasks.backend.facade import api as tasks_facade++ state = task_run.state or {}+ try:+ change = resolve_live_run_override(+ override,+ runtime_adapter=state.get("runtime_adapter"),+ model=state.get("model"),+ reasoning_effort=state.get("reasoning_effort"),+ )+ except Exception:+ logger.exception("slack_app_followup_model_override_resolve_failed", task_run_id=str(task_run.id))+ return++ if change.is_empty:+ return++ if change.refused_model:+ _post_thread_context(+ slack,+ channel,+ thread_ts,+ f"I can't move this task onto {describe_run_model(change.refused_model, None)}. The runtime is fixed "+ "once an agent starts, so start a new thread to run on it.",+ )+ return++ try:+ applied = tasks_facade.apply_task_run_model_config(+ task_run.id,+ task_id,+ task_run.team_id,+ model=change.model,+ reasoning_effort=change.reasoning_effort,+ actor_user_id=actor_user.id if actor_user and actor_user.id else None,+ )+ except Exception:+ logger.exception("slack_app_followup_model_override_apply_failed", task_run_id=str(task_run.id))+ return++ if not applied:+ logger.warning(+ "slack_app_followup_model_override_not_applied",+ task_run_id=str(task_run.id),+ model=change.model,+ reasoning_effort=change.reasoning_effort,+ )+ return++ logger.info(+ "slack_app_followup_model_override_applied",+ task_run_id=str(task_run.id),+ model=change.model,+ reasoning_effort=change.reasoning_effort,+ )+++def _run_preference_state(+ integration: Any,+ slack_user_id: str,+ model_override: SlackAppModelOverride | None,+) -> dict[str, Any]:+ """The run-state keys that pin a new run's harness, model and effort.++ ``create_and_run_task`` derives these from its own arguments; a run created straight+ off a task has to write them itself, and a run with none of them set falls back to+ whatever the agent server defaults to.+ """+ from products.slack_app.backend.facade.run_preferences import resolve_run_preferences+ from products.tasks.backend.facade.run_config import get_provider_for_runtime_adapter++ prefs = resolve_run_preferences(integration, slack_user_id, override=model_override)+ provider = get_provider_for_runtime_adapter(prefs.runtime_adapter) if prefs.runtime_adapter else None+ state = {+ "runtime_adapter": prefs.runtime_adapter,+ "provider": provider.value if provider else None,+ "model": prefs.model,+ "reasoning_effort": prefs.reasoning_effort,+ }+ return {key: value for key, value in state.items() if value}+++def _post_thread_context(slack: Any, channel: str, thread_ts: str, text: str) -> None:+ """A one-line context block in the thread. Best-effort — it annotates the run."""+ try:+ post_slack_thread_reply(+ slack.client,+ channel=channel,+ thread_ts=thread_ts,+ text=text,+ blocks=[context_block(text)],+ )+ except Exception:+ logger.warning("slack_app_thread_context_post_failed", channel=channel, thread_ts=thread_ts)++def _terminal_recovery_strategy(previous_run: Any) -> str | None:from products.tasks.backend.facade import api as tasks_facade@@ -1081,9 +1215,9 @@ def _resume_task_with_new_run(user_message_ts: str | None,actor_user: Any | None = None,user_text_prefix: str | None = None,+ model_override: SlackAppModelOverride | None = None,) -> bool:"""Create a new run on the same task when a follow-up arrives after the previous run completed."""- from products.slack_app.backend.facade.run_preferences import resolve_run_preferences # noqa: PLC0415from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415from products.slack_app.backend.slack_thread import SlackThreadContextfrom products.tasks.backend.facade import api as tasks_facade@@ -1126,22 +1260,16 @@ def _resume_task_with_new_run(**_artifact_delivery_state_updates(integration),}- # `create_run` builds a fresh state, so a follow-up that says nothing about the model- # reaches the sandbox with none and the agent server picks its own — the thread then- # can't say what ran. Resolved again rather than carried over, like the keys above: a- # follow-up honours whatever the picker says now.- run_prefs = resolve_run_preferences(integration, slack_user_id)- if run_prefs.model:- extra_state["model"] = run_prefs.model- if run_prefs.runtime_adapter:- extra_state["runtime_adapter"] = run_prefs.runtime_adapter- if run_prefs.reasoning_effort:- extra_state["reasoning_effort"] = run_prefs.reasoning_effort-previous_state = previous_run.state or {}if previous_state.get("slack_thread_url"):extra_state["slack_thread_url"] = previous_state["slack_thread_url"]+ # A successor launches its own agent server, so the whole triple is open again —+ # including the runtime a live run could never be moved onto. Resolved rather than+ # carried over, like the keys above: a preference changed since the previous run is+ # picked up too.+ extra_state.update(_run_preference_state(integration, slack_user_id, model_override))+extra_state.update(tasks_facade.get_resume_snapshot_carry_state(previous_state))extra_state["resume_from_run_id"] = str(previous_run.id)diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.pyindex 2bf9476945f3..c5d27f145baf 100644--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py@@ -9,6 +9,7 @@ from temporalio.common import RetryPolicyfrom posthog.temporal.ai.slack_app import (POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,PostHogCodeSlackMentionWorkflowInputs,+ SlackAppModelOverride,SlackAppModelOverrideInput,cascade_posthog_code_repository_activity,classify_posthog_code_task_needs_repo_activity,@@ -36,9 +37,10 @@ POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15# remains, keeping the recorded marker compatible for executions in flight# across the deploy that removes them. Standard two-step Temporal patch# lifecycle: those calls come out once the histories that recorded a plain-# marker have drained in turn. The confirmation patch is younger and still-# gated, so it stays a full `workflow.patched` branch until it drains too.+# marker have drained in turn. The last two are younger and still gated, so they+# stay full `workflow.patched` branches until they drain too._PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS = "slack-file-only-followup-bypass-v1"+_PATCH_ID_FOLLOWUP_MODEL_CLASSIFIER = "slack-app-followup-model-classifier-v1"_PATCH_ID_MODEL_CLASSIFIER = "slack-app-model-classifier-v1"_PATCH_ID_NO_PERSONAL_GITHUB_GATE = "slack-no-personal-github-gate-v1"_PATCH_ID_UNTAGGED_FOLLOWUP_CONFIRMATION = "slack-untagged-followup-confirmation-v1"@@ -141,15 +143,48 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):if awaiting_confirmation:return- followup_handled = await _execute_posthog_code_activity(- forward_posthog_code_followup_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event.get("text", ""),- event.get("ts"),- )+ # Read a model or effort request ("use fable for this one", "actually run+ # this on opus") out of the message. Classified above the follow-up/new-task+ # split because the mapping lookup that tells the two apart lives inside the+ # follow-up activity: one call here serves whichever path the message takes,+ # and recording the choice in history once stops a retry of either activity+ # from landing on a different model than the first attempt announced. The+ # feature flag is checked inside the activity — branching the workflow on a+ # flag would be non-deterministic on replay.+ model_override: SlackAppModelOverride | None = None+ classified_before_split = workflow.patched(_PATCH_ID_FOLLOWUP_MODEL_CLASSIFIER)+ if classified_before_split:+ 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", ""),+ ),+ )++ followup_handled = await _execute_posthog_code_activity(+ forward_posthog_code_followup_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event.get("text", ""),+ event.get("ts"),+ model_override,+ )+ else:+ # Pre-patch histories recorded this activity without the override, and+ # classified further down. Replaying them has to schedule the same call.+ followup_handled = await _execute_posthog_code_activity(+ forward_posthog_code_followup_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event.get("text", ""),+ event.get("ts"),+ )if followup_handled:return@@ -250,20 +285,21 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):)returnrepository = self._selected_repo- # 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.workflow.deprecate_patch(_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", ""),- ),- )+ if not classified_before_split:+ # Where pre-patch histories classify: past every gate that can still+ # abandon the mention, so the call is only spent on a task that gets+ # created. Newer executions trade that for one classification shared+ # with the follow-up path, which retries far more often than it is+ # abandoned here.+ 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,diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_followup_model_override.py b/posthog/temporal/tests/ai/slack_app/activities/test_followup_model_override.pynew file mode 100644index 000000000000..33e80d907ab7--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/activities/test_followup_model_override.py@@ -0,0 +1,149 @@+"""Tests for the model switch a follow-up can ask a run for.++The precedence rules themselves live in+``products/slack_app/backend/tests/services/test_run_preferences.py``. What is+covered here is what the follow-up path does with the answer: which asks reach the+agent server, which are refused in the thread, and what a resumed run is pinned to.+"""++from types import SimpleNamespace++import pytest+from unittest.mock import MagicMock, patch++from posthog.temporal.ai.slack_app.activities.task_creation import _apply_followup_model_override, _run_preference_state+from posthog.temporal.ai.slack_app.types import SlackAppModelOverride++from products.slack_app.backend.services.model_catalogue import ModelChoice+from products.slack_app.backend.services.slack_settings import AIPreferences++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("codex", "gpt-5.6-sol", "GPT-5.6 Sol", ("low", "medium", "high", "xhigh", "max")),+)++RUNNING_STATE = {"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "reasoning_effort": "medium"}+++def catalogue():+ with patch(+ "products.slack_app.backend.services.run_preferences.available_model_choices",+ return_value=CATALOGUE,+ ):+ yield+++def apply_config():+ with patch("products.tasks.backend.facade.api.apply_task_run_model_config", return_value=True) as mock:+ yield mock+++def _run(state=None):+ return SimpleNamespace(id="run-1", team_id=7, state=state if state is not None else dict(RUNNING_STATE))+++def _slack():+ return SimpleNamespace(client=MagicMock())+++def _posted_text(slack) -> str:+ return slack.client.chat_postMessage.call_args.kwargs["text"]+++class TestApplyFollowupModelOverride:+ @pytest.mark.parametrize("applied", [True, False], ids=["agent_server_accepts", "agent_server_refuses"])+ def test_switches_the_running_agent_without_announcing_it(self, catalogue, apply_config, applied):+ """The footer under the next reply reads the model back out of the run's state,+ so a switch that lands needs no line of its own, and one that doesn't must not+ claim otherwise."""+ apply_config.return_value = applied+ slack = _slack()+ _apply_followup_model_override(+ slack,+ "C1",+ "111.1",+ task_run=_run(),+ task_id="task-1",+ override=SlackAppModelOverride(model="claude-fable-5", reasoning_effort="xhigh"),+ actor_user=SimpleNamespace(id=42),+ )+ assert apply_config.call_args.kwargs == {+ "model": "claude-fable-5",+ "reasoning_effort": "xhigh",+ "actor_user_id": 42,+ }+ slack.client.chat_postMessage.assert_not_called()++ def test_refuses_a_model_from_the_other_runtime_without_touching_the_run(self, catalogue, apply_config):+ """The harness is the process the sandbox started with, so this one can only be+ answered — and it has to be, or the author is left thinking it was honoured."""+ slack = _slack()+ _apply_followup_model_override(+ slack,+ "C1",+ "111.1",+ task_run=_run(),+ task_id="task-1",+ override=SlackAppModelOverride(model="gpt-5.6-sol"),+ actor_user=SimpleNamespace(id=42),+ )+ apply_config.assert_not_called()+ assert "*GPT-5.6 Sol*" in _posted_text(slack)++ @pytest.mark.parametrize(+ "override",+ [+ None,+ SlackAppModelOverride(model="claude-sonnet-4-6", reasoning_effort="medium"),+ ],+ ids=["no_request", "already_on_it"],+ )+ def test_stays_quiet_when_nothing_changes(self, catalogue, apply_config, override):+ slack = _slack()+ _apply_followup_model_override(+ slack,+ "C1",+ "111.1",+ task_run=_run(),+ task_id="task-1",+ override=override,+ actor_user=SimpleNamespace(id=42),+ )+ apply_config.assert_not_called()+ slack.client.chat_postMessage.assert_not_called()+++class TestRunPreferenceState:+ @pytest.mark.parametrize(+ "prefs,expected",+ [+ (+ AIPreferences(runtime_adapter="codex", model="gpt-5.6-sol", reasoning_effort="high"),+ {+ "runtime_adapter": "codex",+ "provider": "openai",+ "model": "gpt-5.6-sol",+ "reasoning_effort": "high",+ },+ ),+ # What was never resolved is left out rather than written as None, so the+ # agent server keeps its own default for it.+ (+ AIPreferences(runtime_adapter="claude", model="claude-fable-5", reasoning_effort=None),+ {"runtime_adapter": "claude", "provider": "anthropic", "model": "claude-fable-5"},+ ),+ ],+ ids=["full_triple", "no_effort_resolved"],+ )+ def test_pins_the_successor_run_to_what_resolved(self, prefs, expected):+ """A run created straight off a task writes these itself — without them the new+ sandbox falls back to whatever the agent server defaults to."""+ with patch(+ "products.slack_app.backend.facade.run_preferences.resolve_run_preferences",+ return_value=prefs,+ ):+ state = _run_preference_state(integration=None, slack_user_id="U1", model_override=None)+ assert state == expecteddiff --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.pyindex 4480709fc54c..273f90408240 100644--- 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.py@@ -45,21 +45,24 @@ def _input(integration: Integration, text: str) -> SlackAppModelOverrideInput:class TestClassifySlackAppModelOverrideActivity:@pytest.mark.parametrize(- "flag_on,catalogue",+ "text,flag_on,catalogue",[- (False, CATALOGUE),+ ("use fable for this one", 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, ()),+ ("use fable for this one", True, ()),+ # A follow-up that is only an attachment carries no sentence to read.+ (" ", True, CATALOGUE),],+ ids=["flag_off", "empty_catalogue", "blank_text"],)- def test_gates_return_no_override_without_calling_the_llm(self, integration, flag_on, catalogue):+ def test_gates_return_no_override_without_calling_the_llm(self, integration, text, 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"))+ result = classify_slack_app_model_override_activity(_input(integration, text))assert result is Noneclassify.assert_not_called()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 a0d3e06158c1..99ce2aae521b 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@@ -56,6 +56,8 @@ class _Recorder:self.processing_marked: list[str] = []# ts per forwarded followup, in execution order.self.forwarded: list[str] = []+ # ts -> model override the forward call actually received.+ self.forwarded_with_override: dict[str, SlackAppModelOverride | None] = {}# ts per internal-error notice posted back to the thread, in execution order.self.internal_errors: list[str] = []# ts -> forward result; missing means False (no existing task, fall through to new-task path).@@ -112,8 +114,10 @@ def _fake_activities(rec: _Recorder) -> list:slack_user_id: str,event_text: str,user_message_ts: str | None,+ model_override: SlackAppModelOverride | None = None,) -> bool:ts = inputs.event["ts"]+ rec.forwarded_with_override[ts] = model_overrideif rec.forward_results.get(ts, False):rec.forwarded.append(ts)return True@@ -350,6 +354,25 @@ async def test_model_override_reaches_task_creation():assert rec.created_with_override == {"1.1": None, "1.2": override}+async def test_model_override_reaches_a_followup_without_creating_a_task():+ """The classifier runs above the follow-up/new-task split, so a reply naming a model+ steers the run it lands on instead of being read as prose."""+ rec = _Recorder()+ override = SlackAppModelOverride(model="claude-fable-5", reasoning_effort="high")+ rec.model_overrides["actually run this on fable"] = override+ rec.forward_results["1.1"] = True++ async with _Harness(rec) as h:+ handle = await _signal_with_start(+ h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1", text="actually run this on fable")+ )+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.forwarded_with_override == {"1.1": override}+ assert rec.created == []++@pytest.mark.asyncioasync def test_signal_with_start_on_running_workflow_signals_same_run():rec = _Recorder()diff --git a/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py b/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.pyindex 21d23dab3961..11b813adc177 100644--- a/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py+++ b/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py@@ -44,6 +44,8 @@ async def test_untagged_followup_with_files_classifier_gating(return Trueif activity_fn is posthog_code_slack_mention.request_untagged_followup_confirmation_activity:return False+ if activity_fn is posthog_code_slack_mention.classify_slack_app_model_override_activity:+ return Noneif activity_fn is posthog_code_slack_mention.forward_posthog_code_followup_activity:return True@@ -62,6 +64,9 @@ async def test_untagged_followup_with_files_classifier_gating(expected.append("classify_untagged_followup_activity")if patched:expected.append("request_untagged_followup_confirmation_activity")+ # The model-override classifier sits above the follow-up/new-task split, so it+ # runs for a reply too — but only for histories that recorded it there.+ expected.append("classify_slack_app_model_override_activity")expected.append("forward_posthog_code_followup_activity")assert calls == expected@@ -85,6 +90,8 @@ async def test_confirmed_untagged_followup_skips_the_classifier_and_the_prompt()calls.append(activity_fn.__name__)if activity_fn is posthog_code_slack_mention.enforce_posthog_code_billing_quota_activity:return False+ if activity_fn is posthog_code_slack_mention.classify_slack_app_model_override_activity:+ return Noneif activity_fn is posthog_code_slack_mention.forward_posthog_code_followup_activity:return Trueraise AssertionError(f"unexpected activity: {activity_fn.__name__}")@@ -97,5 +104,6 @@ async def test_confirmed_untagged_followup_skips_the_classifier_and_the_prompt()assert calls == ["enforce_posthog_code_billing_quota_activity",+ "classify_slack_app_model_override_activity","forward_posthog_code_followup_activity",]diff --git a/products/slack_app/backend/facade/run_preferences.py b/products/slack_app/backend/facade/run_preferences.pyindex b3c04b80f0d6..1151a1de73e6 100644--- a/products/slack_app/backend/facade/run_preferences.py+++ b/products/slack_app/backend/facade/run_preferences.py@@ -7,14 +7,27 @@ catalogue those settings pick from and the precedence that resolves them for one"""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, group_by_runtime-from products.slack_app.backend.services.run_preferences import find_model_choice, resolve_run_preferences+from products.slack_app.backend.services.model_catalogue import (+ ModelChoice,+ available_model_choices,+ describe_run_model,+ group_by_runtime,+)+from products.slack_app.backend.services.run_preferences import (+ LiveRunModelChange,+ find_model_choice,+ resolve_live_run_override,+ resolve_run_preferences,+)__all__ = [+ "LiveRunModelChange","ModelChoice","available_model_choices",+ "describe_run_model","find_model_choice","group_by_runtime","is_slack_app_model_classifier_enabled",+ "resolve_live_run_override","resolve_run_preferences",]diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.pyindex d64998742e40..3b6194805ef9 100644--- a/products/slack_app/backend/services/run_preferences.py+++ b/products/slack_app/backend/services/run_preferences.py@@ -12,10 +12,15 @@ built through `_coherent_preferences` rather than field by field. A model namedmention additionally has to be in the live catalogue (`model_catalogue`) — the sameset the App Home picker offers — so an override can never select something the pickeritself would refuse.++A follow-up in a thread the agent is already working in resolves against a narrower+rule, in `resolve_live_run_override`: the runtime adapter is the harness process the+sandbox launched with and cannot change, so only the model and effort are still open."""from __future__ import annotations+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Protocolfrom products.slack_app.backend.services.model_catalogue import (@@ -106,6 +111,70 @@ def resolve_run_preferences(return requested if requested.reasoning_effort else base+@dataclass(frozen=True)+class LiveRunModelChange:+ """What a run already in flight can take from a model request in a follow-up.++ `model` and `reasoning_effort` carry only what actually changes, so an ask that+ matches what the run is already on produces nothing to send. `refused_model` is the+ one ask that has to be answered out loud: a model belonging to the other runtime,+ which no live sandbox can be moved to.+ """++ model: str | None = None+ reasoning_effort: str | None = None+ refused_model: str | None = None++ @property+ def is_empty(self) -> bool:+ return self.model is None and self.reasoning_effort is None and self.refused_model is None+++_NO_CHANGE = LiveRunModelChange()+++def resolve_live_run_override(+ override: ModelOverride | None,+ *,+ runtime_adapter: str | None,+ model: str | None,+ reasoning_effort: str | None,+) -> LiveRunModelChange:+ """What a running agent can be switched to, given what a follow-up asked for.++ The three arguments describe the run as it stands. The runtime adapter is fixed for+ the life of a sandbox — the harness is a process that was started with one — so a+ model belonging to a different runtime is refused whole rather than half-applied,+ and its effort goes with it: "run this on sol at high" is one request, and honouring+ the effort alone would land it on a model the author didn't ask for.++ Beyond that the rules are the run resolver's: the effort is validated against the+ model the run will actually be on, and anything the catalogue doesn't offer is+ ignored, leaving the run where it was.+ """+ if override is None:+ return _NO_CHANGE++ # A run started before models were pinned carries neither; derive what we can, and+ # treat a run we can't place as unswitchable rather than guessing its harness.+ adapter = runtime_adapter or runtime_adapter_for(model)++ requested = find_model_choice(override.model, available_model_choices()) if override.model else None+ if override.model and requested is None:+ return _NO_CHANGE+ if requested is not None and requested.runtime_adapter != adapter:+ return LiveRunModelChange(refused_model=requested.model)++ target_model = requested.model if requested else model+ effort = filter_unsupported_effort(+ adapter, target_model, override.reasoning_effort.strip().lower() if override.reasoning_effort else None+ )+ return LiveRunModelChange(+ model=target_model if requested and requested.model != model else None,+ reasoning_effort=effort if effort and effort != reasoning_effort else None,+ )++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:@@ -116,6 +185,8 @@ def find_model_choice(model: str | None, choices: tuple[ModelChoice, ...]) -> Mo__all__ = ["SLACK_DEFAULT_MODEL",+ "LiveRunModelChange","find_model_choice",+ "resolve_live_run_override","resolve_run_preferences",]diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.pyindex 991cc25f83b7..28c3044c4248 100644--- a/products/slack_app/backend/tests/services/test_run_preferences.py+++ b/products/slack_app/backend/tests/services/test_run_preferences.py@@ -10,7 +10,12 @@ from products.slack_app.backend.services.model_catalogue import (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.run_preferences import (+ SLACK_DEFAULT_MODEL,+ LiveRunModelChange,+ resolve_live_run_override,+ 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@@ -95,6 +100,57 @@ class TestResolveRunPreferences:assert _resolve(saved).runtime_adapter == "claude"+class TestResolveLiveRunOverride:+ """A run already in flight can only move within the runtime its sandbox started on."""++ RUNNING = {"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "reasoning_effort": "medium"}++ @pytest.mark.parametrize(+ "override_model,override_effort,expected",+ [+ # The everyday ask: a different model on the same runtime.+ ("claude-fable-5", None, LiveRunModelChange(model="claude-fable-5")),+ (None, "high", LiveRunModelChange(reasoning_effort="high")),+ ("claude-fable-5", "xhigh", LiveRunModelChange(model="claude-fable-5", reasoning_effort="xhigh")),+ # The harness is the process the sandbox launched with, so a Codex model is+ # refused outright — effort included, since it was one request.+ ("gpt-5.6-sol", "high", LiveRunModelChange(refused_model="gpt-5.6-sol")),+ # Asking for what the run is already on changes nothing.+ ("claude-sonnet-4-6", "medium", LiveRunModelChange()),+ # `xhigh` is real for Fable but not for Sonnet 4.6, so it is dropped rather+ # than sent to an agent that would reject it.+ (None, "xhigh", LiveRunModelChange()),+ (None, None, LiveRunModelChange()),+ ],+ )+ def test_only_sends_what_the_run_can_take(self, catalogue, override_model, override_effort, expected):+ assert (+ resolve_live_run_override(_Override(model=override_model, reasoning_effort=override_effort), **self.RUNNING)+ == expected+ )++ def test_derives_the_runtime_from_the_model_when_the_run_never_recorded_one(self, catalogue):+ """Runs started before models were pinned carry no adapter; the model still places them."""+ change = resolve_live_run_override(+ _Override(model="gpt-5.6-sol"),+ runtime_adapter=None,+ model="claude-sonnet-4-6",+ reasoning_effort=None,+ )+ assert change == LiveRunModelChange(refused_model="gpt-5.6-sol")++ def test_refuses_to_place_a_run_it_cannot_identify(self, catalogue):+ """With neither adapter nor model there is nothing to check a request against,+ and guessing the harness would hand the agent a model it can't load."""+ change = resolve_live_run_override(+ _Override(model="claude-fable-5"), runtime_adapter=None, model=None, reasoning_effort=None+ )+ assert change == LiveRunModelChange(refused_model="claude-fable-5")++ def test_ignores_a_model_the_catalogue_does_not_offer(self, catalogue):+ assert resolve_live_run_override(_Override(model="gemini-3-pro"), **self.RUNNING).is_empty++class TestDescribeRunModel:@pytest.mark.parametrize("model,reasoning_effort,expected",diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 6de746ca0f2a..c4c75bde3e2a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -172,6 +172,7 @@ __all__ = ["TaskRunEnvironment","TaskRunStatus","append_task_run_log",+ "apply_task_run_model_config","ensure_task_run_session","beacon_task_presence","bootstrap_task_run",@@ -3946,6 +3947,76 @@ def signal_task_run_peer_message()+def apply_task_run_model_config(+ run_id: str | UUID,+ task_id: str | UUID,+ team_id: int,+ *,+ model: str | None = None,+ reasoning_effort: str | None = None,+ actor_user_id: int | None = None,+) -> bool:+ """Switch a live run's model and/or reasoning effort on its agent server.++ The runtime adapter is not switchable — it is the harness process the sandbox was+ started with — so the model has to belong to the adapter the run is already on; the+ agent-server rejects anything else outright. Returns whether every requested change+ landed, and writes the ones that did back to ``state`` so readers of the run agree+ with what the sandbox is actually running.++ Model first, then effort: which efforts exist depends on the model, and the+ agent-server rebuilds its effort options the moment the model changes.+ """+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import path+ send_set_config_option,+ )+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the api import path+ create_sandbox_connection_token,+ )+ from products.tasks.backend.logic.services.run_actor import ( # noqa: PLC0415 — keep sandbox deps off the api import path+ get_actor_distinct_id,+ )++ # (agent-server option id, value, run-state key), in the order they must be sent.+ requested = [+ (config_id, value, state_key)+ for config_id, value, state_key in (("model", model, "model"), ("effort", reasoning_effort, "reasoning_effort"))+ if value+ ]+ if not requested:+ return False++ run = _get_visible_run(run_id, task_id, team_id)+ if run is None:+ return False++ actor = User.objects.filter(id=actor_user_id).first() if actor_user_id else None+ distinct_id = get_actor_distinct_id(actor) if actor else None+ if model and get_model_access_error(model, distinct_id=distinct_id) is not None:+ # The entitlement check the run-create path applies, so a follow-up can't reach a+ # gated model the caller could not have started the run on.+ logger.warning("Model access denied switching task run %s to %s", run.id, model)+ return False++ auth_token = (+ create_sandbox_connection_token(run, user_id=actor.id, distinct_id=distinct_id)+ if actor and actor.id and distinct_id+ else None+ )++ applied: dict[str, Any] = {}+ for config_id, value, state_key in requested:+ result = send_set_config_option(run, config_id, value, auth_token=auth_token)+ if not result.success:+ logger.warning("Failed to set %s=%s on task run %s: %s", config_id, value, run.id, result.error)+ break+ applied[state_key] = value++ if applied:+ TaskRun.update_state_atomic(run.id, updates=applied)+ return len(applied) == len(requested)++def get_task_run_sandbox_connection(run_id: str | UUID, task_id: str | UUID, team_id: int, *, user_id: int, distinct_id: str) -> contracts.TaskRunSandboxConnectionDTO | None:diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.pyindex f0d0ca5937ab..157c6eb7a350 100644--- a/products/tasks/backend/logic/services/agent_command.py+++ b/products/tasks/backend/logic/services/agent_command.py@@ -310,6 +310,30 @@ def send_user_message()+def send_set_config_option(+ task_run: Any,+ config_id: str,+ value: str,+ auth_token: str | None = None,+ timeout: int = COMMAND_TIMEOUT_SECONDS,+) -> CommandResult:+ """Change one option on the agent-server's live session (`model`, `effort`, `mode`).++ The agent applies the change to the session it is already holding, so the run keeps+ its conversation history and the new setting takes effect from the next turn. Only+ options the session currently offers are accepted — a model belonging to a runtime+ this sandbox isn't running comes back as an RPC error, since the harness is the+ process the sandbox was started with.+ """+ return send_agent_command(+ task_run,+ method="set_config_option",+ params={"configId": config_id, "value": value},+ auth_token=auth_token,+ timeout=timeout,+ )++def send_cancel(task_run: Any, auth_token: str | None = None) -> CommandResult:"""Send a cancel command to the sandbox agent."""return send_agent_command(diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 8c5cfd459b4a..e4e35050fd31 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -1401,3 +1401,80 @@ class TestSelfDrivingQuotaRefreshDispatch(TestCase):with self.captureOnCommitCallbacks(execute=True):facade._refresh_self_driving_quota_for_pr(run, None)task_mock.delay.assert_not_called()+++class TestApplyTaskRunModelConfig(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Config Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Config Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="config-distinct")++ def _run(self) -> TaskRun:+ task = Task.objects.create(+ team=self.team,+ title="A task",+ description="desc",+ origin_product=Task.OriginProduct.USER_CREATED,+ created_by=self.user,+ repository="posthog/posthog",+ )+ return TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "sandbox_url": "https://sandbox"},+ )++ def _apply(self, run: TaskRun, **kwargs) -> bool:+ return facade.apply_task_run_model_config(run.id, run.task_id, self.team.id, **kwargs)++ @patch("products.tasks.backend.logic.services.agent_command.send_set_config_option")+ def test_sends_the_model_before_the_effort_and_records_both(self, send_mock):+ # Which efforts exist depends on the model, so the agent-server has to see the+ # model change first or it validates the effort against the outgoing one.+ send_mock.return_value = MagicMock(success=True)+ run = self._run()++ applied = self._apply(run, model="claude-fable-5", reasoning_effort="xhigh")++ self.assertTrue(applied)+ self.assertEqual(+ [(c.args[1], c.args[2]) for c in send_mock.call_args_list],+ [("model", "claude-fable-5"), ("effort", "xhigh")],+ )+ run.refresh_from_db()+ self.assertEqual(run.state["model"], "claude-fable-5")+ self.assertEqual(run.state["reasoning_effort"], "xhigh")++ @patch("products.tasks.backend.logic.services.agent_command.send_set_config_option")+ def test_a_rejected_model_leaves_the_effort_alone(self, send_mock):+ # The agent-server rejects a model its harness can't drive. Sending the effort+ # anyway would half-apply a single request onto the model the author didn't ask for.+ send_mock.return_value = MagicMock(success=False, error="Invalid value for config option model")+ run = self._run()++ applied = self._apply(run, model="gpt-5.6-sol", reasoning_effort="xhigh")++ self.assertFalse(applied)+ self.assertEqual(send_mock.call_count, 1)+ run.refresh_from_db()+ self.assertEqual(run.state["model"], "claude-sonnet-4-6")+ self.assertNotIn("reasoning_effort", run.state)++ @patch("products.tasks.backend.facade.api.get_model_access_error", return_value="'x' is not available.")+ @patch("products.tasks.backend.logic.services.agent_command.send_set_config_option")+ def test_a_gated_model_never_reaches_the_sandbox(self, send_mock, _access_mock):+ run = self._run()++ self.assertFalse(self._apply(run, model="claude-fable-5", actor_user_id=self.user.id))+ send_mock.assert_not_called()++ @patch("products.tasks.backend.logic.services.agent_command.send_set_config_option")+ def test_nothing_to_change_is_not_a_sandbox_call(self, send_mock):+ self.assertFalse(self._apply(self._run()))+ send_mock.assert_not_called()