: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
fix(slack_app): make App Home tab controls respond (#80329)
Vojta Bartoš343c00fb4594
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex c60cc361bfc6..7f8242dbe017 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -78,18 +78,8 @@ from products.slack_app.backend.services.integration_resolver import (user_resolution_failure_reply,)from products.slack_app.backend.services.slack_app_home import (- ACTION_EDIT_PERSONAL,- ACTION_RESET_PERSONAL,- ACTION_RESET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_WORKSPACE,- ACTION_TASKS_FILTER_REPO,- ACTION_TASKS_FILTER_STATUS,- ACTION_TASKS_PAGE_NEXT,- ACTION_TASKS_PAGE_PREV,- ACTION_TASKS_REFRESH,- ACTION_UNLINK_ACCOUNT,EDIT_MODAL_PERSONAL_CALLBACK_ID,+ HOME_ACTION_IDS,MODAL_ACTION_MODEL,MODAL_ACTION_RUNTIME_ADAPTER,handle_ai_preferences_block_action as _handle_ai_preferences_block_action,@@ -1839,7 +1829,9 @@ def _route_app_home_opened(if region_route is not None:return region_route- integration = result.integration if result.integration in result.candidates else result.candidates[0]+ integration = result.resolved_or_first()+ if integration is None:+ return ROUTE_NO_INTEGRATIONtry:_handle_app_home_opened(event, slack_team_id, integration=integration)except Exception:@@ -3088,23 +3080,10 @@ def _extract_context_token(payload: dict) -> str:return payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("context_token", "")-_AI_PREFERENCES_ACTION_IDS = frozenset(- {- ACTION_EDIT_PERSONAL,- ACTION_RESET_PERSONAL,- ACTION_RESET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_PERSONAL,- ACTION_SET_PROJECT_WORKSPACE,- ACTION_TASKS_FILTER_REPO,- ACTION_TASKS_FILTER_STATUS,- ACTION_TASKS_PAGE_NEXT,- ACTION_TASKS_PAGE_PREV,- ACTION_TASKS_REFRESH,- ACTION_UNLINK_ACCOUNT,- MODAL_ACTION_RUNTIME_ADAPTER,- MODAL_ACTION_MODEL,- }-)+# Every Home tab control, plus the two modal selects that re-render the edit modal.+# Sourced from `HOME_ACTION_IDS` rather than re-listed, so a control added to the tab+# is routable here the moment it exists.+_AI_PREFERENCES_ACTION_IDS = HOME_ACTION_IDS | {MODAL_ACTION_RUNTIME_ADAPTER, MODAL_ACTION_MODEL}_AI_PREFERENCES_CALLBACK_IDS = frozenset({EDIT_MODAL_PERSONAL_CALLBACK_ID})diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 8dac1d8b17a4..a7ac207968ed 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -62,6 +62,19 @@ class ResolutionResult:source: ResolutionSourcecandidates: list[Integration] = field(default_factory=list)+ def resolved_or_first(self) -> Integration | None:+ """The resolved integration, falling back to the workspace's oldest install.++ Surfaces that must act on *some* integration rather than prompt for one share this+ tie-break, so a workspace with no saved pick is answered for the same project+ whichever surface handles it. Ordered by id rather than taken off the front of+ `candidates`: the auth filter sorts that list freshest-verdict-first, which+ reshuffles as cache entries expire and would make the fallback drift.+ """+ if self.integration is not None and self.integration in self.candidates:+ return self.integration+ return min(self.candidates, key=lambda candidate: candidate.id, default=None)+def format_project_candidate_list(candidates: list[Integration]) -> str:return "\n".join(f"• `{c.team_id}` — {c.team.organization.name} · {c.team.name}" for c in candidates)diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex beb2d86c8580..c331b78cddca 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -20,18 +20,20 @@ from dataclasses import dataclass, replacefrom datetime import datetime, timedeltafrom typing import Any+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.http import HttpResponse, JsonResponseimport structlog-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user_integration import UserIntegrationfrom posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.feature_flags import is_slack_app_home_enabled, is_slack_app_oauth_enabledfrom products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.slack_app.backend.services.integration_resolver import load_integrationsfrom products.slack_app.backend.services.model_catalogue import (REASONING_EFFORT_DISPLAY_NAMES,RUNTIME_ADAPTER_DISPLAY_NAMES,@@ -86,6 +88,28 @@ ACTION_TASKS_PAGE_NEXT = "slack_app_home:tasks_page_next"ACTION_STATS_WINDOW = "slack_app_home:stats_window"ACTION_STATS_REFRESH = "slack_app_home:stats_refresh"+# Every control the Home tab renders, in one place. The interactivity endpoint reads+# this to claim region ownership and to dispatch, so a control that isn't listed here+# renders as a button that silently does nothing. Adding an action id above without+# adding it here is the failure this set exists to prevent.+HOME_ACTION_IDS: frozenset[str] = frozenset(+ {+ ACTION_EDIT_PERSONAL,+ ACTION_RESET_PERSONAL,+ ACTION_UNLINK_ACCOUNT,+ ACTION_SET_PROJECT_PERSONAL,+ ACTION_SET_PROJECT_WORKSPACE,+ ACTION_RESET_PROJECT_PERSONAL,+ ACTION_TASKS_FILTER_REPO,+ ACTION_TASKS_FILTER_STATUS,+ ACTION_TASKS_REFRESH,+ ACTION_TASKS_PAGE_PREV,+ ACTION_TASKS_PAGE_NEXT,+ ACTION_STATS_WINDOW,+ ACTION_STATS_REFRESH,+ }+)+# Single block_id for the whole controls row. Block Kit only persists# state in `view.state.values` under blocks that carry a `block_id`, so# both the repo and the status dropdowns live under the same key here and@@ -333,6 +357,7 @@ def render_home_view(project_state: ProjectState | None = None,tasks_state: TasksState | None = None,stats_state: StatsState | None = None,+ has_project_access: bool = True,) -> dict:"""Render the Block Kit payload for `views.publish` on the App Home tab."""@@ -341,6 +366,14 @@ def render_home_view(blocks.extend(_header_blocks())+ # Nothing below the fold means anything to someone who can't reach a project: the+ # cards are scoped to one, and mentioning @PostHog won't work either. Say so once+ # and stop, rather than drawing empty cards that read as "you have no tasks yet".+ if not has_project_access:+ blocks.append({"type": "divider"})+ blocks.extend(_no_project_access_blocks())+ return {"type": "home", "callback_id": HOME_CALLBACK_ID, "blocks": blocks}+# Section 1 — workspace activity: aggregates across everyone's Slack-started work,# rather than the calling user's own. Admin-only, and first because it's the reason# an admin opens the tab at all — the settings below are set once and rarely revisited.@@ -447,6 +480,45 @@ def _header_blocks() -> list[dict]:]+def _no_project_access_blocks() -> list[dict]:+ """Shown when the viewer can't reach any PostHog project connected to this workspace.++ Covers both halves of the same dead end — no project is connected yet, or one is but+ the viewer isn't a member of its organization — because from Slack the two are+ indistinguishable and the next step is the same page either way.+ """+ site_url = (settings.SITE_URL or "").rstrip("/")+ blocks: list[dict] = [+ _section_title(+ "🔒 No project to show yet",+ "This Slack workspace isn't connected to a PostHog project you can see, "+ "so there's nothing to set up here and @PostHog mentions won't run.",+ ),+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": ("Connect a project in PostHog, or ask an admin to add you to one that's already connected."),+ },+ },+ ]+ if site_url:+ blocks.append(+ {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "url": f"{site_url}/settings/project-integrations",+ "text": {"type": "plain_text", "text": "Connect PostHog to Slack", "emoji": True},+ "style": "primary",+ }+ ],+ }+ )+ return blocks++def _active_model_blocks(effective: AIPreferences, source: PreferenceSource) -> list[dict]:"""Headline that shows which model is actually running, and why.@@ -1291,6 +1363,7 @@ def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Inteproject_state=project_state,tasks_state=tasks_state,stats_state=stats_state,+ has_project_access=bool(accessible),)try:slack.client.views_publish(user_id=slack_user_id, view=view)@@ -1316,7 +1389,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResposlack_user_id = (payload.get("user") or {}).get("id", "")trigger_id = payload.get("trigger_id")- integration = _get_slack_integration(slack_team_id)+ integration = _resolve_interaction_integration(slack_team_id, slack_user_id)if integration is None:return HttpResponse(status=200)@@ -1399,7 +1472,7 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespoif action_id in (MODAL_ACTION_RUNTIME_ADAPTER, MODAL_ACTION_MODEL):# Modal re-render: a runtime / model change updates which downstream# blocks (model list, effort options) are valid. Push an updated view.- return _update_modal_after_input_change(payload)+ return _update_modal_after_input_change(payload, integration)return HttpResponse(status=200)@@ -1414,7 +1487,7 @@ def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonResponsslack_team_id = (payload.get("team") or {}).get("id", "")slack_user_id = (payload.get("user") or {}).get("id", "")- integration = _get_slack_integration(slack_team_id)+ integration = _resolve_interaction_integration(slack_team_id, slack_user_id)if integration is None:return _modal_error_response("This Slack workspace is no longer connected to PostHog.")@@ -1445,14 +1518,22 @@ def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonRespons# ----------------------------------------------------------------------------def _get_slack_integration(slack_team_id: str) -> Integration | None:+def _resolve_interaction_integration(slack_team_id: str, slack_user_id: str) -> Integration | None:+ """The integration the viewer's Home tab is rendered against.++ Same resolver the publish path runs, so a click is answered for the project the viewer+ was looking at. Any row of the workspace would do for fetching a bot token, but the+ rollout flag is scoped to an organization and the task list to a team, so answering+ against an arbitrary one makes the tab disagree with itself.+ """if not slack_team_id:return None- return (- Integration.objects.select_related("team", "team__organization")- .filter(kind="slack", integration_id=slack_team_id)- .first()+ result = load_integrations(+ slack_team_id=slack_team_id,+ kinds=list(SLACK_INTEGRATION_KINDS),+ slack_user_id=slack_user_id,)+ return result.resolved_or_first()def _load_user_row(integration: Integration, slack_user_id: str) -> SlackSettings | None:@@ -1521,7 +1602,7 @@ def _render_unavailable_modal() -> dict:}-def _update_modal_after_input_change(payload: dict) -> HttpResponse:+def _update_modal_after_input_change(payload: dict, integration: Integration) -> HttpResponse:"""Re-render the modal in response to a runtime_adapter or model change.Reads the in-flight state from `payload["view"]`, drops whatever the change@@ -1539,11 +1620,6 @@ def _update_modal_after_input_change(payload: dict) -> HttpResponse:updated_view = render_edit_modal(current=current, supported_efforts=supported)- slack_team_id = (payload.get("team") or {}).get("id", "")- integration = _get_slack_integration(slack_team_id)- if integration is None:- return HttpResponse(status=200)-slack = SlackIntegration(integration)try:slack.client.views_update(view_id=view.get("id"), hash=view.get("hash"), view=updated_view)@@ -1662,11 +1738,26 @@ def _republish_home(project_state=project_state,tasks_state=tasks_state,stats_state=stats_state,+ has_project_access=bool(accessible),)try:slack.client.views_publish(user_id=slack_user_id, view=view)except Exception:logger.exception("slack_app_home_republish_failed")+ return+ # Carries the controls the click resolved to, so a report of "the filter does+ # nothing" can be told apart from a click that never reached us at all.+ logger.info(+ "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_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,+ )_TASKS_PAGE_SIZE = 10@@ -1694,7 +1785,6 @@ def _resolve_tasks_state(accessible-team scoping) does not generalise."""- from django.conf import settingsfrom django.utils import timezone as django_timezonefrom products.slack_app.backend.models import SlackThreadTaskMappingdiff --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 96806562db5b..6e39f66ff61f 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@@ -24,19 +24,30 @@ from posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team-from products.slack_app.backend.models import SlackSettings+from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping+from products.slack_app.backend.services import slack_app_homefrom products.slack_app.backend.services.slack_app_home import (ACTION_EDIT_PERSONAL,ACTION_RESET_PERSONAL,ACTION_RESET_PROJECT_PERSONAL,+ ACTION_TASKS_FILTER_REPO,+ ACTION_TASKS_PAGE_NEXT,+ ACTION_TASKS_PAGE_PREV,+ ACTION_UNLINK_ACCOUNT,+ BLOCK_TASKS_CONTROLS,EDIT_MODAL_PERSONAL_CALLBACK_ID,+ HOME_ACTION_IDS,MODAL_ACTION_MODEL,MODAL_ACTION_REASONING_EFFORT,MODAL_ACTION_RUNTIME_ADAPTER,MODAL_BLOCK_MODEL,MODAL_BLOCK_REASONING_EFFORT,MODAL_BLOCK_RUNTIME_ADAPTER,+ AccountState,PreferenceSource,+ ProjectChoice,+ ProjectState,+ StatsState,TaskItem,TasksState,handle_ai_preferences_block_action,@@ -48,6 +59,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.models import Task, TaskRunSLACK_WORKSPACE_ID = "T_HOME"@@ -329,6 +341,23 @@ def _block_action_payload(}+def _tasks_click_payload(action_id: str, *, value: str | None = None, repo: str | None = None) -> dict:+ """A Home tab Tasks click: the page rides on the button's value, the filter on view state."""+ action: dict[str, Any] = {"action_id": action_id}+ if value is not None:+ action["value"] = value+ controls: dict[str, Any] = {}+ if repo:+ controls[ACTION_TASKS_FILTER_REPO] = {"selected_option": {"value": repo}}+ return {+ "type": "block_actions",+ "team": {"id": SLACK_WORKSPACE_ID},+ "user": {"id": "U001"},+ "actions": [action],+ "view": {"id": "V1", "hash": "H1", "type": "home", "state": {"values": {BLOCK_TASKS_CONTROLS: controls}}},+ }++def _view_submission_payload(*,callback_id: str,@@ -390,6 +419,47 @@ class TestRenderHomeView:assert "Claude Opus 4.7" in text_blobassert "Your personal override" 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,+ account_state=AccountState(enabled=True, link_url="https://app/link"),+ project_state=ProjectState(+ candidates=(ProjectChoice(team_id=1, label="Org · Team"),),+ personal_team_id=1,+ workspace_team_id=1,+ workspace_team_label="Org · Team",+ ),+ tasks_state=TasksState(+ items=(+ TaskItem(+ title="Fix flaky retention test",+ posthog_url="https://app/project/1/tasks/abc",+ status="in_progress",+ repository="posthog/posthog",+ pr_url=None,+ thread_url=None,+ updated_at_label="5m ago",+ ),+ ),+ available_repos=("posthog/posthog",),+ has_any_tasks=True,+ page=1,+ total_pages=3,+ total_filtered=25,+ ),+ stats_state=StatsState(tasks_started=4, tasks_with_pr=2, tasks_merged=1, active_people=2),+ )++ # Equality both ways: an unroutable control fails on the left, and a card that+ # stopped rendering fails on the right instead of passing a subset check trivially.+ # Unlink only renders once an account is linked, which this fixture deliberately isn't.+ assert set(_action_ids(view)) == HOME_ACTION_IDS - {ACTION_UNLINK_ACCOUNT}+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()@@ -708,6 +778,124 @@ class TestParseModalSubmission:assert parse_modal_submission(view) == ("claude", None, None)+# ---------------------------------------------------------------------------+# Handler tests — Tasks card controls+# ---------------------------------------------------------------------------+++class TestTasksControlsRepublishTheList:+ """A click has to reach Slack as a different view, or the tab looks frozen.++ The rest of the Tasks coverage stops at a boundary — the renderer takes a+ hand-built `TasksState`, the decoding tests stop at the resolved view state. This+ joins them: a real `block_actions` payload in, the `views.publish` payload out.+ """++ def _seed(self, integration) -> None:+ # More than one page, so a Next click has somewhere to go.+ for index in range(12):+ task = Task.objects.create(+ team=integration.team,+ title=f"Task {index}",+ description="d",+ origin_product=Task.OriginProduct.SLACK,+ repository="posthog/posthog" if index % 2 == 0 else "posthog/other",+ )+ run = TaskRun.objects.create(task=task, team=integration.team, status=TaskRun.Status.IN_PROGRESS)+ SlackThreadTaskMapping.objects.create(+ team=integration.team,+ integration=integration,+ slack_workspace_id=SLACK_WORKSPACE_ID,+ channel="C1",+ thread_ts=f"170000000.{index:06d}",+ task=task,+ task_run=run,+ mentioning_slack_user_id="U001",+ )++ def _published_titles(self, view: dict) -> list[str]:+ titles = []+ for block in view["blocks"]:+ text = (block.get("text") or {}).get("text", "")+ if text.startswith("*<") and "/tasks/" in text:+ titles.append(text.split("|", 1)[1].rstrip(">*"))+ return titles++ def test_next_publishes_a_different_page_and_the_filter_narrows_it(+ self, slack_integration, mock_slack_client, flag_on+ ):+ self._seed(slack_integration)++ with patch("products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin", return_value=False):+ first = _tasks_click_payload(ACTION_TASKS_PAGE_NEXT, value="0")+ handle_ai_preferences_block_action(first, first["actions"][0])+ page_one = self._published_titles(mock_slack_client.views_publish.call_args.kwargs["view"])++ second = _tasks_click_payload(ACTION_TASKS_PAGE_NEXT, value="1")+ handle_ai_preferences_block_action(second, second["actions"][0])+ page_two = self._published_titles(mock_slack_client.views_publish.call_args.kwargs["view"])++ narrowed = _tasks_click_payload(ACTION_TASKS_FILTER_REPO, repo="posthog/other")+ handle_ai_preferences_block_action(narrowed, narrowed["actions"][0])+ filtered = self._published_titles(mock_slack_client.views_publish.call_args.kwargs["view"])++ assert len(page_one) == 10+ assert page_two and not set(page_two) & set(page_one)+ # Odd indices carry posthog/other, so the filter must leave only those.+ assert filtered and all(int(title.split()[1]) % 2 == 1 for title in filtered)+++class TestTasksControlsResolveViewState:+ """What the Tasks controls ask the resolver for, without touching the database.++ The Home tab holds no server-side state: the page rides on the clicked button's+ `value` and the filters ride on the view's input state. These lock that decoding,+ which is otherwise only observable through a full publish.+ """++ def _resolved_state(self, monkeypatch, payload: dict):+ captured: dict[str, Any] = {}+ monkeypatch.setattr(slack_app_home, "_resolve_interaction_integration", lambda team_id, user_id: object())+ monkeypatch.setattr(slack_app_home, "is_slack_app_home_enabled", lambda integration: True)+ monkeypatch.setattr(+ slack_app_home,+ "_republish_home",+ lambda integration, slack_user_id, *, view_state=None: captured.update(state=view_state),+ )+ handle_ai_preferences_block_action(payload, payload["actions"][0])+ assert "state" in captured, "the click never reached a republish"+ return captured["state"]++ @pytest.mark.parametrize(+ "action_id,value,expected_page",+ [+ (ACTION_TASKS_PAGE_NEXT, "1", 1),+ (ACTION_TASKS_PAGE_PREV, "0", 0),+ (ACTION_TASKS_PAGE_NEXT, "7", 7),+ # A button that somehow arrives without a usable page falls back to the first.+ (ACTION_TASKS_PAGE_NEXT, None, 0),+ (ACTION_TASKS_PAGE_NEXT, "not-a-number", 0),+ ],+ )+ def test_page_comes_off_the_clicked_button(self, monkeypatch, action_id, value, expected_page):+ state = self._resolved_state(monkeypatch, _tasks_click_payload(action_id, value=value))+ assert state.tasks_page == expected_page++ def test_paging_keeps_the_active_repo_filter(self, monkeypatch):+ # Paging must not silently widen the list back to every repo.+ state = self._resolved_state(+ monkeypatch, _tasks_click_payload(ACTION_TASKS_PAGE_NEXT, value="1", repo="posthog/posthog")+ )+ assert (state.selected_repo, state.tasks_page) == ("posthog/posthog", 1)++ def test_changing_the_filter_returns_to_the_first_page(self, monkeypatch):+ # Otherwise a narrower result set leaves the viewer stranded past its last page.+ state = self._resolved_state(+ monkeypatch, _tasks_click_payload(ACTION_TASKS_FILTER_REPO, repo="posthog/posthog")+ )+ assert (state.selected_repo, state.tasks_page) == ("posthog/posthog", 0)++# ---------------------------------------------------------------------------# Handler tests — app_home_opened event# ---------------------------------------------------------------------------@@ -918,3 +1106,105 @@ class TestRetiredWorkspaceModal:response = handle_app_home_view_submission(payload)assert response.status_code == 200assert not SlackSettings.objects.exists()+++class TestInteractionResolvesTheViewersIntegration:+ """A workspace connected to two organizations must answer clicks for the right one.++ Everything the tab is keyed on hangs off the resolved integration — the rollout flag+ is scoped to an organization, and the task list, project card and account link are all+ scoped to its team. Answering a click against an arbitrary row of the workspace makes+ the tab disagree with itself, which reads as a control that does nothing.+ """++ def _second_org_integration(self) -> Integration:+ organization = Organization.objects.create(name="Other Org")+ team = Team.objects.create(organization=organization, name="Other Team")+ return Integration.objects.create(+ team=team,+ kind="slack",+ integration_id=SLACK_WORKSPACE_ID,+ sensitive_config={"access_token": "xoxb-other"},+ )++ # Personal pick and workspace default are separate rungs of the ladder; both must beat+ # row order, since `slack_integration` is created first and any unordered lookup wins with it.+ @pytest.mark.parametrize("pick_owner", ["U001", None])+ def test_the_saved_project_pick_beats_row_order(self, slack_integration, pick_owner):+ preferred = self._second_org_integration()+ SlackSettings.objects.create(+ slack_workspace_id=SLACK_WORKSPACE_ID,+ slack_user_id=pick_owner,+ default_integration=preferred,+ )++ resolved = slack_app_home._resolve_interaction_integration(SLACK_WORKSPACE_ID, "U001")++ assert resolved is not None and resolved.id == preferred.id++ def test_unknown_workspace_resolves_to_nothing(self, db):+ assert slack_app_home._resolve_interaction_integration("T_NOT_CONNECTED", "U001") is None++ def test_no_pick_falls_back_to_the_same_install_regardless_of_candidate_order(self, slack_integration):+ # The auth filter hands back candidates freshest-verdict-first, so the fallback+ # can't take the front of that list and stay put across cache expiries.+ newer = self._second_org_integration()+ oldest = min(slack_integration.id, newer.id)++ first = slack_app_home._resolve_interaction_integration(SLACK_WORKSPACE_ID, "U001")+ with patch(+ "products.slack_app.backend.services.slack_auth.check_integrations_auth_and_filter",+ side_effect=lambda candidates, **_: list(reversed(candidates)),+ ):+ reordered = slack_app_home._resolve_interaction_integration(SLACK_WORKSPACE_ID, "U001")++ assert first is not None and reordered is not None+ assert first.id == reordered.id == oldest+++class TestNoProjectAccessCard:+ """What someone sees when no PostHog project connected here is visible to them.++ Without this the tab draws its normal cards against nothing: no project picker, and a+ Tasks card inviting them to mention @PostHog — which won't run either, for the same+ reason. The regression to catch is a card reappearing in that state.+ """++ def _view(self, **overrides) -> dict:+ kwargs: dict[str, Any] = {+ "effective": AIPreferences(),+ "user_row": None,+ "is_admin": True,+ "has_project_access": False,+ "tasks_state": TasksState(),+ "stats_state": StatsState(tasks_started=4),+ "account_state": AccountState(enabled=True, link_url="https://app/link"),+ "project_state": ProjectState(candidates=(ProjectChoice(team_id=1, label="Org · Team"),)),+ }+ kwargs.update(overrides)+ return render_home_view(**kwargs)++ def test_explains_the_dead_end_and_links_to_the_settings_page(self):+ text = _all_text(self._view())++ assert "No project to show yet" in text+ assert "ask an admin" in text+ urls = [+ element["url"]+ for block in self._view()["blocks"]+ for element in block.get("elements", []) or []+ if "url" in element+ ]+ assert urls == ["http://localhost:8010/settings/project-integrations"]++ def test_suppresses_every_card_that_needs_a_project(self):+ # Each of these would otherwise render from the states passed above.+ text = _all_text(self._view())++ assert "🦔 Tasks" not in text+ assert "Workspace activity" not in text+ assert "Project routing" not in text+ assert not _action_ids(self._view())++ def test_normal_tab_is_untouched_when_a_project_is_reachable(self):+ assert "No project to show yet" not in _all_text(self._view(has_project_access=True))