: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): App Home model picker writes the central tasks config (#98354)
Vojta Bartoš8ce20f9249fa
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 6433bfbf5625..8e0a2c226f12 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -22,6 +22,7 @@ from typing import Anyfrom django.conf import settingsfrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.http import HttpResponse, JsonResponseimport structlog@@ -61,10 +62,8 @@ from products.slack_app.backend.services.slack_app_home_stats import ()from products.slack_app.backend.services.slack_settings import (AIPreferences,- build_ai_preferences_payload,resolve_ai_preferences,resolve_untagged_followup_mode,- validate_ai_preferences,)from products.slack_app.backend.services.slack_user_info import is_slack_workspace_adminfrom products.slack_app.backend.services.slack_user_oauth import build_invite_url, find_linked_posthog_user@@ -474,7 +473,7 @@ def render_home_view(# model default to inherit from.blocks.append({"type": "divider"})blocks.extend(_active_model_blocks(effective, source, run_defaults or RunDefaultsState()))- blocks.extend(_personal_section_blocks(user_row))+ blocks.extend(_personal_section_blocks(user_row, run_defaults or RunDefaultsState()))# Section 4 — thread follow-ups: whether replies other people leave in the# threads you started reach PostHog on their own. Absent when the workspace@@ -837,8 +836,14 @@ def _github_account_button(github_state: GitHubState) -> dict | None:return button-def _personal_section_blocks(user_row: SlackSettings | None) -> list[dict]:- """Personal AI override sub-card. Always editable by the user themselves."""+def _personal_section_blocks(user_row: SlackSettings | None, run_defaults: RunDefaultsState) -> list[dict]:+ """Personal AI override 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.+ """has_override = bool(user_row and user_row.runtime_adapter and user_row.model)summary = (@@ -854,7 +859,7 @@ def _personal_section_blocks(user_row: SlackSettings | None) -> list[dict]:"text": {"type": "plain_text", "text": "Edit my settings", "emoji": True},}]- if has_override:+ if has_override or run_defaults.source == "user":actions.append({"type": "button",@@ -862,10 +867,12 @@ def _personal_section_blocks(user_row: SlackSettings | None) -> list[dict]:"style": "danger","text": {"type": "plain_text", "text": "Reset to default", "emoji": True},"confirm": {- "title": {"type": "plain_text", "text": "Clear your override?"},+ "title": {"type": "plain_text", "text": "Clear your model preference?"},"text": {"type": "mrkdwn",- "text": "You'll go back to PostHog's default until you set new personal preferences.",+ "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.",},"confirm": {"type": "plain_text", "text": "Reset"},"deny": {"type": "plain_text", "text": "Cancel"},@@ -1475,7 +1482,7 @@ def parse_modal_submission(view: dict) -> tuple[str | None, str | None, str | No"""Pull `(runtime_adapter, model, reasoning_effort)` out of a Slack view_submission payload.Returns `(None, None, None)` for any block the user didn't fill in. The- caller validates the triple via `validate_ai_preferences`.+ central config write validates the triple."""state = view.get("state", {}).get("values", {})@@ -1604,7 +1611,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResporeturn HttpResponse(status=200)if action_id == ACTION_RESET_PERSONAL:- _clear_personal_override(integration, slack_user_id)+ _reset_personal_preferences(integration, slack_user_id)republish()return HttpResponse(status=200)@@ -1690,19 +1697,19 @@ def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonResponsruntime_adapter, model, reasoning_effort = parse_modal_submission(view)+ # Triple validation happens inside the central write — the tasks config's+ # `validate_ai_run_preferences` runs the same pair/effort rules.try:- validate_ai_preferences(runtime_adapter, model, reasoning_effort)+ _apply_personal_preferences(+ integration,+ slack_user_id,+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,+ )except ValidationError as exc:return _modal_error_response(_first_validation_message(exc))- _write_row(- integration,- slack_user_id=slack_user_id,- runtime_adapter=runtime_adapter,- model=model,- reasoning_effort=reasoning_effort,- )-capture_slack_event(integration,"slack app ai preferences saved",@@ -1857,27 +1864,128 @@ def _supported_efforts(runtime_adapter: str | None, model: str | None) -> list[sreturn [e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)] or None-def _write_row(+def _routed_project_integration(+ integration: Integration, slack_user_id: str, *, accessible: list[Integration] | None = None+) -> Integration | None:+ """The integration of the project this viewer's mentions currently route to,+ restricted to projects the viewer can access. None when they can reach none.+ Pass `accessible` when the caller already resolved it, to skip the repeat+ permissions build."""+ if accessible is None:+ accessible = _accessible_integrations(integration, slack_user_id)+ try:+ return resolve_from_candidates(+ accessible,+ slack_team_id=integration.integration_id,+ slack_user_id=slack_user_id,+ ).resolved_or_first()+ except Exception:+ logger.exception("slack_app_home_routed_project_resolution_failed", slack_user_id=slack_user_id)+ return None+++def _personal_preference_target(integration: Integration, slack_user_id: str) -> tuple[User, Integration]:+ """The PostHog user behind this viewer and the project whose central config+ they edit — the one their mentions route to, restricted to this user's own+ access via `resolve_from_candidates(user=...)`.++ Fail-closed on purpose: the result picks the tenant for a team-scoped+ write, so an unmapped viewer, an unauthorized workspace, or an ambiguous+ route each raise a `ValidationError` naming the next step instead of+ falling back to an arbitrary project.+ """+ user = _resolve_home_user(integration, slack_user_id)+ if user is None:+ raise ValidationError(+ "Link your PostHog account first. You can do that from the Linked accounts card on the Home tab."+ )+ result = resolve_from_candidates(+ _workspace_integrations(integration.integration_id),+ slack_team_id=integration.integration_id,+ slack_user_id=slack_user_id,+ user=user,+ )+ target = result.integration+ if target is None and len(result.candidates) == 1:+ target = result.candidates[0]+ if target is None:+ raise ValidationError(+ "Pick a default project first. You can do that from the Project routing card on the Home tab."+ )+ return user, target+++def _apply_personal_preferences(integration: Integration,- *,slack_user_id: str,+ *,runtime_adapter: str | None,model: str | None,reasoning_effort: str | None,) -> None:- """Upsert a SlackSettings row with the given AI 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.- `default_integration` is left untouched on existing rows so saving AI- preferences doesn't accidentally overwrite the user's routing pick.+ Raises `ValidationError` when the viewer has no authorized target project+ (see `_personal_preference_target`) or picks a model their account is not+ entitled to — storing it would only produce runs the resolver skips."""+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path+ ai_run_defaults,+ )+ from products.tasks.backend.facade.run_config import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path+ get_model_access_error,+ )- payload = build_ai_preferences_payload(runtime_adapter, model, reasoning_effort)- SlackSettings.objects.update_or_create(- slack_workspace_id=integration.integration_id,- slack_user_id=slack_user_id,- defaults={"ai_preferences": payload or None},+ user, target = _personal_preference_target(integration, slack_user_id)++ access_error = get_model_access_error(model, distinct_id=user.distinct_id)+ 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)+++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.+ """+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path+ ai_run_defaults,)+ 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)+ 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)+def _apply_untagged_followup_mode_pick(integration: Integration, slack_user_id: str, action: dict) -> None:"""Persist the picked mode. An unrecognised value is ignored rather than stored."""@@ -2158,15 +2266,7 @@ def _resolve_run_defaults_state(ai_run_defaults,)- try:- target = resolve_from_candidates(- accessible,- slack_team_id=integration.integration_id,- slack_user_id=slack_user_id,- ).resolved_or_first()- except Exception:- logger.exception("slack_app_home_run_defaults_routing_failed", slack_user_id=slack_user_id)- target = None+ target = _routed_project_integration(integration, slack_user_id, accessible=accessible)if target is None:# No reachable project: nothing to describe and no settings page to offer.return RunDefaultsState()diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex edd5656e901e..14a8fc42438e 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@@ -58,6 +58,7 @@ from products.slack_app.backend.services.slack_app_home import (PreferenceSource,ProjectChoice,ProjectState,+ RunDefaultsState,StatsState,TaskItem,TasksState,@@ -70,6 +71,7 @@ from products.slack_app.backend.services.slack_app_home import (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_preferencesfrom products.tasks.backend.models import Task, TaskRunSLACK_WORKSPACE_ID = "T_HOME"@@ -423,6 +425,17 @@ class TestRenderHomeView:assert ACTION_EDIT_PERSONAL in idsassert 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.+ 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"),@@ -1243,6 +1256,30 @@ class TestResetPersonal:assert row.reasoning_effort is Noneassert mock_slack_client.views_publish.called+ def test_mapped_viewer_reset_clears_central_config_and_row(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]"+ )+ 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",+ trigger_id="trig.8",+ )+ 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+class TestResetProjectPersonal:def test_clears_routing_only_when_ai_preferences_present(@@ -1304,7 +1341,11 @@ class TestResetProjectPersonal:class TestPersonalSubmit:- def test_writes_row_and_republishes(self, slack_integration, mock_slack_client, flag_on, admin_user):+ def test_unmapped_viewer_submit_is_refused_with_a_link_prompt(+ self, slack_integration, mock_slack_client, flag_on, admin_user+ ):+ # No PostHog user maps to U001, so there is nowhere to store the+ # preference — the modal must say so instead of writing a Slack pin.payload = _view_submission_payload(callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,slack_user_id="U001",@@ -1313,44 +1354,150 @@ class TestPersonalSubmit:effort="high",)response = handle_app_home_view_submission(payload)- assert response.status_code == 200- assert json.loads(response.content) == {"response_action": "clear"}+ body = json.loads(response.content)+ assert body["response_action"] == "errors"+ assert "Link your PostHog account" in str(body["errors"])+ assert not SlackSettings.objects.filter(slack_user_id="U001").exists()- row = SlackSettings.objects.get(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U001")- assert row.runtime_adapter == "claude"- assert row.model == "claude-opus-4-7"- assert row.reasoning_effort == "high"- assert mock_slack_client.views_publish.called+ def test_multi_project_viewer_without_a_routing_default_is_asked_to_pick(+ self, slack_integration, mock_slack_client, flag_on+ ):+ # Two accessible projects and no routing default must not silently save+ # against the oldest install; the mention path refuses in the same state.+ organization = slack_integration.team.organization+ team_b = Team.objects.create(organization=organization, name="B")+ Integration.objects.create(+ team=team_b, kind="slack", integration_id=SLACK_WORKSPACE_ID, sensitive_config={"access_token": "x"}+ )+ User.objects.create_and_join(organization, "[email protected]", None)+ for i in Integration.objects.filter(integration_id=SLACK_WORKSPACE_ID):+ SlackUserProfileCache.objects.create(integration=i, slack_user_id="U001", email="[email protected]")- def test_invalid_pair_keeps_modal_open_with_error(self, slack_integration, mock_slack_client, flag_on):- # `xhigh` isn't supported on claude-sonnet-4-6 — validate_ai_preferences rejects.payload = _view_submission_payload(callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,slack_user_id="U001",runtime_adapter="claude",- model="claude-sonnet-4-6",- effort="xhigh",+ model="claude-opus-4-7",+ effort="high",)response = handle_app_home_view_submission(payload)body = json.loads(response.content)assert body["response_action"] == "errors"- assert MODAL_BLOCK_RUNTIME_ADAPTER in body["errors"]- # Modal left open: no row written, no publish.- assert not SlackSettings.objects.filter(slack_user_id="U001").exists()+ assert "Pick a default project" in str(body["errors"])- def test_model_from_another_runtime_keeps_modal_open_with_error(+ def test_save_targets_the_viewers_accessible_project_not_the_oldest_install(self, slack_integration, mock_slack_client, flag_on):+ # The workspace's oldest install (the fixture's) belongs to an org the+ # viewer isn't in; the save must land on their own project rather than+ # falling open to the oldest one.+ foreign = slack_integration+ own_org = Organization.objects.create(name="Mine")+ own = Integration.objects.create(+ team=Team.objects.create(organization=own_org, name="Mine team"),+ kind="slack",+ integration_id=SLACK_WORKSPACE_ID,+ sensitive_config={"access_token": "x"},+ )+ user = User.objects.create_and_join(own_org, "[email protected]", None)+ for i in (foreign, own):+ SlackUserProfileCache.objects.create(integration=i, slack_user_id="U001", email="[email protected]")+payload = _view_submission_payload(callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,slack_user_id="U001",runtime_adapter="claude",- model="gpt-5",- effort=None,+ model="claude-opus-4-7",+ effort="high",)response = handle_app_home_view_submission(payload)- assert json.loads(response.content)["response_action"] == "errors"- assert not SlackSettings.objects.filter(slack_user_id="U001").exists()+ assert json.loads(response.content) == {"response_action": "clear"}+ assert get_user_ai_run_preferences(own.team_id, user.id).get("model") == "claude-opus-4-7"+ assert get_user_ai_run_preferences(foreign.team_id, user.id) == {}++ def test_gated_model_is_rejected_at_save(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]"+ )+ payload = _view_submission_payload(+ callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,+ slack_user_id="U001",+ runtime_adapter="claude",+ model="claude-opus-4-7",+ effort="high",+ )+ with patch(+ "products.tasks.backend.facade.run_config.get_model_access_error",+ return_value="This model is not available on your account.",+ ):+ response = handle_app_home_view_submission(payload)+ body = json.loads(response.content)+ assert body["response_action"] == "errors"+ 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+ ):+ 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",+ runtime_adapter="claude",+ model="claude-opus-4-7",+ effort="high",+ )+ response = handle_app_home_view_submission(payload)+ assert json.loads(response.content) == {"response_action": "clear"}++ 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",+ [+ # `max` isn't supported on claude-sonnet-4-6.+ pytest.param("claude", "claude-sonnet-4-6", "max", id="unsupported-effort"),+ # A model owned by the other runtime.+ pytest.param("claude", "gpt-5.5", None, id="cross-runtime-model"),+ ],+ )+ def test_invalid_triple_keeps_modal_open_with_error(+ self, slack_integration, mock_slack_client, flag_on, runtime_adapter, model, effort+ ):+ # A mapped viewer, so the request reaches the central config write —+ # whose validation is what rejects the triple.+ 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]"+ )+ payload = _view_submission_payload(+ callback_id=EDIT_MODAL_PERSONAL_CALLBACK_ID,+ slack_user_id="U001",+ runtime_adapter=runtime_adapter,+ model=model,+ effort=effort,+ )+ response = handle_app_home_view_submission(payload)+ body = json.loads(response.content)+ assert body["response_action"] == "errors"+ assert MODAL_BLOCK_RUNTIME_ADAPTER in body["errors"]+ # Modal left open: nothing stored.+ assert get_user_ai_run_preferences(slack_integration.team_id, user.id) == {}class TestModalRerender: