: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack): forward safe message attachments to agent (#66834)
Chris Volzerbf2f2af4936b
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 21d9b1895b01..b77a1f8893de 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -1,4 +1,5 @@import re+import uuidimport textwrapfrom dataclasses import dataclassfrom typing import Any, Literal@@ -8,6 +9,12 @@ from django.db import modelsimport structlogfrom temporalio import activity+from posthog.temporal.ai.slack_app.attachments import (+ PreparedSlackAttachments,+ build_slack_attachment_prompt_text,+ get_slack_bot_token,+ prepare_slack_file_artifacts,+)from posthog.temporal.ai.slack_app.helpers import block_if_team_over_quota, safe_reactfrom posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputsfrom posthog.temporal.common.utils import close_db_connections@@ -186,6 +193,107 @@ def _with_slack_delivery_constraints(prompt: str, *, canvas_file_artifacts_enablreturn f"{constraints}\n{prompt}"+def _uploaded_attachment_ids(uploaded_artifacts: list[dict[str, Any]]) -> list[str]:+ return [str(artifact["id"]) for artifact in uploaded_artifacts if artifact.get("id")]+++def _apply_followup_prefix(user_text: str, prefix: str | None) -> str:+ """Prefix a cross-user follow-up with the actor's name; substitute a placeholder for file-only messages."""+ if prefix:+ return prefix + user_text if user_text else f"{prefix}attached Slack file(s)."+ return user_text or "Attached Slack file(s)."+++def _pending_attachment_state_updates(+ message: str | None,+ *,+ uploaded_attachments: list[dict[str, Any]],+ attachment_skips: list[str],+) -> dict[str, Any]:+ """Build the run-state updates that stage attachments for delivery once the sandbox is up."""+ updates: dict[str, Any] = {}+ pending_user_message = build_slack_attachment_prompt_text(+ message,+ uploaded_artifacts=uploaded_attachments,+ skipped_messages=attachment_skips,+ )+ if pending_user_message:+ updates["pending_user_message"] = pending_user_message+ pending_user_artifact_ids = _uploaded_attachment_ids(uploaded_attachments)+ if pending_user_artifact_ids:+ updates["pending_user_artifact_ids"] = pending_user_artifact_ids+ return updates+++def _post_attachment_rejection_notice(+ slack: Any,+ channel: str,+ thread_ts: str,+ skipped_messages: list[str],+) -> None:+ """Tell the thread why nothing was forwarded when every attachment was rejected.++ This is the only delivery mechanism for the skip reasons in that case — without it+ the agent would be woken (or a whole sandbox provisioned) just to relay a rejection.+ """+ skipped = "\n".join(f"- {msg}" for msg in skipped_messages)+ text = "I couldn't forward that to the agent — no attachment was accepted:\n" + skipped+ try:+ slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text)+ except Exception:+ logger.warning("slack_attachment_rejection_notice_failed", channel=channel, thread_ts=thread_ts)+++def _slack_followup_message_id(channel: str, message_ts: str | None, thread_ts: str) -> str:+ """Deterministic agent-server idempotency key so activity retries can't double-deliver."""+ return str(uuid.uuid5(uuid.NAMESPACE_URL, f"posthog:slack_followup:{channel}:{message_ts or thread_ts}"))+++def _upload_prepared_slack_attachments(+ tasks_facade: Any,+ *,+ task_run_id: Any,+ task_id: Any,+ team_id: int,+ prepared: PreparedSlackAttachments,+ channel: str,+ thread_ts: str,+) -> tuple[list[dict[str, Any]], list[str]]:+ skipped_messages = list(prepared.skipped_messages)+ if not prepared.artifacts:+ return [], skipped_messages++ try:+ result = tasks_facade.upload_task_run_artifacts(+ task_run_id,+ task_id,+ team_id,+ artifacts=prepared.artifacts,+ )+ except Exception:+ logger.exception(+ "slack_attachment_upload_failed",+ task_run_id=str(task_run_id),+ channel=channel,+ thread_ts=thread_ts,+ )+ skipped_messages.append("Slack attachment(s) could not be uploaded to the agent workspace.")+ return [], skipped_messages++ if result is None:+ logger.warning(+ "slack_attachment_upload_run_not_found",+ task_run_id=str(task_run_id),+ channel=channel,+ thread_ts=thread_ts,+ )+ skipped_messages.append("Slack attachment(s) could not be uploaded to the agent workspace.")+ return [], skipped_messages++ uploaded, _manifest = result+ return uploaded, skipped_messages++def _build_posthog_code_task_description(initiator_text: str,thread_messages: list[dict[str, str]],@@ -448,6 +556,26 @@ def create_posthog_code_task_for_repo_activity()slack = SlackIntegration(integration)+ # Idempotency guard: this activity runs under a retry policy but its body is+ # not idempotent — a retry after the mapping write would create a duplicate+ # task + run, re-upload attachments to it, and repoint the mapping, orphaning+ # the first task. A mapping for this thread means a prior attempt (or a+ # concurrent duplicate mention) already created the task; a run left QUEUED+ # by a crash before the workflow start is recovered by the orphaned-run+ # janitor sweep.+ if SlackThreadTaskMapping.objects.filter(+ integration_id=inputs.integration_id,+ channel=channel,+ thread_ts=thread_ts,+ ).exists():+ logger.info(+ "posthog_code_task_creation_skipped_existing_mapping",+ channel=channel,+ thread_ts=thread_ts,+ integration_id=inputs.integration_id,+ )+ return+# Refuse before the :eyes: reaction or the permalink fetch: a denied# mention should not first ack-react and then refuse a second later.if block_if_team_over_quota(@@ -587,6 +715,17 @@ def create_posthog_code_task_for_repo_activity(# where the agent finishes and tries to relay before the mapping existstask_run = created.latest_runif task_run:+ prepared_attachments = prepare_slack_file_artifacts(event.get("files"), get_slack_bot_token(slack, integration))+ uploaded_attachments, attachment_skips = _upload_prepared_slack_attachments(+ tasks_facade,+ task_run_id=task_run.id,+ task_id=created.task_id,+ team_id=created.team_id,+ prepared=prepared_attachments,+ channel=channel,+ thread_ts=thread_ts,+ )+# `last_forwarded_ts` seeds the follow-up diff watermark — anything# strictly newer than this when a follow-up arrives is rendered into a# `<slack_thread_context_update>` block so the agent catches up on@@ -623,14 +762,23 @@ def create_posthog_code_task_for_repo_activity(if repo_research_task_id and repo_research_run_id:state_updates["repo_research_task_id"] = repo_research_task_idstate_updates["repo_research_run_id"] = repo_research_run_id+ if prepared_attachments.has_files:+ state_updates.update(+ _pending_attachment_state_updates(+ description,+ uploaded_attachments=uploaded_attachments,+ attachment_skips=attachment_skips,+ )+ )try:tasks_facade.update_task_run_state(task_run.id, updates=state_updates)except Exception:logger.exception(- "posthog_code_persist_mention_workflow_id_failed",+ "posthog_code_persist_initial_run_state_failed",task_run_id=str(task_run.id),channel=channel,thread_ts=thread_ts,+ state_keys=sorted(state_updates),)# 3. Now start the workflow@@ -782,10 +930,17 @@ def forward_posthog_code_followup_activity()user_text = decode_slack_event_text(slack, integration, event_text)- if not user_text:+ prepared_attachments = prepare_slack_file_artifacts(+ inputs.event.get("files"), get_slack_bot_token(slack, integration)+ )+ if not user_text and not prepared_attachments.has_files:+ return True+ if not user_text and not prepared_attachments.artifacts:+ # Every attachment was rejected and there is no text: waking the agent+ # would deliver a content-free prompt. Surface the skip reasons directly.+ _post_attachment_rejection_notice(slack, channel, thread_ts, prepared_attachments.skipped_messages)return True- if followup_user_text_prefix:- user_text = followup_user_text_prefix + user_text+ user_text = _apply_followup_prefix(user_text, followup_user_text_prefix)# Catch the agent up on any messages posted in the thread between the last time# we forwarded and now. Without this the agent sees only the new follow-up text,@@ -832,9 +987,38 @@ def forward_posthog_code_followup_activity(task_run.id, user_id=actor_user.id, distinct_id=distinct_id)- result = tasks_facade.send_user_message(task_run.id, user_text, auth_token=auth_token, timeout=90)+ uploaded_attachments, attachment_skips = _upload_prepared_slack_attachments(+ tasks_facade,+ task_run_id=task_run.id,+ task_id=mapping.task_id,+ team_id=task_run.team_id,+ prepared=prepared_attachments,+ channel=channel,+ thread_ts=thread_ts,+ )+ user_text = (+ build_slack_attachment_prompt_text(+ user_text,+ uploaded_artifacts=uploaded_attachments,+ skipped_messages=attachment_skips,+ )+ or user_text+ )++ send_kwargs: dict[str, Any] = {+ "auth_token": auth_token,+ "timeout": 90,+ # Deterministic across activity retries: a retry after a partial failure+ # (or the in-line resend below) redelivers with the same id, and the+ # agent-server drops the duplicate instead of applying the message twice.+ "message_id": _slack_followup_message_id(channel, user_message_ts, thread_ts),+ }+ if uploaded_attachments:+ send_kwargs["artifacts"] = uploaded_attachments++ result = tasks_facade.send_user_message(task_run.id, user_text, **send_kwargs)if not result.success and result.retryable and result.status_code != 504:- result = tasks_facade.send_user_message(task_run.id, user_text, auth_token=auth_token, timeout=90)+ result = tasks_facade.send_user_message(task_run.id, user_text, **send_kwargs)if not result.success:logger.warning(@@ -989,10 +1173,17 @@ def _resume_task_with_new_run(integration = slack.integrationuser_text = decode_slack_event_text(slack, integration, event_text)- if not user_text:+ prepared_attachments = prepare_slack_file_artifacts(+ inputs.event.get("files"), get_slack_bot_token(slack, integration)+ )+ if not user_text and not prepared_attachments.has_files:return True- if user_text_prefix:- user_text = user_text_prefix + user_text+ if not user_text and not prepared_attachments.artifacts:+ # Every attachment was rejected and there is no text: provisioning a whole+ # new sandbox run just to relay the rejection is wasteful — post it directly.+ _post_attachment_rejection_notice(slack, channel, thread_ts, prepared_attachments.skipped_messages)+ return True+ user_text = _apply_followup_prefix(user_text, user_text_prefix)created_by = mapping.task.created_byrun_actor = actor_user or created_by@@ -1067,6 +1258,33 @@ def _resume_task_with_new_run()return True+ uploaded_attachments, attachment_skips = _upload_prepared_slack_attachments(+ tasks_facade,+ task_run_id=new_run.id,+ task_id=mapping.task_id,+ team_id=new_run.team_id,+ prepared=prepared_attachments,+ channel=channel,+ thread_ts=thread_ts,+ )+ if prepared_attachments.has_files:+ pending_updates = _pending_attachment_state_updates(+ initial_prompt_override,+ uploaded_attachments=uploaded_attachments,+ attachment_skips=attachment_skips,+ )+ if pending_updates:+ try:+ tasks_facade.update_task_run_state(new_run.id, updates=pending_updates)+ except Exception:+ logger.exception(+ "posthog_code_resume_attachment_state_update_failed",+ channel=channel,+ thread_ts=thread_ts,+ task_id=str(mapping.task_id),+ run_id=str(new_run.id),+ )+slack_thread_context = SlackThreadContext(integration_id=inputs.integration_id,channel=channel,diff --git a/posthog/temporal/ai/slack_app/attachments.py b/posthog/temporal/ai/slack_app/attachments.pynew file mode 100644index 000000000000..099302015132--- /dev/null+++ b/posthog/temporal/ai/slack_app/attachments.py@@ -0,0 +1,341 @@+import os+import uuid+from dataclasses import dataclass+from typing import Any+from urllib.parse import urljoin, urlparse++import requests+import structlog++logger = structlog.get_logger(__name__)++MAX_SLACK_ATTACHMENTS_PER_MESSAGE = 5+MAX_SLACK_ATTACHMENT_BYTES = 10 * 1024 * 1024+SLACK_DOWNLOAD_TIMEOUT_SECONDS = 15+MAX_SLACK_DOWNLOAD_REDIRECTS = 5++_ALLOWED_SLACK_FILE_HOST_SUFFIXES = ("slack.com", "slack-edge.com", "slack-files.com")++# Allowlist, not denylist: a wrongly blocked file produces a visible "skipped+# because…" note the user can act on, while a wrongly allowed file is silent.+# The realistic Slack-attachment set is small — images, PDFs, and plain-text+# data formats. Anything executable, scripted, or macro-capable stays out.+_ALLOWED_EXTENSIONS = frozenset(+ {+ ".bmp",+ ".csv",+ ".gif",+ ".jpeg",+ ".jpg",+ ".json",+ ".log",+ ".markdown",+ ".md",+ ".pdf",+ ".png",+ ".tsv",+ ".txt",+ ".webp",+ ".yaml",+ ".yml",+ }+)+_ALLOWED_MIME_TYPES = frozenset(+ {+ "application/json",+ "application/pdf",+ "application/x-yaml",+ "application/yaml",+ "image/bmp",+ "image/gif",+ "image/jpeg",+ "image/png",+ "image/webp",+ "text/csv",+ "text/markdown",+ "text/plain",+ "text/tab-separated-values",+ "text/yaml",+ }+)+_ALLOWED_SLACK_FILETYPES = frozenset(+ {+ "bmp",+ "csv",+ "gif",+ "jpeg",+ "jpg",+ "json",+ "markdown",+ "pdf",+ "png",+ "text",+ "tsv",+ "webp",+ "yaml",+ }+)++_ATTACHMENT_TYPE_SKIP_REASON = (+ "only image, PDF, and plain-text attachments (logs, markdown, CSV, JSON, YAML) are supported"+)++_EXECUTABLE_MAGIC_PREFIXES = (+ b"MZ",+ b"\x7fELF",+ b"\xcf\xfa\xed\xfe",+ b"\xce\xfa\xed\xfe",+ b"\xfe\xed\xfa\xcf",+ b"\xfe\xed\xfa\xce",+ b"\xca\xfe\xba\xbe",+)+++@dataclass(frozen=True)+class PreparedSlackAttachments:+ artifacts: list[dict[str, Any]]+ skipped_messages: list[str]+ requested_count: int++ @property+ def has_files(self) -> bool:+ return self.requested_count > 0+++def get_slack_bot_token(slack: Any, integration: Any) -> str | None:+ token = getattr(integration, "access_token", None)+ if isinstance(token, str) and token:+ return token++ client = getattr(slack, "client", None)+ token = getattr(client, "token", None)+ return token if isinstance(token, str) and token else None+++def _normalize_content_type(value: Any) -> str:+ if not isinstance(value, str):+ return ""+ return value.split(";")[0].strip().lower()+++def _safe_filename(file: dict[str, Any]) -> str:+ raw_name = file.get("name") or file.get("title") or file.get("id") or "slack-attachment"+ name = os.path.basename(str(raw_name)).strip()+ return name or "slack-attachment"+++def _is_allowed_slack_file_url(url: str) -> bool:+ parsed = urlparse(url)+ hostname = parsed.hostname or ""+ if parsed.scheme != "https":+ return False+ return any(hostname == suffix or hostname.endswith(f".{suffix}") for suffix in _ALLOWED_SLACK_FILE_HOST_SUFFIXES)+++def _is_allowed_metadata(filename: str, content_type: str, slack_filetype: Any) -> bool:+ """Every signal present must be allowed, and at least one positive signal must exist.++ Fails closed on contradiction (a ``.png`` name with a script mimetype) and on+ files with no recognizable signal. ``application/octet-stream`` is treated as+ "no mimetype" — Slack falls back to it for perfectly safe uploads, so it neither+ allows nor blocks on its own.+ """+ extension = os.path.splitext(filename.lower())[1]+ filetype = slack_filetype.lower() if isinstance(slack_filetype, str) else ""+ extension_allowed = extension in _ALLOWED_EXTENSIONS+ mime_allowed = content_type in _ALLOWED_MIME_TYPES+ filetype_allowed = filetype in _ALLOWED_SLACK_FILETYPES+ if extension and not extension_allowed:+ return False+ if content_type and content_type != "application/octet-stream" and not mime_allowed:+ return False+ if filetype and not filetype_allowed:+ return False+ return extension_allowed or mime_allowed or filetype_allowed+++def _is_dangerous_payload(payload: bytes) -> bool:+ stripped = payload.lstrip()+ if stripped.startswith(b"#!"):+ return True+ return any(payload.startswith(prefix) for prefix in _EXECUTABLE_MAGIC_PREFIXES)+++def _source_url(file: dict[str, Any]) -> str | None:+ url = file.get("url_private_download") or file.get("url_private")+ return url if isinstance(url, str) and url else None+++def _file_size(file: dict[str, Any]) -> int | None:+ size = file.get("size")+ if isinstance(size, int) and not isinstance(size, bool):+ return size+ if isinstance(size, str):+ try:+ return int(size)+ except ValueError:+ return None+ return None+++def _download_slack_file(url: str, bot_token: str) -> bytes | None:+ next_url = url+ for _ in range(MAX_SLACK_DOWNLOAD_REDIRECTS + 1):+ if not _is_allowed_slack_file_url(next_url):+ parsed = urlparse(next_url)+ logger.warning("slack_attachment_download_rejected_host", host=parsed.hostname)+ return None++ response = requests.get(+ next_url,+ headers={"Authorization": f"Bearer {bot_token}"},+ timeout=SLACK_DOWNLOAD_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )+ try:+ if response.is_redirect:+ location = response.headers.get("Location")+ if not location:+ return None+ next_url = urljoin(next_url, location)+ continue++ if response.status_code != 200:+ logger.warning("slack_attachment_download_failed_status", status_code=response.status_code)+ return None++ # Slack answers HTTP 200 with an HTML login/interstitial page when the+ # token lacks files:read or the file is access-restricted. HTML is never+ # an allowed attachment type, so an HTML body is always the interstitial+ # — forwarding it would silently hand the agent a login page as the file.+ response_content_type = _normalize_content_type(response.headers.get("Content-Type"))+ if response_content_type in ("text/html", "application/xhtml+xml"):+ logger.warning("slack_attachment_download_html_interstitial", content_type=response_content_type)+ return None++ content_length = response.headers.get("Content-Length")+ if content_length:+ try:+ if int(content_length) > MAX_SLACK_ATTACHMENT_BYTES:+ logger.warning("slack_attachment_download_rejected_size", content_length=content_length)+ return None+ except ValueError:+ return None++ chunks: list[bytes] = []+ total = 0+ for chunk in response.iter_content(chunk_size=64 * 1024):+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_SLACK_ATTACHMENT_BYTES:+ logger.warning("slack_attachment_download_rejected_body_size", total=total)+ return None+ chunks.append(chunk)+ return b"".join(chunks)+ finally:+ response.close()++ logger.warning("slack_attachment_download_too_many_redirects")+ return None+++def prepare_slack_file_artifacts(files: Any, bot_token: str | None) -> PreparedSlackAttachments:+ if not isinstance(files, list) or not files:+ return PreparedSlackAttachments(artifacts=[], skipped_messages=[], requested_count=0)++ requested_count = len(files)+ if not bot_token:+ return PreparedSlackAttachments(+ artifacts=[],+ skipped_messages=["Slack attachment(s) could not be read because the Slack bot token was unavailable."],+ requested_count=requested_count,+ )++ artifacts: list[dict[str, Any]] = []+ skipped_messages: list[str] = []++ for index, file in enumerate(files):+ if index >= MAX_SLACK_ATTACHMENTS_PER_MESSAGE:+ skipped_messages.append(+ f"Additional Slack attachment(s) skipped: only {MAX_SLACK_ATTACHMENTS_PER_MESSAGE} files are supported per message."+ )+ break+ if not isinstance(file, dict):+ skipped_messages.append("A Slack attachment was skipped because its metadata was invalid.")+ continue++ filename = _safe_filename(file)+ content_type = _normalize_content_type(file.get("mimetype")) or "application/octet-stream"+ if not _is_allowed_metadata(filename, content_type, file.get("filetype")):+ skipped_messages.append(f"{filename} was skipped because {_ATTACHMENT_TYPE_SKIP_REASON}.")+ continue++ size = _file_size(file)+ if size is not None and size > MAX_SLACK_ATTACHMENT_BYTES:+ skipped_messages.append(f"{filename} was skipped because it exceeds the 10 MB Slack attachment limit.")+ continue++ url = _source_url(file)+ if not url:+ skipped_messages.append(f"{filename} was skipped because Slack did not provide a download URL.")+ continue+ if not _is_allowed_slack_file_url(url):+ skipped_messages.append(f"{filename} was skipped because its download URL was not a Slack file URL.")+ continue++ try:+ payload = _download_slack_file(url, bot_token)+ except Exception:+ logger.exception("slack_attachment_download_exception", file_id=file.get("id"))+ payload = None++ if payload is None:+ skipped_messages.append(f"{filename} was skipped because it could not be downloaded from Slack.")+ continue+ if _is_dangerous_payload(payload):+ skipped_messages.append(f"{filename} was skipped because its content looks like an executable or script.")+ continue++ artifact: dict[str, Any] = {+ "name": filename,+ "type": "user_attachment",+ "source": "slack_user_attachment",+ "content_type": content_type,+ "content_bytes": payload,+ }+ # A deterministic id (keyed on Slack's globally-unique file id) makes the+ # manifest append an upsert: activity retries after a partial failure+ # re-upload to the same id instead of appending duplicate entries.+ file_id = file.get("id")+ if isinstance(file_id, str) and file_id:+ artifact["id"] = uuid.uuid5(uuid.NAMESPACE_URL, f"posthog:slack_user_attachment:{file_id}").hex+ artifacts.append(artifact)++ return PreparedSlackAttachments(+ artifacts=artifacts,+ skipped_messages=skipped_messages,+ requested_count=requested_count,+ )+++def build_slack_attachment_prompt_text(+ message: str | None,+ *,+ uploaded_artifacts: list[dict[str, Any]],+ skipped_messages: list[str],+) -> str | None:+ pieces: list[str] = []+ if message:+ pieces.append(message)++ if uploaded_artifacts:+ names = ", ".join(str(artifact.get("name") or "attachment") for artifact in uploaded_artifacts)+ pieces.append(f"Slack attachment(s) available to the agent as task files: {names}.")++ if skipped_messages:+ skipped = "\n".join(f"- {msg}" for msg in skipped_messages)+ pieces.append(f"Slack attachment(s) skipped:\n{skipped}")++ return "\n\n".join(pieces) if pieces else Nonediff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.pyindex 882ca077f2c7..ce3839b76de8 100644--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py@@ -30,6 +30,9 @@ from posthog.temporal.common.base import PostHogWorkflowPOSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS = 10 * 60POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15+# Temporal patch ID — an arbitrary string recorded in workflow history.+_PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS = "slack-file-only-followup-bypass-v1"+@workflow.defn(name="posthog-code-slack-mention-processing")class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):@@ -126,7 +129,20 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):# forward. The webhook handler punted on this so its 3-second ack# budget stays unencumbered; here we run it under Temporal's retry# policy. Drop on chitchat or any failure (default-deny).- if inputs.untagged_followup:+ # File-only replies skip the classifier: there is no text to+ # classify, and default-deny would silently drop the attachment.+ # Replies with text still face it even when files are attached, so+ # chitchat with a screenshot doesn't wake the agent.+ # workflow.patched() returns False for executions started before+ # this deploy so replay still schedules the classifier for+ # file-only replies. Delete the gate once history retention+ # exceeds our longest possible run.+ event_files = event.get("files")+ event_has_files = isinstance(event_files, list) and len(event_files) > 0+ file_only_followup = event_has_files and not (event.get("text") or "").strip()+ if inputs.untagged_followup and not (+ file_only_followup and workflow.patched(_PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS)+ ):should_forward = await _execute_posthog_code_activity(classify_untagged_followup_activity,inputs,diff --git a/posthog/temporal/tests/ai/slack_app/test_attachments.py b/posthog/temporal/tests/ai/slack_app/test_attachments.pynew file mode 100644index 000000000000..8da545666d88--- /dev/null+++ b/posthog/temporal/tests/ai/slack_app/test_attachments.py@@ -0,0 +1,130 @@+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.temporal.ai.slack_app.attachments import build_slack_attachment_prompt_text, prepare_slack_file_artifacts++_TYPE_SKIP_SUFFIX = (+ "was skipped because only image, PDF, and plain-text attachments (logs, markdown, CSV, JSON, YAML) are supported."+)+++def _slack_file(**overrides: object) -> dict[str, object]:+ file: dict[str, object] = {+ "id": "F123",+ "name": "debug.log",+ "mimetype": "text/plain",+ "filetype": "text",+ "size": 12,+ "url_private_download": "https://files.slack.com/files-pri/T123-F123/debug.log",+ }+ file.update(overrides)+ return file+++class TestSlackAttachments(SimpleTestCase):+ @parameterized.expand(+ [+ ("declared_mimetype", "text/plain", "text", "text/plain"),+ # Slack falls back to octet-stream for safe uploads; it must stay neutral.+ ("octet_stream_fallback", "application/octet-stream", None, "application/octet-stream"),+ ]+ )+ def test_prepares_safe_slack_file_as_user_attachment(+ self, _name: str, mimetype: str, filetype: str | None, expected_content_type: str+ ) -> None:+ file = _slack_file(mimetype=mimetype, filetype=filetype)+ with patch("posthog.temporal.ai.slack_app.attachments._download_slack_file", return_value=b"hello") as download:+ prepared = prepare_slack_file_artifacts([file], "xoxb-token")+ prepared_again = prepare_slack_file_artifacts([file], "xoxb-token")++ download.assert_called_with("https://files.slack.com/files-pri/T123-F123/debug.log", "xoxb-token")+ assert prepared.requested_count == 1+ assert prepared.skipped_messages == []+ assert len(prepared.artifacts) == 1+ artifact = prepared.artifacts[0]+ assert artifact["name"] == "debug.log"+ assert artifact["type"] == "user_attachment"+ assert artifact["source"] == "slack_user_attachment"+ assert artifact["content_type"] == expected_content_type+ assert artifact["content_bytes"] == b"hello"+ # Retried preparation must produce the same artifact id so uploads upsert.+ assert artifact["id"]+ assert prepared_again.artifacts == prepared.artifacts++ @parameterized.expand(+ [+ ("installer.exe", "application/x-msdownload", None),+ ("deploy.sh", "text/plain", "shell"),+ # Shebang-less macOS script: extension is the only dangerous signal.+ ("run.command", "text/plain", None),+ ("report.docm", "application/vnd.ms-word.document.macroEnabled.12", None),+ ("page.html", "text/html", "html"),+ ("diagram.svg", "image/svg+xml", None),+ # Contradiction: allowed extension, disallowed mimetype — fail closed.+ ("notes.txt", "application/x-sh", None),+ ]+ )+ def test_rejects_disallowed_attachment_metadata_without_downloading(+ self, name: str, mimetype: str, filetype: str | None+ ) -> None:+ with patch("posthog.temporal.ai.slack_app.attachments._download_slack_file") as download:+ prepared = prepare_slack_file_artifacts(+ [_slack_file(name=name, mimetype=mimetype, filetype=filetype)],+ "xoxb-token",+ )++ download.assert_not_called()+ assert prepared.artifacts == []+ assert prepared.skipped_messages == [f"{name} {_TYPE_SKIP_SUFFIX}"]++ def test_blocks_script_payload_after_download(self) -> None:+ with patch(+ "posthog.temporal.ai.slack_app.attachments._download_slack_file",+ return_value=b"#!/bin/sh\necho unsafe\n",+ ):+ prepared = prepare_slack_file_artifacts([_slack_file(name="notes.txt")], "xoxb-token")++ assert prepared.artifacts == []+ assert prepared.skipped_messages == [+ "notes.txt was skipped because its content looks like an executable or script."+ ]++ def test_rejects_html_interstitial_response(self) -> None:+ # Slack serves an HTTP 200 HTML login page when the token can't read the+ # file; the body must not be forwarded as the attachment's content.+ response = MagicMock()+ response.is_redirect = False+ response.status_code = 200+ response.headers = {"Content-Type": "text/html; charset=utf-8"}+ with patch("posthog.temporal.ai.slack_app.attachments.requests.get", return_value=response):+ prepared = prepare_slack_file_artifacts([_slack_file()], "xoxb-token")++ assert prepared.artifacts == []+ assert prepared.skipped_messages == ["debug.log was skipped because it could not be downloaded from Slack."]++ def test_rejects_non_slack_download_url(self) -> None:+ with patch("posthog.temporal.ai.slack_app.attachments._download_slack_file") as download:+ prepared = prepare_slack_file_artifacts(+ [_slack_file(url_private_download="https://example.com/debug.log")],+ "xoxb-token",+ )++ download.assert_not_called()+ assert prepared.artifacts == []+ assert prepared.skipped_messages == ["debug.log was skipped because its download URL was not a Slack file URL."]++ def test_build_prompt_handles_file_only_message(self) -> None:+ prompt = build_slack_attachment_prompt_text(+ None,+ uploaded_artifacts=[{"name": "debug.log"}],+ skipped_messages=[f"deploy.sh {_TYPE_SKIP_SUFFIX}"],+ )++ assert prompt == (+ "Slack attachment(s) available to the agent as task files: debug.log.\n\n"+ "Slack attachment(s) skipped:\n"+ f"- deploy.sh {_TYPE_SKIP_SUFFIX}"+ )diff --git a/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py b/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.pynew file mode 100644index 000000000000..cefa4eec7afd--- /dev/null+++ b/posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py@@ -0,0 +1,60 @@+import pytest+from unittest.mock import patch++from posthog.temporal.ai.slack_app import posthog_code_slack_mention+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs+++ "text,patched,expect_classifier",+ [+ # File-only replies skip the classifier so the attachment isn't dropped.+ ("", True, False),+ # Replies with text still face the classifier even when files are attached.+ ("nice weather today", True, True),+ # Replays of histories recorded before the patch keep the old always-classify sequence.+ ("", False, True),+ ],+)+async def test_untagged_followup_with_files_classifier_gating(+ text: str, patched: bool, expect_classifier: bool+) -> None:+ workflow = posthog_code_slack_mention.PostHogCodeSlackMentionWorkflow()+ calls: list[str] = []+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event={+ "channel": "C123",+ "ts": "1234.5679",+ "user": "U_ALICE",+ "text": text,+ "files": [{"id": "F123", "name": "debug.log"}],+ },+ integration_id=1,+ slack_team_id="T_SLACK",+ user_id=42,+ untagged_followup=True,+ )++ async def fake_execute_activity(activity_fn, *args):+ calls.append(activity_fn.__name__)+ if activity_fn is posthog_code_slack_mention.enforce_posthog_code_billing_quota_activity:+ return False+ if activity_fn is posthog_code_slack_mention.classify_untagged_followup_activity:+ return True+ if activity_fn is posthog_code_slack_mention.forward_posthog_code_followup_activity:+ return True++ raise AssertionError(f"unexpected activity: {activity_fn.__name__}")++ with (+ patch.object(posthog_code_slack_mention.workflow, "patched", return_value=patched),+ patch.object(posthog_code_slack_mention, "_execute_posthog_code_activity", side_effect=fake_execute_activity),+ ):+ await workflow.run(inputs)++ expected = ["enforce_posthog_code_billing_quota_activity"]+ if expect_classifier:+ expected.append("classify_untagged_followup_activity")+ expected.append("forward_posthog_code_followup_activity")+ assert calls == expecteddiff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 6e335e10bcf1..22ff9f184041 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -1103,6 +1103,11 @@ def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:return None+def _thread_message_event_has_files(event: dict[str, Any]) -> bool:+ files = event.get("files")+ return isinstance(files, list) and len(files) > 0++def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:"""Return a short reason if this ``message`` event shouldn't be considered as anuntagged thread follow-up, else None.@@ -1114,7 +1119,10 @@ def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:"""if not event.get("user"):return "no_user"- if not event.get("text"):+ # A file-only reply has empty text and the ``file_share`` subtype — both+ # must be admitted here or the attachment silently never reaches the agent.+ has_files = _thread_message_event_has_files(event)+ if not event.get("text") and not has_files:return "no_text"if event.get("edited") or event.get("subtype") == "message_changed":return "edit"@@ -1132,8 +1140,9 @@ def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:# etc.) is system noise from this gate's perspective. ``thread_broadcast``# is the only one a human types, but it's typically an announcement to the# parent channel, not agent-directed work.- if event.get("subtype"):- return f"subtype:{event.get('subtype')}"+ subtype = event.get("subtype")+ if subtype and not (subtype == "file_share" and has_files):+ return f"subtype:{subtype}"return Nonediff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex c23215ab8fa2..884d6e79b173 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -1,7 +1,7 @@from types import SimpleNamespacefrom unittest import TestCase as UnitTestCase-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.apps import appsfrom django.test import TestCase@@ -35,6 +35,19 @@ def _make_inputs(integration_id: int, slack_team_id: str = "T_SLACK") -> PostHog)+def _make_slack_file(**overrides: object) -> dict[str, object]:+ file: dict[str, object] = {+ "id": "F123",+ "name": "debug.log",+ "mimetype": "text/plain",+ "filetype": "text",+ "size": 12,+ "url_private_download": "https://files.slack.com/files-pri/T123-F123/debug.log",+ }+ file.update(overrides)+ return file++def _command_result(**kwargs):defaults = {"success": False, "status_code": 0, "error": None, "retryable": False, "data": None}defaults.update(kwargs)@@ -231,6 +244,111 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert mapping.task_id == task.idassert mapping.task_run_id == task.latest_run.id+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("posthog.models.integration.SlackIntegration")+ def test_initial_task_uploads_slack_attachment_to_pending_prompt(+ self, mock_slack_cls, mock_execute_workflow+ ) -> None:+ mock_slack_instance = MagicMock()+ mock_slack_instance.client.token = "xoxb-test"+ mock_slack_instance.client.chat_getPermalink.return_value = {+ "ok": True,+ "permalink": "https://slack.example.com/thread",+ }+ mock_slack_cls.return_value = mock_slack_instance++ event = {+ "channel": "C123",+ "ts": "1234.5678",+ "user": "U_ALICE",+ "text": "<@BOT> review this log",+ "files": [_make_slack_file(name="debug.log", size=9)],+ }+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=event,+ integration_id=self.integration.id,+ slack_team_id="T_SLACK",+ )++ with (+ patch("posthog.temporal.ai.slack_app.attachments._download_slack_file", return_value=b"log bytes"),+ patch("posthog.storage.object_storage.write") as mock_write,+ patch("posthog.storage.object_storage.tag"),+ ):+ create_posthog_code_task_for_repo_activity(+ inputs,+ "C123",+ "1234.5678",+ "U_ALICE",+ self.user.id,+ event,+ [{"user": "U_ALICE", "text": "review this log", "ts": "1234.5678"}],+ None,+ )++ task = self.Task.objects.get(team=self.team)+ run = self.TaskRun.objects.get(task=task)+ assert "review this log" in run.state["pending_user_message"]+ assert (+ "Slack attachment(s) available to the agent as task files: debug.log." in run.state["pending_user_message"]+ )+ assert len(run.state["pending_user_artifact_ids"]) == 1+ assert run.artifacts[0]["id"] == run.state["pending_user_artifact_ids"][0]+ assert run.artifacts[0]["name"] == "debug.log"+ assert run.artifacts[0]["type"] == "user_attachment"+ assert run.artifacts[0]["source"] == "slack_user_attachment"+ assert run.artifacts[0]["content_type"] == "text/plain"+ mock_write.assert_called_once()+ assert mock_write.call_args.args[1] == b"log bytes"+ mock_execute_workflow.assert_called_once()++ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("posthog.models.integration.SlackIntegration")+ def test_existing_mapping_skips_duplicate_task_creation(self, mock_slack_cls, mock_execute_workflow):+ """A retried activity (or a concurrent duplicate mention) must not create a+ second task for a thread that already has one and repoint the mapping."""+ mock_slack_cls.return_value = MagicMock()+ existing_task = self.Task.objects.create(+ team=self.team,+ title="Existing task",+ description="desc",+ origin_product=self.Task.OriginProduct.SLACK,+ created_by=self.user,+ )+ existing_run = self.TaskRun.objects.create(+ task=existing_task, team=self.team, status=self.TaskRun.Status.IN_PROGRESS+ )+ SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=self.integration,+ slack_workspace_id="T_SLACK",+ channel="C123",+ thread_ts="1234.5678",+ task=existing_task,+ task_run=existing_run,+ mentioning_slack_user_id="U_ALICE",+ )++ inputs = _make_inputs(self.integration.id)+ create_posthog_code_task_for_repo_activity(+ inputs,+ "C123",+ "1234.5678",+ "U_ALICE",+ self.user.id,+ inputs.event,+ [{"user": "U_ALICE", "text": "do something"}],+ None,+ )++ assert self.Task.objects.count() == 1+ mapping = SlackThreadTaskMapping.objects.get(+ integration=self.integration, channel="C123", thread_ts="1234.5678"+ )+ assert mapping.task_id == existing_task.id+ assert mapping.task_run_id == existing_run.id+ mock_execute_workflow.assert_not_called()+@patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_persists_explicit_event_id_in_workflow_id(self, mock_slack_cls, mock_execute_workflow):@@ -609,6 +727,52 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):)mock_slack_instance.client.chat_postMessage.assert_not_called()+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("posthog.models.integration.SlackIntegration")+ def test_terminal_run_resumes_with_slack_attachment(self, mock_slack_cls, mock_execute_workflow) -> None:+ self.task_run.status = self.TaskRun.Status.COMPLETED+ self.task_run.save()+ self._create_mapping()+ mock_slack_instance = MagicMock()+ mock_slack_instance.client.token = "xoxb-test"+ mock_slack_cls.return_value = mock_slack_instance++ event = {+ "channel": "C123",+ "ts": "1234.5679",+ "user": "U_ALICE",+ "text": "<@BOT> check this run",+ "files": [_make_slack_file(name="resume.txt", size=11)],+ }+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=event,+ integration_id=self.integration.id,+ slack_team_id="T_SLACK",+ )++ with (+ patch("posthog.temporal.ai.slack_app.attachments._download_slack_file", return_value=b"resume data"),+ patch("posthog.storage.object_storage.write"),+ patch("posthog.storage.object_storage.tag"),+ ):+ result = forward_posthog_code_followup_activity(+ inputs, "C123", "1234.5678", "U_ALICE", "<@BOT> check this run", "1234.5679"+ )++ assert result is True+ new_run_id = mock_execute_workflow.call_args.kwargs["run_id"]+ new_run = self.TaskRun.objects.get(id=new_run_id)+ assert new_run.state["initial_prompt_override"] == "check this run"+ assert "check this run" in new_run.state["pending_user_message"]+ assert (+ "Slack attachment(s) available to the agent as task files: resume.txt."+ in new_run.state["pending_user_message"]+ )+ assert len(new_run.state["pending_user_artifact_ids"]) == 1+ assert new_run.artifacts[0]["id"] == new_run.state["pending_user_artifact_ids"][0]+ assert new_run.artifacts[0]["name"] == "resume.txt"+ assert new_run.artifacts[0]["source"] == "slack_user_attachment"+@patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_no_repo_run_resumes_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):@@ -786,7 +950,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert result is Trueassert mock_token.call_args.args[1] == bob.idmock_send.assert_called_once_with(- self.task_run, "Bob: please retry the build", auth_token="jwt-token", timeout=90+ self.task_run, "Bob: please retry the build", auth_token="jwt-token", timeout=90, message_id=ANY)# No "Only the person who started" denial; the message went through.post_calls = [@@ -816,7 +980,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_BOB", "<@BOT> ping", "1234.5679")assert mock_token.call_args.args[1] == bob.id- mock_send.assert_called_once_with(self.task_run, "[email protected]: ping", auth_token="jwt-token", timeout=90)+ mock_send.assert_called_once_with(+ self.task_run, "[email protected]: ping", auth_token="jwt-token", timeout=90, message_id=ANY+ )@patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.models.integration.SlackIntegration")@@ -906,7 +1072,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert result is Truemock_token.assert_called_once()- mock_send.assert_called_once_with(self.task_run, "do something", auth_token="jwt-token", timeout=90)+ mock_send.assert_called_once_with(+ self.task_run, "do something", auth_token="jwt-token", timeout=90, message_id=ANY+ )# Agent is now working on the message, so the :eyes: reaction stays up — it is# not swapped to :hedgehog: until the task genuinely completes.mock_slack_instance.client.reactions_add.assert_called_once_with(@@ -924,6 +1092,106 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert mapping.latest_actor_slack_user_id == "U_ALICE"assert mapping.mentioning_slack_user_id == "U_ALICE"+ def test_attachment_only_followup_uploads_and_forwards_to_sandbox(self) -> None:+ self._create_mapping()+ event = {+ "channel": "C123",+ "ts": "1234.5679",+ "user": "U_ALICE",+ "text": "",+ "files": [_make_slack_file(name="only-log.txt", size=10)],+ }+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=event,+ integration_id=self.integration.id,+ slack_team_id="T_SLACK",+ )++ with (+ patch("posthog.models.integration.SlackIntegration") as mock_slack_cls,+ patch("products.tasks.backend.logic.services.agent_command.send_user_message") as mock_send,+ patch(+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",+ return_value="jwt-token",+ ),+ patch("posthog.temporal.ai.slack_app.attachments._download_slack_file", return_value=b"log bytes"),+ patch("products.slack_app.backend.services.slack_messages.collect_thread_messages", return_value=[]),+ patch("posthog.storage.object_storage.write") as mock_write,+ patch("posthog.storage.object_storage.tag"),+ ):+ mock_slack_instance = MagicMock()+ mock_slack_instance.client.token = "xoxb-test"+ mock_slack_instance.client.auth_test.return_value = {"bot_id": "B123"}+ mock_slack_cls.return_value = mock_slack_instance+ mock_send.return_value = _command_result(success=True, status_code=200)++ result = forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_ALICE", "", "1234.5679")+ # Temporal retries re-run the whole activity body; the re-upload must+ # upsert the same manifest entry, not append a duplicate.+ forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_ALICE", "", "1234.5679")++ assert result is True+ sent_run, sent_message = mock_send.call_args.args+ assert sent_run.id == self.task_run.id+ assert sent_message.startswith("Attached Slack file(s).")+ assert "Slack attachment(s) available to the agent as task files: only-log.txt." in sent_message+ sent_artifacts = mock_send.call_args.kwargs["artifacts"]+ assert len(sent_artifacts) == 1+ assert sent_artifacts[0]["name"] == "only-log.txt"+ assert sent_artifacts[0]["source"] == "slack_user_attachment"+ assert mock_send.call_args.kwargs["auth_token"] == "jwt-token"+ assert mock_write.call_count == 2+ assert mock_write.call_args_list[0].args[0] == mock_write.call_args_list[1].args[0]+ self.task_run.refresh_from_db()+ assert len(self.task_run.artifacts) == 1++ @parameterized.expand(+ [+ ("live_run", False),+ ("terminal_run", True),+ ]+ )+ def test_followup_with_only_rejected_attachments_posts_notice_without_waking_agent(+ self, _name: str, terminal: bool+ ) -> None:+ if terminal:+ self.task_run.status = self.TaskRun.Status.COMPLETED+ self.task_run.save()+ self._create_mapping()+ event = {+ "channel": "C123",+ "ts": "1234.5679",+ "user": "U_ALICE",+ "text": "",+ "files": [_make_slack_file(name="installer.exe", mimetype="application/x-msdownload", filetype="binary")],+ }+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=event,+ integration_id=self.integration.id,+ slack_team_id="T_SLACK",+ )++ with (+ patch("posthog.models.integration.SlackIntegration") as mock_slack_cls,+ patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow") as mock_execute_workflow,+ patch("products.tasks.backend.logic.services.agent_command.send_user_message") as mock_send,+ patch("posthog.storage.object_storage.write") as mock_write,+ ):+ mock_slack_instance = MagicMock()+ mock_slack_instance.client.token = "xoxb-test"+ mock_slack_cls.return_value = mock_slack_instance++ result = forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_ALICE", "", "1234.5679")++ assert result is True+ mock_send.assert_not_called()+ mock_write.assert_not_called()+ mock_execute_workflow.assert_not_called()+ assert self.TaskRun.objects.count() == 1+ notice = mock_slack_instance.client.chat_postMessage.call_args.kwargs["text"]+ assert "no attachment was accepted" in notice+ assert "installer.exe" in notice+@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",return_value="jwt-token",@@ -995,6 +1263,10 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert result is Trueassert mock_send.call_count == 2+ # Redelivery must reuse the idempotency key or the agent applies the message twice.+ first_id = mock_send.call_args_list[0].kwargs["message_id"]+ second_id = mock_send.call_args_list[1].kwargs["message_id"]+ assert first_id and first_id == second_id# The :eyes: reaction stays up while the agent works — no swap to :hedgehog:.mock_slack_instance.client.reactions_add.assert_called_once_with(channel="C123", timestamp="1234.5679", name="eyes"diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.pyindex 4a459e028e69..457b4fa094a3 100644--- a/products/slack_app/backend/tests/test_thread_message_routing.py+++ b/products/slack_app/backend/tests/test_thread_message_routing.py@@ -330,6 +330,26 @@ class TestRouteThreadMessage(TestCase):assert kwargs["posthog_user"].id == self.user.idassert kwargs["untagged_followup"] is True+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_file_only_reply_reaches_mention_workflow(self):+ """A file-only thread reply has empty text and the ``file_share`` subtype —+ both gates must admit it or attachments silently never reach the agent."""+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY++ event = self._make_event(+ user="U_ALICE",+ text="",+ subtype="file_share",+ files=[{"id": "F123", "name": "debug.log"}],+ )+ with patch(+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY+ ) as mock_start:+ result = self._route(event)+ assert result == ROUTE_HANDLED_LOCALLY+ mock_start.assert_called_once()+ assert mock_start.call_args.kwargs["untagged_followup"] is True+# --- Symmetry with the app_mention path -------------------------------@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2133260d65b6..475af462fcbc 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1850,8 +1850,17 @@ def _save_artifact_manifest(run: TaskRun, manifest: list[dict]) -> None:def upload_task_run_artifacts(run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifacts: list[dict]-) -> list[dict] | None:- """Write artifact bytes to S3 and append them to the run manifest. Returns the full manifest."""+) -> tuple[list[dict], list[dict]] | None:+ """Write artifact bytes to S3 and append them to the run manifest.++ Returns ``(uploaded, manifest)`` — the entries created for ``artifacts`` and the full+ manifest including them — or ``None`` when the run isn't visible.++ An artifact may carry an explicit ``id``; entries with that id are upserted into the+ manifest (same-id S3 writes overwrite the same key), so callers that derive ids+ deterministically get idempotent uploads under retries. Without an ``id`` each call+ appends a fresh entry.+ """import uuid as uuid_module # noqa: PLC0415from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path@@ -1862,7 +1871,7 @@ def upload_task_run_artifacts(uploaded: list[dict] = []for artifact in artifacts:- artifact_id = uuid_module.uuid4().hex+ artifact_id = str(artifact.get("id") or uuid_module.uuid4().hex)safe_name, storage_path = _build_artifact_storage_path(run, artifact_id, artifact["name"])content_bytes = artifact["content_bytes"]@@ -1899,11 +1908,12 @@ def upload_task_run_artifacts(with transaction.atomic():run = TaskRun.objects.select_for_update().get(pk=run.pk)- manifest = list(run.artifacts or [])+ uploaded_ids = {entry["id"] for entry in uploaded}+ manifest = [entry for entry in (run.artifacts or []) if entry.get("id") not in uploaded_ids]manifest.extend(uploaded)_save_artifact_manifest(run, manifest)- return manifest+ return uploaded, manifestdef prepare_task_run_artifact_uploads(@@ -4456,8 +4466,13 @@ def send_user_message(artifacts: list[dict] | None = None,auth_token: str | None = None,timeout: int | None = None,+ message_id: str | None = None,):- """Push a follow-up user message (and/or artifacts) into a run's live sandbox."""+ """Push a follow-up user message (and/or artifacts) into a run's live sandbox.++ ``message_id`` is the agent-server idempotency key — pass a deterministic id when the+ caller may retry delivery so a redelivered message isn't applied twice.+ """from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import pathsend_user_message as _send,)@@ -4469,6 +4484,8 @@ def send_user_message(extra["artifacts"] = artifactsif timeout is not None:extra["timeout"] = timeout+ if message_id is not None:+ extra["message_id"] = message_idreturn _send(run, message, auth_token=auth_token, **extra)diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 7126971be81b..80a4ea4aac08 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -1098,11 +1098,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def artifacts(self, request, pk=None, **kwargs):task_id = self._ensure_task_accessible()- manifest = tasks_facade.upload_task_run_artifacts(+ result = tasks_facade.upload_task_run_artifacts(pk, task_id, self.team_id, artifacts=request.validated_data["artifacts"])- if manifest is None:+ if result is None:raise NotFound()+ _uploaded, manifest = resultserializer = TaskRunArtifactsUploadResponseSerializer({"artifacts": manifest})return Response(serializer.data)