Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(slack_app): don't reply to a deleted message (#83601)

Vojta Bartošeb68875a6669
diff --git a/posthog/temporal/ai/slack_app/activities/messaging.py b/posthog/temporal/ai/slack_app/activities/messaging.py
index b762891afeb9..1a4cb1550cc2 100644
--- a/posthog/temporal/ai/slack_app/activities/messaging.py
+++ b/posthog/temporal/ai/slack_app/activities/messaging.py
@@ -14,6 +14,8 @@ from posthog.temporal.ai.slack_app.types import (
)
from posthog.temporal.common.utils import close_db_connections
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
+
logger = structlog.get_logger(__name__)
POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE = (
@@ -37,7 +39,8 @@ def post_posthog_code_no_repos_activity(
integration_id=inputs.slack_team_id,
)
slack = SlackIntegration(integration)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=(
@@ -132,7 +135,8 @@ def _post_connect_personal_github_prompt(
"the pull request as you. Connect it, then mention me again."
)
button_text = "Connect GitHub"
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=text,
@@ -254,7 +258,8 @@ def post_posthog_code_picker_timeout_activity(
integration_id=inputs.slack_team_id,
)
slack = SlackIntegration(integration)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="Repository selection expired. Please mention PostHog again to retry.",
@@ -284,7 +289,8 @@ def post_posthog_code_internal_error_activity(
integration_id=inputs.slack_team_id,
)
slack = SlackIntegration(integration)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="Sorry, I hit an internal error while processing that request. Please try again.",
diff --git a/posthog/temporal/ai/slack_app/activities/rules.py b/posthog/temporal/ai/slack_app/activities/rules.py
index 1c6e096a7a71..cbde52a1c32e 100644
--- a/posthog/temporal/ai/slack_app/activities/rules.py
+++ b/posthog/temporal/ai/slack_app/activities/rules.py
@@ -9,6 +9,8 @@ from posthog.temporal.ai.slack_app.types import (
)
from posthog.temporal.common.utils import close_db_connections
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
+
logger = structlog.get_logger(__name__)
@@ -45,6 +47,7 @@ def handle_posthog_code_rules_command_activity(
integration,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=inputs.event.get("ts") or "",
slack_user_id=slack_user_id,
slack_workspace_id=inputs.slack_team_id,
user_id=user_id,
@@ -83,7 +86,8 @@ def create_posthog_code_routing_rule_activity(
team_id=integration.team_id,
user_id=user_id,
)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=f"Repository `{repository}` is no longer connected to your account.",
@@ -104,7 +108,8 @@ def create_posthog_code_routing_rule_activity(
priority=max_priority,
created_by_id=user_id,
)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=f"Added rule: {rule_text} → `{matched_repo}`",
@@ -187,6 +192,9 @@ def handle_posthog_code_slack_mention_command_activity(
target,
channel=channel,
thread_ts=thread_ts,
+ # The command message itself, which a top-level reply is answering even though it
+ # is deliberately placed at channel root. A slash command creates no message.
+ trigger_ts=event.get("ts") or "",
slack_user_id=slack_user_id,
slack_workspace_id=inputs.slack_team_id,
user_id=user_id,
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 5653a5838bce..cdb421323211 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -19,6 +19,8 @@ from posthog.temporal.ai.slack_app.helpers import block_if_team_over_quota, safe
from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs, SlackAppModelOverride
from posthog.temporal.common.utils import close_db_connections
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
+
logger = structlog.get_logger(__name__)
_RESUME_ERROR_MSG = "Sorry, I ran into an internal error restarting the agent. Please try again in a minute."
@@ -193,7 +195,7 @@ def _post_attachment_rejection_notice(
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)
+ post_slack_thread_reply(slack.client, channel=channel, thread_ts=thread_ts, text=text)
except Exception:
logger.warning("slack_attachment_rejection_notice_failed", channel=channel, thread_ts=thread_ts)
@@ -646,7 +648,8 @@ def create_posthog_code_task_for_repo_activity(
thread_ts=thread_ts,
)
try:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="Sorry, I ran into an internal error creating the task. Please try again in a minute.",
@@ -855,7 +858,8 @@ def forward_posthog_code_followup_activity(
sandbox_url = (task_run.state or {}).get("sandbox_url")
if not sandbox_url:
logger.info("posthog_code_followup_sandbox_not_ready", channel=channel, thread_ts=thread_ts)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="The agent is still starting up. Give it a moment and try again.",
@@ -957,7 +961,8 @@ def forward_posthog_code_followup_activity(
signal_result=signal_result,
)
_set_followup_done_reaction(slack, channel, user_message_ts, "x")
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="I couldn't deliver your message to the agent. The sandbox may have stopped. Please try starting a new task.",
@@ -1104,7 +1109,8 @@ def _resume_task_with_new_run(
created_by = mapping.task.created_by
run_actor = actor_user or created_by
if not created_by or not run_actor:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text="I can't restart the agent — the original task creator is no longer available.",
@@ -1175,7 +1181,8 @@ def _resume_task_with_new_run(
thread_ts=thread_ts,
task_id=str(mapping.task_id),
)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=_RESUME_ERROR_MSG,
@@ -1235,7 +1242,8 @@ def _resume_task_with_new_run(
task_id=str(mapping.task_id),
run_id=str(new_run.id),
)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=_RESUME_ERROR_MSG,
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py b/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
index 1eaf2df9dea9..d3f5b7b7521b 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
@@ -44,6 +44,7 @@ def process_posthog_code_task_termination_payload(payload: dict[str, Any]) -> No
from posthog.models.integration import Integration, SlackIntegration
from posthog.temporal.common.client import sync_connect
+ from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.temporal import ProcessTaskWorkflow
@@ -112,7 +113,8 @@ def process_posthog_code_task_termination_payload(payload: dict[str, Any]) -> No
if channel and thread_ts:
try:
slack_client = SlackIntegration(integration).client
- slack_client.chat_postMessage(
+ post_slack_thread_reply(
+ slack_client,
channel=channel,
thread_ts=thread_ts,
text=f"This run is already `{task_run.status}`. There is nothing to terminate.",
diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
index 8c4dedd0f6a8..3f4f2caccd63 100644
--- a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
@@ -60,6 +60,9 @@ class _Recorder:
self.internal_errors: list[str] = []
# ts -> forward result; missing means False (no existing task, fall through to new-task path).
self.forward_results: dict[str, bool] = {}
+ # ts -> thread snapshot; missing means a one-message thread. An empty list is what
+ # a deleted trigger message reads as.
+ self.thread_messages: dict[str, list[dict[str, str]]] = {}
# ts -> cascade mode; missing means "auto" with a fixed repository.
self.cascade_modes: dict[str, Literal["auto", "no_repo", "agent_needed", "needs_user_github"]] = {}
# ts per personal-GitHub gate call, in execution order.
@@ -109,7 +112,8 @@ def _fake_activities(rec: _Recorder) -> list:
async def collect(
inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str
) -> list[dict[str, str]]:
- return [{"user": "U1", "text": inputs.event["text"]}]
+ ts = inputs.event["ts"]
+ return rec.thread_messages.get(ts, [{"user": "U1", "text": inputs.event["text"]}])
@activity.defn(name="cascade_posthog_code_repository_activity")
async def cascade(
@@ -495,3 +499,19 @@ async def test_continue_as_new_carry_over_processes_pending_and_dedups_seen():
await asyncio.wait_for(handle.result(), timeout=30)
assert rec.created == [("1.1", "org/auto-repo")]
+
+
+async def test_deleted_trigger_message_creates_no_task_and_says_nothing():
+ # A prompt deleted right after posting reads back as an empty thread. Slack posts a
+ # reply with an unresolvable thread_ts at channel root, so anything we say here —
+ # including an "internal error" notice — lands in front of the whole channel.
+ rec = _Recorder()
+ rec.thread_messages["1.1"] = []
+
+ async with _Harness(rec) as h:
+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1"))
+ await asyncio.wait_for(handle.result(), timeout=30)
+
+ assert rec.created == []
+ assert rec.internal_errors == []
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 62dcf250eef3..dc3db76bf19f 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -86,6 +86,7 @@ from products.slack_app.backend.services.slack_app_home import (
handle_app_home_opened as _handle_app_home_opened,
handle_app_home_view_submission as _handle_app_home_view_submission,
)
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
from products.slack_app.backend.services.slack_user_info import (
clear_workspace_profile_cache,
get_cached_bot_user_id,
@@ -296,11 +297,14 @@ def _post_slack_user_feedback(
prefer_thread_message: bool = False,
) -> bool:
"""Post feedback to a Slack user. Returns whether anything reached Slack, so callers
- that report on whether the user was actually told something aren't guessing."""
+ that report on whether the user was actually told something aren't guessing.
+
+ A thread post whose root has been deleted is skipped rather than posted — see
+ ``post_slack_thread_reply``. That counts as "nothing reached Slack", which is
+ accurate: the user retracted the message this feedback answers."""
if prefer_thread_message:
try:
- slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text)
- return True
+ return post_slack_thread_reply(slack.client, channel=channel, thread_ts=thread_ts, text=text) is not None
except Exception:
logger.warning("slack_user_feedback_thread_post_failed", channel=channel, slack_user_id=slack_user_id)
@@ -308,7 +312,7 @@ def _post_slack_user_feedback(
slack.client.chat_postEphemeral(channel=channel, user=slack_user_id, thread_ts=thread_ts, text=text)
except Exception:
try:
- slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text)
+ return post_slack_thread_reply(slack.client, channel=channel, thread_ts=thread_ts, text=text) is not None
except Exception:
logger.warning("slack_user_feedback_failed", channel=channel, slack_user_id=slack_user_id)
return False
@@ -880,7 +884,8 @@ def _post_repo_picker_message(
}
)
- response = slack.client.chat_postMessage(
+ response = post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
text=guidance,
@@ -890,6 +895,9 @@ def _post_repo_picker_message(
"event_payload": {"context_token": context_token, "workflow_id": workflow_id},
},
)
+ if response is None:
+ # No prompt left to route, so there is nothing to ask about and nothing to await.
+ return
if workflow_id:
response_data = normalize_slack_response(response)
@@ -1631,6 +1639,7 @@ def _handle_assistant_thread_started(slack: SlackIntegration, channel_id: str, t
title="What can I help you ship?",
prompts=_ASSISTANT_SUGGESTED_PROMPTS,
)
+ # Slack's own assistant container thread, not a reply to a user message that can be deleted.
slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_WELCOME)
except Exception:
logger.warning("assistant_thread_started_failed", exc_info=True)
@@ -1639,6 +1648,7 @@ def _handle_assistant_thread_started(slack: SlackIntegration, channel_id: str, t
def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, thread_ts: str) -> None:
try:
+ # Slack's own assistant container thread, not a reply to a user message that can be deleted.
slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_UNAVAILABLE)
except Exception:
logger.warning("assistant_unavailable_post_failed", exc_info=True)
@@ -3426,7 +3436,8 @@ def _handle_repo_picker_submit(payload: dict) -> HttpResponse:
integration = Integration.objects.get(
id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id
)
- SlackIntegration(integration).client.chat_postMessage(
+ post_slack_thread_reply(
+ SlackIntegration(integration).client,
channel=channel,
thread_ts=thread_ts,
text="Repository selection expired. Please mention PostHog again to retry.",
@@ -3552,7 +3563,8 @@ def _post_channel_approval_outcome(
if not thread_ts:
return
try:
- SlackIntegration(integration).client.chat_postMessage(
+ post_slack_thread_reply(
+ SlackIntegration(integration).client,
channel=channel_id,
thread_ts=thread_ts,
text=text,
@@ -4156,6 +4168,7 @@ def _post_insight_alert_snooze_modal_confirmation(
actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"
text = f"😴 Snoozed until {until.strftime('%Y-%m-%d %H:%M')} UTC by {actor}"
try:
+ # Insight-alert surface: anchored on the alert the bot posted, not on an @PostHog prompt.
SlackIntegration(integration).client.chat_postMessage(
channel=channel, thread_ts=meta.get("message_ts"), text=text
)
diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.py
index 52076bae3724..6ad2069ac7f3 100644
--- a/products/slack_app/backend/services/commands.py
+++ b/products/slack_app/backend/services/commands.py
@@ -2,6 +2,8 @@ from typing import TYPE_CHECKING
from posthog.models.integration import Integration, SlackIntegration
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply
+
if TYPE_CHECKING:
from products.slack_app.backend.api import RulesCommand
from products.slack_app.backend.services.integration_resolver import ResolutionResult
@@ -14,6 +16,7 @@ def _handle_help(
thread_ts: str,
slack_user_id: str,
*,
+ trigger_ts: str = "",
command_prefix: str = "@PostHog",
) -> None:
from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin
@@ -44,7 +47,9 @@ def _handle_help(
if command_prefix == "@PostHog":
lines.append("You can also reply in an active thread to send follow-up messages to the agent.")
- slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text="\n".join(lines))
+ post_slack_thread_reply(
+ slack.client, channel=channel, thread_ts=thread_ts, trigger_ts=trigger_ts, text="\n".join(lines)
+ )
def _handle_rules_list(
@@ -53,15 +58,18 @@ def _handle_rules_list(
channel: str,
thread_ts: str,
*,
+ trigger_ts: str = "",
command_prefix: str = "@PostHog",
) -> None:
from posthog.models.repo_routing_rule import RepoRoutingRule
rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))
if not rules:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=(
f'No routing rules configured. Add one with `{command_prefix} rules add "description" '
"[org/repo]`. Omit the repo to pick from a list."
@@ -70,9 +78,11 @@ def _handle_rules_list(
return
lines = [f"{i + 1}. {r.rule_text} → `{r.repository}`" for i, r in enumerate(rules)]
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text="*Routing rules:*\n" + "\n".join(lines),
)
@@ -85,6 +95,8 @@ def _handle_rules_add(
user_id: int,
rule_text: str,
repository: str,
+ *,
+ trigger_ts: str = "",
) -> None:
from posthog.models.repo_routing_rule import RepoRoutingRule
@@ -92,18 +104,22 @@ def _handle_rules_add(
all_repos = _get_full_repo_names(integration, user_id=user_id)
if not all_repos:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text="No connected GitHub repositories found for your account.",
)
return
matched_repo = _extract_explicit_repo(repository, all_repos)
if not matched_repo:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f"Repository `{repository}` is not connected to this project.",
)
return
@@ -122,9 +138,11 @@ def _handle_rules_add(
priority=max_priority,
created_by_id=user_id,
)
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f"Added rule: {rule_text} → `{matched_repo}`",
)
@@ -136,14 +154,17 @@ def _handle_rules_remove(
thread_ts: str,
rule_numbers: list[int] | None,
*,
+ trigger_ts: str = "",
command_prefix: str = "@PostHog",
) -> None:
from posthog.models.repo_routing_rule import RepoRoutingRule
if not rule_numbers or any(n < 1 for n in rule_numbers):
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f"Please provide valid rule number(s). Use `{command_prefix} rules list` to see current rules.",
)
return
@@ -151,9 +172,11 @@ def _handle_rules_remove(
rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))
invalid = [n for n in rule_numbers if n > len(rules)]
if invalid:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f"Rule {'number' if len(invalid) == 1 else 'numbers'} {', '.join(f'#{n}' for n in invalid)} {'does' if len(invalid) == 1 else 'do'} not exist. There are {len(rules)} rule(s). Use `{command_prefix} rules list` to see them.",
)
return
@@ -166,9 +189,11 @@ def _handle_rules_remove(
rule.delete()
removed.reverse()
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f"Removed rule{'s' if len(removed) > 1 else ''} {', '.join(removed)}",
)
@@ -443,6 +468,7 @@ def dispatch_rules_command(
slack: SlackIntegration,
integration: Integration,
*,
+ trigger_ts: str = "",
channel: str,
thread_ts: str,
slack_user_id: str,
@@ -464,23 +490,40 @@ def dispatch_rules_command(
surface. Defaults preserve the mention copy for existing callers.
"""
if command.action == "help":
- _handle_help(slack, integration, channel, thread_ts, slack_user_id, command_prefix=command_prefix)
+ _handle_help(
+ slack, integration, channel, thread_ts, slack_user_id, trigger_ts=trigger_ts, command_prefix=command_prefix
+ )
elif command.action == "list":
- _handle_rules_list(slack, integration, channel, thread_ts, command_prefix=command_prefix)
+ _handle_rules_list(slack, integration, channel, thread_ts, trigger_ts=trigger_ts, command_prefix=command_prefix)
elif command.action == "add":
if not command.repository:
- slack.client.chat_postMessage(
+ post_slack_thread_reply(
+ slack.client,
channel=channel,
thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
text=f'Please specify the repo inline: `{command_prefix} rules add "description" org/repo`.',
)
else:
_handle_rules_add(
- slack, integration, channel, thread_ts, user_id, command.rule_text or "", command.repository
+ slack,
+ integration,
+ channel,
+ thread_ts,
+ user_id,
+ command.rule_text or "",
+ command.repository,
+ trigger_ts=trigger_ts,
)
elif command.action == "remove":
_handle_rules_remove(
- slack, integration, channel, thread_ts, command.rule_numbers, command_prefix=command_prefix
+ slack,
+ integration,
+ channel,
+ thread_ts,
+ command.rule_numbers,
+ trigger_ts=trigger_ts,
+ command_prefix=command_prefix,
)
elif command.action == "project_show":
_handle_project_show(
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 6d18e23b188e..f42b4d9f8504 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -28,6 +28,8 @@ from django.conf import settings
from django.core.cache import cache
import structlog
+from slack_sdk import WebClient
+from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from posthog.models.integration import Integration, SlackIntegration
@@ -217,6 +219,95 @@ def _thread_replies_cache_key(integration_id: int, channel: str, thread_ts: str)
return f"slack_thread_replies:{integration_id}:{channel}:{thread_ts}"
+def _message_exists_cache_key(channel: str, ts: str) -> str:
+ # Keyed on the Slack coordinates rather than the integration: the message either
+ # exists in that channel or it doesn't, regardless of which install is asking.
+ return f"slack_message_exists:{channel}:{ts}"
+
+
+def slack_message_exists(
+ client: WebClient,
+ channel: str,
+ ts: str,
+ *,
+ ttl: int = THREAD_REPLIES_CACHE_TTL_SECONDS,
+) -> bool:
+ """Whether a Slack message is still there.
+
+ Asked with a one-message window on `ts` itself: Slack answers with that message when
+ it is there and an empty list when it isn't. `conversations.replies` would answer a
+ different question — its result also depends on whether a thread was ever started and
+ on how Slack represents a deleted parent.
+
+ Cached on the same short TTL as the thread snapshot: a burst of relay chunks for one
+ reply collapses onto a single `conversations.history` call, while a message deleted
+ mid-run is noticed within seconds.
+ """
+ key = _message_exists_cache_key(channel, ts)
+ cached = cache.get(key)
+ if cached is not None:
+ return bool(cached)
+
+ try:
+ response = client.conversations_history(channel=channel, latest=ts, oldest=ts, inclusive=True, limit=1)
+ exists = bool(response.get("messages"))
+ except Exception:
+ # Rate limits, transient 5xx, a scope we happen to lack — none of these are
+ # evidence the message is gone, and treating them as such would silence real
+ # replies. Fail open and let the post itself surface any real problem.
+ logger.warning("slack_app_message_exists_probe_failed", channel=channel, ts=ts, exc_info=True)
+ return True
+
+ try:
+ cache.set(key, exists, timeout=ttl)
+ except Exception:
+ logger.warning("slack_app_message_exists_cache_set_failed", channel=channel, ts=ts, exc_info=True)
+ return exists
+
+
+def post_slack_thread_reply(
+ client: WebClient,
+ *,
+ channel: str,
+ thread_ts: str | None,
+ trigger_ts: str | None = None,
+ **kwargs: Any,
+) -> Any:
+ """Post a reply once confirmed the message it answers still exists.
+
+ The single funnel for every `@PostHog` reply. A deleted prompt has nobody left to
+ answer, and replies to one were seen landing at channel level rather than in the
+ thread. Returns ``None`` when nothing was posted.
+
+ Where the reply goes and what it answers are separate questions. ``thread_ts`` places
+ it — falsy posts at channel root, which some replies do deliberately because a
+ thread-anchored one is invisible to anyone not already reading that thread.
+ ``trigger_ts`` is the message being answered, and defaults to the anchor. Pass it
+ whenever the two differ, or a root-placed reply would go out unchecked.
+
+ With neither set there is nothing to check — a slash command creates no message — so
+ the reply posts unconditionally.
+ """
+ check_ts = trigger_ts or thread_ts
+ if check_ts and not slack_message_exists(client, channel, check_ts):
+ logger.warning(
+ "slack_app_thread_reply_skipped_message_deleted",
+ channel=channel,
+ thread_ts=thread_ts,
+ trigger_ts=trigger_ts,
+ )
+ return None
+ if thread_ts:
+ return client.chat_postMessage(channel=channel, thread_ts=thread_ts, **kwargs)
+ return client.chat_postMessage(channel=channel, **kwargs)
+
+
+# `conversations.replies` answers `thread_not_found` for a ts that no longer resolves to a
+# message; `message_not_found` is carried alongside it because Slack uses that spelling on
+# neighbouring methods and the two mean the same thing here.
+_MISSING_THREAD_ERRORS = frozenset({"thread_not_found", "message_not_found"})
+
+
def collect_thread_messages(
slack: SlackIntegration,
integration: Integration,
@@ -224,10 +315,23 @@ def collect_thread_messages(
thread_ts: str,
our_bot_id: str | None,
) -> list[dict[str, str]]:
- """Fetch thread messages, strip bot mentions, and resolve user display names."""
+ """Fetch thread messages, strip bot mentions, and resolve user display names.
+
+ A thread whose root no longer exists — the user deleted the message that triggered
+ us — comes back empty rather than raising. Callers read an empty thread as "nothing
+ to do"; letting `thread_not_found` escape instead would exhaust the activity's
+ retries and land in the workflow's error handler, which announces the failure in
+ Slack. There is nothing to announce: the prompt was retracted.
+ """
client = slack.client
client.retry_handlers.append(RateLimitErrorRetryHandler(max_retry_count=3))
- thread_response = client.conversations_replies(channel=channel, ts=thread_ts)
+ try:
+ thread_response = client.conversations_replies(channel=channel, ts=thread_ts)
+ except SlackApiError as e:
+ if e.response.get("error") not in _MISSING_THREAD_ERRORS:
+ raise
+ logger.warning("slack_app_thread_message_deleted", channel=channel, thread_ts=thread_ts)
+ return []
raw_messages: list[dict] = thread_response.get("messages", [])
user_cache: dict[str, str] = {}
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index ecfb6e367358..dc401704f817 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -15,7 +15,9 @@ from products.slack_app.backend.services.slack_messages import (
app_home_url,
context_block,
normalize_labeled_mentions_to_bare,
+ post_slack_thread_reply,
reply_footer_block,
+ slack_message_exists,
viewer_has_code_access,
)
@@ -221,6 +223,19 @@ class SlackThreadHandler:
logger.warning("slack_auth_test_failed", error=str(e))
return self._bot_user_id
+ def _post_in_thread(self, **kwargs: Any) -> Any:
+ """Post in the run's thread, or nothing at all once the prompt it answers is gone.
+
+ Every lifecycle card and relayed answer goes through here, so a user who deletes
+ the prompt mid-run simply stops hearing from us.
+ """
+ return post_slack_thread_reply(
+ self._get_client(),
+ channel=self.context.channel,
+ thread_ts=self.context.thread_ts,
+ **kwargs,
+ )
+
def _find_progress_message_ts(self) -> str | None:
"""Find existing progress message in the thread."""
try:
@@ -282,6 +297,9 @@ class SlackThreadHandler:
return None
try:
client = self._get_client()
+ if not slack_message_exists(client, self.context.channel, self.context.thread_ts):
+ logger.warning("slack_app_status_stream_skipped_message_deleted", channel=self.context.channel)
+ return None
integration = self._get_integration()
response = client.chat_startStream(
channel=self.context.channel,
@@ -418,12 +436,7 @@ class SlackThreadHandler:
blocks=blocks,
)
else:
- client.chat_postMessage(
- channel=self.context.channel,
- thread_ts=self.context.thread_ts,
- text=text,
- blocks=blocks,
- )
+ self._post_in_thread(text=text, blocks=blocks)
except Exception as e:
logger.exception("slack_progress_update_failed", error=str(e))
@@ -489,12 +502,7 @@ class SlackThreadHandler:
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],
- )
+ self._post_in_thread(text=footer["elements"][0]["text"], blocks=[footer])
except Exception as e:
logger.warning("slack_app_post_footer_failed", error=str(e))
@@ -521,12 +529,7 @@ class SlackThreadHandler:
else None
)
try:
- self._get_client().chat_postMessage(
- channel=self.context.channel,
- thread_ts=self.context.thread_ts,
- text=text,
- blocks=blocks,
- )
+ self._post_in_thread(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.
@@ -664,11 +667,6 @@ class SlackThreadHandler:
blocks = [*blocks, footer]
try:
self.delete_progress()
- self._get_client().chat_postMessage(
- channel=self.context.channel,
- thread_ts=self.context.thread_ts,
- text=text,
- blocks=blocks,
- )
+ self._post_in_thread(text=text, blocks=blocks)
except Exception as e:
logger.exception("slack_completion_post_failed", error=str(e))
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py b/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py
index acc9fa870fa7..db623c1b8fef 100644
--- a/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py
+++ b/products/slack_app/backend/tests/services/slack_messages/test_collect_thread_messages.py
@@ -2,6 +2,7 @@ import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from posthog.models.integration import Integration, SlackIntegration
@@ -528,3 +529,17 @@ class TestCollectThreadMessages:
assert len(result) == 2
assert result[0]["user"] == "PostHog"
assert result[1]["text"] == "still here"
+
+ @parameterized.expand(["thread_not_found", "message_not_found"])
+ def test_deleted_root_reads_as_an_empty_thread(self, error):
+ # Raising instead would exhaust the activity's retries and land in the workflow's
+ # error handler, which announces the failure in Slack — for a retracted prompt.
+ self.slack.client.conversations_replies.side_effect = SlackApiError(error, {"error": error})
+
+ assert collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None) == []
+
+ def test_other_slack_errors_still_propagate(self):
+ self.slack.client.conversations_replies.side_effect = SlackApiError("ratelimited", {"error": "ratelimited"})
+
+ with pytest.raises(SlackApiError):
+ collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None)
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_deleted_message_guard.py b/products/slack_app/backend/tests/services/slack_messages/test_deleted_message_guard.py
new file mode 100644
index 000000000000..25f6d1db7167
--- /dev/null
+++ b/products/slack_app/backend/tests/services/slack_messages/test_deleted_message_guard.py
@@ -0,0 +1,131 @@
+import pytest
+from unittest.mock import MagicMock
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
+
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply, slack_message_exists
+
+THREAD_TS = "1700000000.000100"
+
+PRESENT = {"messages": [{"ts": THREAD_TS, "user": "U_ANDY", "text": "@PostHog fix the flaky test"}]}
+DELETED: dict = {"messages": []}
+
+
+class TestSlackMessageExists:
+ @pytest.fixture(autouse=True)
+ def clear_probe_cache(self):
+ cache.clear()
+ yield
+ cache.clear()
+
+ @parameterized.expand(
+ [
+ ("message_present", PRESENT, True),
+ ("message_deleted", DELETED, False),
+ ("missing_messages_key", {}, False),
+ # None of these is evidence the message is gone, and silencing a real reply is
+ # the worse failure, so the probe fails open.
+ ("rate_limited", SlackApiError("ratelimited", {"error": "ratelimited"}), True),
+ ("missing_scope", SlackApiError("missing_scope", {"error": "missing_scope"}), True),
+ ("transport_error", ConnectionError("boom"), True),
+ ]
+ )
+ def test_existence(self, _name, history_outcome, expected):
+ client = MagicMock()
+ if isinstance(history_outcome, Exception):
+ client.conversations_history.side_effect = history_outcome
+ else:
+ client.conversations_history.return_value = history_outcome
+
+ assert slack_message_exists(client, "C001", THREAD_TS) is expected
+
+ def test_probe_asks_for_that_one_message(self):
+ # A one-message window on the ts itself: anything wider would report a neighbouring
+ # message as proof this one survives.
+ client = MagicMock()
+ client.conversations_history.return_value = PRESENT
+
+ slack_message_exists(client, "C001", THREAD_TS)
+
+ client.conversations_history.assert_called_once_with(
+ channel="C001", latest=THREAD_TS, oldest=THREAD_TS, inclusive=True, limit=1
+ )
+
+ def test_repeated_probes_collapse_onto_one_slack_call(self):
+ client = MagicMock()
+ client.conversations_history.return_value = PRESENT
+
+ assert slack_message_exists(client, "C001", THREAD_TS) is True
+ assert slack_message_exists(client, "C001", THREAD_TS) is True
+
+ assert client.conversations_history.call_count == 1
+
+
+class TestPostSlackThreadReply:
+ @pytest.fixture(autouse=True)
+ def clear_probe_cache(self):
+ cache.clear()
+ yield
+ cache.clear()
+
+ def test_reply_posts_while_the_message_is_there(self):
+ client = MagicMock()
+ client.conversations_history.return_value = PRESENT
+
+ post_slack_thread_reply(client, channel="C001", thread_ts=THREAD_TS, text="on it")
+
+ client.chat_postMessage.assert_called_once_with(channel="C001", thread_ts=THREAD_TS, text="on it")
+
+ def test_reply_is_dropped_once_the_message_is_deleted(self):
+ client = MagicMock()
+ client.conversations_history.return_value = DELETED
+
+ assert post_slack_thread_reply(client, channel="C001", thread_ts=THREAD_TS, text="on it") is None
+
+ client.chat_postMessage.assert_not_called()
+
+ def test_root_level_post_skips_the_check(self):
+ client = MagicMock()
+
+ post_slack_thread_reply(client, channel="C001", thread_ts=None, text="hello")
+
+ client.conversations_history.assert_not_called()
+ client.chat_postMessage.assert_called_once_with(channel="C001", text="hello")
+
+ def test_root_placed_reply_is_still_checked_against_its_trigger(self):
+ # Top-level @PostHog commands answer at channel root on purpose, so the anchor is
+ # empty. The command message they answer must still be checked, or deleting it
+ # leaves the reply posting to the whole channel.
+ client = MagicMock()
+ client.conversations_history.return_value = DELETED
+
+ result = post_slack_thread_reply(client, channel="C001", thread_ts="", trigger_ts=THREAD_TS, text="help text")
+
+ assert result is None
+ client.chat_postMessage.assert_not_called()
+
+ def test_root_placed_reply_posts_without_an_anchor_when_its_trigger_lives(self):
+ client = MagicMock()
+ client.conversations_history.return_value = PRESENT
+
+ post_slack_thread_reply(client, channel="C001", thread_ts="", trigger_ts=THREAD_TS, text="help text")
+
+ client.chat_postMessage.assert_called_once_with(channel="C001", text="help text")
+
+ def test_trigger_takes_precedence_over_the_anchor(self):
+ # A command posted inside a live thread: the reply threads under the root, but what
+ # it answers is the command message, so that is what decides.
+ client = MagicMock()
+ client.conversations_history.return_value = DELETED
+
+ result = post_slack_thread_reply(
+ client, channel="C001", thread_ts="1700000000.000001", trigger_ts=THREAD_TS, text="hi"
+ )
+
+ assert result is None
+ client.conversations_history.assert_called_once_with(
+ channel="C001", latest=THREAD_TS, oldest=THREAD_TS, inclusive=True, limit=1
+ )
diff --git a/products/slack_app/backend/tests/test_mention_command_activity.py b/products/slack_app/backend/tests/test_mention_command_activity.py
index a49144c88eff..9b2bb423113e 100644
--- a/products/slack_app/backend/tests/test_mention_command_activity.py
+++ b/products/slack_app/backend/tests/test_mention_command_activity.py
@@ -69,5 +69,6 @@ class TestMentionCommandActivity:
assert result.status == "done"
client.chat_postMessage.assert_called_once()
- assert client.chat_postMessage.call_args.kwargs["thread_ts"] == expected_thread_ts
+ # A channel-root reply carries no anchor at all rather than an empty one.
+ assert client.chat_postMessage.call_args.kwargs.get("thread_ts", "") == expected_thread_ts
assert command_prefix in client.chat_postMessage.call_args.kwargs["text"]
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 55646a51180a..133bb039f8e6 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -1,5 +1,6 @@
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.test import SimpleTestCase
from parameterized import parameterized
@@ -475,3 +476,54 @@ class TestRelayedAnswerFooter(SimpleTestCase):
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
+
+
+class TestDeletedTriggerMessage(SimpleTestCase):
+ """A run whose prompt has been deleted has nobody left to answer, so it says nothing."""
+
+ def setUp(self) -> None:
+ cache.clear()
+
+ def tearDown(self) -> None:
+ cache.clear()
+
+ def _handler(self) -> SlackThreadHandler:
+ return SlackThreadHandler(
+ SlackThreadContext(
+ integration_id=1,
+ channel="C_DELETED",
+ thread_ts="1700000000.000100",
+ mentioning_slack_user_id="U123",
+ )
+ )
+
+ @parameterized.expand(
+ [
+ ("relayed_answer", lambda h: h.post_thread_message("here is the answer")),
+ ("completion_card", lambda h: h.post_completion(task_url=None)),
+ ("failure_card", lambda h: h.post_error("boom", task_url=None)),
+ ("progress_update", lambda h: h.post_or_update_progress("planning")),
+ ]
+ )
+ @patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_nothing_is_posted_once_the_prompt_is_deleted(
+ self, _name, post, mock_get_client, _mock_find_progress
+ ) -> None:
+ mock_client = MagicMock()
+ mock_client.conversations_history.return_value = {"messages": []}
+ mock_get_client.return_value = mock_client
+
+ post(self._handler())
+
+ mock_client.chat_postMessage.assert_not_called()
+
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_status_stream_does_not_start_for_a_deleted_prompt(self, mock_get_client) -> None:
+ mock_client = MagicMock()
+ mock_client.conversations_history.return_value = {"messages": []}
+ mock_get_client.return_value = mock_client
+
+ assert self._handler().start_status_stream(first_markdown_text="thinking") is None
+
+ mock_client.chat_startStream.assert_not_called()
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index 4e9c3958abbc..2a488e90b98c 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -29,6 +29,7 @@ from posthog.storage import object_storage
from posthog.utils import absolute_uri
from products.exports.backend.facade.api import get_delivery_image_url
+from products.slack_app.backend.services.slack_messages import post_slack_thread_reply, slack_message_exists
from products.tasks.backend.models import TaskArtifact, TaskRun
logger = structlog.get_logger(__name__)
@@ -589,13 +590,16 @@ class SlackMessageArtifactAdapter(LivingArtifactAdapter):
mapping = _get_slack_mapping(run)
text = content.strip() or name
if artifact is None:
- response = _slack_client_for_mapping(mapping).chat_postMessage(
+ response = post_slack_thread_reply(
+ _slack_client_for_mapping(mapping),
channel=mapping.channel,
thread_ts=mapping.thread_ts,
text=text,
unfurl_links=False,
unfurl_media=False,
)
+ if response is None:
+ raise ValueError("Slack message artifact has no thread left to deliver into")
message_ts = response.get("ts")
if not message_ts:
raise ValueError("Slack message delivery did not return a message timestamp")
@@ -893,6 +897,12 @@ def deliver_pending_slack_file_artifacts(
return result
slack_integration = _slack_integration_for_mapping(mapping)
+ # Nobody is waiting on charts or file shares for a prompt that has been deleted.
+ # Leave the artifacts pending rather than delivering them into the thread.
+ if not slack_message_exists(slack_integration.client, mapping.channel, mapping.thread_ts):
+ logger.warning("task_artifact.slack_delivery_skipped_message_deleted", task_run_id=str(run.id))
+ return result
+
has_file_scope = not slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
# The relay activity's start_to_close_timeout is a minute; a self-inflicted timeout would
@@ -1146,18 +1156,18 @@ def _post_composed_answer_message(
if len(kept) + len(card_blocks) <= _SLACK_MESSAGE_BLOCK_LIMIT:
fallback_text = sections[0] if sections else _artifact_fallback_text(image_cards[0].artifact)
try:
- _post_blocks_with_processing_retry(
+ if _post_blocks_with_processing_retry(
slack,
channel=mapping.channel,
thread_ts=mapping.thread_ts,
text=fallback_text,
blocks=[*kept, *card_blocks],
deadline=deadline,
- )
- for card in image_cards:
- mark_delivered(card)
- posted_blocks += len(kept)
- return bool(section_blocks) and posted_blocks == len(section_blocks)
+ ):
+ for card in image_cards:
+ mark_delivered(card)
+ posted_blocks += len(kept)
+ return bool(section_blocks) and posted_blocks == len(section_blocks)
except Exception:
logger.warning("task_artifact.slack_composed_message_failed", exc_info=True)
@@ -1167,7 +1177,7 @@ def _post_composed_answer_message(
posted_blocks += 1 if _post_thread_text(slack, mapping=mapping, text=block["text"]["text"]) else 0
for card in image_cards:
try:
- _post_blocks_with_processing_retry(
+ if _post_blocks_with_processing_retry(
slack,
channel=mapping.channel,
thread_ts=mapping.thread_ts,
@@ -1175,8 +1185,8 @@ def _post_composed_answer_message(
blocks=_chart_card_blocks(card),
attempts=_IMAGE_BLOCK_FALLBACK_ATTEMPTS,
deadline=deadline,
- )
- mark_delivered(card)
+ ):
+ mark_delivered(card)
except Exception:
logger.warning("task_artifact.slack_file_delivery_failed", artifact_id=str(card.artifact.id), exc_info=True)
return bool(section_blocks) and posted_blocks == len(section_blocks)
@@ -1232,8 +1242,9 @@ def _post_thread_text(slack: Any, *, mapping: Any, text: str) -> bool:
"""Post one plain text message, reporting whether it landed — callers use this to decide
whether the answer still needs a fallback, so a swallowed failure must not read as sent."""
try:
- slack.chat_postMessage(channel=mapping.channel, thread_ts=mapping.thread_ts, text=text)
- return True
+ return (
+ post_slack_thread_reply(slack, channel=mapping.channel, thread_ts=mapping.thread_ts, text=text) is not None
+ )
except Exception:
logger.warning("task_artifact.slack_thread_text_failed", exc_info=True)
return False
@@ -1328,11 +1339,13 @@ def _post_blocks_with_processing_retry(
blocks: list[dict[str, Any]],
attempts: int = _IMAGE_BLOCK_POST_ATTEMPTS,
deadline: float | None = None,
-) -> None:
+) -> bool:
+ """Whether the message actually landed. A skipped post — the message it would answer
+ is gone — returns False, so the caller leaves the cards pending instead of delivered."""
for attempt in range(1, attempts + 1):
try:
- slack.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text, blocks=blocks)
- return
+ posted = post_slack_thread_reply(slack, channel=channel, thread_ts=thread_ts, text=text, blocks=blocks)
+ return posted is not None
except SlackApiError as e:
error = e.response.get("error")
if attempt == attempts or error not in ("invalid_blocks", "ratelimited"):
@@ -1349,6 +1362,7 @@ def _post_blocks_with_processing_retry(
if deadline is not None and time.monotonic() + wait >= deadline:
raise
time.sleep(wait)
+ return False # unreachable: attempts >= 1, so the loop always returns or raises
def _pending_slack_file_version(artifact: TaskArtifact) -> tuple[int, dict[str, Any]] | None:
@@ -1575,7 +1589,8 @@ def _post_canvas_created_message(
escaped_canvas_id = _escape_slack_mrkdwn_text(canvas_id)
canvas_reference = f"<{canvas_url}|{escaped_name}>" if canvas_url else f"*{escaped_name}*"
try:
- slack.chat_postMessage(
+ post_slack_thread_reply(
+ slack,
channel=mapping.channel,
thread_ts=mapping.thread_ts,
text=f"Created Slack canvas {canvas_reference} (`{escaped_canvas_id}`).",
diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
index 9bb33da0b336..b27a8d328c39 100644
--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py
+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
@@ -885,3 +885,31 @@ class TestChartCardBlockBuilders(SimpleTestCase):
self.assertEqual(slack.chat_postMessage.call_count, 1 if card_count == 1 else card_count)
for call in slack.chat_postMessage.call_args_list:
self.assertEqual(call.kwargs["text"], "&lt;!channel&gt; spike")
+
+ @parameterized.expand(
+ [
+ ("composed", 1),
+ ("per_card", _SLACK_MESSAGE_BLOCK_LIMIT // 2 + 1),
+ ]
+ )
+ def test_deleted_prompt_skips_delivery_without_marking_cards_delivered(self, _name, card_count):
+ # A prompt deleted mid-delivery makes the reply funnel skip the post and return None.
+ # A skipped post must not read as delivered: the chart never reached the thread, and
+ # marking it delivered would drop it from every later relay pass.
+ slack = MagicMock()
+ slack.conversations_history.return_value = {"messages": []} # the message is gone
+ delivered: list[_SlackImageCard] = []
+ cards = [_SlackImageCard(TaskArtifact(name="Chart"), {}, file_id=f"F{index}") for index in range(card_count)]
+
+ answer_posted = _post_composed_answer_message(
+ slack,
+ mapping=MagicMock(channel="C_DELETED", thread_ts="8888.1"),
+ image_cards=cards,
+ answer_sections=[],
+ mark_delivered=delivered.append,
+ deadline=time.monotonic() + 30,
+ )
+
+ self.assertEqual(delivered, [])
+ slack.chat_postMessage.assert_not_called()
+ self.assertFalse(answer_posted)