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): tell Slack users when a PR is bot-authored (#86353)

Vojta Bartošfe03ed20f250
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index e874df5a9830..71742b203efa 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -2189,9 +2189,10 @@ def _resolve_github_state(integration: Integration, slack_user_id: str) -> GitHu
deep-links to Personal integrations settings — the same target the
in-thread "Connect GitHub" prompt uses.
"""
+ from products.slack_app.backend.services.slack_messages import personal_integrations_url
from products.tasks.backend.facade import api as tasks_facade
- settings_url = f"{settings.SITE_URL.rstrip('/')}/project/{integration.team_id}/settings/user-personal-integrations"
+ settings_url = personal_integrations_url(integration.team_id)
try:
user = _resolve_home_user(integration, slack_user_id)
if user is None:
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index f42b4d9f8504..d41ae2266014 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -545,6 +545,15 @@ def app_home_url(integration: Integration) -> str | None:
return f"slack://app?team={integration.integration_id}&id={app_id}&tab=home"
+def personal_integrations_url(team_id: int) -> str:
+ """Where someone connects their own GitHub, so @PostHog opens pull requests as them.
+
+ Connecting requires an authenticated PostHog session, so every surface that asks for it
+ deep-links to this settings page instead of starting an OAuth flow from Slack.
+ """
+ return _public_url(f"/project/{team_id}/settings/user-personal-integrations")
+
+
def _task_url(team_id: int, task_id: UUID, run_id: UUID) -> str:
# `unfurl=false` asks our own link unfurler to leave this one alone: the footer already
# says what the card would, right next to the link.
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index dc401704f817..099becc065a4 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -15,6 +15,7 @@ from products.slack_app.backend.services.slack_messages import (
app_home_url,
context_block,
normalize_labeled_mentions_to_bare,
+ personal_integrations_url,
post_slack_thread_reply,
reply_footer_block,
slack_message_exists,
@@ -445,6 +446,7 @@ class SlackThreadHandler:
pr_url: str,
task_url: str | None,
reply_target_slack_user_id: str | None = None,
+ bot_authored: bool = False,
) -> None:
"""Post the single per-run "PR opened" card.
@@ -456,6 +458,12 @@ class SlackThreadHandler:
``reply_target_slack_user_id`` is the resolved actor — typically the
most recent thread participant. ``None`` produces an untagged message.
+
+ ``bot_authored`` means the run fell back to the team GitHub installation
+ because the actor had no usable personal one, so the pull request carries
+ the bot's identity rather than theirs. This card is the first place that
+ becomes visible, and it is the only surface guaranteed to reach someone
+ who only ever talks to @PostHog from Slack.
"""
mention_prefix = f"<@{reply_target_slack_user_id}> " if reply_target_slack_user_id else ""
header = f"{mention_prefix}*Pull request opened* :rocket:"
@@ -488,9 +496,21 @@ class SlackThreadHandler:
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
{"type": "actions", "elements": buttons},
]
+ if bot_authored:
+ blocks.append(context_block(self._personal_github_hint()))
self._delete_progress_and_post(header, blocks)
+ def _personal_github_hint(self) -> str:
+ """One muted line telling the reader why the pull request isn't theirs.
+
+ Written for the next run rather than this one: authorship is fixed when a run is
+ created, so connecting now changes who the following pull requests belong to, and
+ the commits this thread pushes once someone replies here.
+ """
+ url = personal_integrations_url(self._get_integration().team_id)
+ return f"Opened by the PostHog bot. <{url}|Connect your GitHub> so pull requests are opened as you."
+
def post_footer(self) -> None:
"""Post the footer alone, for an answer with no message of its own to close.
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 2a0c5b8cabef..7721b5036aa2 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -329,6 +329,38 @@ class TestPostPrOpenedReplyTarget(SimpleTestCase):
assert kwargs["text"].startswith(expected_text_start)
+class TestPostPrOpenedPersonalGithubHint(SimpleTestCase):
+ @parameterized.expand([("bot_authored", True, True), ("user_authored", False, False)])
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(team_id=7))
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_only_a_bot_authored_pr_asks_for_a_personal_github(
+ self,
+ _name: str,
+ bot_authored: bool,
+ expect_hint: bool,
+ mock_get_client,
+ _mock_get_integration,
+ _mock_delete_progress,
+ ):
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ handler = SlackThreadHandler(SlackThreadContext(integration_id=1, channel="C001", thread_ts="1.0"))
+
+ handler.post_pr_opened(
+ "https://github.com/org/repo/pull/1",
+ task_url=None,
+ bot_authored=bot_authored,
+ )
+
+ blocks = mock_client.chat_postMessage.call_args.kwargs["blocks"]
+ contexts = [b for b in blocks if b["type"] == "context"]
+ assert bool(contexts) is expect_hint
+ if expect_hint:
+ text = contexts[0]["elements"][0]["text"]
+ assert "/project/7/settings/user-personal-integrations|Connect your GitHub>" in text
+
+
class TestReplyFooterGate(SimpleTestCase):
def _handler(self, footer: RunFooter | None = None) -> SlackThreadHandler:
context = SlackThreadContext(
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
index 6f7d73f30432..cbb2c31eb169 100644
--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
@@ -10,6 +10,7 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_sta
TIMED_OUT_INACTIVITY_STATE_KEY,
TIMED_OUT_WALL_CLOCK_STATE_KEY,
)
+from products.tasks.backend.temporal.process_task.utils import is_bot_authorship_fallback
logger = get_logger(__name__)
@@ -209,11 +210,29 @@ def _post_pr_opened_notification_once(
mapping = SlackThreadTaskMapping.objects.filter(task_run=task_run).first()
reply_target_slack_user_id = mapping.mentioning_slack_user_id if mapping else None
- handler.post_pr_opened(pr_url, task_url, reply_target_slack_user_id=reply_target_slack_user_id)
+ handler.post_pr_opened(
+ pr_url,
+ task_url,
+ reply_target_slack_user_id=reply_target_slack_user_id,
+ bot_authored=_is_bot_authored_fallback(task_run),
+ )
task_run.task.mark_slack_pr_notified(pr_url)
+def _is_bot_authored_fallback(task_run: Any) -> bool:
+ """Whether this pull request went out under the bot's name for want of a personal GitHub.
+
+ Failure to answer must not cost the reader the card, so an unexpected error here means
+ no hint rather than no announcement.
+ """
+ try:
+ return is_bot_authorship_fallback(task_run.task, str(task_run.id), task_run.state)
+ except Exception:
+ logger.warning("post_slack_update_bot_authorship_check_failed", run_id=str(task_run.id))
+ return False
+
+
def _is_terminal_notified(task_run: Any, status: str, error: str | None = None) -> bool:
from products.tasks.backend.models import TaskRun
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 9cd55dc4cb25..dc10bc66eb9b 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -28,6 +28,7 @@ from products.tasks.backend.temporal.process_task.utils import (
get_task_run_actor_user,
get_task_run_credential_user,
get_user_mcp_server_configs,
+ is_bot_authorship_fallback,
is_caller_token_run,
loop_mcp_installation_allowlist,
upgrade_run_to_user_authorship,
@@ -1373,3 +1374,38 @@ class TestUpgradeRunToUserAuthorship(_AuthorshipFixture):
self.task_run.refresh_from_db()
assert self.task_run.state == state_before
+
+
+class TestIsBotAuthorshipFallback(_AuthorshipFixture):
+ def _set_state(self, state: dict) -> None:
+ self.task_run.state = state
+ self.task_run.save(update_fields=["state"])
+
+ def test_a_slack_run_without_a_personal_install_is_a_fallback(self) -> None:
+ assert is_bot_authorship_fallback(self.task, str(self.task_run.id), self.task_run.state) is True
+
+ def _user_authored(self) -> None:
+ self._set_state({"pr_authorship_mode": "user"})
+
+ def _caller_token_run(self) -> None:
+ self._set_state({"pr_authorship_mode": "bot", "github_credential_source": "caller_token"})
+
+ def _signal_report_run(self) -> None:
+ self._set_state({"pr_authorship_mode": "bot", "run_source": "signal_report"})
+
+ def _signal_report_origin(self) -> None:
+ self.task.origin_product = Task.OriginProduct.SIGNAL_REPORT
+ self.task.save(update_fields=["origin_product"])
+
+ @parameterized.expand(
+ [
+ ("user_authored",),
+ ("caller_token_run",),
+ ("signal_report_run",),
+ ("signal_report_origin",),
+ ]
+ )
+ def test_nothing_is_flagged(self, case: str) -> None:
+ getattr(self, f"_{case}")()
+
+ assert is_bot_authorship_fallback(self.task, str(self.task_run.id), self.task_run.state) is False
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index f98ff9492e32..9ce31c67c727 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1368,6 +1368,28 @@ def get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> P
return PrAuthorshipMode.USER if task.origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS else PrAuthorshipMode.BOT
+def is_bot_authorship_fallback(task: Task, run_id: str, state: dict[str, Any] | None = None) -> bool:
+ """Whether this run was meant to carry a human git identity but couldn't.
+
+ True exactly when the run's origin is user-authorable and it still resolved to bot
+ authorship, which happens when the creator had no usable personal GitHub installation
+ at creation time. Runs that are bot-authored by design (signal reports) and runs pinned
+ to a caller-supplied token are excluded: neither would be fixed by anyone connecting
+ their own GitHub.
+
+ Selects the same population `upgrade_run_to_user_authorship` promotes, so a surface can
+ tell someone their pull request went out under the bot's name and know that connecting
+ is what changes it.
+ """
+ if task.origin_product not in USER_AUTHORABLE_ORIGIN_PRODUCTS:
+ return False
+ if parse_run_state(state).run_source == RunSource.SIGNAL_REPORT:
+ return False
+ if get_pr_authorship_mode(task, state) != PrAuthorshipMode.BOT:
+ return False
+ return not is_caller_token_run(run_id, state)
+
+
def upgrade_run_to_user_authorship(
task_run: TaskRun, actor_user: User | None, state: dict[str, Any] | None
) -> dict[str, Any] | None:
diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
index a12429580c68..9a416de860e5 100644
--- a/products/tasks/backend/tests/test_post_slack_update.py
+++ b/products/tasks/backend/tests/test_post_slack_update.py
@@ -84,6 +84,24 @@ class TestPostSlackUpdate(TestCase):
mock_post_pr_opened.assert_called_once()
mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/1")
+ @patch.object(SlackThreadHandler, "post_pr_opened")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_a_slack_run_that_fell_back_to_the_bot_asks_for_a_personal_github(
+ self, mock_task_run_class, _mock_update_reaction, mock_post_pr_opened
+ ):
+ mock_run = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED,
+ output={"pr_url": "https://github.com/org/repo/pull/1"},
+ state={"pr_authorship_mode": "bot"},
+ )
+ mock_run.task.origin_product = "slack"
+ mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ assert mock_post_pr_opened.call_args.kwargs["bot_authored"] is True
+
@patch.object(SlackThreadHandler, "post_completion")
@patch.object(SlackThreadHandler, "update_reaction")
@patch("products.tasks.backend.models.TaskRun")
@@ -219,6 +237,7 @@ class TestPostSlackUpdate(TestCase):
"https://github.com/org/repo/pull/1",
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=expected_target,
+ bot_authored=False,
)
mock_update_reaction.assert_called_once_with("eyes")
mock_post_progress.assert_not_called()
@@ -358,6 +377,7 @@ class TestPostSlackUpdate(TestCase):
"https://github.com/org/repo/pull/1",
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=None,
+ bot_authored=False,
)
@patch.object(SlackThreadHandler, "delete_progress")
@@ -448,6 +468,7 @@ class TestPostSlackUpdate(TestCase):
"https://github.com/org/repo/pull/2",
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=None,
+ bot_authored=False,
)
mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/2")
@@ -546,6 +567,7 @@ class TestPostSlackUpdate(TestCase):
"https://github.com/org/repo/pull/2",
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=None,
+ bot_authored=False,
)
@patch.object(SlackThreadHandler, "post_completion")
@@ -664,4 +686,5 @@ class TestPostSlackUpdate(TestCase):
"https://github.com/org/repo/pull/2",
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=None,
+ bot_authored=False,
)