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): show run provenance under Slack replies (#80519)

Vojta Bartošb166a7f4ccc4
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index 31f12bab20f9..0e3b55d46a33 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -115,6 +115,10 @@ def is_slack_app_model_classifier_enabled(integration: Integration) -> bool:
so this is the flag alone. Keyed on the Slack workspace + PostHog org, matching
the other Slack-app gates.
+ Also gates the provenance footer under a finished reply: naming a model in a mention
+ and being told which model ran are two halves of the same feature, and splitting them
+ across two flags would let a workspace pick a model and then not be shown it.
+
Independent of ``slack-app-home``: an override applies whether or not the
workspace has opted into the settings tab."""
try:
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index c331b78cddca..29fe75e46e5f 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -274,6 +274,7 @@ class TaskItem:
pr_url: str | None
thread_url: str | None
updated_at_label: str
+ desktop_url: str | None = None # omitted for viewers without PostHog Code access
error_message: str | None = None # surfaced on row 2 in place of the normal meta line
@@ -777,25 +778,32 @@ def _task_item_block(item: TaskItem) -> list[dict]:
"""One task row split across two Block Kit blocks for visual hierarchy.
The title goes in a `section` (full-size mrkdwn); the optional error
- message and the status · repo · thread · PR · updated meta go in a single
+ message and the status · repo · links · PR · updated meta go in a single
`context` block underneath. Context renders text noticeably smaller and
dimmer than section, so the supporting detail recedes while the title
stays scannable.
+ The title opens the Slack thread, because that is where the conversation the
+ row summarises actually happened and it keeps the reader in Slack. The web
+ and desktop views are the alternatives, so they sit in the meta line.
+
Failed tasks surface the error and the meta line — error context never
replaces the surrounding state. Newlines in the upstream error message
collapse to spaces so a traceback doesn't blow the row open vertically.
"""
status_label = _TASK_STATUS_LABELS.get(item.status or "", "")
- title_line = f"*<{item.posthog_url}|{item.title}>*" if item.posthog_url else f"*{item.title}*"
+ title_target = item.thread_url or item.posthog_url
+ title_line = f"*<{title_target}|{item.title}>*" if title_target else f"*{item.title}*"
meta_parts: list[str] = []
if status_label:
meta_parts.append(status_label)
if item.repository:
meta_parts.append(f"`{item.repository}`")
- if item.thread_url:
- meta_parts.append(f"<{item.thread_url}|Thread>")
+ if item.posthog_url:
+ meta_parts.append(f"<{item.posthog_url}|View on web>")
+ if item.desktop_url:
+ meta_parts.append(f"<{item.desktop_url}|View on desktop>")
if item.pr_url:
meta_parts.append(f"<{item.pr_url}|PR>")
if item.updated_at_label:
@@ -1788,6 +1796,7 @@ def _resolve_tasks_state(
from django.utils import timezone as django_timezone
from products.slack_app.backend.models import SlackThreadTaskMapping
+ from products.slack_app.backend.services.slack_messages import DESKTOP_URL_SCHEME, viewer_has_code_access
from products.tasks.backend.facade import api as tasks_facade
slack_team_id = integration.integration_id
@@ -1821,6 +1830,9 @@ def _resolve_tasks_state(
mapping_by_task = {str(m["task_id"]): m for m in mappings}
site_url = (settings.SITE_URL or "").rstrip("/")
+ # The desktop link only resolves for someone who has the app, so it is offered
+ # alongside the web one rather than instead of it.
+ show_desktop = viewer_has_code_access(integration, slack_user_id)
now = django_timezone.now()
all_items: list[TaskItem] = []
repos_seen: list[str] = []
@@ -1841,6 +1853,7 @@ def _resolve_tasks_state(
thread_url=_slack_thread_permalink(mapping.get("channel", ""), mapping.get("thread_ts", "")),
updated_at_label=_format_relative(mapping.get("updated_at"), now=now),
error_message=run.error_message if run else None,
+ desktop_url=f"{DESKTOP_URL_SCHEME}://task/{t.id}" if show_desktop else None,
)
)
if t.repository and t.repository not in seen_repo_set:
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index a9203665ca04..15f574145c81 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -12,18 +12,28 @@ Also houses ``collect_thread_messages`` (and its cached wrapper) — fetching th
full thread shape used by the agent context block lives next to the text logic
it depends on, kept out of ``api.py`` so the pure helpers stay testable in
isolation.
+
+The outbound half lives here too: the small Block Kit builders and the reply
+footer that says where to open a run and what produced it. All of it is what a
+Slack message is made of, and none of it needs a client, so it stays testable
+without one.
"""
import re
+from dataclasses import dataclass
from typing import Any
+from uuid import UUID
+from django.conf import settings
from django.core.cache import cache
import structlog
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from posthog.models.integration import Integration, SlackIntegration
+from posthog.utils import absolute_uri
+from products.slack_app.backend.services.model_catalogue import describe_run_model
from products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id, get_slack_user_info
logger = structlog.get_logger(__name__)
@@ -317,3 +327,163 @@ def invalidate_thread_messages_cache(integration_id: int, channel: str, thread_t
thread_ts=thread_ts,
exc_info=True,
)
+
+
+# The scheme a production desktop install registers. Dev builds register
+# `posthog-code-dev://` instead, which the server can't tell apart from here, so links
+# minted server-side always target the production build.
+DESKTOP_URL_SCHEME = "posthog-code"
+
+# Query param a link we compose can carry to tell our own unfurler to leave it alone
+# (honoured by `parse_posthog_resource_link`).
+UNFURL_OPT_OUT_PARAM = "unfurl"
+
+
+@dataclass(frozen=True)
+class RunFooter:
+ """What a reply can say about the run behind it.
+
+ Constant for the life of a handler, so it is supplied once at construction rather
+ than threaded through every posting method. An empty instance is the "say nothing"
+ case, which is what every caller outside the footer rollout gets.
+ """
+
+ task_url: str | None = None
+ desktop_url: str | None = None
+ model: str | None = None
+ reasoning_effort: str | None = None
+
+ def has_content(self) -> bool:
+ """Whether this would render as anything.
+
+ A caller checks it to skip the flag lookups behind a footer that can't appear.
+ Spelled out rather than given as ``__bool__`` so that ``footer or RunFooter()``
+ keeps meaning "None-coalesce" and cannot silently discard a partial instance.
+ """
+ return any((self.task_url, self.desktop_url, self.model))
+
+
+def load_run_footer(run_id: str | UUID | None) -> RunFooter:
+ """Describe a run for the footer.
+
+ Never raises: the footer is the last thing added to an answer that is already
+ written, so failing to describe the run must not cost the reader the answer.
+
+ Describes the run in full, links included. Whether the reader may open them is
+ ``viewer_has_code_access``'s question, asked where the reader is known.
+ """
+ # Deferred so the tasks product stays off this module's import path, matching
+ # `model_catalogue`.
+ from products.tasks.backend.facade.api import get_task_run # noqa: PLC0415
+ from products.tasks.backend.facade.run_config import parse_run_state # noqa: PLC0415
+
+ if not run_id:
+ return RunFooter()
+ try:
+ run = get_task_run(run_id)
+ if run is None:
+ return RunFooter()
+ state = parse_run_state(run.state)
+ return RunFooter(
+ task_url=_task_url(run.team_id, run.task_id, run.id),
+ # Task-scoped, matching the desktop app's own task route — the run id has no
+ # equivalent there.
+ desktop_url=f"{DESKTOP_URL_SCHEME}://task/{run.task_id}",
+ model=state.model,
+ reasoning_effort=state.reasoning_effort,
+ )
+ except Exception:
+ logger.exception("slack_app_run_footer_load_failed", run_id=str(run_id))
+ return RunFooter()
+
+
+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.
+
+ The answer itself is the message, so this is muted rather than competing with the
+ prose. A run with no links and no pinned model contributes no segments and gets no
+ trailing line at all.
+ """
+ segments: list[str] = []
+ if footer.task_url:
+ segments.append(f"<{footer.task_url}|View on web>")
+ if footer.desktop_url:
+ segments.append(f"<{footer.desktop_url}|View on desktop>")
+ if footer.model:
+ segments.append(describe_run_model(footer.model, footer.reasoning_effort))
+ if configure_url:
+ segments.append(f"<{configure_url}|Configure>")
+ if not segments:
+ return None
+ return context_block(" · ".join(segments))
+
+
+def context_block(text: str) -> dict[str, Any]:
+ """A line of muted supporting text.
+
+ Block Kit has no footer block; `context` is what renders small and grey under the
+ content it describes.
+ """
+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}
+
+
+def app_home_url(integration: Integration) -> str | None:
+ """Deep link to this install's Home tab, where the model picker lives.
+
+ The native `slack://` form rather than the https `app_redirect` one: the reader is
+ already in Slack, so this opens the tab in place instead of bouncing them through a
+ browser — and Slack doesn't unfurl a non-http scheme, so it costs no preview card.
+
+ Needs the app id (`A…`), which the OAuth exchange already persisted on the
+ integration, so this stays correct even where more than one Slack app is in play. A
+ row installed by some other path may not carry it, which simply means no link.
+ """
+ app_id = (integration.config or {}).get("app_id")
+ if not app_id or not integration.integration_id:
+ return None
+ return f"slack://app?team={integration.integration_id}&id={app_id}&tab=home"
+
+
+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.
+ path = f"/project/{team_id}/tasks/{task_id}?runId={run_id}&{UNFURL_OPT_OUT_PARAM}=false"
+ # Mirrors the Slack onboarding links: in local dev the tunnel is what makes a link
+ # posted into Slack actually reachable.
+ if settings.DEBUG and settings.NGROK_URL:
+ return f"{settings.NGROK_URL.rstrip('/')}{path}"
+ return absolute_uri(path)
+
+
+def workspace_org_ids(slack_team_id: str) -> set:
+ """Organizations connected to this Slack workspace — the scope a Slack identity may
+ resolve a PostHog user within."""
+ return set(
+ Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list(
+ "team__organization_id", flat=True
+ )
+ )
+
+
+def viewer_has_code_access(integration: Integration, slack_user_id: str | None) -> bool:
+ """Whether the Slack identity reading this can open a PostHog Code link.
+
+ Asked about the reader rather than the task's creator: the two can differ, and a link
+ is only useful to the person looking at it. Fail closed — an unlinked identity or a
+ flag-service error means no link rather than one that dead-ends.
+ """
+ from products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user # noqa: PLC0415
+ from products.tasks.backend.facade.access import has_tasks_access # noqa: PLC0415
+
+ if not slack_user_id:
+ return False
+ try:
+ user = find_linked_posthog_user(
+ slack_user_id=slack_user_id,
+ slack_team_id=integration.integration_id,
+ candidate_org_ids=workspace_org_ids(integration.integration_id),
+ )
+ return user is not None and has_tasks_access(user)
+ except Exception:
+ logger.exception("slack_app_viewer_code_access_check_failed", integration_id=integration.id)
+ return False
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index 04a5057f57ed..cb3c7b14af25 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from typing import Literal
-from urllib.parse import urlparse
+from urllib.parse import parse_qs, urlparse
from uuid import UUID
from django.core.exceptions import ValidationError
@@ -19,6 +19,7 @@ from posthog.rbac.user_access_control import UserAccessControl, access_level_sat
from products.conversations.backend.models.ticket import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.models.insight import Insight
+from products.slack_app.backend.services.slack_messages import UNFURL_OPT_OUT_PARAM
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.contracts import TaskSlackUnfurlDTO
@@ -75,12 +76,17 @@ def parse_posthog_resource_link(
Reference is insight short_id (str), dashboard primary key (int), or ticket ref (str — ticket
number or UUID).
+ A URL carrying `?unfurl=false` is not a resource here: links we post ourselves already
+ sit beside the detail a card would add, so they opt out rather than repeat it.
+
If the path includes `/project/:id`, that segment is ignored — lookup is always scoped to the
Slack-connected project and the resolved PostHog user, not to any project id in the URL.
Related: `removeProjectIdIfPresent` + `urlToResource` (`router-utils.ts`, `urls.ts`); legacy paths in `get_target_queryset` (`middleware.py`).
"""
parsed = urlparse(url)
+ if "false" in parse_qs(parsed.query).get(UNFURL_OPT_OUT_PARAM, []):
+ return None
parts = [p for p in parsed.path.split("/") if p]
if not parts:
return None
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 816b0e9460f8..c098d24e56f6 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -1,14 +1,23 @@
import re
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any
import structlog
from slack_sdk import WebClient
+from slack_sdk.errors import SlackApiError
from posthog.models.integration import Integration, SlackIntegration
+from products.slack_app.backend.feature_flags import is_slack_app_home_enabled, is_slack_app_model_classifier_enabled
from products.slack_app.backend.services.model_catalogue import describe_run_model
-from products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_bare
+from products.slack_app.backend.services.slack_messages import (
+ RunFooter,
+ app_home_url,
+ context_block,
+ normalize_labeled_mentions_to_bare,
+ reply_footer_block,
+ viewer_has_code_access,
+)
logger = structlog.get_logger(__name__)
@@ -28,6 +37,7 @@ DEFAULT_CANCELLED_RECOVERY_HINT = (
_TASK_FIELD_LIMIT = 256
_MARKDOWN_CHUNK_LIMIT = 12000
+_SECTION_TEXT_LIMIT = 3000
def _split_markdown_text(text: str, limit: int = _MARKDOWN_CHUNK_LIMIT) -> list[str]:
@@ -114,11 +124,22 @@ class SlackThreadContext:
class SlackThreadHandler:
"""Handler for posting updates to a Slack thread during task execution."""
- def __init__(self, context: SlackThreadContext) -> None:
+ def __init__(
+ self,
+ context: SlackThreadContext,
+ run_footer: RunFooter | None = None,
+ actor_slack_user_id: str | None = None,
+ ) -> None:
self.context = context
+ self.run_footer = run_footer or RunFooter()
+ # Who this reply is for. Links are gated on their access, not the task creator's:
+ # a thread outlives its opener, and a link only helps the person looking at it.
+ self.actor_slack_user_id = actor_slack_user_id or context.mentioning_slack_user_id
self._integration: Integration | None = None
self._client: WebClient | None = None
self._bot_user_id: str | None = None
+ self._footer_flag: bool | None = None
+ self._code_access: bool | None = None
def _get_integration(self) -> Integration:
if self._integration is None:
@@ -132,6 +153,47 @@ class SlackThreadHandler:
self._client = SlackIntegration(integration).client
return self._client
+ def footer_enabled(self) -> bool:
+ """Whether this workspace shows run provenance.
+
+ Shares the model-classifier flag: choosing a model in a mention and being told
+ which model ran are two halves of one feature. Public so a caller can skip the
+ work of describing a run nobody will be shown, and memoized because that caller
+ and the footer builder both ask.
+ """
+ if self._footer_flag is None:
+ self._footer_flag = is_slack_app_model_classifier_enabled(self._get_integration())
+ return bool(self._footer_flag)
+
+ def viewer_can_open_code_links(self) -> bool:
+ """Whether this reply's reader can open a PostHog Code link. Memoized: the cards
+ ask for their buttons and the footer asks again for its own links."""
+ if self._code_access is None:
+ self._code_access = viewer_has_code_access(self._get_integration(), self.actor_slack_user_id)
+ return bool(self._code_access)
+
+ def _footer_block(self, include_task_url: bool = True) -> dict[str, Any] | None:
+ """This handler's footer, or `None` when the workspace isn't in the rollout.
+
+ "Configure" points at the Home tab, so it only appears where that tab exists — a
+ workspace outside the Home rollout would land on an empty one. The Home flag is
+ only consulted once there is actually a link to gate.
+ """
+ # A handler with nothing to describe can't produce a footer, so it never pays for
+ # the flag lookups. Configure alone, under a reply, isn't worth a line.
+ if not self.run_footer.has_content():
+ return None
+ if not self.footer_enabled():
+ return None
+ integration = self._get_integration()
+ configure_url = app_home_url(integration)
+ if configure_url and not is_slack_app_home_enabled(integration):
+ configure_url = None
+ footer = self.run_footer if include_task_url else replace(self.run_footer, task_url=None)
+ if not self.viewer_can_open_code_links():
+ footer = replace(footer, task_url=None, desktop_url=None)
+ return reply_footer_block(footer, configure_url)
+
def _get_bot_user_id(self) -> str | None:
if self._bot_user_id is None:
try:
@@ -256,7 +318,11 @@ class SlackThreadHandler:
) -> None:
"""Final flush: mark the last plan-block step complete, stream the final
answer as markdown_text chunks (this is what STAYS in the message body),
- append a trailing @-mention for one notification, then chat.stopStream."""
+ append a trailing @-mention for one notification, then chat.stopStream.
+
+ The provenance footer closes the message. It arrives as a `blocks` chunk
+ because a `context` block is the only way to get muted text, and it goes
+ after the mention so the ping stays adjacent to the prose it answers."""
final_chunks: list[dict[str, Any]] = []
if complete_task_id and complete_task_title:
final_chunks.append(
@@ -268,6 +334,9 @@ class SlackThreadHandler:
if self.context.mentioning_slack_user_id:
# Newlines keep the mention off the tail of the last streamed prose chunk.
final_chunks.append({"type": "markdown_text", "text": f"\n\n<@{self.context.mentioning_slack_user_id}>"})
+ footer = self._footer_block()
+ if footer:
+ final_chunks.append({"type": "blocks", "blocks": [footer]})
if final_chunks:
try:
self._get_client().chat_appendStream(
@@ -285,31 +354,21 @@ class SlackThreadHandler:
except Exception as e:
logger.warning("slack_app_status_stream_stop_failed", error=str(e))
- def post_or_update_progress(
- self,
- stage: str,
- task_url: str | None = None,
- model: str | None = None,
- reasoning_effort: str | None = None,
- ) -> None:
+ 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 model rides along as a context line rather than its own message: which
model is running is a property of the task, and the thread already has one
- place that describes the task while it works.
+ place that describes the task while it works. Unlike the reply footer this
+ is not gated — a running task says what it is running on either way.
"""
text = f"*{PROGRESS_MESSAGE_MARKER}* :hourglass_flowing_sand:\nStage: {stage}"
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": text}},
]
- if model:
- blocks.append(
- {
- "type": "context",
- "elements": [{"type": "mrkdwn", "text": describe_run_model(model, reasoning_effort)}],
- }
- )
+ if self.run_footer.model:
+ blocks.append(context_block(describe_run_model(self.run_footer.model, self.run_footer.reasoning_effort)))
if task_url:
blocks.append(
@@ -401,14 +460,63 @@ class SlackThreadHandler:
self._delete_progress_and_post(header, blocks)
- def post_thread_message(self, text: str) -> None:
- """Post a plain message in the existing thread."""
+ def post_footer(self) -> None:
+ """Post the footer alone, for an answer with no message of its own to close.
+
+ Only the file-delivery path needs this: the answer rode along as a file upload's
+ initial comment, which takes no blocks, so the footer has nothing to attach to.
+ """
+ footer = self._footer_block()
+ if not footer:
+ return
+ try:
+ self._get_client().chat_postMessage(
+ channel=self.context.channel,
+ thread_ts=self.context.thread_ts,
+ text=footer["elements"][0]["text"],
+ blocks=[footer],
+ )
+ except Exception as e:
+ logger.warning("slack_app_post_footer_failed", error=str(e))
+
+ def post_thread_message(self, text: str, with_footer: bool = False) -> None:
+ """Post a plain message in the existing thread.
+
+ ``with_footer`` closes the message with the provenance footer, for the last
+ chunk of a non-streamed answer — the streamed path appends its own instead.
+ Passing it only adds blocks when there is actually a footer to show, so an
+ ordinary message stays a plain-text post.
+ """
+ # A section block caps at 3000 characters; over that, dropping the footer costs a
+ # line of provenance, while keeping it would cost the whole message.
+ footer = self._footer_block() if with_footer and len(text) <= _SECTION_TEXT_LIMIT else None
+ # No footer means no blocks at all, so an ordinary message stays the plain-text
+ # post it has always been. `expand` keeps the answer fully visible: a section
+ # collapses behind "Show more", which plain text never did.
+ blocks: list[dict[str, Any]] | None = (
+ [
+ {"type": "section", "expand": True, "text": {"type": "mrkdwn", "text": text}},
+ footer,
+ ]
+ if footer
+ else None
+ )
try:
self._get_client().chat_postMessage(
channel=self.context.channel,
thread_ts=self.context.thread_ts,
text=text,
+ blocks=blocks,
)
+ except SlackApiError as e:
+ # Slack rejects a request whose blocks are invalid outright — the `text`
+ # fallback does not rescue it — so the answer would go down with its footer.
+ # Describing a run must never cost the reader the run's answer.
+ if blocks and e.response.get("error") == "invalid_blocks":
+ logger.warning("slack_app_footer_blocks_rejected", error=str(e))
+ self.post_thread_message(text)
+ return
+ logger.warning("slack_post_thread_message_failed", error=str(e))
except Exception as e:
logger.warning("slack_post_thread_message_failed", error=str(e))
@@ -513,7 +621,7 @@ class SlackThreadHandler:
blocks: list[dict[str, Any]] = [
{"type": "section", "text": {"type": "mrkdwn", "text": text}},
]
- self._delete_progress_and_post(text, blocks)
+ self._delete_progress_and_post(text, blocks, with_footer=False)
def delete_progress(self) -> None:
"""Delete the progress message if it exists."""
@@ -525,8 +633,16 @@ 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]]) -> None:
- """Delete progress message if exists and post final message."""
+ def _delete_progress_and_post(self, text: str, blocks: list[dict[str, Any]], with_footer: bool = True) -> None:
+ """Delete any progress message and post the final one in its place.
+
+ Terminal cards close with the provenance footer, minus the web link their own
+ button already carries.
+ """
+ if with_footer:
+ footer = self._footer_block(include_task_url=False)
+ if footer:
+ blocks = [*blocks, footer]
try:
self.delete_progress()
self._get_client().chat_postMessage(
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_app_home_url.py b/products/slack_app/backend/tests/services/slack_messages/test_app_home_url.py
new file mode 100644
index 000000000000..53dcc0cb87cb
--- /dev/null
+++ b/products/slack_app/backend/tests/services/slack_messages/test_app_home_url.py
@@ -0,0 +1,25 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+
+from products.slack_app.backend.services.slack_messages import app_home_url
+
+
+class TestSlackLinks(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("resolves", {"app_id": "A1"}, "T1", "slack://app?team=T1&id=A1&tab=home"),
+ ("no_app_id", {}, "T1", None),
+ ("no_workspace", {"app_id": "A1"}, "", None),
+ ]
+ )
+ def test_app_home_url_needs_both_ids(
+ self, _name: str, config: dict, integration_id: str, expected: str | None
+ ) -> None:
+ # Installs predating the OAuth path may carry no `app_id`; interpolating it anyway
+ # would put an `app=None` link under every reply.
+ integration = Integration(config=config, integration_id=integration_id)
+
+ assert app_home_url(integration) == expected
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
new file mode 100644
index 000000000000..d1a19d98067c
--- /dev/null
+++ b/products/slack_app/backend/tests/services/slack_messages/test_run_footer.py
@@ -0,0 +1,114 @@
+from types import SimpleNamespace
+from uuid import uuid4
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+
+from products.slack_app.backend.services.slack_messages import (
+ RunFooter,
+ load_run_footer,
+ reply_footer_block,
+ viewer_has_code_access,
+)
+
+TASK_URL = "https://us.posthog.com/project/1/tasks/2?runId=3&unfurl=false"
+DESKTOP_URL = "posthog-code://task/2"
+
+
+class TestRunFooter(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "everything",
+ RunFooter(TASK_URL, DESKTOP_URL, "claude-opus-5", "high"),
+ "slack://app?team=T1&id=A1&tab=home",
+ f"<{TASK_URL}|View on web> · <{DESKTOP_URL}|View on desktop>"
+ " · *Claude Opus 5* · Reasoning: *High* · <slack://app?team=T1&id=A1&tab=home|Configure>",
+ ),
+ (
+ "links_only",
+ RunFooter(TASK_URL, DESKTOP_URL),
+ None,
+ f"<{TASK_URL}|View on web> · <{DESKTOP_URL}|View on desktop>",
+ ),
+ ("model_without_effort", RunFooter(model="claude-opus-5"), None, "*Claude Opus 5*"),
+ (
+ "configure_only",
+ RunFooter(),
+ "slack://app?team=T1&id=A1&tab=home",
+ "<slack://app?team=T1&id=A1&tab=home|Configure>",
+ ),
+ ]
+ )
+ def test_renders_present_segments_as_slack_links(
+ self, _name: str, footer: RunFooter, configure_url: str | None, expected: str
+ ) -> None:
+ # Slack's mrkdwn linkifies `<url|label>` only. CommonMark `[label](url)` renders as
+ # literal text, so the segment syntax is load-bearing, not cosmetic.
+ block = reply_footer_block(footer, configure_url)
+
+ assert block == {"type": "context", "elements": [{"type": "mrkdwn", "text": expected}]}
+
+ def test_contributes_no_block_when_there_is_nothing_to_say(self) -> None:
+ # A context block with an empty `elements` list is rejected by Slack, which would
+ # fail the whole message post rather than just dropping the footer.
+ assert reply_footer_block(RunFooter()) is None
+
+
+class TestLoadRunFooter(SimpleTestCase):
+ @patch("products.tasks.backend.facade.run_config.parse_run_state")
+ @patch("products.tasks.backend.facade.api.get_task_run")
+ def test_describes_the_run_links_included(self, mock_get_run, mock_parse) -> None:
+ # Whether the reader may open the links is asked later, where the reader is known.
+ task_id = uuid4()
+ mock_get_run.return_value = SimpleNamespace(id=uuid4(), task_id=task_id, team_id=1, state={})
+ mock_parse.return_value = SimpleNamespace(model="claude-opus-5", reasoning_effort="high")
+
+ footer = load_run_footer("run-1")
+
+ assert footer.desktop_url == f"posthog-code://task/{task_id}"
+ assert f"/tasks/{task_id}" in (footer.task_url or "")
+ assert footer.model == "claude-opus-5"
+
+ @patch("products.tasks.backend.facade.api.get_task_run", side_effect=RuntimeError("db down"))
+ def test_a_failure_to_describe_the_run_costs_the_footer_not_the_answer(self, _mock_get_run) -> None:
+ assert load_run_footer("run-1") == RunFooter()
+
+
+class TestViewerHasCodeAccess(SimpleTestCase):
+ def _integration(self) -> Integration:
+ return Integration(config={}, integration_id="T1")
+
+ @patch("products.tasks.backend.facade.access.has_tasks_access")
+ def test_no_slack_identity_means_no_access_without_consulting_the_flag(self, mock_has_access) -> None:
+ assert viewer_has_code_access(self._integration(), None) is False
+ mock_has_access.assert_not_called()
+
+ @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", return_value=set())
+ @patch("products.slack_app.backend.services.slack_user_oauth.find_linked_posthog_user", return_value=None)
+ @patch("products.tasks.backend.facade.access.has_tasks_access")
+ def test_an_unlinked_slack_identity_means_no_access(self, mock_has_access, _mock_find, _mock_orgs) -> None:
+ assert viewer_has_code_access(self._integration(), "U1") is False
+ mock_has_access.assert_not_called()
+
+ @parameterized.expand([("granted", True, True), ("denied", False, False)])
+ @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", return_value=set())
+ @patch("products.slack_app.backend.services.slack_user_oauth.find_linked_posthog_user")
+ @patch("products.tasks.backend.facade.access.has_tasks_access")
+ def test_a_linked_identity_follows_its_own_code_access(
+ self, _name: str, granted: bool, expected: bool, mock_has_access, mock_find, _mock_orgs
+ ) -> None:
+ # The reader, not the task creator: a thread outlives whoever opened it.
+ mock_find.return_value = object()
+ mock_has_access.return_value = granted
+
+ assert viewer_has_code_access(self._integration(), "U1") is expected
+
+ @patch("products.slack_app.backend.services.slack_messages.workspace_org_ids", side_effect=RuntimeError("db down"))
+ def test_a_lookup_failure_withholds_the_links_rather_than_guessing(self, _mock_orgs) -> None:
+ assert viewer_has_code_access(self._integration(), "U1") is False
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
index 6e39f66ff61f..e211b4807bb1 100644
--- a/products/slack_app/backend/tests/services/test_slack_app_home.py
+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import sys
import json
+import importlib
from dataclasses import dataclass
from types import ModuleType
from typing import Any
@@ -188,6 +189,10 @@ def _stub_picker_facade():
# the stdlib `ModuleType` rejects them outright, and ruff B010 reverts any
# `setattr` workaround back to attribute syntax.
fake: Any = ModuleType(facade_name)
+ # Seed from the real module so overriding a handful of functions doesn't hide the
+ # rest of its namespace from anything else that imports it while the swap is in
+ # place — the tasks serializers pull a dozen constants from here.
+ fake.__dict__.update(vars(importlib.import_module(facade_name)))
fake.RuntimeAdapter = _RuntimeAdapter()
fake.get_supported_reasoning_efforts = fake_get_supported
fake.get_reasoning_effort_error = fake_get_error
@@ -469,6 +474,9 @@ class TestRenderHomeView:
)
+_TASK_TITLES = ("Fix flaky retention test", "Refactor mention dispatcher")
+
+
class TestTasksCard:
def _kwargs(self, **overrides):
base = {
@@ -505,7 +513,9 @@ class TestTasksCard:
if (
block.get("type") == "section"
and isinstance(block.get("text"), dict)
- and "https://app/project/" in block["text"].get("text", "")
+ and "|Fix flaky retention test>" in block["text"].get("text", "")
+ or block.get("type") == "section"
+ and "|Refactor mention dispatcher>" in block.get("text", {}).get("text", "")
):
title = block["text"]["text"]
neighbour = blocks[index + 1] if index + 1 < len(blocks) else None
@@ -540,10 +550,11 @@ class TestTasksCard:
# Title is the full-size mrkdwn section; meta lives under it in a
# context block so Slack renders it smaller/dimmer than the title.
title, sub = items[0]
- assert title == "*<https://app/project/1/tasks/abc|Fix flaky retention test>*"
+ # The title opens the Slack thread — the conversation this row summarises.
+ assert title == "*<https://slack.com/archives/C1/p1234567890123456|Fix flaky retention test>*"
assert "🔄 in progress" in sub
assert "`posthog/posthog`" in sub
- assert "<https://slack.com/archives/C1/p1234567890123456|Thread>" in sub
+ assert "<https://app/project/1/tasks/abc|View on web>" in sub
assert "<https://github.com/posthog/posthog/pull/123|PR>" in sub
assert "_Updated 5m ago_" in sub
@@ -562,9 +573,9 @@ class TestTasksCard:
)
view = render_home_view(**self._kwargs(tasks_state=state))
title, sub = self._task_items(view, expected_count=1)[0]
- assert title == "*<https://app/project/1/tasks/abc|Fix flaky retention test>*"
+ assert title == "*<https://slack.com/archives/C1/p1234567890123456|Fix flaky retention test>*"
# The supporting context block stacks the error message above the
- # standard status/repo/thread/PR/updated meta. Error never replaces
+ # standard status/repo/links/PR/updated meta. Error never replaces
# the surrounding state.
sub_rows = sub.split("\n\n")
assert len(sub_rows) == 2
@@ -573,10 +584,36 @@ class TestTasksCard:
assert sub_rows[0] == "`boom: timed out waiting for runner stack trace omitted`"
assert "❌ failed" in sub_rows[1]
assert "`posthog/posthog`" in sub_rows[1]
- assert "<https://slack.com/archives/C1/p1234567890123456|Thread>" in sub_rows[1]
+ assert "<https://app/project/1/tasks/abc|View on web>" in sub_rows[1]
assert "<https://github.com/posthog/posthog/pull/123|PR>" in sub_rows[1]
assert "_Updated 5m ago_" in sub_rows[1]
+ @pytest.mark.parametrize(
+ "desktop_url,expected",
+ [
+ ("posthog-code://task/abc", "<posthog-code://task/abc|View on desktop>"),
+ (None, None),
+ ],
+ )
+ def test_desktop_link_appears_only_for_a_viewer_who_can_open_it(self, desktop_url, expected):
+ # A `posthog-code://` link dead-ends for anyone without the app, so it rides
+ # alongside the web link rather than replacing it.
+ state = TasksState(
+ items=(self._item(desktop_url=desktop_url),),
+ has_any_tasks=True,
+ page=0,
+ total_pages=1,
+ total_filtered=1,
+ )
+ view = render_home_view(**self._kwargs(tasks_state=state))
+ _, sub = self._task_items(view, expected_count=1)[0]
+
+ assert "<https://app/project/1/tasks/abc|View on web>" in sub
+ if expected:
+ assert expected in sub
+ else:
+ assert "View on desktop" not in sub
+
def test_task_with_no_repo_or_pr_skips_those_meta_parts(self):
state = TasksState(
items=(self._item(repository=None, pr_url=None),),
@@ -814,10 +851,12 @@ class TestTasksControlsRepublishTheList:
)
def _published_titles(self, view: dict) -> list[str]:
+ # A row's title is a bold link — to its Slack thread, so the target is not a
+ # task URL — followed by the meta line in a context block.
titles = []
for block in view["blocks"]:
text = (block.get("text") or {}).get("text", "")
- if text.startswith("*<") and "/tasks/" in text:
+ if text.startswith("*<") and text.endswith(">*"):
titles.append(text.split("|", 1)[1].rstrip(">*"))
return titles
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 17f7b72bdc60..d7717791bf48 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -3,7 +3,11 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
+from posthog.models.integration import Integration
+
+from products.slack_app.backend.services.slack_messages import RunFooter
from products.slack_app.backend.slack_thread import (
UPSTREAM_PROVIDER_FAILURE_MESSAGE,
SlackThreadContext,
@@ -322,3 +326,118 @@ class TestPostPrOpenedReplyTarget(SimpleTestCase):
kwargs = mock_client.chat_postMessage.call_args.kwargs
assert kwargs["text"].startswith(expected_text_start)
+
+
+class TestReplyFooterGate(SimpleTestCase):
+ def _handler(self) -> SlackThreadHandler:
+ context = SlackThreadContext(
+ integration_id=1,
+ channel="C001",
+ thread_ts="1234.5678",
+ mentioning_slack_user_id="U123",
+ )
+ return SlackThreadHandler(context, RunFooter(model="claude-opus-5"))
+
+ @parameterized.expand([("off", False, False), ("on", True, True)])
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_home_enabled", return_value=False)
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_streamed_reply_carries_the_footer_only_inside_the_rollout(
+ self,
+ _name: str,
+ flag_enabled: bool,
+ expected: bool,
+ mock_get_client,
+ mock_get_integration,
+ _mock_home_enabled,
+ ) -> None:
+ # Losing this gate would put the footer under every workspace's replies at once.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(config={}, integration_id="T1")
+
+ with patch(
+ "products.slack_app.backend.slack_thread.is_slack_app_model_classifier_enabled",
+ return_value=flag_enabled,
+ ):
+ self._handler().stop_status_stream(ts="1.0", final_markdown="Done.")
+
+ chunks = mock_client.chat_appendStream.call_args.kwargs["chunks"]
+ # The footer rides as a `blocks` chunk: a `context` block is the only muted text,
+ # and Slack's streamed markdown_text has no equivalent.
+ assert any(chunk.get("type") == "blocks" for chunk in chunks) is expected
+
+
+class TestFooterNeverCostsTheAnswer(SimpleTestCase):
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_home_enabled", return_value=False)
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_model_classifier_enabled", return_value=True)
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_a_rejected_footer_reposts_the_answer_as_plain_text(
+ self, mock_get_client, mock_get_integration, _mock_flag, _mock_home
+ ) -> None:
+ # Slack fails the whole request when blocks are invalid — the text fallback does
+ # not rescue it — so without this the reader loses the answer, not just its footer.
+ mock_client = MagicMock()
+ mock_client.chat_postMessage.side_effect = [
+ SlackApiError("invalid_blocks", {"error": "invalid_blocks"}),
+ MagicMock(),
+ ]
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(config={}, integration_id="T1")
+ context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
+
+ SlackThreadHandler(context, RunFooter(model="claude-opus-5")).post_thread_message(
+ "the answer", with_footer=True
+ )
+
+ assert mock_client.chat_postMessage.call_count == 2
+ retry = mock_client.chat_postMessage.call_args_list[1].kwargs
+ assert retry["text"] == "the answer"
+ assert not retry.get("blocks")
+
+
+class TestRelayedAnswerFooter(SimpleTestCase):
+ def _handler(self, footer: RunFooter) -> SlackThreadHandler:
+ context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
+ return SlackThreadHandler(context, footer)
+
+ @parameterized.expand(
+ [
+ ("final_chunk_with_model", RunFooter(model="claude-opus-5"), True, True),
+ ("final_chunk_nothing_to_say", RunFooter(), True, False),
+ ("earlier_chunk", RunFooter(model="claude-opus-5"), False, False),
+ ]
+ )
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_home_enabled", return_value=False)
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_model_classifier_enabled", return_value=True)
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_footer_rides_the_last_chunk_only(
+ self,
+ _name: str,
+ footer: RunFooter,
+ with_footer: bool,
+ expected: bool,
+ mock_get_client,
+ mock_get_integration,
+ _mock_flag,
+ _mock_home,
+ ) -> None:
+ # A non-streamed answer is split only to fit Slack's length cap, so a footer on
+ # any chunk but the last would appear mid-answer.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(config={}, integration_id="T1")
+
+ self._handler(footer).post_thread_message("the answer", with_footer=with_footer)
+
+ kwargs = mock_client.chat_postMessage.call_args.kwargs
+ assert kwargs["text"] == "the answer"
+ # Without a footer the message carries no blocks, staying the plain-text post it
+ # has always been.
+ assert bool(kwargs.get("blocks")) is expected
+ if expected:
+ assert kwargs["blocks"][-1]["type"] == "context"
+ # A section collapses behind "Show more" unless it is told to expand.
+ assert kwargs["blocks"][0]["expand"] is True
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 e7760f0a3871..9f784ea3e9a9 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
@@ -1,15 +1,11 @@
from dataclasses import dataclass
from typing import Any
-from django.conf import settings
-
from temporalio import activity
-from posthog.models.user import User
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
-from products.tasks.backend.access import has_tasks_access
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
TIMED_OUT_INACTIVITY_STATE_KEY,
TIMED_OUT_WALL_CLOCK_STATE_KEY,
@@ -85,32 +81,12 @@ class PostSlackUpdateInput:
sandbox_cleaned: bool = False
-def _viewer_has_posthog_code_access(viewer: User | None) -> bool:
- """Fail closed: missing creator or any flag-service error suppresses the link.
-
- The PostHog Desktop app is rolled out via cohort + invite redemption; surfacing
- deep links to users who can't open them sends them into an install flow we
- don't want to scale right now. Errors from the flag service therefore default
- to "no access" rather than "show the link anyway".
- """
- if viewer is None:
- return False
- try:
- return has_tasks_access(viewer)
- except Exception:
- logger.exception("post_slack_update_access_check_failed", user_id=getattr(viewer, "id", None))
- return False
-
-
@activity.defn
@close_db_connections
def post_slack_update(input: PostSlackUpdateInput) -> None:
"""Post Slack update based on current task run state. Idempotent."""
+ from products.slack_app.backend.services.slack_messages import load_run_footer
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
-
- # Deferred with the model import below: `facade.run_config` re-exports from
- # `process_task.utils`, whose import graph reaches back to this module.
- from products.tasks.backend.facade.run_config import parse_run_state
from products.tasks.backend.models import TaskRun
try:
@@ -121,13 +97,10 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
- handler = SlackThreadHandler(context)
- creator_has_access = _viewer_has_posthog_code_access(task_run.task.created_by)
- task_url: str | None = (
- f"{settings.SITE_URL}/project/{task_run.task.team_id}/tasks/{task_run.task_id}?runId={task_run.id}"
- if creator_has_access
- else None
- )
+ footer = load_run_footer(task_run.id)
+ handler = SlackThreadHandler(context, footer)
+ # The buttons lead where the footer's links do, so they answer to the same reader.
+ task_url = footer.task_url if handler.viewer_can_open_code_links() else None
pr_url = (task_run.output or {}).get("pr_url")
if input.sandbox_cleaned:
@@ -161,13 +134,7 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:
handler.update_reaction("eyes")
return
stage = _get_stage_from_status(task_run.status, task_run.stage)
- run_state = parse_run_state(task_run.state)
- handler.post_or_update_progress(
- stage,
- task_url,
- model=run_state.model,
- reasoning_effort=run_state.reasoning_effort,
- )
+ handler.post_or_update_progress(stage, task_url)
except Exception:
logger.exception("post_slack_update_failed", run_id=input.run_id)
diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
index 63118b5389bc..de32e8a90968 100644
--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
@@ -54,6 +54,9 @@ class StopSlackAgentDesignStreamInput:
complete_task_details: Optional[str] = None
# Streamed as markdown_text chunks below the plan block right before stopStream.
final_markdown: Optional[str] = None
+ # Sources the provenance footer. Optional so a relay started before this field
+ # existed replays cleanly — it just closes without one.
+ run_id: Optional[str] = None
@activity.defn
@@ -99,11 +102,17 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->
@close_db_connections
def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> None:
"""Mark the last step complete, stream the final answer, append @-mention, close."""
+ from products.slack_app.backend.services.slack_messages import load_run_footer
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
- SlackThreadHandler(context).stop_status_stream(
+ handler = SlackThreadHandler(context)
+ # Describing the run costs a query and a flag call, so only do it for a
+ # workspace that will actually be shown the result.
+ if handler.footer_enabled():
+ handler.run_footer = load_run_footer(input.run_id)
+ handler.stop_status_stream(
ts=input.ts,
complete_task_id=input.complete_task_id,
complete_task_title=input.complete_task_title,
diff --git a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
index a29e54257d13..49de4b1e11b3 100644
--- a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
@@ -52,6 +52,9 @@ class PendingStep:
@dataclass
class SlackAgentDesignRelayInput:
slack_thread_context: dict[str, Any]
+ # Trailing and defaulted so a relay already in flight decodes it as absent and
+ # simply closes without a footer, rather than failing replay.
+ run_id: Optional[str] = None
@workflow.defn(name="slack-agent-design-relay")
@@ -288,6 +291,7 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):
complete_task_title=self._current_task_title,
complete_task_details=self._current_task_details,
final_markdown=final_for_stop,
+ run_id=input.run_id,
),
start_to_close_timeout=timedelta(seconds=10),
retry_policy=RetryPolicy(maximum_attempts=3),
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 7f149641e756..8a04ab5cb3dd 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -2205,7 +2205,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._current_slack_relay_workflow_id = relay_workflow_id
await workflow.start_child_workflow(
SlackAgentDesignRelayWorkflow.run,
- SlackAgentDesignRelayInput(slack_thread_context=slack_ctx),
+ SlackAgentDesignRelayInput(slack_thread_context=slack_ctx, run_id=self.context.run_id),
id=relay_workflow_id,
task_queue=workflow.info().task_queue,
# Cancel on parent close so the relay's finally block runs
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index a92918efa9bc..fa9494ab9e4e 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -360,7 +360,7 @@ class RelaySlackMessageInput:
@close_db_connections
def relay_slack_message(input: RelaySlackMessageInput) -> None:
from products.slack_app.backend.models import SlackThreadTaskMapping
- from products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_bare
+ from products.slack_app.backend.services.slack_messages import load_run_footer, normalize_labeled_mentions_to_bare
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.process_task.utils import get_message_actor
@@ -416,10 +416,9 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
user_message_ts=input.user_message_ts,
mentioning_slack_user_id=mapping.mentioning_slack_user_id,
)
- handler = SlackThreadHandler(context)
-
# Mention resolution, most precise first: the echoed message's recorded
- # sender, then the live/mapping actors for pre-rollout runs.
+ # sender, then the live/mapping actors for pre-rollout runs. Resolved before the
+ # handler so the footer's links are gated on whoever this reply is actually for.
mention_from_message = get_message_actor(input.run_id, input.message_id) if input.message_id else None
target = (
mention_from_message
@@ -427,6 +426,10 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
or mapping.latest_actor_slack_user_id
or mapping.mentioning_slack_user_id
)
+
+ handler = SlackThreadHandler(context, actor_slack_user_id=target)
+ if handler.footer_enabled():
+ handler.run_footer = load_run_footer(task_run.id)
mention_prefix = f"<@{target}> " if target else ""
if input.delete_progress:
handler.delete_progress()
@@ -443,7 +446,13 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
for index, chunk in enumerate(chunks_to_post):
prefix = mention_prefix if delivered_file_count == 0 and index == 0 else ""
- handler.post_thread_message(f"{prefix}{chunk}")
+ # This relay carries one agent answer, split only to fit Slack's length cap, so
+ # the last chunk is where the turn ends and the footer belongs.
+ handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks_to_post) - 1)
+ if delivered_file_count and not chunks_to_post:
+ # A short answer went out whole as the file's initial comment, which takes no
+ # blocks, so the footer follows it rather than being dropped.
+ handler.post_footer()
if input.reaction_emoji is not None:
handler.update_reaction(input.reaction_emoji)
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
index 13a16cdccd8a..02fc4f531c12 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -724,3 +724,33 @@ class TestRelaySlackMessageChunking(TestCase):
self.task_run.refresh_from_db()
assert "relay-chunked" in self.task_run.state.get("slack_sent_relay_ids", [])
+
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_footer")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.deliver_pending_slack_file_artifacts")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.has_pending_slack_file_artifacts")
+ def test_answer_consumed_by_a_file_upload_still_gets_its_footer(
+ self,
+ mock_has_files,
+ mock_deliver,
+ mock_delete_progress,
+ mock_post,
+ mock_post_footer,
+ ):
+ # A short answer rides out whole as the file's initial comment, leaving no message
+ # to close — without this the reply would carry no provenance at all.
+ mock_has_files.return_value = True
+ mock_deliver.return_value = 1
+
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-file-only",
+ text="Here you go.",
+ user_message_ts="1234.5",
+ )
+ )
+
+ mock_post.assert_not_called()
+ mock_post_footer.assert_called_once()
diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
index c57bdfdcdbfe..e5b509645718 100644
--- a/products/tasks/backend/tests/test_post_slack_update.py
+++ b/products/tasks/backend/tests/test_post_slack_update.py
@@ -6,6 +6,7 @@ from django.test import TestCase, override_settings
from parameterized import parameterized
+from products.slack_app.backend.services.slack_messages import RunFooter
from products.slack_app.backend.slack_thread import SlackThreadHandler
_post_slack_update_module = importlib.import_module(
@@ -24,12 +25,18 @@ class TestPostSlackUpdate(TestCase):
"thread_ts": "1111.0000",
"user_message_ts": "2222.0000",
}
- # Default the access gate to allow so existing call/URL assertions remain meaningful;
- # tests that exercise the deny / error paths re-patch it locally.
- self._access_patcher = patch(
- "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
- return_value=True,
- )
+ # The footer, and the access gate behind its links, is built in slack_app and
+ # tested there. Here it only decides whether the cards carry a url, so default to
+ # "linkable" and let the deny-path test re-patch it.
+ self._footer_patcher = patch(
+ "products.slack_app.backend.services.slack_messages.load_run_footer",
+ return_value=RunFooter(task_url="http://localhost:8000/project/1/tasks/10?runId=run-1"),
+ )
+ self._footer_patcher.start()
+ self.addCleanup(self._footer_patcher.stop)
+ # These tests mock the handler's __init__, so the reader gate is patched on the
+ # class rather than resolved from a Slack identity.
+ self._access_patcher = patch.object(SlackThreadHandler, "viewer_can_open_code_links", return_value=True)
self._access_patcher.start()
self.addCleanup(self._access_patcher.stop)
# The PR-opened notification path resolves the reply target from a live
@@ -595,10 +602,7 @@ class TestPostSlackUpdate(TestCase):
# (including the progress handler) receives ``task_url=None`` so the
# web buttons are skipped.
self._access_patcher.stop()
- deny_patcher = patch(
- "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
- return_value=False,
- )
+ deny_patcher = patch.object(SlackThreadHandler, "viewer_can_open_code_links", return_value=False)
deny_patcher.start()
self.addCleanup(deny_patcher.stop)
@@ -662,75 +666,6 @@ class TestPostSlackUpdate(TestCase):
# task_url is the second positional argument on post_pr_opened.
assert mock_post_pr_opened.call_args.args[1] is None
- @patch.object(SlackThreadHandler, "post_pr_opened")
- @patch.object(SlackThreadHandler, "update_reaction")
- @patch.object(SlackThreadHandler, "__init__", return_value=None)
- @patch("products.tasks.backend.models.TaskRun")
- def test_missing_created_by_omits_task_url(
- self,
- mock_task_run_class,
- _mock_handler_init,
- _mock_update_reaction,
- mock_post_pr_opened,
- ):
- # ``has_tasks_access`` is never reached when the run has no creator —
- # a None viewer short-circuits to "no access" without consulting the
- # flag service.
- self._access_patcher.stop()
-
- sentinel = MagicMock(name="should_not_be_called")
- sentinel_patcher = patch(
- "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
- sentinel,
- )
- sentinel_patcher.start()
- self.addCleanup(sentinel_patcher.stop)
-
- run = self._make_mock_run(
- mock_task_run_class.Status.COMPLETED, output={"pr_url": "https://github.com/org/repo/pull/1"}
- )
- run.task.created_by = None
- mock_task_run_class.objects.select_related.return_value.get.return_value = run
-
- post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
-
- sentinel.assert_not_called()
- mock_post_pr_opened.assert_called_once_with(
- "https://github.com/org/repo/pull/1", None, reply_target_slack_user_id=None
- )
-
- @patch.object(SlackThreadHandler, "post_pr_opened")
- @patch.object(SlackThreadHandler, "update_reaction")
- @patch.object(SlackThreadHandler, "__init__", return_value=None)
- @patch("products.tasks.backend.models.TaskRun")
- def test_access_check_exception_fails_closed(
- self,
- mock_task_run_class,
- _mock_handler_init,
- _mock_update_reaction,
- mock_post_pr_opened,
- ):
- # A flag-service blip must not surface the link to a user we can't
- # confirm has access — and must not break the surrounding update.
- self._access_patcher.stop()
- boom_patcher = patch(
- "products.tasks.backend.temporal.process_task.activities.post_slack_update.has_tasks_access",
- side_effect=RuntimeError("flag service down"),
- )
- boom_patcher.start()
- self.addCleanup(boom_patcher.stop)
-
- run = self._make_mock_run(
- mock_task_run_class.Status.COMPLETED, output={"pr_url": "https://github.com/org/repo/pull/1"}
- )
- mock_task_run_class.objects.select_related.return_value.get.return_value = run
-
- post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
-
- mock_post_pr_opened.assert_called_once_with(
- "https://github.com/org/repo/pull/1", None, reply_target_slack_user_id=None
- )
-
@patch.object(SlackThreadHandler, "post_pr_opened")
@patch.object(SlackThreadHandler, "update_reaction")
@patch.object(SlackThreadHandler, "__init__", return_value=None)