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.

fix(slack_app): use the view session footer on every run message (#129614)

Vojta Bartoš9423c31eeb90
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.md
index 3868e284b2c7..775b603262b4 100644
--- a/docs/internal/slack-local-setup-guide.md
+++ b/docs/internal/slack-local-setup-guide.md
@@ -261,7 +261,7 @@ In a channel in your dev workspace:
(The real @-handle is whatever Slack assigned — type `@p` and let autocomplete confirm.)
A successful run reacts 🌱 `:seedling:` on your message and posts a threaded "Working on task… ⏳"
-with a **View agent logs** button — that's what we saw. You may also see 🔍 `:mag:` first, but only
+with a footer whose **View session** link opens the task — that's what we saw. You may also see 🔍 `:mag:` first, but only
when the repo-discovery agent has to choose among repos (a no-repo prompt skips it, as ours did).
Follow-ups — reply in-thread with another `@mention` — are forwarded to the running sandbox and
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 65f48ffbeb8e..5c05a60d4c94 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -894,8 +894,7 @@ def _run_context_segments(footer: RunFooter) -> list[str]:
"""What the run is, as footer segments: the model, the thread cost, the plan that pays for
it, then the project it answered from.
- Shared by the reply footer and the progress message so the two cannot describe one
- run differently, and so the escaping below has a single home.
+ Kept apart from the links so the escaping below has a single home.
"""
segments: list[str] = []
if footer.model:
@@ -912,17 +911,6 @@ def _run_context_segments(footer: RunFooter) -> list[str]:
return segments
-def run_context_block(footer: RunFooter) -> dict[str, Any] | None:
- """The run's project and model as a standalone `context` block, or `None` when
- neither is known.
-
- What a message that is still working can say about its run: the links the reply
- footer carries lead to an answer that does not exist yet.
- """
- segments = _run_context_segments(footer)
- return context_block(" · ".join(segments)) if segments else None
-
-
def reply_footer_block(footer: RunFooter, configure_url: str | None = None) -> dict[str, Any] | None:
"""The footer as a `context` block, or `None` when there is nothing to say.
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 29bafbc46c86..2285f8dab7e6 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -40,7 +40,6 @@ from products.slack_app.backend.services.slack_messages import (
post_slack_thread_reply,
project_web_url,
reply_footer_block,
- run_context_block,
slack_message_exists,
turn_feedback_block,
)
@@ -229,23 +228,14 @@ class _PostedAnswer:
blocks: list[dict[str, Any]]
-def _pr_buttons(pr_url: str, task_url: str | None) -> list[dict[str, Any]]:
- buttons: list[dict[str, Any]] = [
+def _pr_buttons(pr_url: str) -> list[dict[str, Any]]:
+ return [
{
"type": "button",
"text": {"type": "plain_text", "text": "View PR", "emoji": True},
"url": pr_url,
},
]
- if task_url:
- buttons.append(
- {
- "type": "button",
- "text": {"type": "plain_text", "text": "Open in PostHog", "emoji": True},
- "url": task_url,
- }
- )
- return buttons
class SlackThreadHandler:
@@ -359,13 +349,18 @@ class SlackThreadHandler:
every reader; the page enforces access itself."""
return self.run_footer.task_url
- def _footer_block(self, include_task_url: bool = True) -> dict[str, Any] | None:
- """This handler's footer, or `None` when there is nothing to describe."""
- if not self.run_footer.has_content():
- return None
+ def _footer_block(self, fallback_task_url: str | None = None) -> dict[str, Any] | None:
+ """This handler's footer, or `None` when there is nothing to describe.
+
+ Every message about a run closes with this same line, so the session link is never a
+ button on one card and a footer link on the next. ``fallback_task_url`` is the link a
+ caller was handed for a run whose footer did not load one.
+ """
footer = self.run_footer
- if not include_task_url:
- footer = replace(footer, task_url=None)
+ if not footer.task_url and fallback_task_url:
+ footer = replace(footer, task_url=fallback_task_url)
+ if not footer.has_content():
+ return None
configure_url = app_home_url(self._get_integration())
return reply_footer_block(footer, configure_url)
@@ -697,36 +692,18 @@ class SlackThreadHandler:
def post_or_update_progress(self, stage: str, task_url: str | None = None) -> None:
"""Post a new progress message or update the existing one.
- The project and model ride along as a context line rather than their own
- message: what a task is running on and against is a property of the task, and
- the thread already has one place that describes it while it works.
+ The run footer rides along rather than a message of its own: what a task is
+ running on and against is a property of the task, and the thread already has
+ one place that describes it while it works.
"""
text = f"*{PROGRESS_MESSAGE_MARKER}* :hourglass_flowing_sand:\nStage: {stage}"
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": text}},
]
- run_context = run_context_block(self.run_footer)
- if run_context:
- blocks.append(run_context)
-
- if task_url:
- blocks.append(
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "View agent logs",
- "emoji": True,
- },
- "url": task_url,
- }
- ],
- }
- )
+ footer = self._footer_block(task_url)
+ if footer:
+ blocks.append(footer)
try:
client = self._get_client()
@@ -774,12 +751,14 @@ class SlackThreadHandler:
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
- {"type": "actions", "elements": _pr_buttons(pr_url, task_url)},
+ {"type": "actions", "elements": _pr_buttons(pr_url)},
]
if bot_authored:
blocks.append(context_block(self._personal_github_hint()))
- self.capture_reply_posted(ReplyKind.PR_OPENED, delivered=self._delete_progress_and_post(header, blocks))
+ self.capture_reply_posted(
+ ReplyKind.PR_OPENED, delivered=self._delete_progress_and_post(header, blocks, task_url=task_url)
+ )
def post_pr_closed(
self,
@@ -800,10 +779,13 @@ class SlackThreadHandler:
header = f"{mention_prefix}{outcome}"
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
- {"type": "actions", "elements": _pr_buttons(pr_url, task_url)},
+ {"type": "actions", "elements": _pr_buttons(pr_url)},
]
if not merged:
blocks.append(context_block("Reply in this thread to try a different approach."))
+ footer = self._footer_block(task_url)
+ if footer:
+ blocks.append(footer)
try:
return self._post_in_thread(text=header, blocks=blocks) is not None
except Exception as e:
@@ -942,30 +924,15 @@ class SlackThreadHandler:
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": header}},
]
- if task_url:
- blocks.append(
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "Open in PostHog",
- "emoji": True,
- },
- "url": task_url,
- }
- ],
- }
- )
- self.capture_reply_posted(ReplyKind.COMPLETION, delivered=self._delete_progress_and_post(header, blocks))
+ self.capture_reply_posted(
+ ReplyKind.COMPLETION, delivered=self._delete_progress_and_post(header, blocks, task_url=task_url)
+ )
def post_error(
self, error: str, task_url: str | None, recovery_hint: str | None = DEFAULT_FAILURE_RECOVERY_HINT
) -> None:
- """Post error message with link to PostHog for details."""
+ """Post the error message. The session link is in the footer."""
header = "*Task Failed* :x:"
error = _format_task_error(error)
truncated_error = error[:200] if len(error) > 200 else error
@@ -976,26 +943,10 @@ class SlackThreadHandler:
]
if recovery_hint:
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": recovery_hint}})
- if task_url:
- blocks.append(
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {
- "type": "plain_text",
- "text": "See details in PostHog",
- "emoji": True,
- },
- "url": task_url,
- },
- ],
- }
- )
self.capture_reply_posted(
- ReplyKind.ERROR, delivered=self._delete_progress_and_post(f"{header}\n{truncated_error}", blocks)
+ ReplyKind.ERROR,
+ delivered=self._delete_progress_and_post(f"{header}\n{truncated_error}", blocks, task_url=task_url),
)
def post_note(self, text: str) -> None:
@@ -1015,14 +966,19 @@ class SlackThreadHandler:
except Exception as e:
logger.warning("slack_delete_progress_failed", error=str(e))
- def _delete_progress_and_post(self, text: str, blocks: list[dict[str, Any]], with_footer: bool = True) -> bool:
+ def _delete_progress_and_post(
+ self,
+ text: str,
+ blocks: list[dict[str, Any]],
+ with_footer: bool = True,
+ task_url: str | None = None,
+ ) -> bool:
"""Delete any progress message and post the final one in its place. Returns whether it posted.
- Terminal cards close with the provenance footer, minus the web link their own
- button already carries.
+ Terminal cards close with the same provenance footer as an answer, session link included.
"""
if with_footer:
- footer = self._footer_block(include_task_url=False)
+ footer = self._footer_block(task_url)
if footer:
blocks = [*blocks, footer]
try:
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 753dab433ac3..6c7f8b2748b2 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -148,9 +148,12 @@ class TestSlackThreadHandler(SimpleTestCase):
]
assert order == expected_order
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(config={}, integration_id="T1"))
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
- def test_progress_message_carries_only_the_logs_button(self, mock_get_client, _mock_find_progress):
+ def test_progress_message_links_the_session_in_the_footer(
+ self, mock_get_client, _mock_find_progress, _mock_get_integration
+ ):
mock_client = MagicMock()
mock_get_client.return_value = mock_client
@@ -168,12 +171,9 @@ class TestSlackThreadHandler(SimpleTestCase):
)
mock_client.chat_postMessage.assert_called_once()
- blocks = mock_client.chat_postMessage.call_args.kwargs["blocks"]
- actions = blocks[1]["elements"]
-
- assert len(actions) == 1
- assert actions[0]["text"]["text"] == "View agent logs"
- assert actions[0]["url"] == "https://us.posthog.com/project/1/tasks/abc?runId=xyz"
+ kwargs = mock_client.chat_postMessage.call_args.kwargs
+ assert _action_blocks(kwargs) == []
+ assert _context_texts(kwargs) == ["<https://us.posthog.com/project/1/tasks/abc?runId=xyz|View session>"]
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value="1234.9999")
@patch.object(SlackThreadHandler, "_get_client")
@@ -235,8 +235,9 @@ class TestSlackThreadHandler(SimpleTestCase):
mock_client.reactions_remove.assert_called_once_with(channel="C001", timestamp=user_message_ts, name="eyes")
mock_client.reactions_add.assert_called_once_with(channel="C001", timestamp=user_message_ts, name="x")
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(config={}, integration_id="T1"))
@patch.object(SlackThreadHandler, "_get_client")
- def test_post_pr_opened_posts_buttons(self, mock_get_client):
+ def test_post_pr_opened_posts_buttons(self, mock_get_client, _mock_get_integration):
mock_client = MagicMock()
mock_get_client.return_value = mock_client
@@ -255,9 +256,8 @@ class TestSlackThreadHandler(SimpleTestCase):
assert kwargs["channel"] == "C001"
assert kwargs["thread_ts"] == "1234.5678"
assert "Pull request opened" in kwargs["text"]
- actions = kwargs["blocks"][1]["elements"]
- assert actions[0]["text"]["text"] == "View PR"
- assert actions[1]["text"]["text"] == "Open in PostHog"
+ assert [_button_texts(block) for block in _action_blocks(kwargs)] == [["View PR"]]
+ assert _context_texts(kwargs) == ["<https://posthog.com/task/1|View session>"]
@parameterized.expand(
[
@@ -265,9 +265,10 @@ class TestSlackThreadHandler(SimpleTestCase):
("merged", True, "<@U456> *Pull request merged* :tada:", False),
]
)
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(config={}, integration_id="T1"))
@patch.object(SlackThreadHandler, "_get_client")
def test_post_pr_closed_replies_in_thread_and_keeps_progress(
- self, _name, merged, expected_text, expects_retry_hint, mock_get_client
+ self, _name, merged, expected_text, expects_retry_hint, mock_get_client, _mock_get_integration
):
mock_client = MagicMock()
mock_get_client.return_value = mock_client
@@ -286,12 +287,16 @@ class TestSlackThreadHandler(SimpleTestCase):
kwargs = mock_client.chat_postMessage.call_args.kwargs
assert kwargs["thread_ts"] == "1234.5678"
assert kwargs["text"] == expected_text
- assert _button_texts(_action_blocks(kwargs)[0]) == ["View PR", "Open in PostHog"]
- assert any(block["type"] == "context" for block in kwargs["blocks"]) == expects_retry_hint
+ assert [_button_texts(block) for block in _action_blocks(kwargs)] == [["View PR"]]
+ retry_hint = ["Reply in this thread to try a different approach."] if expects_retry_hint else []
+ assert _context_texts(kwargs) == [*retry_hint, "<https://posthog.com/task/1|View session>"]
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(config={}, integration_id="T1"))
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
- def test_post_error_formats_upstream_provider_failure(self, mock_get_client, _mock_find_progress):
+ def test_post_error_formats_upstream_provider_failure(
+ self, mock_get_client, _mock_find_progress, _mock_get_integration
+ ):
mock_client = MagicMock()
mock_get_client.return_value = mock_client
@@ -312,6 +317,8 @@ class TestSlackThreadHandler(SimpleTestCase):
assert kwargs["text"] == f"*Task Failed* :x:\n{UPSTREAM_PROVIDER_FAILURE_MESSAGE}"
assert kwargs["blocks"][1]["text"]["text"] == UPSTREAM_PROVIDER_FAILURE_MESSAGE
assert "retry" in kwargs["blocks"][2]["text"]["text"]
+ assert _action_blocks(kwargs) == []
+ assert _context_texts(kwargs) == ["<https://posthog.com/task/1|View session>"]
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
@@ -336,6 +343,10 @@ def _button_texts(action_block: dict) -> list[str]:
return [element["text"]["text"] for element in action_block["elements"]]
+def _context_texts(call_kwargs: dict) -> list[str]:
+ return [block["elements"][0]["text"] for block in call_kwargs["blocks"] if block.get("type") == "context"]
+
+
class TestSlackThreadHandlerWithoutTaskUrl(SimpleTestCase):
"""A ``task_url=None`` payload signals the recipient does not have PostHog Desktop access.
@@ -365,9 +376,12 @@ class TestSlackThreadHandlerWithoutTaskUrl(SimpleTestCase):
mock_client.chat_postMessage.assert_called_once()
assert _action_blocks(mock_client.chat_postMessage.call_args.kwargs) == []
+ @patch.object(SlackThreadHandler, "_get_integration", return_value=Integration(config={}, integration_id="T1"))
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
- def test_post_or_update_progress_names_the_project_it_runs_against(self, mock_get_client, _mock_find_progress):
+ def test_post_or_update_progress_names_the_project_it_runs_against(
+ self, mock_get_client, _mock_find_progress, _mock_get_integration
+ ):
# A task that routed itself to another project says so while it works, not only
# in the footer of the answer minutes later.
mock_client = MagicMock()