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): app home tab (#65216)

Vojta Bartoš09a7785111d7
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.md
index 1c3f619f7746..2b6688aad7a2 100644
--- a/docs/internal/slack-local-setup-guide.md
+++ b/docs/internal/slack-local-setup-guide.md
@@ -96,9 +96,14 @@ features:
bot_user:
display_name: posthog-slack-dev
always_online: true
+ app_home:
+ home_tab_enabled: true
+ messages_tab_enabled: false
+ messages_tab_read_only_enabled: false
oauth_config:
redirect_urls:
- https://<you>-posthog.ngrok.dev/integrations/slack/callback
+ - https://<you>-posthog.ngrok.dev/complete/slack-link/
scopes:
bot:
- app_mentions:read
@@ -110,11 +115,15 @@ oauth_config:
- reactions:write
- users:read
- users:read.email
+ user:
+ - identity.basic
+ - identity.email
settings:
event_subscriptions:
request_url: https://<you>-posthog.ngrok.dev/slack/event-callback
bot_events:
- app_mention
+ - app_home_opened
interactivity:
is_enabled: true
request_url: https://<you>-posthog.ngrok.dev/slack/interactivity-callback
@@ -130,6 +139,11 @@ Django must be up at that moment.
> `link_shared` is left out on purpose — it needs the `links:read` scope (the manifest won't save
> otherwise) and the coding agent doesn't use it.
+> The `app_home` block + `app_home_opened` bot event power the App Home tab; the
+> sign-in-with-Slack flow needs `user` scopes `identity.basic` + `identity.email` and the second
+> redirect URL (`/complete/slack-link/`). Drop those if you don't want either feature locally —
+> they're behind the `slack-app-home` and `slack-app-oauth` flags.
+
## Step 3 — backend credentials and `SITE_URL`
PostHog Code reuses the regular Slack notifications app, so set the standard
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 9e79a5357c36..6cb630802fc5 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -62,6 +62,14 @@ from products.slack_app.backend.services.integration_resolver import (
resolve_user_for_workspace,
user_resolution_failure_reply,
)
+from products.slack_app.backend.services.slack_app_home import (
+ ACTION_RESET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_WORKSPACE,
+ ACTION_UNLINK_ACCOUNT,
+ handle_app_home_opened as _handle_app_home_opened,
+ handle_home_block_action as _handle_home_block_action,
+)
from products.slack_app.backend.services.slack_user_info import (
get_cached_bot_user_id,
get_slack_user_info,
@@ -84,6 +92,7 @@ HANDLED_EVENT_TYPES = [
"member_joined_channel",
"assistant_thread_started",
"assistant_thread_context_changed",
+ "app_home_opened",
]
# The notifications Slack app (`slack`) install carries every scope the coding-agent flow
@@ -1694,6 +1703,16 @@ def route_posthog_code_event_to_relevant_region(
eu_domain=_eu_region_domain(),
)
+ # App Home tab: published per-user when they open the Home tab. Always
+ # handled locally — `views.publish` just renders a snapshot of the user's
+ # AI preferences against the integration row, no cross-region state.
+ if event_type == "app_home_opened":
+ try:
+ _handle_app_home_opened(event, slack_team_id)
+ except Exception:
+ logger.exception("slack_app_home_opened_failed", slack_team_id=slack_team_id, event_id=event_id)
+ return ROUTE_HANDLED_LOCALLY
+
# Assistant surface: DMs to the app and agent-container events resolve the DMing user and run
# against their project. A ``message`` is a DM iff ``channel_type == "im"`` — channel ``message``
# events (untagged thread follow-ups) and ``app_mention`` share the pipeline below instead.
@@ -2545,6 +2564,31 @@ def _extract_context_token(payload: dict) -> str:
return payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("context_token", "")
+_HOME_TAB_ACTION_IDS = frozenset(
+ {
+ ACTION_RESET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_WORKSPACE,
+ ACTION_UNLINK_ACCOUNT,
+ }
+)
+
+
+def _is_home_tab_interactivity(payload: dict, payload_type: str) -> bool:
+ """Return True if this payload is a Home tab block_actions interaction.
+
+ Home-tab buttons carry no per-row hint — they're workspace-scoped, not
+ tied to a specific task or repo. The cross-region router uses this to
+ claim locality based on the workspace integration alone rather than
+ dropping the click.
+ """
+ if payload_type == "block_actions":
+ for action in payload.get("actions", []) or ():
+ if action.get("action_id", "") in _HOME_TAB_ACTION_IDS:
+ return True
+ return False
+
+
def _extract_picker_hints(payload: dict) -> tuple[int | None, str | None]:
"""Extract integration_id and mentioning user id from block_id for fallback handling."""
block_id = payload.get("block_id", "")
@@ -3239,6 +3283,15 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
kind=SLACK_INTEGRATION_KIND,
integration_id=slack_team_id,
).exists()
+ elif slack_team_id and _is_home_tab_interactivity(payload, payload_type):
+ # App Home routing/account actions carry no per-row hint — the button
+ # is tied to the workspace, not a specific picker context. Claim
+ # locality based on the workspace integration alone; if we own *any*
+ # Integration for this Slack team, the click is ours to handle.
+ local = Integration.objects.filter(
+ kind=SLACK_INTEGRATION_KIND,
+ integration_id=slack_team_id,
+ ).exists()
proxied = _was_proxied(request)
incoming_host = request.get_host()
@@ -3314,25 +3367,28 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
if payload_type == "block_actions":
actions = payload.get("actions", [])
for action in actions:
- if action.get("action_id") == "posthog_code_repo_select":
+ action_id = action.get("action_id")
+ if action_id == "posthog_code_repo_select":
return _handle_repo_picker_submit(payload)
- if action.get("action_id") == "posthog_code_repo_none":
+ if action_id == "posthog_code_repo_none":
return _handle_no_repo_needed_submit(payload)
- if action.get("action_id") == "posthog_code_terminate_task":
+ if action_id == "posthog_code_terminate_task":
return _handle_terminate_task_submit(payload)
- if action.get("action_id") == CHANNEL_APPROVAL_ACTION_APPROVE:
+ if action_id == CHANNEL_APPROVAL_ACTION_APPROVE:
return _handle_channel_approval_submit(payload)
- if action.get("action_id") == CHANNEL_APPROVAL_ACTION_DENY:
+ if action_id == CHANNEL_APPROVAL_ACTION_DENY:
return _handle_channel_approval_deny(payload)
- if action.get("action_id") == SIGNALS_DISMISS_REPORT_ACTION_ID:
+ if action_id == SIGNALS_DISMISS_REPORT_ACTION_ID:
return _handle_signals_dismiss_report(payload)
- if action.get("action_id") == onboarding.INBOX_CREATE_ACTION_ID:
+ if action_id == onboarding.INBOX_CREATE_ACTION_ID:
return inbox_interactivity.handle_inbox_create(payload)
- if action.get("action_id") == onboarding.INBOX_JOIN_ACTION_ID:
+ if action_id == onboarding.INBOX_JOIN_ACTION_ID:
return inbox_interactivity.handle_inbox_join(payload)
- if action.get("action_id") == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION:
+ if action_id == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION:
return inbox_interactivity.handle_inbox_sources(payload)
- if action.get("action_id") == onboarding.INBOX_AI_APPROVAL_ACTION_ID:
+ if action_id == onboarding.INBOX_AI_APPROVAL_ACTION_ID:
return inbox_interactivity.handle_inbox_ai_approval(payload)
+ if action_id in _HOME_TAB_ACTION_IDS:
+ return _handle_home_block_action(payload, action)
return HttpResponse(status=200)
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index 67bdb176fdef..6af616adb358 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -1,10 +1,12 @@
"""Feature-flag checks for the Slack app backend.
-One module per flag-check function, so flag rollouts are easy to find and
+One module for all Slack-app flag checks so rollouts are easy to find and
audit. Every check here is fail-closed: a flaky ``posthoganalytics.feature_enabled``
call must not silently enable a feature for everyone.
"""
+from __future__ import annotations
+
import structlog
import posthoganalytics
@@ -15,6 +17,7 @@ logger = structlog.get_logger(__name__)
SLACK_APP_OAUTH_FLAG = "slack-app-oauth"
+SLACK_APP_HOME_FLAG = "slack-app-home"
def slack_oauth_link_enabled(integration: Integration, slack_team_id: str) -> bool:
@@ -53,3 +56,35 @@ def slack_oauth_link_enabled(integration: Integration, slack_team_id: str) -> bo
integration_id=integration.id,
)
return False
+
+
+def is_slack_app_home_enabled(integration: Integration, *, region: str | None = None) -> bool:
+ """Return True when the ``slack-app-home`` flag is on for this workspace.
+
+ The flag controls the App Home tab surface and the AI-settings resolver
+ that feeds Slack-triggered task runs. Keyed on Slack workspace id +
+ PostHog org so the same flag rule can target either dimension.
+
+ ``region`` overrides the auto-detected instance region — useful in dev
+ environments where ``get_instance_region()`` returns ``None``. The
+ default fallback is ``"dev"`` (not ``"unknown"``), so a flag rule
+ targeting ``region == "dev"`` opts local environments in without
+ leaking to prod.
+ """
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ SLACK_APP_HOME_FLAG,
+ f"slack_workspace:{integration.integration_id}",
+ groups={"organization": str(integration.team.organization_id)},
+ person_properties={"region": region or get_instance_region() or "dev"},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception(
+ "slack_app_home_feature_flag_check_failed",
+ integration_id=integration.id,
+ )
+ return False
diff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.py
index aaa024d69167..4092e1d6be74 100644
--- a/products/slack_app/backend/models.py
+++ b/products/slack_app/backend/models.py
@@ -120,7 +120,8 @@ class SlackSettings(UUIDModel):
def __str__(self) -> str:
who = self.slack_user_id or "(workspace default)"
- return f"{self.slack_workspace_id} / {who} → integration {self.default_integration_id}"
+ target = self.default_integration_id if self.default_integration_id else "(inherit)"
+ return f"{self.slack_workspace_id} / {who} → integration {target}"
class SlackChannel(UUIDModel):
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
new file mode 100644
index 000000000000..b86d0b6af7ba
--- /dev/null
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -0,0 +1,598 @@
+"""App Home tab renderer + interactivity handlers for the PostHog Slack app.
+
+The Home tab is the user-facing control panel for the integration. This
+first iteration carries two cards — project routing (which PostHog project
+@PostHog mentions land in) and account linking (Sign-in-with-Slack). The
+layout leaves room for additional cards as they come online.
+
+All Block Kit payloads are built as plain dicts here so they can be
+unit-tested without any Slack client. The event/interactivity handlers in
+`products/slack_app/backend/api.py` are the ones that actually call
+`views.publish` / `views.open`.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from django.http import HttpResponse
+
+import structlog
+
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user_integration import UserIntegration
+from posthog.user_permissions import UserPermissions
+
+from products.slack_app.backend.feature_flags import is_slack_app_home_enabled, slack_oauth_link_enabled
+from products.slack_app.backend.models import SlackSettings, SlackUserProfileCache
+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
+
+logger = structlog.get_logger(__name__)
+
+HOME_CALLBACK_ID = "slack_app_home"
+
+ACTION_UNLINK_ACCOUNT = "slack_app_home:unlink_account"
+ACTION_SET_PROJECT_PERSONAL = "slack_app_home:set_project_personal"
+ACTION_SET_PROJECT_WORKSPACE = "slack_app_home:set_project_workspace"
+ACTION_RESET_PROJECT_PERSONAL = "slack_app_home:reset_project_personal"
+
+
+@dataclass(frozen=True)
+class ProjectChoice:
+ """One PostHog project the user can route their @PostHog mentions to."""
+
+ team_id: int
+ label: str
+
+
+@dataclass(frozen=True)
+class ProjectState:
+ """Inputs the renderer needs to draw the project-routing card.
+
+ ``candidates`` is the accessible subset the user can pick from; the
+ workspace default is resolved against the full workspace integration
+ list so it surfaces even when the user can't access that project.
+ """
+
+ candidates: tuple[ProjectChoice, ...] = ()
+ personal_team_id: int | None = None
+ workspace_team_id: int | None = None
+ workspace_team_label: str | None = None
+
+ @property
+ def has_anything_to_show(self) -> bool:
+ return bool(self.candidates) or self.workspace_team_label is not None
+
+
+@dataclass(frozen=True)
+class AccountState:
+ """Inputs the renderer needs to draw the optional account-link card."""
+
+ enabled: bool = False
+ linked_email: str | None = None
+ link_url: str | None = None
+
+
+def render_home_view(
+ *,
+ is_admin: bool,
+ account_state: AccountState | None = None,
+ project_state: ProjectState | None = None,
+) -> dict:
+ """Render the Block Kit payload for `views.publish` on the App Home tab."""
+
+ blocks: list[dict] = []
+ blocks.extend(_header_blocks())
+
+ if project_state and project_state.has_anything_to_show:
+ blocks.append({"type": "divider"})
+ blocks.extend(_project_section_blocks(project_state, is_admin=is_admin))
+
+ if account_state and account_state.enabled:
+ blocks.append({"type": "divider"})
+ blocks.extend(_account_section_blocks(account_state))
+
+ blocks.append({"type": "divider"})
+ blocks.extend(_footer_blocks())
+
+ return {"type": "home", "callback_id": HOME_CALLBACK_ID, "blocks": blocks}
+
+
+def _section_title(title: str, subtitle: str | None = None) -> dict:
+ text = f"*{title}*"
+ if subtitle:
+ text += f"\n{subtitle}"
+ return {"type": "section", "text": {"type": "mrkdwn", "text": text}}
+
+
+def _subsection_label(text: str) -> dict:
+ """Bold mrkdwn line in a `context` block — smaller than a section title."""
+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": f"*{text}*"}]}
+
+
+def _header_blocks() -> list[dict]:
+ return [
+ _section_title(
+ "Welcome to PostHog! 👋",
+ "Tune how @PostHog mentions get routed and answered from this Slack workspace.",
+ ),
+ ]
+
+
+def _project_section_blocks(state: ProjectState, *, is_admin: bool) -> list[dict]:
+ """Render the project-routing card.
+
+ Personal dropdown for the calling user; workspace dropdown for admins.
+ Each `static_select` dispatches its own action_id so a single change
+ triggers a single block_actions roundtrip and an immediate republish.
+ """
+ options = [
+ {"text": {"type": "plain_text", "text": c.label, "emoji": True}, "value": str(c.team_id)}
+ for c in state.candidates
+ ]
+
+ blocks: list[dict] = [
+ _section_title(
+ "Project routing",
+ "Which PostHog project @PostHog mentions land in. Personal picks override the workspace default.",
+ ),
+ ]
+
+ if options:
+ blocks.append(_subsection_label("Your default"))
+ personal_select: dict[str, Any] = {
+ "type": "static_select",
+ "action_id": ACTION_SET_PROJECT_PERSONAL,
+ "placeholder": {"type": "plain_text", "text": "Inherit workspace default"},
+ "options": options,
+ }
+ personal_elements: list[dict[str, Any]] = [personal_select]
+ if state.personal_team_id is not None and any(c.team_id == state.personal_team_id for c in state.candidates):
+ personal_select["initial_option"] = next(o for o in options if o["value"] == str(state.personal_team_id))
+ personal_elements.append(
+ {
+ "type": "button",
+ "action_id": ACTION_RESET_PROJECT_PERSONAL,
+ "text": {"type": "plain_text", "text": "Reset to workspace default", "emoji": True},
+ }
+ )
+ blocks.append({"type": "actions", "elements": personal_elements})
+
+ if is_admin and options:
+ blocks.append(_subsection_label("Workspace default"))
+ workspace_select: dict[str, Any] = {
+ "type": "static_select",
+ "action_id": ACTION_SET_PROJECT_WORKSPACE,
+ "placeholder": {"type": "plain_text", "text": "No workspace default"},
+ "options": options,
+ }
+ if state.workspace_team_id is not None and any(c.team_id == state.workspace_team_id for c in state.candidates):
+ workspace_select["initial_option"] = next(o for o in options if o["value"] == str(state.workspace_team_id))
+ blocks.append({"type": "actions", "elements": [workspace_select]})
+ # Footnote when the default points at a project the admin can't access:
+ # the picker can't surface it via `initial_option` since it isn't in `options`.
+ if state.workspace_team_label and not any(c.team_id == state.workspace_team_id for c in state.candidates):
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [
+ {"type": "mrkdwn", "text": f"Currently set to _{state.workspace_team_label}_ (no access)"}
+ ],
+ }
+ )
+ elif state.workspace_team_label:
+ blocks.append(_subsection_label("Workspace default"))
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"_{state.workspace_team_label}_"}})
+
+ return blocks
+
+
+def _account_section_blocks(account_state: AccountState) -> list[dict]:
+ """Render the Sign-in-with-Slack account card.
+
+ Visible only when `slack_oauth_link_enabled` returned True. Linked
+ state mirrors the Claude home pattern: ✅ + email, with a danger-styled
+ Disconnect button at the bottom.
+ """
+ if account_state.linked_email:
+ return [
+ _section_title("Linked PostHog account"),
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"✅ Connected as *{account_state.linked_email}*",
+ },
+ },
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "action_id": ACTION_UNLINK_ACCOUNT,
+ "style": "danger",
+ "text": {"type": "plain_text", "text": "Disconnect", "emoji": True},
+ "confirm": {
+ "title": {"type": "plain_text", "text": "Disconnect your PostHog account?"},
+ "text": {
+ "type": "mrkdwn",
+ "text": "@PostHog will fall back to matching your Slack email against PostHog users until you link again.",
+ },
+ "confirm": {"type": "plain_text", "text": "Disconnect"},
+ "deny": {"type": "plain_text", "text": "Cancel"},
+ },
+ }
+ ],
+ },
+ ]
+ blocks: list[dict] = [
+ _section_title(
+ "Connect your PostHog account",
+ "Link your Slack identity to a PostHog user so @PostHog knows it's you without falling back to email matching.",
+ ),
+ ]
+ if account_state.link_url:
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "url": account_state.link_url,
+ "text": {"type": "plain_text", "text": "Connect to PostHog", "emoji": True},
+ "style": "primary",
+ }
+ ],
+ }
+ )
+ return blocks
+
+
+def _footer_blocks() -> list[dict]:
+ return [
+ {
+ "type": "context",
+ "elements": [
+ {"type": "mrkdwn", "text": "Mention @PostHog in any channel to get started."},
+ ],
+ }
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Event + interactivity handlers
+# ---------------------------------------------------------------------------
+
+
+def handle_app_home_opened(event: dict, slack_team_id: str) -> None:
+ """Publish the Home tab for the user who just opened it.
+
+ Gated by the slack-app-home flag — when off the publish is skipped so
+ installs without the manifest changes (and workspaces that haven't
+ opted in) keep getting Slack's default blank Home tab.
+ """
+
+ slack_user_id = event.get("user")
+ if not slack_user_id:
+ return
+
+ integration = _get_slack_integration(slack_team_id)
+ if integration is None:
+ return
+
+ if not is_slack_app_home_enabled(integration):
+ return
+
+ slack = SlackIntegration(integration)
+ is_admin = _is_admin(slack, integration, slack_user_id)
+ account_state = _resolve_account_state(integration, slack_user_id)
+ project_state = _resolve_project_state(integration, slack_user_id)
+
+ view = render_home_view(
+ is_admin=is_admin,
+ account_state=account_state,
+ project_state=project_state,
+ )
+ try:
+ slack.client.views_publish(user_id=slack_user_id, view=view)
+ except Exception:
+ logger.exception(
+ "slack_app_home_publish_failed",
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ )
+
+
+def handle_home_block_action(payload: dict, action: dict) -> HttpResponse:
+ """Dispatch a `block_actions` payload originating from the Home tab."""
+
+ action_id = action.get("action_id")
+ slack_team_id = (payload.get("team") or {}).get("id", "")
+ slack_user_id = (payload.get("user") or {}).get("id", "")
+
+ integration = _get_slack_integration(slack_team_id)
+ if integration is None:
+ return HttpResponse(status=200)
+
+ # The flag is the kill-switch for the whole feature — writes must
+ # respect it too, otherwise a flipped-off flag silently accumulates
+ # rows that the resolver will ignore.
+ if not is_slack_app_home_enabled(integration):
+ return HttpResponse(status=200)
+
+ if action_id == ACTION_SET_PROJECT_PERSONAL:
+ _apply_project_pick(integration, slack_user_id=slack_user_id, action=action, scope="personal")
+ _republish_home(integration, slack_user_id)
+ return HttpResponse(status=200)
+
+ if action_id == ACTION_RESET_PROJECT_PERSONAL:
+ _clear_project_personal(integration, slack_user_id)
+ _republish_home(integration, slack_user_id)
+ return HttpResponse(status=200)
+
+ if action_id == ACTION_SET_PROJECT_WORKSPACE:
+ slack = SlackIntegration(integration)
+ if not _is_admin(slack, integration, slack_user_id):
+ _post_ephemeral_admin_only(slack, payload)
+ return HttpResponse(status=200)
+ _apply_project_pick(integration, slack_user_id=None, action=action, scope="workspace")
+ _republish_home(integration, slack_user_id)
+ return HttpResponse(status=200)
+
+ if action_id == ACTION_UNLINK_ACCOUNT:
+ # Only act when the OAuth-link feature is on for this workspace —
+ # otherwise the button shouldn't have been rendered, and a stale
+ # cached view shouldn't be allowed to drive deletes.
+ if slack_oauth_link_enabled(integration, integration.integration_id):
+ _unlink_user_account(integration, slack_user_id)
+ _republish_home(integration, slack_user_id)
+ return HttpResponse(status=200)
+
+ return HttpResponse(status=200)
+
+
+# ---------------------------------------------------------------------------
+# Handler internals
+# ---------------------------------------------------------------------------
+
+
+def _get_slack_integration(slack_team_id: str) -> Integration | None:
+ if not slack_team_id:
+ return None
+ return (
+ Integration.objects.select_related("team", "team__organization")
+ .filter(kind="slack", integration_id=slack_team_id)
+ .first()
+ )
+
+
+def _is_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:
+ try:
+ return is_slack_workspace_admin(slack, integration, slack_user_id)
+ except Exception:
+ logger.exception(
+ "slack_app_home_is_admin_check_failed",
+ slack_user_id=slack_user_id,
+ integration_id=integration.id,
+ )
+ return False
+
+
+def _clear_project_personal(integration: Integration, slack_user_id: str) -> None:
+ """Clear the personal routing override."""
+ SlackSettings.objects.filter(
+ slack_workspace_id=integration.integration_id,
+ slack_user_id=slack_user_id,
+ ).delete()
+
+
+def _republish_home(integration: Integration, slack_user_id: str) -> None:
+ slack = SlackIntegration(integration)
+ is_admin = _is_admin(slack, integration, slack_user_id)
+ account_state = _resolve_account_state(integration, slack_user_id)
+ project_state = _resolve_project_state(integration, slack_user_id)
+ view = render_home_view(
+ is_admin=is_admin,
+ account_state=account_state,
+ project_state=project_state,
+ )
+ try:
+ slack.client.views_publish(user_id=slack_user_id, view=view)
+ except Exception:
+ logger.exception("slack_app_home_republish_failed")
+
+
+def _resolve_account_state(integration: Integration, slack_user_id: str) -> AccountState:
+ slack_team_id = integration.integration_id
+ if not slack_oauth_link_enabled(integration, slack_team_id):
+ return AccountState(enabled=False)
+
+ candidate_org_ids = _workspace_org_ids(slack_team_id)
+ linked_user = find_linked_posthog_user(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ candidate_org_ids=candidate_org_ids,
+ )
+ if linked_user is not None:
+ return AccountState(enabled=True, linked_email=linked_user.email)
+
+ try:
+ link_url = build_invite_url(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ posthog_team_id=integration.team_id,
+ channel=None,
+ thread_ts=None,
+ )
+ except Exception:
+ logger.exception(
+ "slack_app_home_build_invite_url_failed",
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ )
+ link_url = None
+ return AccountState(enabled=True, linked_email=None, link_url=link_url)
+
+
+def _resolve_project_state(integration: Integration, slack_user_id: str) -> ProjectState:
+ candidates = list(
+ Integration.objects.filter(kind="slack", integration_id=integration.integration_id)
+ .select_related("team", "team__organization")
+ .order_by("id")
+ )
+ if not candidates:
+ return ProjectState()
+
+ accessible = _filter_accessible_integrations(integration, slack_user_id, candidates)
+
+ user_row = (
+ SlackSettings.objects.filter(
+ slack_workspace_id=integration.integration_id,
+ slack_user_id=slack_user_id,
+ )
+ .select_related("default_integration")
+ .first()
+ )
+ workspace_row = (
+ SlackSettings.objects.filter(
+ slack_workspace_id=integration.integration_id,
+ slack_user_id__isnull=True,
+ )
+ .select_related("default_integration")
+ .first()
+ )
+
+ def _label(c: Integration) -> str:
+ return f"{c.team.organization.name} · {c.team.name}"
+
+ # Look up the workspace default's label against the full candidate list,
+ # not `accessible`, so a default pointing at an inaccessible project still
+ # surfaces in the UI.
+ workspace_team_id = (
+ workspace_row.default_integration.team_id if workspace_row and workspace_row.default_integration_id else None
+ )
+ workspace_team_label: str | None = None
+ if workspace_team_id is not None:
+ workspace_team_label = next((_label(c) for c in candidates if c.team_id == workspace_team_id), None)
+
+ return ProjectState(
+ candidates=tuple(ProjectChoice(team_id=c.team_id, label=_label(c)) for c in accessible),
+ personal_team_id=(
+ user_row.default_integration.team_id if user_row and user_row.default_integration_id else None
+ ),
+ workspace_team_id=workspace_team_id,
+ workspace_team_label=workspace_team_label,
+ )
+
+
+def _filter_accessible_integrations(
+ integration: Integration, slack_user_id: str, candidates: list[Integration]
+) -> list[Integration]:
+ # Falls back to the full candidate list when we can't identify the user —
+ # hiding the picker would mean an unidentified user has no way to change
+ # their routing at all.
+ profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id).first()
+ if profile is None or not profile.email:
+ return candidates
+ membership = (
+ OrganizationMembership.objects.filter(
+ user__email=profile.email,
+ organization_id__in={c.team.organization_id for c in candidates},
+ )
+ .select_related("user")
+ .first()
+ )
+ if membership is None:
+ return candidates
+ permissions = UserPermissions(user=membership.user)
+ return [c for c in candidates if permissions.team(c.team).effective_membership_level is not None]
+
+
+def _apply_project_pick(
+ integration: Integration,
+ *,
+ slack_user_id: str | None,
+ action: dict,
+ scope: str,
+) -> None:
+ selected = (action.get("selected_option") or {}).get("value")
+ if not selected:
+ return
+ try:
+ team_id = int(selected)
+ except (TypeError, ValueError):
+ return
+ target = (
+ Integration.objects.filter(kind="slack", integration_id=integration.integration_id, team_id=team_id)
+ .select_related("team", "team__organization")
+ .first()
+ )
+ if target is None:
+ return
+ # Personal-scope picks are user-driven, so re-check that the picker
+ # actually had this team in its accessible set. The renderer hides
+ # inaccessible options but a hand-crafted block_actions can still arrive
+ # with any team_id in the workspace.
+ if scope == "personal" and slack_user_id:
+ accessible = _filter_accessible_integrations(integration, slack_user_id, [target] if target else [])
+ if not accessible:
+ return
+ SlackSettings.objects.update_or_create(
+ slack_workspace_id=integration.integration_id,
+ slack_user_id=slack_user_id,
+ defaults={"default_integration": target},
+ )
+ logger.info(
+ "slack_app_home_project_default_set",
+ slack_workspace_id=integration.integration_id,
+ slack_user_id=slack_user_id,
+ scope=scope,
+ team_id=team_id,
+ )
+
+
+def _unlink_user_account(integration: Integration, slack_user_id: str) -> None:
+ # Scope across every org connected to this Slack workspace, not just the
+ # one for the integration the click happened to land on — for multi-org
+ # workspaces, the linked row may live in any of them.
+ slack_team_id = integration.integration_id
+ candidate_user_ids = set(
+ OrganizationMembership.objects.filter(
+ organization_id__in=_workspace_org_ids(slack_team_id),
+ ).values_list("user_id", flat=True)
+ )
+ if not candidate_user_ids:
+ return
+ UserIntegration.objects.filter(
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id=slack_user_id,
+ config__slack_team_id=slack_team_id,
+ user_id__in=candidate_user_ids,
+ ).delete()
+
+
+def _workspace_org_ids(slack_team_id: str) -> set:
+ return set(
+ Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list(
+ "team__organization_id", flat=True
+ )
+ )
+
+
+def _post_ephemeral_admin_only(slack: SlackIntegration, payload: dict) -> None:
+ """Tell a non-admin that workspace edits are gated."""
+ slack_user_id = (payload.get("user") or {}).get("id", "")
+ if not slack_user_id:
+ return
+ text = "Only Slack workspace admins can change the PostHog workspace default."
+ channel = (payload.get("channel") or {}).get("id") or (payload.get("container") or {}).get("channel_id")
+ try:
+ if channel:
+ slack.client.chat_postEphemeral(channel=channel, user=slack_user_id, text=text)
+ else:
+ slack.client.chat_postMessage(channel=slack_user_id, text=text)
+ except Exception:
+ logger.warning("slack_app_home_admin_only_notice_failed")
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
new file mode 100644
index 000000000000..6aa23ab6965b
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py
@@ -0,0 +1,267 @@
+"""Tests for the App Home tab (project routing + OAuth account linking).
+
+Block Kit renderer tests run as pure functions on dicts; handler tests
+exercise the real Django flow with the Slack API client mocked out.
+"""
+
+from __future__ import annotations
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+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
+from products.slack_app.backend.services.slack_app_home import (
+ ACTION_RESET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_PERSONAL,
+ ACTION_SET_PROJECT_WORKSPACE,
+ ACTION_UNLINK_ACCOUNT,
+ AccountState,
+ ProjectChoice,
+ ProjectState,
+ handle_app_home_opened,
+ handle_home_block_action,
+ render_home_view,
+)
+
+SLACK_WORKSPACE_ID = "T_HOME"
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def slack_integration(db):
+ organization = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=organization, name="Team")
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id=SLACK_WORKSPACE_ID,
+ sensitive_config={"access_token": "xoxb"},
+ )
+
+
+def mock_slack_client():
+ fake_client = MagicMock()
+ with patch("products.slack_app.backend.services.slack_app_home.SlackIntegration") as cls:
+ instance = MagicMock()
+ instance.client = fake_client
+ cls.return_value = instance
+ yield fake_client
+
+
+def flag_on():
+ with patch(
+ "products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled",
+ return_value=True,
+ ):
+ yield
+
+
+def admin_user():
+ with patch(
+ "products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",
+ return_value=True,
+ ):
+ yield
+
+
+def non_admin_user():
+ with patch(
+ "products.slack_app.backend.services.slack_app_home.is_slack_workspace_admin",
+ return_value=False,
+ ):
+ yield
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _action_ids(view: dict) -> list[str]:
+ out: list[str] = []
+ for block in view["blocks"]:
+ for el in block.get("elements", []) or []:
+ if "action_id" in el:
+ out.append(el["action_id"])
+ return out
+
+
+def _all_text(view: dict) -> str:
+ out: list[str] = []
+
+ def walk(node):
+ if isinstance(node, dict):
+ if "text" in node and isinstance(node["text"], str):
+ out.append(node["text"])
+ for v in node.values():
+ walk(v)
+ elif isinstance(node, list):
+ for item in node:
+ walk(item)
+
+ walk(view)
+ return " ".join(out)
+
+
+def _block_action_payload(*, action_id: str, slack_user_id: str, channel: str | None = None) -> dict:
+ return {
+ "type": "block_actions",
+ "team": {"id": SLACK_WORKSPACE_ID},
+ "user": {"id": slack_user_id},
+ "channel": {"id": channel} if channel else None,
+ "actions": [{"action_id": action_id}],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Renderer tests
+# ---------------------------------------------------------------------------
+
+
+class TestRenderHomeView:
+ def test_renders_home_type(self):
+ view = render_home_view(is_admin=False)
+ assert view["type"] == "home"
+
+ def test_hides_project_section_when_no_candidates_and_no_default(self):
+ view = render_home_view(is_admin=False, project_state=ProjectState())
+ assert "Project routing" not in _all_text(view)
+
+ def test_shows_personal_picker_when_candidates_present(self):
+ state = ProjectState(
+ candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),
+ )
+ view = render_home_view(is_admin=False, project_state=state)
+ assert ACTION_SET_PROJECT_PERSONAL in _action_ids(view)
+ assert "Project routing" in _all_text(view)
+
+ def test_personal_pick_renders_reset_button(self):
+ state = ProjectState(
+ candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),
+ personal_team_id=1,
+ )
+ view = render_home_view(is_admin=False, project_state=state)
+ assert ACTION_RESET_PROJECT_PERSONAL in _action_ids(view)
+
+ def test_workspace_default_shows_to_non_admin_as_read_only(self):
+ # Non-admin doesn't get the workspace picker but sees what's set.
+ state = ProjectState(
+ candidates=(ProjectChoice(team_id=1, label="Org · A"),),
+ workspace_team_id=1,
+ workspace_team_label="Org · A",
+ )
+ view = render_home_view(is_admin=False, project_state=state)
+ assert ACTION_SET_PROJECT_WORKSPACE not in _action_ids(view)
+ assert "Workspace default" in _all_text(view)
+ assert "Org · A" in _all_text(view)
+
+ def test_admin_sees_workspace_picker(self):
+ state = ProjectState(
+ candidates=(ProjectChoice(team_id=1, label="Org · A"), ProjectChoice(team_id=2, label="Org · B")),
+ )
+ view = render_home_view(is_admin=True, project_state=state)
+ assert ACTION_SET_PROJECT_WORKSPACE in _action_ids(view)
+
+ def test_admin_no_access_footnote_when_default_is_inaccessible(self):
+ # workspace_team_id is set but not in candidates → admin sees footnote.
+ state = ProjectState(
+ candidates=(ProjectChoice(team_id=1, label="Org · A"),),
+ workspace_team_id=42,
+ workspace_team_label="Other Org · Secret",
+ )
+ view = render_home_view(is_admin=True, project_state=state)
+ assert "no access" in _all_text(view)
+ assert "Other Org · Secret" in _all_text(view)
+
+ def test_account_section_hidden_when_disabled(self):
+ view = render_home_view(is_admin=False, account_state=AccountState(enabled=False))
+ assert "Linked PostHog account" not in _all_text(view)
+ assert "Connect to PostHog" not in _all_text(view)
+
+ def test_account_section_linked_shows_email_and_disconnect(self):
+ view = render_home_view(
+ is_admin=False,
+ account_state=AccountState(enabled=True, linked_email="[email protected]"),
+ )
+ assert "[email protected]" in _all_text(view)
+ assert ACTION_UNLINK_ACCOUNT in _action_ids(view)
+
+ def test_account_section_unlinked_shows_connect_button(self):
+ view = render_home_view(
+ is_admin=False,
+ account_state=AccountState(enabled=True, linked_email=None, link_url="https://example/auth"),
+ )
+ assert "Connect to PostHog" in _all_text(view)
+
+
+# ---------------------------------------------------------------------------
+# Handler tests — app_home_opened event
+# ---------------------------------------------------------------------------
+
+
+class TestHandleAppHomeOpened:
+ def test_publishes_view_for_known_user(self, slack_integration, mock_slack_client, flag_on, admin_user):
+ handle_app_home_opened({"user": "U001"}, SLACK_WORKSPACE_ID)
+ assert mock_slack_client.views_publish.called
+ kwargs = mock_slack_client.views_publish.call_args.kwargs
+ assert kwargs["user_id"] == "U001"
+ assert kwargs["view"]["type"] == "home"
+
+ def test_noop_when_user_missing(self, slack_integration, mock_slack_client, flag_on):
+ handle_app_home_opened({}, SLACK_WORKSPACE_ID)
+ assert not mock_slack_client.views_publish.called
+
+ def test_noop_when_integration_missing(self, db, mock_slack_client, flag_on):
+ handle_app_home_opened({"user": "U001"}, "T_UNKNOWN")
+ assert not mock_slack_client.views_publish.called
+
+
+# ---------------------------------------------------------------------------
+# Handler tests — block_actions
+# ---------------------------------------------------------------------------
+
+
+class TestResetProjectPersonal:
+ def test_drops_row_when_reset(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="U002",
+ )
+ payload = _block_action_payload(action_id=ACTION_RESET_PROJECT_PERSONAL, slack_user_id="U002")
+ handle_home_block_action(payload, payload["actions"][0])
+
+ assert not SlackSettings.objects.filter(slack_workspace_id=SLACK_WORKSPACE_ID, slack_user_id="U002").exists()
+ assert mock_slack_client.views_publish.called
+
+ def test_no_row_is_a_noop(self, slack_integration, mock_slack_client, flag_on, admin_user):
+ payload = _block_action_payload(action_id=ACTION_RESET_PROJECT_PERSONAL, slack_user_id="U003")
+ handle_home_block_action(payload, payload["actions"][0])
+ # Nothing to clear — still republish so the view stays in sync.
+ assert mock_slack_client.views_publish.called
+
+
+class TestSetWorkspaceProjectAdminGate:
+ def test_non_admin_blocked(self, slack_integration, mock_slack_client, flag_on, non_admin_user):
+ payload = _block_action_payload(
+ action_id=ACTION_SET_PROJECT_WORKSPACE,
+ slack_user_id="U_NONADMIN",
+ channel="C1",
+ )
+ # Payload doesn't pick a team, but the admin gate should short-circuit first.
+ handle_home_block_action(payload, payload["actions"][0])
+ assert not SlackSettings.objects.filter(slack_user_id__isnull=True).exists()
+ # Non-admin notice goes via ephemeral or DM.
+ assert mock_slack_client.chat_postEphemeral.called or mock_slack_client.chat_postMessage.called