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.

24.6 KB
Raw Blame
from collections.abc import Sequence
from typing import TYPE_CHECKING

from posthog.models.integration import SlackIntegration
from posthog.models.repo_routing_rule import RepoRoutingRule

from products.slack_app.backend.services.slack_messages import app_home_url, post_slack_ephemeral
from products.slack_app.backend.services.workspace_integrations import (
    WorkspaceIntegration,
    get_team_workspace_integration,
)

if TYPE_CHECKING:
    from products.slack_app.backend.api import RulesCommand
    from products.slack_app.backend.models import ChannelWelcomeMode
    from products.slack_app.backend.services.integration_resolver import ResolutionResult

MENTION_COMMAND_PREFIX = "@PostHog"
SLASH_COMMAND_PREFIX = "/posthog"

# `help` and the retired `default repo` verbs have no entry, so they fall back to the listing.
_SLASH_EQUIVALENT = {
    "list": "rules list",
    "add": 'rules add "description" org/repo',
    "remove": "rules remove <number>",
    "project_show": "project",
    "project_set": "project <id>",
    "project_set_workspace": "project workspace <id>",
    "welcome_show": "welcome",
    "welcome_set": "welcome channel|private|off",
}


def mention_command_redirect(command: "RulesCommand") -> str:
    """The reply to a mention that reads as a command. Only the slash surface runs commands."""
    return (
        f"Commands have moved. Run `{SLASH_COMMAND_PREFIX} {_SLASH_EQUIVALENT.get(command.action, 'help')}` instead.\n"
        "To start a task, mention me with a description of the work."
    )


def rule_text_too_long_message(rule_text: str) -> str:
    return (
        f"Rule not added: it is {len(rule_text)} characters and the limit is "
        f"{RepoRoutingRule.MAX_RULE_TEXT_LENGTH}. Shorten it and try again."
    )


def rules_limit_reached_message() -> str:
    return (
        f"Rule not added: this project already has {RepoRoutingRule.MAX_RULES_PER_TEAM} rules, "
        "the maximum. Remove one with `rules remove <number>`, then try again."
    )


def reject_invalid_rule_text(team_id: int, rule_text: str) -> str | None:
    """The Slack reply refusing this rule, or None when it can be stored.

    The single gate for both add paths (inline repo and picker), so no path can store a
    rule the prompt renderers would truncate or drop.
    """
    if len(rule_text) > RepoRoutingRule.MAX_RULE_TEXT_LENGTH:
        return rule_text_too_long_message(rule_text)
    if RepoRoutingRule.objects.filter(team_id=team_id).count() >= RepoRoutingRule.MAX_RULES_PER_TEAM:
        return rules_limit_reached_message()
    return None


def _handle_help(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    *,
    command_prefix: str,
) -> None:
    from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin

    # Task creation and thread follow-ups stay on the mention surface, and this listing is the only
    # help a user can reach, so it documents them under the mention prefix they actually type.
    lines = [
        "*Available commands:*\n",
        f"`{MENTION_COMMAND_PREFIX} <task description>` — Create a task for the agent to work on",
        f"`{command_prefix} rules list` — Show all routing rules",
        f'`{command_prefix} rules add "description" org/repo` — Add a routing rule',
        f'`{command_prefix} rules add "description"` — Add a routing rule (pick repo from list)',
        f"`{command_prefix} rules remove <number(s)>` — Remove routing rules by number (e.g. `remove 1` or `remove 1,2`)",
        f"`{command_prefix} project` — Show which PostHog project your mentions route to in this workspace",
        f"`{command_prefix} project <id>` — Set the PostHog project your mentions route to in this workspace",
    ]

    lines.append(f"`{command_prefix} welcome` — Show where my welcome message goes when someone adds me to a channel")

    # Workspace-wide settings are admins/owners-only, so only surface them to them.
    if is_slack_workspace_admin(slack, integration, slack_user_id):
        lines.append(
            f"`{command_prefix} project workspace <id>` — Set the workspace-wide default project (Slack admins/owners only)"
        )
        lines.append(
            f"`{command_prefix} welcome channel|private|off` — Post the welcome to the channel, show it only to the "
            "person who added me, or turn it off (Slack admins/owners only)"
        )

    lines.append(f"`{command_prefix} help` — Show this message\n")
    lines.append("You can also reply in an active thread to send follow-up messages to the agent.")

    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text="\n".join(lines),
    )


def _handle_rules_list(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    *,
    slack_user_id: str,
    command_prefix: str,
) -> None:
    from posthog.models.repo_routing_rule import RepoRoutingRule

    rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))
    if not rules:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=(
                f'No routing rules configured. Add one with `{command_prefix} rules add "description" '
                "[org/repo]`. Omit the repo to pick from a list."
            ),
        )
        return

    lines = [f"{i + 1}. {r.rule_text} → `{r.repository}`" for i, r in enumerate(rules)]
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text="*Routing rules:*\n" + "\n".join(lines),
    )


def _handle_rules_add(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    user_id: int,
    rule_text: str,
    repository: str,
    *,
    slack_user_id: str,
) -> None:
    from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names

    rejection = reject_invalid_rule_text(integration.team_id, rule_text)
    if rejection:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=rejection,
        )
        return

    all_repos = _get_full_repo_names(integration, user_id=user_id)
    if not all_repos:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text="No connected GitHub repositories found for your account.",
        )
        return

    matched_repo = _extract_explicit_repo(repository, all_repos)
    if not matched_repo:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=f"Repository `{repository}` is not connected to this project.",
        )
        return

    current_max = (
        RepoRoutingRule.objects.filter(team_id=integration.team_id)
        .order_by("-priority")
        .values_list("priority", flat=True)
        .first()
    )
    max_priority = (current_max + 1) if current_max is not None else 0
    RepoRoutingRule.objects.create(
        team_id=integration.team_id,
        rule_text=rule_text,
        repository=matched_repo,
        priority=max_priority,
        created_by_id=user_id,
    )
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=f"Added rule: {rule_text} → `{matched_repo}`",
    )


def _handle_rules_remove(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    rule_numbers: list[int] | None,
    *,
    slack_user_id: str,
    command_prefix: str,
) -> None:
    from posthog.models.repo_routing_rule import RepoRoutingRule

    if not rule_numbers or any(n < 1 for n in rule_numbers):
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=f"Please provide valid rule number(s). Use `{command_prefix} rules list` to see current rules.",
        )
        return

    rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))
    invalid = [n for n in rule_numbers if n > len(rules)]
    if invalid:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=f"Rule {'number' if len(invalid) == 1 else 'numbers'} {', '.join(f'#{n}' for n in invalid)} {'does' if len(invalid) == 1 else 'do'} not exist. There are {len(rules)} rule(s). Use `{command_prefix} rules list` to see them.",
        )
        return

    to_delete = sorted(set(rule_numbers), reverse=True)
    removed: list[str] = []
    for n in to_delete:
        rule = rules[n - 1]
        removed.append(f"#{n}: {rule.rule_text}")
        rule.delete()

    removed.reverse()
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=f"Removed rule{'s' if len(removed) > 1 else ''} {', '.join(removed)}",
    )


def _handle_project_show(
    slack: SlackIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    user_id: int,
    workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
    *,
    command_prefix: str,
) -> None:
    from posthog.models.user import User

    from products.slack_app.backend.services.integration_resolver import (
        load_integrations,
        pick_a_project_message,
        resolve_from_candidates,
    )

    user = User.objects.get(id=user_id)
    if workspace_candidates is not None:
        result = resolve_from_candidates(
            workspace_candidates,
            slack_team_id=slack_workspace_id,
            slack_user_id=slack_user_id,
            user=user,
        )
    else:
        result = load_integrations(
            slack_team_id=slack_workspace_id,
            kinds=["slack"],
            slack_user_id=slack_user_id,
            user=user,
        )

    if result.integration is not None:
        target = result.integration
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=(
                f"Your mentions in this workspace route to *{target.team.organization.name} · "
                f"{target.team.name}* (id `{target.team_id}`). "
                f"Change it with `{command_prefix} project <id>`."
            ),
        )
        return

    if not result.candidates:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=("I couldn't find your PostHog account in any organization connected to this Slack workspace."),
        )
        return

    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=pick_a_project_message(
            "You haven't set a default project for this Slack workspace yet. You can pick from:",
            result.candidates,
            set_command=command_prefix,
            home_tab_url=app_home_url(slack.integration),
        ),
    )


def _reachable_project_integration(
    slack: SlackIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    user_id: int,
    target_team_id: int,
    workspace_candidates: Sequence[WorkspaceIntegration] | None,
) -> WorkspaceIntegration | None:
    """The workspace's install for the target project, or None after telling the Slack user why not."""
    from posthog.models.user import User

    user = User.objects.get(id=user_id)
    if not user.teams.filter(id=target_team_id).exists():
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=f"You don't have access to project `{target_team_id}`.",
        )
        return None

    if workspace_candidates is not None:
        target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)
    else:
        target = get_team_workspace_integration(target_team_id, slack_workspace_id)
    if target is None:
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text=f"Project `{target_team_id}` isn't connected to this Slack workspace.",
        )
    return target


def _handle_project_set(
    slack: SlackIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    user_id: int,
    target_team_id: int,
    workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
) -> None:
    from products.slack_app.backend.models import SlackSettings

    target = _reachable_project_integration(
        slack, channel, thread_ts, slack_user_id, slack_workspace_id, user_id, target_team_id, workspace_candidates
    )
    if target is None:
        return

    SlackSettings.objects.update_or_create(
        slack_workspace_id=slack_workspace_id,
        slack_user_id=slack_user_id,
        defaults={"default_integration_id": target.id},
    )
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=(
            f"Default set to *{target.team.organization.name} · {target.team.name}* "
            f"(id `{target.team_id}`). I'll route future mentions here — mention me again to "
            "start a task."
        ),
    )


def _handle_project_set_workspace(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    user_id: int,
    target_team_id: int,
    workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
    *,
    command_prefix: str,
) -> None:
    """Set the workspace-wide default project (the ``slack_user_id IS NULL`` row),
    which applies to every Slack user in the workspace without a personal default.
    Restricted to Slack workspace admins and owners.
    """

    from products.slack_app.backend.services.slack_settings import set_workspace_default_integration
    from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin

    if not is_slack_workspace_admin(slack, integration, slack_user_id):
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text="Only Slack workspace admins or owners can set the workspace-wide default project.",
        )
        return

    target = _reachable_project_integration(
        slack, channel, thread_ts, slack_user_id, slack_workspace_id, user_id, target_team_id, workspace_candidates
    )
    if target is None:
        return

    set_workspace_default_integration(slack_workspace_id, target.id)
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=(
            f"Workspace-wide default set to *{target.team.organization.name} · {target.team.name}* "
            f"(id `{target.team_id}`). Mentions from anyone without a personal default "
            f"(`{command_prefix} project <id>`) now route here."
        ),
    )


CHANNEL_WELCOME_MODE_DESCRIPTIONS: dict[str, str] = {
    "channel": "When someone adds me to a channel, I post a welcome message that everyone in the channel sees.",
    "inviter": "When someone adds me to a channel, I show a welcome message only to that person.",
    "off": "When someone adds me to a channel, I don't send a welcome message.",
}


def _handle_welcome_show(
    slack: SlackIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    *,
    command_prefix: str,
) -> None:
    from products.slack_app.backend.services.slack_settings import resolve_channel_welcome_mode

    mode = resolve_channel_welcome_mode(slack_workspace_id)
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=(
            f"{CHANNEL_WELCOME_MODE_DESCRIPTIONS[mode.value]}\n"
            f"Slack workspace admins can change this with `{command_prefix} welcome channel`, "
            f"`{command_prefix} welcome private`, or `{command_prefix} welcome off`."
        ),
    )


def _handle_welcome_set(
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    mode: "ChannelWelcomeMode",
) -> None:
    from products.slack_app.backend.services.slack_settings import set_channel_welcome_mode
    from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin

    if not is_slack_workspace_admin(slack, integration, slack_user_id):
        post_slack_ephemeral(
            slack.client,
            channel=channel,
            user=slack_user_id,
            thread_ts=thread_ts,
            text="Only Slack workspace admins or owners can change the channel welcome message.",
        )
        return

    set_channel_welcome_mode(slack_workspace_id, mode)
    post_slack_ephemeral(
        slack.client,
        channel=channel,
        user=slack_user_id,
        thread_ts=thread_ts,
        text=f"Done. {CHANNEL_WELCOME_MODE_DESCRIPTIONS[mode.value]}",
    )


def resolve_command_target(
    *,
    slack_team_id: str,
    command: "RulesCommand",
    slack_user_id: str,
    user_id: int,
    channel: str,
    thread_ts: str,
) -> tuple[Sequence[WorkspaceIntegration], "ResolutionResult"]:
    """Load workspace candidates and decide which one to dispatch against.

    Returns ``(workspace_candidates, result)``. ``result.integration`` is
    ``None`` when no candidate can be auto-picked for the acting user — either
    because access filtering left them with nothing (``result.candidates``
    empty) or because they have access to multiple projects and haven't set a
    default (``result.candidates`` non-empty). The caller picks the appropriate
    "no access" vs "pick a project" message based on which.
    """
    from posthog.models.user import User

    from products.slack_app.backend.services.integration_resolver import (
        ResolutionResult,
        load_integrations,
        resolve_from_candidates,
    )

    initial = load_integrations(slack_team_id=slack_team_id, kinds=["slack"])
    candidates = initial.candidates
    if not candidates:
        return [], ResolutionResult(integration=None, source="needs_picker", candidates=[])

    # Workspace-level commands don't act on team data: ``help`` posts static
    # text, ``welcome_*`` commands store a workspace setting, and ``project_*``
    # and ``welcome_set`` enforce access inside the handler. They
    # run against any workspace integration as a probe.
    if command.action in (
        "project_show",
        "project_set",
        "project_set_workspace",
        "welcome_show",
        "welcome_set",
        "help",
    ):
        return candidates, ResolutionResult(integration=candidates[0], source="sole_candidate", candidates=candidates)

    # Team-scoped commands (``list``/``add``/``remove``) must go through the
    # access-filtered resolver — including the single-integration case, where
    # the shortcut would otherwise dispatch against a project the user has no
    # access to.
    result = resolve_from_candidates(
        candidates,
        slack_team_id=slack_team_id,
        slack_user_id=slack_user_id,
        user=User.objects.get(id=user_id),
        channel=channel,
        thread_ts=thread_ts,
    )
    return candidates, result


def dispatch_rules_command(
    command: "RulesCommand",
    slack: SlackIntegration,
    integration: WorkspaceIntegration,
    *,
    channel: str,
    thread_ts: str,
    slack_user_id: str,
    slack_workspace_id: str,
    user_id: int,
    workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
    command_prefix: str,
) -> None:
    """Run the right handler for a parsed ``RulesCommand``. Assumes the caller has
    already resolved a single ``integration`` to act on; project commands also
    accept ``workspace_candidates`` so ``project_set`` can skip a DB lookup.

    ``rules add`` without an inline repo is handled here as a plain "specify the
    repo" reply. The mention workflow's picker flow must catch that case
    *before* calling this dispatcher.

    ``command_prefix`` is the entry-point token surfaced in user-facing help and error strings. It
    is the slash command as the workspace invoked it, which a workspace is free to rename, so it is
    read from the payload rather than assumed to be ``/posthog``.

    Commands configure the app rather than produce work: routing rules, project
    defaults, the help listing. The answer concerns whoever ran the command, so
    every reply below goes out ephemerally.
    """
    from posthog.models.user import User

    from products.slack_app.backend.analytics import capture_slack_event

    capture_slack_event(
        integration,
        "slack app command used",
        slack_user_id=slack_user_id,
        posthog_user=User.objects.filter(id=user_id).first(),
        action=command.action,
        source="slash_command",
    )

    if command.action == "help":
        _handle_help(slack, integration, channel, thread_ts, slack_user_id, command_prefix=command_prefix)
    elif command.action == "list":
        _handle_rules_list(
            slack,
            integration,
            channel,
            thread_ts,
            slack_user_id=slack_user_id,
            command_prefix=command_prefix,
        )
    elif command.action == "add":
        if not command.repository:
            post_slack_ephemeral(
                slack.client,
                channel=channel,
                user=slack_user_id,
                thread_ts=thread_ts,
                text=f'Please specify the repo inline: `{command_prefix} rules add "description" org/repo`.',
            )
        else:
            _handle_rules_add(
                slack,
                integration,
                channel,
                thread_ts,
                user_id,
                command.rule_text or "",
                command.repository,
                slack_user_id=slack_user_id,
            )
    elif command.action == "remove":
        _handle_rules_remove(
            slack,
            integration,
            channel,
            thread_ts,
            command.rule_numbers,
            slack_user_id=slack_user_id,
            command_prefix=command_prefix,
        )
    elif command.action == "project_show":
        _handle_project_show(
            slack,
            channel,
            thread_ts,
            slack_user_id,
            slack_workspace_id,
            user_id,
            workspace_candidates=workspace_candidates,
            command_prefix=command_prefix,
        )
    elif command.action == "project_set":
        if command.project_team_id is None:
            return
        _handle_project_set(
            slack,
            channel,
            thread_ts,
            slack_user_id,
            slack_workspace_id,
            user_id,
            command.project_team_id,
            workspace_candidates=workspace_candidates,
        )
    elif command.action == "project_set_workspace":
        if command.project_team_id is None:
            return
        _handle_project_set_workspace(
            slack,
            integration,
            channel,
            thread_ts,
            slack_user_id,
            slack_workspace_id,
            user_id,
            command.project_team_id,
            workspace_candidates=workspace_candidates,
            command_prefix=command_prefix,
        )
    elif command.action == "welcome_show":
        _handle_welcome_show(
            slack,
            channel,
            thread_ts,
            slack_user_id,
            slack_workspace_id,
            command_prefix=command_prefix,
        )
    elif command.action == "welcome_set":
        if command.welcome_mode is None:
            return
        _handle_welcome_set(
            slack,
            integration,
            channel,
            thread_ts,
            slack_user_id,
            slack_workspace_id,
            command.welcome_mode,
        )