Skip to content

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

feat(slack_app): retire the Slack-local model pin store (#98293)

Vojta Bartoš5328eb7749ae
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 08dc2bd7c232..b1edfbe96564 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -662,9 +662,7 @@ def create_posthog_code_task_for_repo_activity(
from products.slack_app.backend.facade.run_preferences import resolve_run_preferences
- run_prefs = resolve_run_preferences(
- integration, slack_user_id, override=model_override, team_id=integration.team_id, user_id=user_id
- )
+ run_prefs = resolve_run_preferences(override=model_override, team_id=integration.team_id, user_id=user_id)
# 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.
@@ -1179,8 +1177,6 @@ def _apply_followup_model_override(
def _run_preference_state(
- integration: Any,
- slack_user_id: str,
model_override: SlackAppModelOverride | None,
*,
team_id: int | None = None,
@@ -1195,9 +1191,7 @@ def _run_preference_state(
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, team_id=team_id, user_id=user_id
- )
+ prefs = resolve_run_preferences(override=model_override, team_id=team_id, user_id=user_id)
provider = get_provider_for_runtime_adapter(prefs.runtime_adapter) if prefs.runtime_adapter else None
state = {
"runtime_adapter": prefs.runtime_adapter,
@@ -1361,11 +1355,7 @@ def _resume_task_with_new_run(
# 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, team_id=mapping.task.team_id, user_id=run_actor.id
- )
- )
+ extra_state.update(_run_preference_state(model_override, team_id=mapping.task.team_id, user_id=run_actor.id))
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/tests/ai/slack_app/activities/test_followup_model_override.py b/posthog/temporal/tests/ai/slack_app/activities/test_followup_model_override.py
index 33e80d907ab7..f3d0f07724be 100644
--- 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.py
@@ -145,5 +145,5 @@ class TestRunPreferenceState:
"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)
+ state = _run_preference_state(model_override=None)
assert state == expected
diff --git a/products/slack_app/backend/facade/run_preferences.py b/products/slack_app/backend/facade/run_preferences.py
index 086869235409..1cb96f8f5f68 100644
--- a/products/slack_app/backend/facade/run_preferences.py
+++ b/products/slack_app/backend/facade/run_preferences.py
@@ -1,9 +1,8 @@
"""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.
+here rather than reaching into `services/`: the model catalogue and the precedence
+that resolves it for one run.
"""
from products.slack_app.backend.services.model_catalogue import (
diff --git a/products/slack_app/backend/facade/slack_settings.py b/products/slack_app/backend/facade/slack_settings.py
deleted file mode 100644
index 9189b7f5ceea..000000000000
--- a/products/slack_app/backend/facade/slack_settings.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""Facade re-exports for the Slack-app per-(workspace, user) settings subsystem.
-
-Cross-product callers (e.g. Temporal activities under `posthog/temporal/`)
-import from here rather than reaching into `services/`. Mirrors the layering
-in `products/tasks/backend/facade/`.
-"""
-
-from products.slack_app.backend.services.slack_settings import (
- AIPreferences,
- resolve_ai_preferences,
- validate_ai_preferences,
-)
-
-__all__ = [
- "AIPreferences",
- "resolve_ai_preferences",
- "validate_ai_preferences",
-]
diff --git a/products/slack_app/backend/migrations/0017_remove_slacksettings_ai_preferences.py b/products/slack_app/backend/migrations/0017_remove_slacksettings_ai_preferences.py
new file mode 100644
index 000000000000..53f99cdfe358
--- /dev/null
+++ b/products/slack_app/backend/migrations/0017_remove_slacksettings_ai_preferences.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.17 on 2026-09-10 12:39
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("slack_app", "0016_backfill_model_pins_to_tasks"),
+ ]
+
+ # State-only removal: the column stays in Postgres so in-flight requests on
+ # the previous release keep working and a rollback still finds it. A later
+ # migration may drop the column with RunSQL once this has been deployed for
+ # a full cycle — see safe-django-migrations.md, "Dropping Columns".
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="slacksettings",
+ name="ai_preferences",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txt
index bf614416c3b7..60bcbfddf7ee 100644
--- a/products/slack_app/backend/migrations/max_migration.txt
+++ b/products/slack_app/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0016_backfill_model_pins_to_tasks
+0017_remove_slacksettings_ai_preferences
diff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.py
index 0ce01d977d39..c37536aa2b79 100644
--- a/products/slack_app/backend/models.py
+++ b/products/slack_app/backend/models.py
@@ -144,8 +144,8 @@ class SlackSettings(UUIDModel):
resolution time.
"""
- # Nullable so a personal row can carry AI preferences while inheriting the
- # workspace routing default.
+ # Nullable so a personal row can carry other settings (e.g. the follow-up
+ # mode) while inheriting the workspace routing default.
default_integration = models.ForeignKey(
"posthog.Integration",
on_delete=models.CASCADE,
@@ -162,8 +162,6 @@ class SlackSettings(UUIDModel):
null=True,
help_text="Per-integration permission mode for Slack-started agent runs, keyed by integration id.",
)
- # Keys mirror the task-run request serializer.
- ai_preferences = models.JSONField(blank=True, null=True)
# NULL means the user has never picked, which resolves to ``NEVER``: nothing
# is picked up in their threads until they turn it on from the Home tab.
untagged_followup_mode = models.CharField(
@@ -197,18 +195,6 @@ class SlackSettings(UUIDModel):
target = self.default_integration_id if self.default_integration_id else "(inherit)"
return f"{self.slack_workspace_id} / {who} → integration {target}"
- @property
- def runtime_adapter(self) -> str | None:
- return (self.ai_preferences or {}).get("runtime_adapter")
-
- @property
- def model(self) -> str | None:
- return (self.ai_preferences or {}).get("model")
-
- @property
- def reasoning_effort(self) -> str | None:
- return (self.ai_preferences or {}).get("reasoning_effort")
-
class SlackChannel(UUIDModel):
"""Per-(Slack workspace, Slack channel) state.
diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.py
index 5870c1eb55d3..e38c9361510e 100644
--- a/products/slack_app/backend/services/run_preferences.py
+++ b/products/slack_app/backend/services/run_preferences.py
@@ -1,10 +1,11 @@
"""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.
+("use fable for this one") beats the central per-(user, project) default, which
+falls back to the Slack default. Model preferences live only in the central
+tasks config (the App Home, the web composer, and the MCP config tools all edit
+it); 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
@@ -29,11 +30,9 @@ from products.slack_app.backend.services.model_catalogue import (
filter_unsupported_effort,
runtime_adapter_for,
)
-from products.slack_app.backend.services.slack_settings import AIPreferences, resolve_ai_preferences
+from products.slack_app.backend.services.slack_settings import AIPreferences
if TYPE_CHECKING:
- from posthog.models.integration import Integration
-
from products.tasks.backend.logic.services.ai_run_defaults import ResolvedAIRunConfig
# What a Slack run uses when neither the user nor the workspace has pinned a model.
@@ -81,8 +80,6 @@ def _coherent_preferences(
def resolve_run_preferences(
- integration: Integration,
- slack_user_id: str | None,
*,
override: ModelOverride | None = None,
team_id: int | None = None,
@@ -94,39 +91,34 @@ def resolve_run_preferences(
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.
-
- Below the saved rows sits the project/user default, which this looks up itself so
- every Slack path — first run and follow-up alike — sits at the same rung. Slack's own
- floor applies only when there is no central default to defer to. `team_id` and
- `user_id` say whose defaults those are; omitting `team_id` skips the level, which is
- what a caller with no project context (or a test exercising the Slack rungs alone)
- wants.
-
- 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 fallback plus
- whatever the mention asked for.
+ model doesn't support — leaves the run on the default it was already resolving to.
+
+ Below the mention sits the central project/user default, which this looks up
+ itself so every Slack path — first run and follow-up alike — sits at the same
+ rung. Slack's own floor applies only when there is no central default to defer
+ to. `team_id` and `user_id` say whose defaults those are; omitting `team_id`
+ skips the level, which is what a caller with no project context (or a test
+ exercising the Slack rungs alone) wants.
"""
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.
+ # Only a model named in the mention needs the catalogue, so it is not 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)
# Slack's floor would make the project and user defaults unreachable from Slack: the
# run would always carry an explicit model. Stepping aside when a central default
# exists leaves the triple empty, so `create_run` resolves it (and a warm run
- # provisioned under that default still matches). Anything pinned in Slack wins.
+ # provisioned under that default still matches).
central_default = _central_run_default(team_id, user_id) if team_id is not None else None
- base = _coherent_preferences(
- saved.model or (None if central_default else SLACK_DEFAULT_MODEL),
- saved.reasoning_effort,
- fallback_runtime_adapter=saved.runtime_adapter,
+ base = (
+ AIPreferences()
+ if central_default
+ else _coherent_preferences(SLACK_DEFAULT_MODEL, None, fallback_runtime_adapter=None)
)
if not override_effort:
return base
@@ -136,7 +128,7 @@ def resolve_run_preferences(
# anyway — a run at a different effort is not the run it would have produced, so there
# is nothing left to defer.
target = base
- if base.model is None and central_default is not None:
+ if central_default is not None:
target = _coherent_preferences(
central_default.model,
central_default.reasoning_effort,
@@ -145,8 +137,8 @@ def resolve_run_preferences(
# 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 — still deferring where it was deferring — instead of quietly clearing
- # the saved effort as well.
+ # run alone — still deferring where it was deferring — instead of pinning a default
+ # it was never asked to pin.
requested = _coherent_preferences(target.model, override_effort, fallback_runtime_adapter=target.runtime_adapter)
return requested if requested.reasoning_effort else base
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index 8e0a2c226f12..c6e956fb5b81 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -22,7 +22,6 @@ from typing import Any
from django.conf import settings
from django.core.exceptions import ValidationError
-from django.db import transaction
from django.http import HttpResponse, JsonResponse
import structlog
@@ -60,11 +59,7 @@ from products.slack_app.backend.services.slack_app_home_stats import (
build_stats_state,
coerce_window_days,
)
-from products.slack_app.backend.services.slack_settings import (
- AIPreferences,
- resolve_ai_preferences,
- resolve_untagged_followup_mode,
-)
+from products.slack_app.backend.services.slack_settings import AIPreferences, resolve_untagged_followup_mode
from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin
from products.slack_app.backend.services.slack_user_oauth import build_invite_url, find_linked_posthog_user
@@ -215,37 +210,6 @@ def _runtime_adapter_options() -> tuple[tuple[str, str], ...]:
return tuple((a.value, a.label) for a in get_picker_choices())
-@dataclass(frozen=True)
-class PreferenceSource:
- """Whether the user's own row contributed the effective `(runtime_adapter,
- model)` pair.
-
- Used to render the "Source: …" line on the active-model card so it's clear
- at a glance whether the running model is a personal pick.
- """
-
- label: str
-
- @classmethod
- def personal(cls) -> PreferenceSource:
- return cls(label="Your personal override")
-
- @classmethod
- def unset(cls) -> PreferenceSource:
- return cls(label="System default")
-
-
-def resolve_source(user_row: SlackSettings | None) -> PreferenceSource:
- """Return where the effective pair came from.
-
- Mirrors the same atomic-pair rule the resolver uses: a row only "sources"
- the pair when both halves are set on it.
- """
- if user_row and user_row.runtime_adapter and user_row.model:
- return PreferenceSource.personal()
- return PreferenceSource.unset()
-
-
@dataclass(frozen=True)
class ProjectChoice:
"""One PostHog project the user can route their @PostHog mentions to."""
@@ -402,12 +366,9 @@ class GitHubState:
@dataclass(frozen=True)
class RunDefaultsState:
- """The PostHog-side default a Slack run falls back to once nothing in Slack applies.
-
- Slack's own rows sit above this; below it sits Slack's hardcoded floor. The card reads
- it so what it names is what a mention would actually launch on, rather than a constant
- that stopped being the answer once project and personal defaults existed.
- """
+ """The central PostHog default a Slack run resolves to; only a model named in
+ the mention sits above it, and Slack's hardcoded floor below. The card reads
+ it so what it names is what a mention would actually launch on."""
model: str | None = None
reasoning_effort: str | None = None
@@ -427,8 +388,6 @@ class RunDefaultsState:
def render_home_view(
*,
- effective: AIPreferences,
- user_row: SlackSettings | None,
is_admin: bool,
run_defaults: RunDefaultsState | None = None,
account_state: AccountState | None = None,
@@ -441,7 +400,7 @@ def render_home_view(
) -> dict:
"""Render the Block Kit payload for `views.publish` on the App Home tab."""
- source = resolve_source(user_row)
+ run_defaults = run_defaults or RunDefaultsState()
blocks: list[dict] = []
blocks.extend(_header_blocks())
@@ -468,12 +427,11 @@ def render_home_view(
blocks.extend(_project_section_blocks(project_state, is_admin=is_admin))
# Section 3 — AI model settings: which model handles those mentions.
- # Headline shows the effective triple (and its source), with the personal
- # picker underneath. Purely a per-user preference — there's no workspace-wide
- # model default to inherit from.
+ # Headline shows the resolved central default (and its source), with the
+ # personal editor underneath.
blocks.append({"type": "divider"})
- blocks.extend(_active_model_blocks(effective, source, run_defaults or RunDefaultsState()))
- blocks.extend(_personal_section_blocks(user_row, run_defaults or RunDefaultsState()))
+ blocks.extend(_active_model_blocks(run_defaults))
+ blocks.extend(_personal_section_blocks(run_defaults))
# Section 4 — thread follow-ups: whether replies other people leave in the
# threads you started reach PostHog on their own. Absent when the workspace
@@ -607,38 +565,28 @@ def _no_project_access_blocks() -> list[dict]:
return blocks
-def _active_model_blocks(
- effective: AIPreferences, source: PreferenceSource, run_defaults: RunDefaultsState
-) -> list[dict]:
- """Headline that shows which model is actually running, and why.
+def _active_model_blocks(run_defaults: RunDefaultsState) -> list[dict]:
+ """Headline that shows which model handles this viewer's mentions, and why.
- Three rungs, named in the order the run resolves them: a Slack row, else the PostHog
- project/personal default, else Slack's own floor. Naming the floor unconditionally
- would describe a run that isn't going to happen wherever a PostHog default is set.
+ Two rungs, in resolution order: the central PostHog default (personal or
+ project), else Slack's own floor.
"""
header = _section_title(
"🤖 AI model",
- "Which Claude / Codex configuration handles your @PostHog mentions. "
- "Set one here to override what your PostHog defaults would pick.",
+ "Which Claude / Codex configuration handles your @PostHog mentions.",
)
- if not effective.is_empty:
+ if run_defaults.applies:
headline = (
# Same phrasing as the notice a mention override posts, so the card and the
# thread describe a run the same way.
- f"Currently running {describe_run_model(effective.model, effective.reasoning_effort)}"
- f" · {label_for(effective.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}"
- )
- source_label = source.label
- elif run_defaults.applies:
- headline = (
f"Currently running {describe_run_model(run_defaults.model, run_defaults.reasoning_effort)}"
f" · {label_for(run_defaults.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}"
)
- source_label = f"{run_defaults.source_label} in PostHog"
+ source_label = run_defaults.source_label
else:
headline = f"Defaulting to {display_name_for_model(SLACK_DEFAULT_MODEL)}. Pick your own settings to override."
- source_label = source.label
+ source_label = "System default"
blocks: list[dict] = [
header,
@@ -652,8 +600,8 @@ def _active_model_blocks(
"elements": [
{
"type": "mrkdwn",
- "text": f"<{run_defaults.settings_url}|Task agent defaults in PostHog> apply everywhere — "
- "the task composer, PostHog Desktop, and Slack when nothing is set here.",
+ "text": f"<{run_defaults.settings_url}|Task agent defaults in PostHog> apply everywhere: "
+ "the task composer, PostHog Desktop, and Slack.",
}
],
}
@@ -836,20 +784,18 @@ def _github_account_button(github_state: GitHubState) -> dict | None:
return button
-def _personal_section_blocks(user_row: SlackSettings | None, run_defaults: RunDefaultsState) -> list[dict]:
- """Personal AI override sub-card. Always editable by the user themselves.
+def _personal_section_blocks(run_defaults: RunDefaultsState) -> list[dict]:
+ """Personal default sub-card. Always editable by the user themselves.
- Saves land on the central per-user tasks config, so the reset button also
- shows when that config carries a personal default (`run_defaults.source ==
- "user"`) with no Slack pin left — otherwise a preference saved here a
- moment ago would render with no way back.
+ Edits land on the viewer's central per-(user, project) tasks config, so
+ whether they have a personal default is read off `run_defaults.source`.
"""
- has_override = bool(user_row and user_row.runtime_adapter and user_row.model)
+ has_preference = run_defaults.source == "user"
summary = (
- _row_summary(user_row)
- if has_override
- else "_No personal override. Inheriting your PostHog task agent default._"
+ "_Your personal default (shown above) applies to Slack, the task composer, and PostHog Desktop._"
+ if has_preference
+ else "_No personal default. Inheriting the project default._"
)
actions: list[dict] = [
@@ -859,7 +805,7 @@ def _personal_section_blocks(user_row: SlackSettings | None, run_defaults: RunDe
"text": {"type": "plain_text", "text": "Edit my settings", "emoji": True},
}
]
- if has_override or run_defaults.source == "user":
+ if has_preference:
actions.append(
{
"type": "button",
@@ -867,12 +813,11 @@ def _personal_section_blocks(user_row: SlackSettings | None, run_defaults: RunDe
"style": "danger",
"text": {"type": "plain_text", "text": "Reset to default", "emoji": True},
"confirm": {
- "title": {"type": "plain_text", "text": "Clear your model preference?"},
+ "title": {"type": "plain_text", "text": "Clear your personal default?"},
"text": {
"type": "mrkdwn",
- "text": "This clears your Slack override and your task agent default, which the "
- "composer and PostHog Desktop use too. You'll inherit the project default "
- "until you set a new one.",
+ "text": "This clears your task agent default, which the composer and PostHog "
+ "Desktop use too. You'll inherit the project default until you set a new one.",
},
"confirm": {"type": "plain_text", "text": "Reset"},
"deny": {"type": "plain_text", "text": "Cancel"},
@@ -881,7 +826,7 @@ def _personal_section_blocks(user_row: SlackSettings | None, run_defaults: RunDe
)
return [
- _subsection_label("Your override"),
+ _subsection_label("Your default"),
{"type": "section", "text": {"type": "mrkdwn", "text": summary}},
{"type": "actions", "elements": actions},
]
@@ -1338,18 +1283,6 @@ def _stats_footnote_blocks(state: StatsState) -> list[dict]:
return blocks
-def _row_summary(row: SlackSettings | None) -> str:
- if not row or not row.runtime_adapter or not row.model:
- return "_(none)_"
- parts = [
- f"*Model:* {display_name_for_model(row.model)}",
- f"*Runtime:* {label_for(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",
- ]
- if row.reasoning_effort:
- parts.append(f"*Reasoning:* {label_for(row.reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}")
- return " · ".join(parts)
-
-
# ---------------------------------------------------------------------------
# Edit modal
# ---------------------------------------------------------------------------
@@ -1528,33 +1461,10 @@ def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Inte
if not slack_user_id:
return
- effective = resolve_ai_preferences(integration, slack_user_id)
- user_row = _load_user_row(integration, slack_user_id)
-
slack = SlackIntegration(integration)
- is_admin = _is_admin(slack, integration, slack_user_id)
- accessible = _accessible_integrations(integration, slack_user_id)
- account_state = _resolve_account_state(integration, slack_user_id)
- github_state = _resolve_github_state(integration, slack_user_id)
- project_state = _resolve_project_state(integration, slack_user_id, accessible=accessible)
- tasks_state = _resolve_tasks_state(integration, slack_user_id, accessible=accessible)
- stats_state = _resolve_stats_state(integration, accessible=accessible, is_admin=is_admin)
-
- view = render_home_view(
- effective=effective,
- user_row=user_row,
- is_admin=is_admin,
- run_defaults=_resolve_run_defaults_state(integration, slack_user_id, accessible=accessible),
- account_state=account_state,
- github_state=github_state,
- project_state=project_state,
- tasks_state=tasks_state,
- stats_state=stats_state,
- untagged_followup_mode=resolve_untagged_followup_mode(integration, slack_user_id),
- has_project_access=bool(accessible),
- )
+ render = _build_home_view(slack, integration, slack_user_id)
try:
- slack.client.views_publish(user_id=slack_user_id, view=view)
+ slack.client.views_publish(user_id=slack_user_id, view=render.view)
except Exception:
logger.exception(
"slack_app_home_publish_failed",
@@ -1571,8 +1481,8 @@ def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Inte
integration,
"slack app home opened",
slack_user_id=slack_user_id,
- account_linked=bool(account_state.linked_email),
- has_project_access=bool(accessible),
+ account_linked=bool(render.account_state.linked_email),
+ has_project_access=render.has_project_access,
)
@@ -1746,20 +1656,27 @@ def _resolve_interaction_integration(slack_team_id: str, slack_user_id: str) ->
return result.resolved_or_first()
-def _load_user_row(integration: Integration, slack_user_id: str) -> SlackSettings | None:
- return SlackSettings.objects.filter(
- slack_workspace_id=integration.integration_id,
- slack_user_id=slack_user_id,
- ).first()
+def _stored_personal_preferences(integration: Integration, slack_user_id: str) -> AIPreferences:
+ """The viewer's stored central preference, for prefilling the edit modal.
+ Deliberately the stored per-user value rather than the resolved default: the
+ modal edits their personal preference, so a project default must not appear
+ preselected as if they had chosen it. Empty for a viewer with no resolvable
+ target — the modal still opens, and the save then reports what is missing.
+ """
+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path
+ ai_run_defaults,
+ )
-def _row_to_settings(row: SlackSettings | None) -> AIPreferences:
- if row is None:
+ try:
+ user, target = _personal_preference_target(integration, slack_user_id)
+ except ValidationError:
return AIPreferences()
+ stored = ai_run_defaults.get_user_ai_run_preferences(target.team_id, user.id)
return AIPreferences(
- runtime_adapter=row.runtime_adapter,
- model=row.model,
- reasoning_effort=row.reasoning_effort,
+ runtime_adapter=stored.get("runtime_adapter"),
+ model=stored.get("model"),
+ reasoning_effort=stored.get("reasoning_effort"),
)
@@ -1776,7 +1693,7 @@ def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id:
def _open_edit_modal(integration: Integration, slack_user_id: str, *, trigger_id: str) -> None:
- current = _row_to_settings(_load_user_row(integration, slack_user_id))
+ current = _stored_personal_preferences(integration, slack_user_id)
supported = _supported_efforts(current.runtime_adapter, current.model)
slack = SlackIntegration(integration)
@@ -1926,10 +1843,8 @@ def _apply_personal_preferences(
"""Persist the modal's triple as the viewer's central tasks preference.
The central per-(user, project) config — the same store the web composer,
- PostHog Desktop, and the MCP config tools edit — is where model preferences
- live; the Slack-local pin store is being retired. The Slack row's AI fields
- are cleared in the same transaction so a pre-existing pin cannot shadow the
- save, and cannot outlive a failed one.
+ PostHog Desktop, and the MCP config tools edit — is the only place a model
+ preference lives.
Raises `ValidationError` when the viewer has no authorized target project
(see `_personal_preference_target`) or picks a model their account is not
@@ -1948,24 +1863,19 @@ def _apply_personal_preferences(
if access_error is not None:
raise ValidationError(access_error)
- with transaction.atomic():
- ai_run_defaults.update_user_ai_run_preferences(
- target.team_id,
- user.id,
- runtime_adapter=runtime_adapter,
- model=model,
- reasoning_effort=reasoning_effort,
- )
- _clear_personal_override(integration, slack_user_id)
+ ai_run_defaults.update_user_ai_run_preferences(
+ target.team_id,
+ user.id,
+ runtime_adapter=runtime_adapter,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ )
def _reset_personal_preferences(integration: Integration, slack_user_id: str) -> None:
- """Clear the viewer's model preference wherever it lives.
-
- For a mapped viewer that is the central per-(user, project) config, which
- resets them to the project default. The Slack row's AI fields are cleared
- either way, so an old pin cannot resurface after the reset.
- """
+ """Clear the viewer's central per-(user, project) preference, which resets
+ them to the project default. The reset button only renders for viewers with
+ such a preference, so an unmapped viewer is a no-op here."""
from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path
ai_run_defaults,
)
@@ -1973,18 +1883,15 @@ def _reset_personal_preferences(integration: Integration, slack_user_id: str) ->
try:
user, target = _personal_preference_target(integration, slack_user_id)
except ValidationError:
- # Nothing central to clear for this viewer; the Slack row still gets cleaned.
- _clear_personal_override(integration, slack_user_id)
+ # Nothing central to clear for this viewer.
return
- with transaction.atomic():
- ai_run_defaults.update_user_ai_run_preferences(
- target.team_id,
- user.id,
- runtime_adapter=None,
- model=None,
- reasoning_effort=None,
- )
- _clear_personal_override(integration, slack_user_id)
+ ai_run_defaults.update_user_ai_run_preferences(
+ target.team_id,
+ user.id,
+ runtime_adapter=None,
+ model=None,
+ reasoning_effort=None,
+ )
def _apply_untagged_followup_mode_pick(integration: Integration, slack_user_id: str, action: dict) -> None:
@@ -2000,15 +1907,6 @@ def _apply_untagged_followup_mode_pick(integration: Integration, slack_user_id:
)
-def _clear_personal_override(integration: Integration, slack_user_id: str) -> None:
- """Clear just the AI fields on the user's row. Leaves routing alone."""
-
- SlackSettings.objects.filter(
- slack_workspace_id=integration.integration_id,
- slack_user_id=slack_user_id,
- ).update(ai_preferences=None)
-
-
def _clear_project_personal(integration: Integration, slack_user_id: str) -> None:
"""Clear the personal routing override; drop the row once it holds nothing else."""
@@ -2018,23 +1916,38 @@ def _clear_project_personal(integration: Integration, slack_user_id: str) -> Non
).first()
if row is None:
return
- if not row.ai_preferences and not row.untagged_followup_mode:
+ if not row.untagged_followup_mode:
row.delete()
return
row.default_integration = None
row.save(update_fields=["default_integration", "updated_at"])
-def _republish_home(
+@dataclass(frozen=True)
+class _HomeRender:
+ """One viewer's rendered Home tab, plus the card states the callers log
+ and report analytics on."""
+
+ view: dict
+ tasks_state: TasksState
+ account_state: AccountState
+ has_project_access: bool
+
+
+def _build_home_view(
+ slack: SlackIntegration,
integration: Integration,
slack_user_id: str,
*,
view_state: HomeViewState | None = None,
-) -> None:
+) -> _HomeRender:
+ """Resolve every card's state for this viewer and render the Home tab payload.
+
+ Shared by the first publish and every interaction republish. `view_state`
+ carries the controls a click resolved to; its defaults match the resolvers'
+ own, so the first publish can omit it.
+ """
view_state = view_state or HomeViewState()
- user_row = _load_user_row(integration, slack_user_id)
- effective = resolve_ai_preferences(integration, slack_user_id)
- slack = SlackIntegration(integration)
is_admin = _is_admin(slack, integration, slack_user_id)
accessible = _accessible_integrations(integration, slack_user_id)
account_state = _resolve_account_state(integration, slack_user_id)
@@ -2056,8 +1969,6 @@ def _republish_home(
force_refresh=view_state.stats_force_refresh,
)
view = render_home_view(
- effective=effective,
- user_row=user_row,
is_admin=is_admin,
run_defaults=_resolve_run_defaults_state(integration, slack_user_id, accessible=accessible),
account_state=account_state,
@@ -2068,8 +1979,25 @@ def _republish_home(
untagged_followup_mode=resolve_untagged_followup_mode(integration, slack_user_id),
has_project_access=bool(accessible),
)
+ return _HomeRender(
+ view=view,
+ tasks_state=tasks_state,
+ account_state=account_state,
+ has_project_access=bool(accessible),
+ )
+
+
+def _republish_home(
+ integration: Integration,
+ slack_user_id: str,
+ *,
+ view_state: HomeViewState | None = None,
+) -> None:
+ view_state = view_state or HomeViewState()
+ slack = SlackIntegration(integration)
+ render = _build_home_view(slack, integration, slack_user_id, view_state=view_state)
try:
- slack.client.views_publish(user_id=slack_user_id, view=view)
+ slack.client.views_publish(user_id=slack_user_id, view=render.view)
except Exception:
logger.exception("slack_app_home_republish_failed")
return
@@ -2079,9 +2007,9 @@ def _republish_home(
"slack_app_home_republished",
slack_user_id=slack_user_id,
slack_team_id=integration.integration_id,
- slack_app_home_tasks_page=tasks_state.page,
- slack_app_home_tasks_total_pages=tasks_state.total_pages,
- slack_app_home_tasks_shown=len(tasks_state.items),
+ slack_app_home_tasks_page=render.tasks_state.page,
+ slack_app_home_tasks_total_pages=render.tasks_state.total_pages,
+ slack_app_home_tasks_shown=len(render.tasks_state.items),
slack_app_home_selected_repo=view_state.selected_repo,
slack_app_home_selected_status=view_state.selected_status,
slack_app_home_stats_window_days=view_state.stats_window_days,
diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.py
index d987dfec51c8..7f780ce8828e 100644
--- a/products/slack_app/backend/services/slack_settings.py
+++ b/products/slack_app/backend/services/slack_settings.py
@@ -1,33 +1,19 @@
-"""Read/write helpers for per-(Slack workspace, Slack user) settings backed
-by `models.SlackSettings`. Exposes AI-preference resolution and the untagged
-follow-up mode; future per-user / per-workspace knobs belong here too.
-
-Key names mirror the task-run request serializer
-(`products/tasks/backend/presentation/serializers.py`) so the resolver output
-can be handed to the task layer with zero translation.
-
-Resolution: AI preferences are a personal setting. Only the user's own row
-counts, and only when it carries the atomic `(runtime_adapter, model)` pair —
-a half-set row reads as "no preference" rather than half-applying.
-`reasoning_effort` is dropped if the resolved model doesn't support it, so a
-stale effort from a previous model choice can't silently stick. Unset keys
-stay `None` so the task layer applies its own defaults rather than
-duplicating them here.
-
-Layering with the tasks product's central defaults: the resolved triple is
-passed to task creation as explicit per-run values, so Slack preferences sit
-above the central per-user / per-team defaults (see
-`products.tasks.backend.facade.ai_run_defaults`). When both Slack rows are
-empty the task layer falls back to those central defaults on its own.
+"""Read helpers for per-(Slack workspace, Slack user) settings backed by
+`models.SlackSettings` (today: the untagged follow-up mode), plus the shared
+AI-triple value object.
+
+Model preferences themselves live in the central tasks config
+(`products.tasks.backend.facade.ai_run_defaults`); `AIPreferences` keeps the
+task-run serializer's field names so resolver output can be handed to the task
+layer with zero translation.
"""
from __future__ import annotations
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING
from products.slack_app.backend.models import UntaggedFollowupMode
-from products.slack_app.backend.services.model_catalogue import filter_unsupported_effort
if TYPE_CHECKING:
from posthog.models.integration import Integration
@@ -35,7 +21,7 @@ if TYPE_CHECKING:
@dataclass(frozen=True)
class AIPreferences:
- """Resolved AI preferences for a single (workspace, slack_user_id) lookup.
+ """A resolved AI-preference triple.
Field names match the task-run request serializer so callers can splat this
straight into the task creation payload.
@@ -45,57 +31,6 @@ class AIPreferences:
model: str | None = None
reasoning_effort: str | None = None
- @property
- def is_empty(self) -> bool:
- return self.runtime_adapter is None and self.model is None and self.reasoning_effort is None
-
-
-_EMPTY = AIPreferences()
-
-
-def resolve_ai_preferences(integration: Integration, slack_user_id: str | None) -> AIPreferences:
- """Resolve the effective AI preferences for a Slack user in a workspace.
-
- Only the user's own row counts, and only when it carries the atomic
- `(runtime_adapter, model)` pair. `reasoning_effort` is dropped if the
- resolved model doesn't support it.
- """
-
- if not slack_user_id:
- return _EMPTY
-
- from products.slack_app.backend.models import SlackSettings
-
- row = (
- SlackSettings.objects.filter(
- slack_workspace_id=integration.integration_id,
- slack_user_id=slack_user_id,
- )
- .values("ai_preferences")
- .first()
- )
- # Pulled into a local dict so mypy can give it a definite type — the
- # JSONField reads back as `Any | None`.
- prefs: dict[str, Any] = (row["ai_preferences"] if row else None) or {}
-
- # `validate_ai_preferences` enforces that `runtime_adapter` and `model` are
- # set together, so a row missing either half was never explicitly
- # configured and contributes nothing.
- runtime_adapter = prefs.get("runtime_adapter") or None
- model = prefs.get("model") or None
- if not runtime_adapter or not model:
- return _EMPTY
-
- reasoning_effort = prefs.get("reasoning_effort") or None
- if reasoning_effort:
- reasoning_effort = filter_unsupported_effort(runtime_adapter, model, reasoning_effort)
-
- return AIPreferences(
- runtime_adapter=runtime_adapter,
- model=model,
- reasoning_effort=reasoning_effort,
- )
-
def resolve_untagged_followup_mode(integration: Integration, slack_user_id: str | None) -> UntaggedFollowupMode:
"""Resolve how untagged replies in a thread this Slack user started are treated.
@@ -125,60 +60,7 @@ def resolve_untagged_followup_mode(integration: Integration, slack_user_id: str
return UntaggedFollowupMode.NEVER
-def build_ai_preferences_payload(
- runtime_adapter: str | None,
- model: str | None,
- reasoning_effort: str | None,
-) -> dict[str, str]:
- """Pack the triple into the JSON shape stored on `SlackSettings.ai_preferences`.
-
- The same shape the tasks product stores on `ai_run_preferences`, so the packing
- rule lives there and this is the Slack-side name for it.
- """
- from products.tasks.backend.facade.ai_run_defaults import ( # noqa: PLC0415 — matches the deferred tasks-facade imports below
- build_ai_run_preferences_payload,
- )
-
- return build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)
-
-
-def validate_ai_preferences(
- runtime_adapter: str | None,
- model: str | None,
- reasoning_effort: str | None,
-) -> None:
- """Validate the `(runtime_adapter, model, reasoning_effort)` triple.
-
- Raises `django.core.exceptions.ValidationError` if the triple is internally
- inconsistent. Call this from the write path so half-set rows never reach
- the DB. The storage rule — both halves of the pair or neither — lives here;
- whether the three values may be used together is the model catalogue's call.
- """
- from django.core.exceptions import ValidationError
-
- from products.tasks.backend.facade.run_config import PUBLIC_REASONING_EFFORTS, validate_model_selection
-
- if (runtime_adapter is None) != (model is None):
- raise ValidationError(
- "runtime_adapter and model must be set together — set both to override the default, or both to null to inherit."
- )
-
- # The catalogue only judges an effort against a model, so an effort stored without a
- # pair — legal, and inherited by whatever model resolves later — still needs a check.
- if reasoning_effort is not None:
- valid_efforts = {e.value for e in PUBLIC_REASONING_EFFORTS}
- if reasoning_effort not in valid_efforts:
- raise ValidationError(
- f"Unknown reasoning_effort '{reasoning_effort}'. Valid: {', '.join(sorted(valid_efforts))}."
- )
-
- validate_model_selection(runtime_adapter, model, reasoning_effort)
-
-
__all__ = [
"AIPreferences",
- "build_ai_preferences_payload",
- "resolve_ai_preferences",
"resolve_untagged_followup_mode",
- "validate_ai_preferences",
]
diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.py
index d72877979664..71a88cf64aa8 100644
--- a/products/slack_app/backend/tests/services/test_run_preferences.py
+++ b/products/slack_app/backend/tests/services/test_run_preferences.py
@@ -28,8 +28,6 @@ CATALOGUE = (
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")
-
@pytest.fixture
def catalogue():
@@ -45,87 +43,59 @@ class _Override:
reasoning_effort: str | None = None
-def _resolve(
- saved: AIPreferences,
- override_model=None,
- override_effort=None,
- central_default=None,
-):
- """Resolve with the saved rows and the central default both stubbed, so these stay
- unit tests over the precedence rules rather than over the rows behind them."""
- with (
- patch.object(run_preferences, "resolve_ai_preferences", return_value=saved),
- patch.object(run_preferences, "_central_run_default", return_value=central_default),
- ):
+def _resolve(override_model=None, override_effort=None, central_default=None):
+ """Resolve with the central default stubbed, so these stay unit tests over the
+ precedence rules rather than over the rows behind them."""
+ with patch.object(run_preferences, "_central_run_default", return_value=central_default):
return resolve_run_preferences(
- integration=None, # type: ignore[arg-type]
- slack_user_id="U1",
override=_Override(model=override_model, reasoning_effort=override_effort),
- # Any id will do — the lookup it feeds is stubbed; passing one is what opts the
- # central-default rung into the chain at all.
+ # Any ids will do — the lookup they feed is stubbed; passing team_id is what
+ # opts the central-default rung into the chain at all.
team_id=1,
+ user_id=7,
)
+CENTRAL = AIPreferences(runtime_adapter="claude", model="claude-fable-5", reasoning_effort=None)
+
+
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")),
+ # A model named in the mention wins outright, over central and floor alike.
("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),
+ # Nothing on offer matches, so the run keeps deferring to the central default.
+ ("gemini-3-pro", None, AIPreferences(None, None, None)),
+ (None, None, AIPreferences(None, None, None)),
# `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_mention_override_precedence_over_a_central_default(
+ self, catalogue, override_model, override_effort, expected
+ ):
+ assert _resolve(override_model, override_effort, central_default=CENTRAL) == 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_falls_back_to_the_slack_default_when_nothing_is_configured(self, catalogue):
+ """A user with no preference anywhere must still get a pinned model, not
+ whatever the agent server would otherwise choose."""
+ assert _resolve() == 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")
+ def test_override_applies_on_top_of_the_floor(self, catalogue):
+ resolved = _resolve(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"
-
- # Pinning a model unconditionally is what put the project and user defaults out of
- # reach from Slack, and it fails silently — the run still works, just never on the
- # configured model. These lock the fall-through in both directions.
- @pytest.mark.parametrize(
- "saved,override_model,expected",
- [
- (AIPreferences(), None, AIPreferences(None, None, None)),
- (SAVED, None, SAVED),
- (AIPreferences(), "claude-fable-5", AIPreferences("claude", "claude-fable-5", None)),
- ],
- )
- def test_with_a_central_default_only_a_slack_selection_pins_the_run(
- self, catalogue, saved, override_model, expected
- ):
- central = AIPreferences(runtime_adapter="claude", model="claude-fable-5", reasoning_effort=None)
- assert _resolve(saved, override_model=override_model, central_default=central) == expected
+ # The floor pinning a model unconditionally is what put the project and user
+ # defaults out of reach from Slack, and it fails silently — the run still works,
+ # just never on the configured model. This locks the deferral in.
+ def test_a_central_default_leaves_the_triple_empty_for_downstream_resolution(self, catalogue):
+ assert _resolve(central_default=CENTRAL) == AIPreferences(None, None, None)
# An effort named on its own has no model to be validated against while the run is
# deferring, so without the deferred default it is silently dropped and the mention
@@ -143,7 +113,7 @@ class TestResolveRunPreferences:
self, catalogue, deferred_model, override_effort, expected
):
central = AIPreferences(runtime_adapter="claude", model=deferred_model, reasoning_effort=None)
- resolved = _resolve(AIPreferences(), override_effort=override_effort, central_default=central)
+ resolved = _resolve(override_effort=override_effort, central_default=central)
assert resolved == expected
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.py
index 14a8fc42438e..9f4f20656270 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
@@ -55,7 +55,6 @@ from products.slack_app.backend.services.slack_app_home import (
AccountState,
GitHubAccount,
GitHubState,
- PreferenceSource,
ProjectChoice,
ProjectState,
RunDefaultsState,
@@ -68,7 +67,6 @@ from products.slack_app.backend.services.slack_app_home import (
parse_modal_submission,
render_edit_modal,
render_home_view,
- resolve_source,
)
from products.slack_app.backend.services.slack_settings import AIPreferences
from products.tasks.backend.facade.ai_run_defaults import get_user_ai_run_preferences, update_user_ai_run_preferences
@@ -257,28 +255,6 @@ def _stub_picker_facade():
# ---------------------------------------------------------------------------
-@dataclass
-class _Row:
- """Duck-type stand-in for a SlackSettings row — keeps the renderer tests
- off the database. Declared at module scope (instead of inside the helper
- below) so mypy can resolve the dataclass-generated attribute types."""
-
- runtime_adapter: str | None = None
- model: str | None = None
- reasoning_effort: str | None = None
-
-
-def _make_row(
- *,
- runtime_adapter: str | None = None,
- model: str | None = None,
- reasoning_effort: str | None = None,
-) -> Any:
- # Returned as Any so call sites that pass this to render_home_view /
- # resolve_source (which expect a real `SlackSettings`) don't trip mypy.
- return _Row(runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort)
-
-
def _action_ids(view: dict) -> list[str]:
out: list[str] = []
for block in view["blocks"]:
@@ -413,11 +389,7 @@ def _view_submission_payload(
class TestRenderHomeView:
@pytest.mark.parametrize("is_admin", [False, True])
def test_empty_state_renders_buttons_and_no_reset(self, is_admin):
- view = render_home_view(
- effective=AIPreferences(),
- user_row=None,
- is_admin=is_admin,
- )
+ view = render_home_view(is_admin=is_admin)
assert view["type"] == "home"
ids = _action_ids(view)
# Personal edit always present; reset hidden when no override. Admins get
@@ -425,44 +397,30 @@ class TestRenderHomeView:
assert ACTION_EDIT_PERSONAL in ids
assert ACTION_RESET_PERSONAL not in ids
- def test_reset_shows_when_only_the_central_user_default_is_set(self):
- # A preference saved from this card lands on the central config and
- # clears the Slack pin, so reset must key off the central source too.
+ def test_reset_shows_when_the_viewer_has_a_personal_default(self):
view = render_home_view(
- effective=AIPreferences(),
- user_row=None,
is_admin=False,
run_defaults=RunDefaultsState(model="claude-opus-4-7", runtime_adapter="claude", source="user"),
)
assert ACTION_RESET_PERSONAL in _action_ids(view)
- def test_personal_override_renders_reset_button(self):
- view = render_home_view(
- effective=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),
- user_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),
- is_admin=False,
- )
- assert ACTION_RESET_PERSONAL in _action_ids(view)
-
def test_active_model_summary_mentions_model_label(self):
view = render_home_view(
- effective=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),
- user_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),
is_admin=True,
+ run_defaults=RunDefaultsState(model="claude-opus-4-7", runtime_adapter="claude", source="user"),
)
text_blob = " ".join(block["text"]["text"] for block in view["blocks"] if block.get("type") == "section")
# Friendly label rather than raw model id; source attribution visible.
assert "Claude Opus 4.7" in text_blob
- assert "Your personal override" in _all_text(view)
+ assert "Your PostHog default" in _all_text(view)
def test_every_control_the_tab_renders_is_routable(self):
# The interactivity endpoint claims region ownership and dispatches off
# HOME_ACTION_IDS, so a control missing from it renders as a button that
# silently does nothing. Render every card at once and check the whole set.
view = render_home_view(
- effective=AIPreferences(runtime_adapter="claude", model="claude-opus-4-7"),
- user_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7"),
is_admin=True,
+ run_defaults=RunDefaultsState(model="claude-opus-4-7", runtime_adapter="claude", source="user"),
account_state=AccountState(enabled=True, link_url="https://app/link"),
github_state=GitHubState(user_resolved=True, settings_url="https://app/settings"),
project_state=ProjectState(
@@ -499,23 +457,10 @@ class TestRenderHomeView:
# Unlink only renders once an account is linked, which this fixture deliberately isn't.
assert set(_action_ids(view)) == HOME_ACTION_IDS - {ACTION_UNLINK_ACCOUNT}
- def test_source_resolution_is_atomic(self):
- # A user row missing half the pair isn't a real override.
- assert resolve_source(_make_row(reasoning_effort="medium")) == PreferenceSource.unset()
- assert resolve_source(None) == PreferenceSource.unset()
- assert (
- resolve_source(_make_row(runtime_adapter="claude", model="claude-opus-4-7")) == PreferenceSource.personal()
- )
-
class TestThreadFollowupsCard:
def _view(self, mode) -> dict:
- return render_home_view(
- effective=AIPreferences(),
- user_row=None,
- is_admin=False,
- untagged_followup_mode=mode,
- )
+ return render_home_view(is_admin=False, untagged_followup_mode=mode)
def test_card_absent_where_untagged_followups_do_not_run(self):
# Nothing to configure when replies are never picked up in the first place.
@@ -573,13 +518,7 @@ class TestThreadFollowupsPicker:
class TestLinkedAccountsCard:
def _view(self, *, account_state=None, github_state=None) -> dict:
- return render_home_view(
- effective=AIPreferences(),
- user_row=None,
- is_admin=False,
- account_state=account_state,
- github_state=github_state,
- )
+ return render_home_view(is_admin=False, account_state=account_state, github_state=github_state)
def _rows(self, view: dict) -> list[tuple[str, dict | None]]:
return [
@@ -673,8 +612,6 @@ _TASK_TITLES = ("Fix flaky retention test", "Refactor mention dispatcher")
class TestTasksCard:
def _kwargs(self, **overrides):
base = {
- "effective": AIPreferences(),
- "user_row": None,
"is_admin": False,
}
base.update(overrides)
@@ -1236,27 +1173,7 @@ class TestEditPersonalAction:
class TestResetPersonal:
- def test_clears_ai_fields_and_republishes(self, slack_integration, mock_slack_client, flag_on, admin_user):
- SlackSettings.objects.create(
- default_integration=slack_integration,
- slack_workspace_id=SLACK_WORKSPACE_ID,
- slack_user_id="U001",
- ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},
- )
- payload = _block_action_payload(
- action_id=ACTION_RESET_PERSONAL,
- slack_user_id="U001",
- trigger_id="trig.4",
- )
- handle_ai_preferences_block_action(payload, payload["actions"][0])
-
- row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")
- assert row.runtime_adapter is None
- assert row.model is None
- assert row.reasoning_effort is None
- assert mock_slack_client.views_publish.called
-
- def test_mapped_viewer_reset_clears_central_config_and_row(self, slack_integration, mock_slack_client, flag_on):
+ def test_mapped_viewer_reset_clears_central_config(self, slack_integration, mock_slack_client, flag_on):
user = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)
SlackUserProfileCache.objects.create(
integration=slack_integration, slack_user_id="U001", email="[email protected]"
@@ -1264,11 +1181,6 @@ class TestResetPersonal:
update_user_ai_run_preferences(
slack_integration.team_id, user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None
)
- SlackSettings.objects.create(
- slack_workspace_id=SLACK_WORKSPACE_ID,
- slack_user_id="U001",
- ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},
- )
payload = _block_action_payload(
action_id=ACTION_RESET_PERSONAL,
slack_user_id="U001",
@@ -1277,20 +1189,19 @@ class TestResetPersonal:
handle_ai_preferences_block_action(payload, payload["actions"][0])
assert get_user_ai_run_preferences(slack_integration.team_id, user.id) == {}
- row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")
- assert row.ai_preferences is None
+ assert mock_slack_client.views_publish.called
class TestResetProjectPersonal:
- def test_clears_routing_only_when_ai_preferences_present(
+ def test_clears_routing_only_when_other_settings_present(
self, slack_integration, mock_slack_client, flag_on, admin_user
):
- # Mixed row → reset clears routing, AI fields stay.
+ # Mixed row → reset clears routing, the follow-up mode stays.
SlackSettings.objects.create(
default_integration=slack_integration,
slack_workspace_id=SLACK_WORKSPACE_ID,
slack_user_id="U001",
- ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},
+ untagged_followup_mode=UntaggedFollowupMode.AUTO,
)
payload = _block_action_payload(
action_id=ACTION_RESET_PROJECT_PERSONAL,
@@ -1301,12 +1212,10 @@ class TestResetProjectPersonal:
row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")
assert row.default_integration_id is None
- assert row.runtime_adapter == "claude"
- assert row.model == "claude-opus-4-7"
- assert row.reasoning_effort == "high"
+ assert row.untagged_followup_mode == UntaggedFollowupMode.AUTO
assert mock_slack_client.views_publish.called
- def test_deletes_row_when_no_ai_preferences_remain(self, slack_integration, mock_slack_client, flag_on, admin_user):
+ def test_deletes_row_when_no_other_settings_remain(self, slack_integration, mock_slack_client, flag_on, admin_user):
# Routing-only row → reset drops it so the resolver falls back to
# the workspace default cleanly.
SlackSettings.objects.create(
@@ -1437,20 +1346,11 @@ class TestPersonalSubmit:
assert "not available" in str(body["errors"])
assert get_user_ai_run_preferences(slack_integration.team_id, user.id) == {}
- def test_mapped_viewer_submit_writes_central_config_and_clears_row(
- self, slack_integration, mock_slack_client, flag_on
- ):
+ def test_mapped_viewer_submit_writes_central_config(self, slack_integration, mock_slack_client, flag_on):
user = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)
SlackUserProfileCache.objects.create(
integration=slack_integration, slack_user_id="U001", email="[email protected]"
)
- # Stale pin on the Slack row: the save must not leave it behind to shadow
- # the central config it just wrote.
- SlackSettings.objects.create(
- slack_workspace_id=SLACK_WORKSPACE_ID,
- slack_user_id="U001",
- ai_preferences={"runtime_adapter": "codex", "model": "gpt-5", "reasoning_effort": None},
- )
payload = _view_submission_payload(
callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,
slack_user_id="U001",
@@ -1464,8 +1364,6 @@ class TestPersonalSubmit:
stored = get_user_ai_run_preferences(slack_integration.team_id, user.id)
assert stored.get("model") == "claude-opus-4-7"
assert stored.get("runtime_adapter") == "claude"
- row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")
- assert row.ai_preferences is None
@pytest.mark.parametrize(
"runtime_adapter,model,effort",
@@ -1609,8 +1507,6 @@ class TestNoProjectAccessCard:
def _view(self, **overrides) -> dict:
kwargs: dict[str, Any] = {
- "effective": AIPreferences(),
- "user_row": None,
"is_admin": True,
"has_project_access": False,
"tasks_state": TasksState(),
diff --git a/products/slack_app/backend/tests/services/test_slack_app_home_stats.py b/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
index 05ef71b8e107..08e35cb0eec6 100644
--- a/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
+++ b/products/slack_app/backend/tests/services/test_slack_app_home_stats.py
@@ -25,7 +25,6 @@ from products.slack_app.backend.services.slack_app_home_stats import (
build_stats_state,
coerce_window_days,
)
-from products.slack_app.backend.services.slack_settings import AIPreferences
WORKSPACE = "T_STATS"
SLACK_USER = "U_ADMIN"
@@ -147,12 +146,7 @@ def _column(view: dict, heading: str) -> str:
def _render(state: StatsState | None) -> dict:
- return render_home_view(
- effective=AIPreferences(),
- user_row=None,
- is_admin=True,
- stats_state=state,
- )
+ return render_home_view(is_admin=True, stats_state=state)
class TestWindowCoercion:
diff --git a/products/slack_app/backend/tests/services/test_slack_settings.py b/products/slack_app/backend/tests/services/test_slack_settings.py
index 7f6cbaaef3ac..5a9e8a4c124e 100644
--- a/products/slack_app/backend/tests/services/test_slack_settings.py
+++ b/products/slack_app/backend/tests/services/test_slack_settings.py
@@ -1,20 +1,11 @@
-from typing import Any
-
import pytest
-from django.core.exceptions import ValidationError
-
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from products.slack_app.backend.models import SlackSettings, UntaggedFollowupMode
-from products.slack_app.backend.services.slack_settings import (
- AIPreferences,
- resolve_ai_preferences,
- resolve_untagged_followup_mode,
- validate_ai_preferences,
-)
+from products.slack_app.backend.services.slack_settings import resolve_untagged_followup_mode
@pytest.fixture
@@ -30,215 +21,6 @@ def slack_setup(db):
return integration
[email protected](autouse=True)
-def _stub_task_runtime_helpers():
- """Replace the lazy tasks-facade imports with a minimal stub.
-
- Slack handler code imports `products.tasks.backend.facade.run_config`,
- which re-exports from `products.tasks.backend.temporal.process_task.utils`.
- Loading either pulls in `tasks.backend.temporal.__init__.py`, which
- eagerly loads the docker sandbox class. The test env sets
- `SANDBOX_PROVIDER=docker` alongside `DEBUG=False` — a combination the
- sandbox module rejects at import time. Production runs
- `SANDBOX_PROVIDER=modal`, so the real lazy import path works there.
- Stubbing the facade module here keeps these tests focused on resolver
- logic without dragging the tasks-temporal import chain in.
- """
- supported_by_model = {
- ("claude", "claude-opus-4-7"): {"low", "medium", "high", "xhigh", "max"},
- ("claude", "claude-sonnet-4-6"): {"low", "medium", "high"},
- ("codex", "gpt-5.5"): {"low", "medium", "high", "xhigh"},
- ("codex", "gpt-5"): {"low", "medium", "high"},
- }
-
- class _Effort:
- def __init__(self, value: str):
- self.value = value
-
- def fake_get_supported(adapter, model):
- return tuple(_Effort(v) for v in supported_by_model.get((adapter, model), set()))
-
- def fake_get_error(adapter, model, effort):
- if adapter is None or model is None or effort is None:
- return None
- supported = supported_by_model.get((adapter, model), set())
- if effort in supported:
- return None
- return f"Reasoning effort '{effort}' is not supported for {adapter}/{model}."
-
- models_by_adapter = {
- "claude": ("claude-opus-4-7", "claude-sonnet-4-6"),
- "codex": ("gpt-5", "gpt-5.5"),
- }
-
- def fake_validate_selection(adapter, model, effort):
- if adapter is not None and adapter not in models_by_adapter:
- raise ValidationError(f"Unknown runtime_adapter '{adapter}'.")
- owning = next((a for a, models in models_by_adapter.items() if model in models), None)
- if adapter is not None and owning is not None and owning != adapter:
- raise ValidationError(f"Model '{model}' runs on runtime_adapter '{owning}', not '{adapter}'.")
- error = fake_get_error(adapter, model, effort)
- if error:
- raise ValidationError(error)
-
- class _Adapter:
- def __init__(self, value):
- self.value = value
-
- class _RuntimeAdapter:
- CLAUDE = _Adapter("claude")
- CODEX = _Adapter("codex")
-
- def __iter__(self):
- return iter([self.CLAUDE, self.CODEX])
-
- class _PublicEffort:
- def __init__(self, value):
- self.value = value
-
- public_efforts = (
- _PublicEffort("low"),
- _PublicEffort("medium"),
- _PublicEffort("high"),
- _PublicEffort("xhigh"),
- _PublicEffort("max"),
- )
-
- import sys
- from types import ModuleType
-
- module_name = "products.tasks.backend.facade.run_config"
- # `Any` annotation so mypy accepts the stub-attribute assignments below —
- # the stdlib `ModuleType` rejects them, and ruff B010 reverts any
- # `setattr` workaround back to attribute syntax.
- fake: Any = ModuleType(module_name)
- fake.get_supported_reasoning_efforts = fake_get_supported
- fake.get_reasoning_effort_error = fake_get_error
- fake.get_models_for_runtime_adapter = lambda adapter: models_by_adapter.get(adapter, ())
- fake.validate_model_selection = fake_validate_selection
- fake.RuntimeAdapter = _RuntimeAdapter()
- fake.PUBLIC_REASONING_EFFORTS = public_efforts
-
- saved = sys.modules.get(module_name)
- sys.modules[module_name] = fake
- try:
- yield
- finally:
- if saved is None:
- sys.modules.pop(module_name, None)
- else:
- sys.modules[module_name] = saved
-
-
-class TestResolveAIPreferences:
- @pytest.mark.parametrize(
- "user_row,workspace_row,expected",
- [
- pytest.param(
- None,
- None,
- AIPreferences(),
- id="no-rows-returns-empty",
- ),
- pytest.param(
- None,
- {"runtime_adapter": "claude", "model": "claude-opus-4-7", "effort": "high"},
- AIPreferences(),
- id="workspace-row-is-ignored",
- ),
- pytest.param(
- {"runtime_adapter": "codex", "model": "gpt-5.5", "effort": "high"},
- None,
- AIPreferences(runtime_adapter="codex", model="gpt-5.5", reasoning_effort="high"),
- id="user-only-applies",
- ),
- pytest.param(
- {"runtime_adapter": "claude", "model": "claude-opus-4-7", "effort": "high"},
- {"runtime_adapter": "codex", "model": "gpt-5.5", "effort": "low"},
- AIPreferences(runtime_adapter="claude", model="claude-opus-4-7", reasoning_effort="high"),
- id="user-wins-over-lingering-workspace-row",
- ),
- ],
- )
- def test_resolution_table(self, slack_setup, user_row, workspace_row, expected):
- integration = slack_setup
- if user_row:
- SlackSettings.objects.create(
- default_integration=integration,
- slack_workspace_id="T_WS",
- slack_user_id="U001",
- ai_preferences={
- "runtime_adapter": user_row["runtime_adapter"],
- "model": user_row["model"],
- "reasoning_effort": user_row["effort"],
- },
- )
- if workspace_row:
- SlackSettings.objects.create(
- default_integration=integration,
- slack_workspace_id="T_WS",
- slack_user_id=None,
- ai_preferences={
- "runtime_adapter": workspace_row["runtime_adapter"],
- "model": workspace_row["model"],
- "reasoning_effort": workspace_row["effort"],
- },
- )
- assert resolve_ai_preferences(integration, "U001") == expected
-
- def test_user_row_with_no_pair_reads_as_no_preference(self, slack_setup):
- """A user row without the atomic `(runtime_adapter, model)` pair is
- treated as "no personal preference" — the orphaned effort never leaks
- into the resolved triple."""
- integration = slack_setup
- SlackSettings.objects.create(
- default_integration=integration,
- slack_workspace_id="T_WS",
- slack_user_id="U001",
- # Orphan effort with no pair — shouldn't reach the DB through the
- # normal write path, but the resolver still has to defend against
- # it (direct writes, older data, schema drift).
- ai_preferences={"reasoning_effort": "medium"},
- )
-
- assert resolve_ai_preferences(integration, "U001") == AIPreferences()
-
- def test_unsupported_effort_dropped_when_model_does_not_support_it(self, slack_setup):
- """If a row stores an effort the resolved model can't honour (e.g.
- the model definition changed since the effort was saved), the
- resolver drops it rather than letting it leak through to the task
- layer."""
- integration = slack_setup
- SlackSettings.objects.create(
- default_integration=integration,
- slack_workspace_id="T_WS",
- slack_user_id="U001",
- # `xhigh` isn't in `supported_by_model` for sonnet-4-6, so the
- # runtime drop must clear it.
- ai_preferences={
- "runtime_adapter": "claude",
- "model": "claude-sonnet-4-6",
- "reasoning_effort": "xhigh",
- },
- )
- result = resolve_ai_preferences(integration, "U001")
- assert result.runtime_adapter == "claude"
- assert result.model == "claude-sonnet-4-6"
- assert result.reasoning_effort is None
-
- def test_user_id_none_resolves_empty(self, slack_setup):
- # No Slack user to attribute the run to, so there's no preference to
- # apply — the workspace row's AI fields are no longer consulted.
- integration = slack_setup
- SlackSettings.objects.create(
- default_integration=integration,
- slack_workspace_id="T_WS",
- slack_user_id=None,
- ai_preferences={"runtime_adapter": "claude", "model": "claude-opus-4-7", "reasoning_effort": "high"},
- )
- assert resolve_ai_preferences(integration, None) == AIPreferences()
-
-
class TestResolveUntaggedFollowupMode:
@pytest.mark.parametrize(
"stored,expected",
@@ -274,43 +56,3 @@ class TestResolveUntaggedFollowupMode:
untagged_followup_mode=UntaggedFollowupMode.AUTO,
)
assert resolve_untagged_followup_mode(integration, "U001") == UntaggedFollowupMode.NEVER
-
-
-class TestValidateAIPreferences:
- def test_all_none_is_valid(self):
- validate_ai_preferences(None, None, None)
-
- def test_full_triple_is_valid(self):
- validate_ai_preferences("claude", "claude-opus-4-7", "high")
-
- def test_pair_without_effort_is_valid(self):
- validate_ai_preferences("claude", "claude-opus-4-7", None)
-
- @pytest.mark.parametrize(
- "runtime_adapter,model",
- [
- ("claude", None),
- (None, "claude-opus-4-7"),
- ],
- )
- def test_half_set_pair_rejected(self, runtime_adapter, model):
- with pytest.raises(ValidationError, match="must be set together"):
- validate_ai_preferences(runtime_adapter, model, None)
-
- def test_unknown_runtime_adapter_rejected(self):
- with pytest.raises(ValidationError, match="Unknown runtime_adapter"):
- validate_ai_preferences("nonsense", "claude-opus-4-7", None)
-
- def test_model_from_another_runtime_rejected(self):
- # The modal offers both runtimes' models, so nothing but this check stops a
- # Claude + GPT pair from being written and handed to a run.
- with pytest.raises(ValidationError, match="runs on runtime_adapter"):
- validate_ai_preferences("claude", "gpt-5.5", None)
-
- def test_unknown_reasoning_effort_rejected(self):
- with pytest.raises(ValidationError, match="Unknown reasoning_effort"):
- validate_ai_preferences("claude", "claude-opus-4-7", "ultra")
-
- def test_effort_unsupported_by_model_rejected(self):
- with pytest.raises(ValidationError, match="not supported"):
- validate_ai_preferences("claude", "claude-sonnet-4-6", "xhigh")
diff --git a/products/slack_app/backend/tests/test_backfill_model_pins_migration.py b/products/slack_app/backend/tests/test_backfill_model_pins_migration.py
deleted file mode 100644
index 80f2bc681ddb..000000000000
--- a/products/slack_app/backend/tests/test_backfill_model_pins_migration.py
+++ /dev/null
@@ -1,219 +0,0 @@
-from importlib import import_module
-
-import pytest
-
-from django.apps import apps as live_apps
-from django.utils.timezone import now
-
-from posthog.models.integration import Integration
-from posthog.models.organization import Organization
-from posthog.models.team.team import Team
-from posthog.models.user import User
-from posthog.models.user_integration import UserIntegration
-
-from products.slack_app.backend.models import SlackSettings, SlackUserProfileCache
-from products.tasks.backend.facade.ai_run_defaults import get_user_ai_run_preferences, update_user_ai_run_preferences
-
-# The function is exercised against the live app registry: at HEAD the historical
-# models are identical, and this keeps the test at the cheapest level that still
-# catches a mapping or conflict-policy regression.
-_migration = import_module("products.slack_app.backend.migrations.0016_backfill_model_pins_to_tasks")
-
-WORKSPACE = "T_BACKFILL"
-PIN = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}
-
-
-def _run():
- _migration.backfill_model_pins(live_apps, None)
-
-
-def setup(db):
- organization = Organization.objects.create(name="Org")
- team_a = Team.objects.create(organization=organization, name="A")
- team_b = Team.objects.create(organization=organization, name="B")
- other_org = Organization.objects.create(name="Other")
- team_outside = Team.objects.create(organization=other_org, name="Outside")
- for team in (team_a, team_b, team_outside):
- Integration.objects.create(
- team=team, kind="slack", integration_id=WORKSPACE, sensitive_config={"access_token": "x"}
- )
- user = User.objects.create_and_join(organization, "[email protected]", None)
- return user, team_a, team_b, team_outside
-
-
-def _link(user, slack_user_id="U001", workspace=WORKSPACE):
- UserIntegration.objects.create(
- user=user,
- kind=UserIntegration.IntegrationKind.SLACK,
- integration_id=slack_user_id,
- config={"slack_team_id": workspace},
- )
-
-
-def _pin_row(slack_user_id="U001", ai_preferences="use-pin"):
- return SlackSettings.objects.create(
- slack_workspace_id=WORKSPACE,
- slack_user_id=slack_user_id,
- ai_preferences=PIN if ai_preferences == "use-pin" else ai_preferences,
- )
-
-
-class TestBackfillModelPinsMigration:
- def test_link_mapped_pin_lands_in_every_member_project_and_is_cleared(self, setup):
- user, team_a, team_b, team_outside = setup
- _link(user)
- row = _pin_row()
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
- assert get_user_ai_run_preferences(team_b.id, user.id) == PIN
- # The workspace also connects a project in an org the user isn't in; the
- # pin must not follow it there.
- assert get_user_ai_run_preferences(team_outside.id, user.id) == {}
- row.refresh_from_db()
- assert row.ai_preferences is None
-
- def test_email_mapped_pin_lands_without_a_link(self, setup):
- user, team_a, _team_b, _team_outside = setup
- integration = Integration.objects.filter(team=team_a, kind="slack").get()
- SlackUserProfileCache.objects.create(
- integration=integration, slack_user_id="U001", email="[email protected]"
- )
- _pin_row()
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
-
- def test_newer_central_config_is_kept_but_the_pin_still_clears(self, setup):
- user, team_a, _team_b, _team_outside = setup
- _link(user)
- row = _pin_row()
- update_user_ai_run_preferences(
- team_a.id, user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None
- )
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id)["model"] == "gpt-5.5"
- row.refresh_from_db()
- assert row.ai_preferences is None
-
- def test_newer_pin_overwrites_older_central_config(self, setup):
- user, team_a, _team_b, _team_outside = setup
- _link(user)
- update_user_ai_run_preferences(
- team_a.id, user.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None
- )
- _pin_row()
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
-
- @pytest.mark.parametrize(
- "ai_preferences",
- [
- pytest.param({"reasoning_effort": "high"}, id="half-set-row"),
- pytest.param({}, id="empty-payload"),
- ],
- )
- def test_rows_without_the_atomic_pair_migrate_nothing(self, setup, ai_preferences):
- user, team_a, _team_b, _team_outside = setup
- _link(user)
- _pin_row(ai_preferences=ai_preferences)
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == {}
-
- def test_unmapped_identity_is_left_untouched(self, setup):
- user, team_a, _team_b, _team_outside = setup
- row = _pin_row(slack_user_id="U_NOBODY")
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == {}
- row.refresh_from_db()
- assert row.ai_preferences == PIN
-
- def test_environment_team_pin_lands_on_the_project_root(self, setup):
- user, team_a, _team_b, _team_outside = setup
- env_team = Team.objects.create(
- organization=team_a.organization, project=team_a.project, parent_team=team_a, name="env"
- )
- Integration.objects.create(
- team=env_team, kind="slack", integration_id="T_ENV", sensitive_config={"access_token": "x"}
- )
- _link(user)
- UserIntegration.objects.filter(user=user).update(config={"slack_team_id": "T_ENV"})
- SlackSettings.objects.create(slack_workspace_id="T_ENV", slack_user_id="U001", ai_preferences=PIN)
-
- _run()
-
- # Config rows are keyed on the project root, matching the resolver.
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
-
- def test_newer_inaccessible_link_does_not_shadow_the_accessible_one(self, setup):
- user, team_a, _team_b, _team_outside = setup
- _link(user)
- # A newer link on the same Slack identity, held by a user outside every
- # connected org — the runtime resolver skips it, so the migration must too.
- stranger = User.objects.create_and_join(
- Organization.objects.create(name="Elsewhere"), "[email protected]", None
- )
- _link(stranger)
- _pin_row()
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
- assert get_user_ai_run_preferences(team_a.id, stranger.id) == {}
-
- def test_pin_with_only_an_inaccessible_link_is_left_untouched(self, setup):
- user, team_a, _team_b, _team_outside = setup
- stranger = User.objects.create_and_join(
- Organization.objects.create(name="Elsewhere"), "[email protected]", None
- )
- _link(stranger)
- row = _pin_row()
-
- _run()
-
- row.refresh_from_db()
- assert row.ai_preferences == PIN
- assert get_user_ai_run_preferences(team_a.id, user.id) == {}
-
- def test_stale_profile_cache_email_loses_to_the_fresh_row(self, setup):
- user, team_a, team_b, _team_outside = setup
- old_owner = User.objects.create_and_join(team_a.organization, "[email protected]", None)
- integrations = list(Integration.objects.filter(integration_id=WORKSPACE, team__in=[team_a, team_b]))
- SlackUserProfileCache.objects.create(
- integration=integrations[0], slack_user_id="U001", email="[email protected]", refreshed_at=None
- )
- SlackUserProfileCache.objects.create(
- integration=integrations[1], slack_user_id="U001", email="[email protected]", refreshed_at=now()
- )
- _pin_row()
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == PIN
- assert get_user_ai_run_preferences(team_a.id, old_owner.id) == {}
-
- def test_newest_pin_wins_across_workspaces(self, setup):
- user, team_a, _team_b, _team_outside = setup
- Integration.objects.create(
- team=team_a, kind="slack", integration_id="T_SECOND", sensitive_config={"access_token": "x"}
- )
- _link(user)
- _link(user, slack_user_id="U9", workspace="T_SECOND")
- _pin_row() # older
- newer = {"runtime_adapter": "codex", "model": "gpt-5.5"}
- SlackSettings.objects.create(slack_workspace_id="T_SECOND", slack_user_id="U9", ai_preferences=newer)
-
- _run()
-
- assert get_user_ai_run_preferences(team_a.id, user.id) == newer
diff --git a/products/tasks/backend/logic/services/ai_run_defaults.py b/products/tasks/backend/logic/services/ai_run_defaults.py
index 24a61c2ce951..4f62bb3ce054 100644
--- a/products/tasks/backend/logic/services/ai_run_defaults.py
+++ b/products/tasks/backend/logic/services/ai_run_defaults.py
@@ -12,7 +12,7 @@ carries the atomic `(runtime_adapter, model)` pair, that level's entire
preference object wins (including its absent `reasoning_effort`). A
field-by-field merge would blend mismatched configurations — for example a
team `reasoning_effort` glued onto the user's non-thinking model — which is
-never what anyone picked. Mirrors the Slack app's `resolve_ai_preferences`.
+never what anyone picked.
Lenient at resolve time by design: preferences are stored as raw ids and the
available model list drifts as the LLM gateway evolves, so an unknown model id