Skip to content

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

feat(slack-app): offer one-click reply buttons after an agent turn (#116807)

Vojta Bartošdc3834b1af39
diff --git a/posthog/temporal/ai/slack_app/activities/fork.py b/posthog/temporal/ai/slack_app/activities/fork.py
index 2c10cab09aea..e27d1a8fa855 100644
--- a/posthog/temporal/ai/slack_app/activities/fork.py
+++ b/posthog/temporal/ai/slack_app/activities/fork.py
@@ -12,6 +12,8 @@ from temporalio import activity
from posthog.temporal.ai.slack_app.types import SlackAppForkThreadInputs
+from products.slack_app.backend.services.slack_conversations import channel_is_ext_shared
+
logger = structlog.get_logger(__name__)
# Long enough to recognise the thread, short enough to stay one line in a DM.
@@ -150,7 +152,7 @@ def process_slack_app_fork_thread_payload(payload: dict[str, Any]) -> None:
# of a Slack Connect channel and past the approval gate that keeps customer-facing
# writes gated. Refuse rather than fork-and-discover-later, and carry the flag
# onto the run so the destination inherits the source's posture.
- is_ext_shared = _source_channel_is_ext_shared(slack, source_channel)
+ is_ext_shared = channel_is_ext_shared(slack, source_channel)
if is_ext_shared and not _channel_is_approved(slack_team_id, source_channel):
logger.info("slack_app_fork_refused", reason="ext_shared_unapproved", slack_team_id=slack_team_id)
_ephemeral(
@@ -264,23 +266,6 @@ def process_slack_app_fork_thread_payload(payload: dict[str, Any]) -> None:
)
-def _source_channel_is_ext_shared(slack: Any, channel: str) -> bool:
- """Whether the forked channel is a Slack Connect channel.
-
- Unlike events, interactivity payloads carry no ``is_ext_shared_channel`` on the
- envelope, so this costs a ``conversations.info`` round trip. Fails closed: an
- unreadable channel is treated as externally shared, which at worst asks the user
- to approve a channel that did not need it.
- """
- try:
- info = slack.client.conversations_info(channel=channel)
- conversation = info.get("channel", {}) or {}
- return bool(conversation.get("is_ext_shared") or conversation.get("is_pending_ext_shared"))
- except Exception:
- logger.warning("slack_app_fork_channel_info_failed", channel=channel)
- return True
-
-
def _read_thread_root(slack: Any, channel: str, thread_ts: str) -> dict[str, Any] | None:
"""The forked thread's opening message, or `None` if we can't read the thread.
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 40f296f065f6..7761e4cb250a 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -25,6 +25,7 @@ from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowI
from posthog.temporal.common.utils import close_db_connections
from products.slack_app.backend.facade.api import slack_artifact_delivery_state_updates
+from products.slack_app.backend.logic.reply_suggestions import clear_open_suggestions
from products.slack_app.backend.services.slack_messages import (
SlackThreadMessage,
context_block,
@@ -967,7 +968,7 @@ def forward_posthog_code_followup_activity(
mapping.save(update_fields=["latest_actor_slack_user_id", "updated_at"])
if task_run.is_terminal:
- return _resume_task_with_new_run(
+ handled = _resume_task_with_new_run(
mapping,
task_run,
slack,
@@ -981,6 +982,8 @@ def forward_posthog_code_followup_activity(
user_text_prefix=followup_user_text_prefix,
model_override=model_override,
)
+ clear_open_suggestions(slack.client, integration.id, channel, thread_ts)
+ return handled
from products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415
collect_thread_messages,
@@ -1143,6 +1146,9 @@ def forward_posthog_code_followup_activity(
thread_ts=thread_ts,
)
+ # Last, so the message reaches the agent before Slack is asked to tidy up. Any message to the
+ # agent answers or overtakes its last question, so the buttons under it are stale.
+ clear_open_suggestions(slack.client, integration.id, channel, thread_ts)
logger.info("posthog_code_followup_forwarded", channel=channel, thread_ts=thread_ts, task_run_id=str(task_run.id))
return True
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 04e98471c7f8..f70a64890731 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -65,6 +65,7 @@ from products.slack_app.backend.feature_flags import (
is_slack_app_project_picker_enabled,
)
from products.slack_app.backend.helpers import local_dev_slack_email
+from products.slack_app.backend.logic import reply_suggestions
from products.slack_app.backend.models import (
ChannelWelcomeMode,
SlackChannel,
@@ -98,6 +99,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_conversations import channel_is_ext_shared
from products.slack_app.backend.services.slack_fork_context import clear_pending_fork, get_pending_fork
from products.slack_app.backend.services.slack_messages import (
FORK_THREAD_ACTION_ID,
@@ -3858,6 +3860,141 @@ def _handle_untagged_followup_dismiss(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
+def _handle_reply_suggestion_click(payload: dict, clicked: reply_suggestions.ClickedSuggestion) -> HttpResponse:
+ """Post the clicked reply in the thread and send it to the agent as the clicker's reply.
+
+ The click already says the message is for the agent, so it takes the confirmed untagged
+ follow-up path: no classifier, no creator prompt, and no new task in a thread without one.
+ The follow-up removes the buttons once the reply reaches the agent, which keeps that
+ Slack call out of the three seconds Slack gives this request.
+ """
+ slack_team_id = payload.get("team", {}).get("id", "")
+ clicker_slack_user_id = payload.get("user", {}).get("id", "")
+ container = payload.get("container") or {}
+ message = payload.get("message") or {}
+ channel = container.get("channel_id") or (payload.get("channel") or {}).get("id")
+ message_ts = container.get("message_ts") or message.get("ts")
+ thread_ts = container.get("thread_ts") or message.get("thread_ts")
+ if not (
+ slack_team_id
+ and clicker_slack_user_id
+ and isinstance(channel, str)
+ and isinstance(message_ts, str)
+ and isinstance(thread_ts, str)
+ ):
+ return HttpResponse(status=200)
+ claim_key = f"slack_app_reply_suggestion_claim:{clicked.integration_id}:{channel}:{message_ts}"
+ if cache.get(claim_key):
+ return HttpResponse(status=200)
+ integration = (
+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team
+ id=clicked.integration_id, # nosemgrep: idor-taint-user-input-to-model-get
+ kind=SLACK_INTEGRATION_KIND,
+ integration_id=slack_team_id,
+ )
+ .select_related("team__organization")
+ .first()
+ )
+ if integration is None:
+ return HttpResponse(status=200)
+ slack = SlackIntegration(integration)
+
+ # Anyone in the channel sees the buttons, so the click must clear the bar a typed reply clears.
+ posthog_user = _is_org_member(integration, clicker_slack_user_id)
+ if posthog_user is None or not _can_access_team(posthog_user, integration):
+ logger.info(
+ "slack_app_reply_suggestion_no_access",
+ integration_id=integration.id,
+ slack_workspace_id=slack_team_id,
+ slack_user_id=clicker_slack_user_id,
+ )
+ _post_slack_user_ephemeral(
+ slack,
+ channel,
+ clicker_slack_user_id,
+ thread_ts,
+ "Only members of this PostHog project can reply to the agent. Ask a project member to reply instead.",
+ )
+ return HttpResponse(status=200)
+
+ # A typed reply in an unapproved Slack Connect channel is dropped before dispatch, and a
+ # channel can become shared after the buttons were posted.
+ if not _channel_is_approved(slack_team_id, channel) and channel_is_ext_shared(slack, channel):
+ logger.info("slack_app_reply_suggestion_channel_unapproved", integration_id=integration.id)
+ _post_slack_user_ephemeral(
+ slack,
+ channel,
+ clicker_slack_user_id,
+ thread_ts,
+ "This channel is shared with another organization, so PostHog needs approval here first. "
+ "Mention @PostHog in the channel to approve it.",
+ )
+ return HttpResponse(status=200)
+
+ # Two people can click before the buttons disappear, and only the first click may reach the agent.
+ # The claim lasts as long as the buttons are tracked, in case removing them fails.
+ if not cache.add(claim_key, clicker_slack_user_id, timeout=reply_suggestions.OPEN_SUGGESTIONS_TTL_SECONDS):
+ return HttpResponse(status=200)
+
+ client = slack.client
+ client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
+
+ # A message of its own keeps the thread in order: the question, the reply, the next answer.
+ # Its ts carries the progress reactions and keys the follow-up's idempotent message id.
+ reply_ts = message_ts
+ posted_reply_ts: str | None = None
+ try:
+ posted = post_slack_thread_reply(
+ client,
+ channel=channel,
+ thread_ts=thread_ts,
+ text=f"<@{clicker_slack_user_id}> picked a suggested reply: *{clicked.text}*",
+ )
+ if posted is not None and isinstance(posted.get("ts"), str):
+ reply_ts = posted_reply_ts = posted["ts"]
+ except Exception:
+ logger.warning("slack_app_reply_suggestion_post_failed", integration_id=integration.id, exc_info=True)
+
+ event = {
+ "type": "message",
+ "user": clicker_slack_user_id,
+ "channel": channel,
+ "ts": reply_ts,
+ "thread_ts": thread_ts,
+ "text": clicked.text,
+ }
+ try:
+ _start_mention_workflow(
+ event,
+ integration,
+ slack_team_id,
+ None,
+ posthog_user=posthog_user,
+ untagged_followup=True,
+ untagged_followup_confirmed=True,
+ )
+ except Exception:
+ # Nothing reached the agent, so the buttons stay usable and the reply does not stand in the thread.
+ cache.delete(claim_key)
+ if posted_reply_ts:
+ try:
+ client.chat_delete(channel=channel, ts=posted_reply_ts)
+ except Exception:
+ logger.warning("slack_app_reply_suggestion_delete_failed", integration_id=integration.id)
+ raise
+
+ capture_slack_event(
+ integration,
+ "slack app reply suggestion clicked",
+ slack_user_id=clicker_slack_user_id,
+ posthog_user=posthog_user,
+ suggestion_index=clicked.index,
+ slack_session_id=slack_session_id(slack_team_id, channel, thread_ts),
+ ai_trace_id=clicked.trace_id,
+ )
+ return HttpResponse(status=200)
+
+
def _report_slack_mention_received(
event: dict,
integration: Integration,
@@ -5381,13 +5518,15 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
alert_snooze_uuid = _extract_alert_snooze_hints(payload)
inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)
project_picker_integration_id = project_picker.picked_integration_id(payload)
- # Both controls a reply carries, and the modal a thumbs-down opens, claim the same
- # workspace, so one hint serves all three. Only the modal needs its own extractor:
- # a view submission carries no action for the generic one to read.
+ # Both controls a reply carries, the modal a thumbs-down opens, and the reply suggestions claim
+ # the same workspace, so one hint serves all of them. The modal and the suggestions need their
+ # own extractors: a view submission carries no action, and each suggestion has its own action id.
+ clicked_reply_suggestion = reply_suggestions.clicked_suggestion(payload)
reply_control_integration_id = (
_extract_action_value_hints(payload, FORK_THREAD_ACTION_ID)[0]
or _extract_action_value_hints(payload, TURN_FEEDBACK_ACTION_ID)[0]
or turn_feedback.extract_modal_hint(payload)
+ or (clicked_reply_suggestion.integration_id if clicked_reply_suggestion else None)
)
requesting_user = payload.get("user", {}).get("id", "")
slack_team_id = payload.get("team", {}).get("id")
@@ -5553,6 +5692,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
return _handle_fork_thread_submit(payload)
if action_id == TURN_FEEDBACK_ACTION_ID:
return turn_feedback.handle_turn_feedback_click(payload)
+ if reply_suggestions.is_reply_suggestion_action(action_id) and clicked_reply_suggestion:
+ return _handle_reply_suggestion_click(payload, clicked_reply_suggestion)
if action_id == CHANNEL_APPROVAL_ACTION_APPROVE:
return _handle_channel_approval_submit(payload)
if action_id == CHANNEL_APPROVAL_ACTION_DENY:
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index e4fffb5db365..4328f76ec209 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -50,6 +50,7 @@ SLACK_APP_FORKING_FLAG = "slack-app-forking"
SLACK_APP_PROJECT_PICKER_FLAG = "slack-app-project-picker"
SLACK_APP_MODEL_ROUTER_FLAG = "slack-app-model-router"
SLACK_APP_INSIGHT_UNFURL_CHARTS_FLAG = "slack-app-insight-unfurl-charts"
+SLACK_APP_REPLY_SUGGESTIONS_FLAG = "slack-app-reply-suggestions"
# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.
@@ -162,6 +163,14 @@ def is_slack_app_insight_unfurl_charts_enabled(integration: Integration, distinc
)
+def is_slack_app_reply_suggestions_enabled(integration: Integration) -> bool:
+ return _workspace_flag_enabled(
+ SLACK_APP_REPLY_SUGGESTIONS_FLAG,
+ integration,
+ failure_log_key="slack_app_reply_suggestions_feature_flag_check_failed",
+ )
+
+
def is_slack_app_assistant_enabled(integration: Integration) -> bool:
"""Gate for the DM assistant: the install must hold the scopes the DM surface
calls — ``im:history`` in particular, without which the assistant would answer
diff --git a/products/slack_app/backend/logic/reply_suggestions.py b/products/slack_app/backend/logic/reply_suggestions.py
new file mode 100644
index 000000000000..aa71c7aa4717
--- /dev/null
+++ b/products/slack_app/backend/logic/reply_suggestions.py
@@ -0,0 +1,288 @@
+"""One-click replies under an agent answer that asks the reader for a permission, a choice, or a next step."""
+
+import json
+from typing import Any
+
+from django.core.cache import cache
+
+import structlog
+from openai.types.shared_params import ResponseFormatJSONSchema
+from slack_sdk import WebClient
+
+from posthog.dataclasses import frozen
+from posthog.llm.gateway_client import build_openai_client
+from posthog.llm.semantic_enrichment import extract_json_object
+
+logger = structlog.get_logger(__name__)
+
+REPLY_SUGGESTION_ACTION_ID_PREFIX = "slack_app_reply_suggestion:"
+REPLY_SUGGESTIONS_BLOCK_ID = "slack_app_reply_suggestions"
+# Online evaluations scope to this call with `slack_app_classifier = reply_suggestions`.
+REPLY_SUGGESTIONS_CLASSIFIER = "reply_suggestions"
+
+# Only one message in a thread holds open buttons at a time. A newer message makes them stale.
+OPEN_SUGGESTIONS_TTL_SECONDS = 60 * 60 * 24 * 7
+
+MAX_SUGGESTIONS = 3
+# Slack rejects a button label or an accessibility label over 75 characters, and the whole message
+# goes down with it. Slack cuts a label well before that, so the prompt asks for a short one.
+MAX_LABEL_CHARS = 75
+MAX_REPLY_CHARS = 300
+
+SUGGESTIONS_MODEL = "gpt-5.6-luna"
+# A reasoning model spends its thinking and the JSON reply from one token budget.
+SUGGESTIONS_MAX_COMPLETION_TOKENS = 2048
+# The activity that delivers the answer is sync and runs once, so the call must end well inside it.
+SUGGESTIONS_TIMEOUT_SECONDS = 15.0
+SUGGESTIONS_MAX_RETRIES = 0
+# The question that asks for a reply is nearly always at the end of an answer.
+ANSWER_HEAD_CHARS = 1500
+ANSWER_TAIL_CHARS = 4500
+
+# The answer goes in its own message, so text in it cannot replace these instructions.
+REPLY_SUGGESTIONS_INSTRUCTIONS = """\
+You write reply buttons for a Slack thread. The PostHog agent posted the answer in the next message. \
+The person who reads it can send one of your replies with one click.
+
+First decide if the answer waits for the person. It does when it:
+- asks for permission, for example "Should I open a pull request?"
+- offers a next step, for example "I can also add tests for the empty case."
+- asks the person to choose between options or to confirm a plan.
+
+If the answer only reports a result, explains something, or asks nothing, return an empty list. \
+When you are not sure, return an empty list.
+
+If the answer waits for the person, write up to 3 replies that the person will most likely send:
+- Write each reply as the person, to the agent. For example "Yes, open the pull request", "Add the tests too", \
+"Use option 2".
+- Make each reply clear on its own. Write "Yes, open the pull request", not "Yes".
+- Offer only actions that the answer names or clearly implies. Do not invent new work.
+- If the answer asks for information that only the person knows, such as a name, a value or a repository, \
+do not guess it. Offer only the replies that are complete without it, or return an empty list.
+- Make each reply a different choice. Do not offer two replies that mean the same thing.
+- Put the most likely reply first.
+- Write in the language of the answer.
+- Do not write replies that only say thanks or close the conversation.
+
+Each suggestion has two parts:
+- "label": the button text. Keep it under 30 characters, because Slack cuts longer labels.
+- "reply": the full message the person sends to the agent. Keep it under 150 characters. \
+It must mean the same as the label and can add the detail the label leaves out.
+
+Answer only with JSON, for example \
+{"suggestions": [{"label": "Yes, open the PR", "reply": "Yes, open the pull request with the fix"}, \
+{"label": "No, keep it local", "reply": "No, keep the change local for now"}]}."""
+
+
+@frozen
+class ReplySuggestionAttribution:
+ trace_id: str | None = None
+ session_id: str | None = None
+ distinct_id: str | None = None
+ task_id: str | None = None
+ run_id: str | None = None
+
+
+@frozen
+class SuggestedReply:
+ label: str
+ reply: str
+
+
+@frozen
+class ClickedSuggestion:
+ integration_id: int
+ text: str
+ index: int
+ trace_id: str | None
+
+
+_RESPONSE_FORMAT: ResponseFormatJSONSchema = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "slack_app_reply_suggestions",
+ "strict": True,
+ "schema": {
+ "type": "object",
+ "properties": {
+ "suggestions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {"label": {"type": "string"}, "reply": {"type": "string"}},
+ "required": ["label", "reply"],
+ "additionalProperties": False,
+ },
+ }
+ },
+ "required": ["suggestions"],
+ "additionalProperties": False,
+ },
+ },
+}
+
+
+def _clip_answer(answer: str) -> str:
+ if len(answer) <= ANSWER_HEAD_CHARS + ANSWER_TAIL_CHARS:
+ return answer
+ return f"{answer[:ANSWER_HEAD_CHARS]}\n…\n{answer[-ANSWER_TAIL_CHARS:]}"
+
+
+def _clean_suggestions(raw: object) -> list[SuggestedReply]:
+ """A label Slack would reject is dropped, not cut, because a cut label can say something the reply does not."""
+ if not isinstance(raw, list):
+ return []
+ suggestions: list[SuggestedReply] = []
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ label = " ".join(str(item.get("label") or "").split())
+ reply = " ".join(str(item.get("reply") or "").split()) or label
+ if not label or len(label) > MAX_LABEL_CHARS or len(reply) > MAX_REPLY_CHARS:
+ continue
+ if any(s.label == label or s.reply == reply for s in suggestions):
+ continue
+ suggestions.append(SuggestedReply(label=label, reply=reply))
+ return suggestions[:MAX_SUGGESTIONS]
+
+
+def request_reply_suggestions(answer_markdown: str, attribution: ReplySuggestionAttribution) -> list[SuggestedReply]:
+ """Raises on a failed call, so the offline eval can tell a failure from an answer that asks nothing."""
+ if not answer_markdown.strip():
+ return []
+ properties = {"slack_app_classifier": REPLY_SUGGESTIONS_CLASSIFIER}
+ if attribution.task_id:
+ properties["task_id"] = attribution.task_id
+ if attribution.run_id:
+ properties["run_id"] = attribution.run_id
+ client = build_openai_client(
+ product="slack_app_routing",
+ ai_product="slack_app_routing",
+ trace_id=attribution.trace_id,
+ session_id=attribution.session_id,
+ distinct_id=attribution.distinct_id,
+ properties=properties,
+ ).with_options(timeout=SUGGESTIONS_TIMEOUT_SECONDS, max_retries=SUGGESTIONS_MAX_RETRIES)
+ extra: dict[str, Any] = {"user": attribution.distinct_id} if attribution.distinct_id else {}
+ response = client.chat.completions.create(
+ model=SUGGESTIONS_MODEL,
+ messages=[
+ {"role": "system", "content": REPLY_SUGGESTIONS_INSTRUCTIONS},
+ {"role": "user", "content": _clip_answer(answer_markdown)},
+ ],
+ max_completion_tokens=SUGGESTIONS_MAX_COMPLETION_TOKENS,
+ response_format=_RESPONSE_FORMAT,
+ **extra,
+ )
+ # Tolerant parse on top of the schema, because the gateway does not apply a response
+ # format the same way on every provider route.
+ parsed = extract_json_object(response.choices[0].message.content or "") or {}
+ return _clean_suggestions(parsed.get("suggestions"))
+
+
+def suggest_replies(answer_markdown: str, attribution: ReplySuggestionAttribution) -> list[SuggestedReply]:
+ """Any failure returns no replies: a missing button costs the reader one typed reply, and a
+ wrong one sends the agent an instruction nobody gave."""
+ try:
+ return request_reply_suggestions(answer_markdown, attribution)
+ except Exception:
+ logger.warning("slack_app_reply_suggestions_failed", exc_info=True)
+ return []
+
+
+def reply_suggestions_block(
+ integration_id: int, suggestions: list[SuggestedReply], trace_id: str | None
+) -> dict[str, Any]:
+ """The index is part of the action id, because Slack needs a unique one for each element in a block.
+
+ Slack has no tooltip on a button, so the full reply reaches only screen readers, through the
+ accessibility label. The value carries it too, because a click sends it. The integration in the
+ value lets the cross-region interactivity router claim the click.
+ """
+ return {
+ "type": "actions",
+ "block_id": REPLY_SUGGESTIONS_BLOCK_ID,
+ "elements": [
+ {
+ "type": "button",
+ "action_id": f"{REPLY_SUGGESTION_ACTION_ID_PREFIX}{index}",
+ "text": {"type": "plain_text", "text": suggestion.label, "emoji": True},
+ "accessibility_label": suggestion.reply[:MAX_LABEL_CHARS],
+ "value": json.dumps({"integration_id": integration_id, "trace_id": trace_id, "text": suggestion.reply}),
+ }
+ for index, suggestion in enumerate(suggestions)
+ ],
+ }
+
+
+def reply_suggestions_fallback_text(suggestions: list[SuggestedReply]) -> str:
+ return "Suggested replies: " + ", ".join(suggestion.label for suggestion in suggestions)
+
+
+def is_reply_suggestion_action(action_id: object) -> bool:
+ return isinstance(action_id, str) and action_id.startswith(REPLY_SUGGESTION_ACTION_ID_PREFIX)
+
+
+def clicked_suggestion(payload: dict) -> ClickedSuggestion | None:
+ action = next((a for a in payload.get("actions", []) if is_reply_suggestion_action(a.get("action_id"))), None)
+ if action is None:
+ return None
+ try:
+ value = json.loads(action.get("value") or "")
+ index = int(action["action_id"].removeprefix(REPLY_SUGGESTION_ACTION_ID_PREFIX))
+ except (json.JSONDecodeError, ValueError):
+ return None
+ if not isinstance(value, dict):
+ return None
+ integration_id = value.get("integration_id")
+ text = value.get("text")
+ trace_id = value.get("trace_id")
+ if not isinstance(integration_id, int) or not isinstance(text, str) or not text.strip():
+ return None
+ return ClickedSuggestion(
+ integration_id=integration_id,
+ text=text.strip(),
+ index=index,
+ trace_id=trace_id if isinstance(trace_id, str) else None,
+ )
+
+
+def _open_suggestions_key(integration_id: int, channel: str, thread_ts: str) -> str:
+ return f"slack_app_reply_suggestions_open:{integration_id}:{channel}:{thread_ts}"
+
+
+def remember_open_suggestions(integration_id: int, channel: str, thread_ts: str, message_ts: str) -> None:
+ cache.set(_open_suggestions_key(integration_id, channel, thread_ts), message_ts, OPEN_SUGGESTIONS_TTL_SECONDS)
+
+
+def clear_open_suggestions(client: WebClient, integration_id: int, channel: str, thread_ts: str) -> None:
+ """Remove buttons that a newer message in the thread made stale, so nobody answers an old question.
+
+ The message is read back from Slack because a streamed answer's blocks exist only there. Slack
+ can only replace a message whole, so it is sent back without the buttons, or deleted when the
+ buttons were all it held.
+ """
+ key = _open_suggestions_key(integration_id, channel, thread_ts)
+ message_ts = cache.get(key)
+ if not isinstance(message_ts, str):
+ return
+ cache.delete(key)
+ try:
+ response = client.conversations_replies(
+ channel=channel, ts=message_ts, oldest=message_ts, latest=message_ts, inclusive=True, limit=1
+ )
+ message = next((m for m in response.get("messages") or [] if m.get("ts") == message_ts), None)
+ if message is None:
+ return
+ blocks = message.get("blocks") or []
+ kept = [block for block in blocks if block.get("block_id") != REPLY_SUGGESTIONS_BLOCK_ID]
+ if len(kept) == len(blocks):
+ return
+ if kept:
+ client.chat_update(channel=channel, ts=message_ts, text=message.get("text") or "", blocks=kept)
+ else:
+ client.chat_delete(channel=channel, ts=message_ts)
+ except Exception:
+ logger.warning(
+ "slack_app_reply_suggestions_clear_failed", channel=channel, message_ts=message_ts, exc_info=True
+ )
diff --git a/products/slack_app/backend/services/slack_conversations.py b/products/slack_app/backend/services/slack_conversations.py
index f5f09b83f6ae..04a10eaf8fb1 100644
--- a/products/slack_app/backend/services/slack_conversations.py
+++ b/products/slack_app/backend/services/slack_conversations.py
@@ -90,3 +90,20 @@ def _channel_privacy_from_slack(
if "is_private" not in channel:
return ConversationType.UNKNOWN
return ConversationType.PRIVATE_CHANNEL if channel["is_private"] else ConversationType.PUBLIC_CHANNEL
+
+
+def channel_is_ext_shared(slack: SlackIntegration, channel: str) -> bool:
+ """Whether the channel is a Slack Connect channel.
+
+ Unlike events, interactivity payloads carry no ``is_ext_shared_channel`` on the
+ envelope, so this costs a ``conversations.info`` round trip. Fails closed: an
+ unreadable channel is treated as externally shared, which at worst asks the user
+ to approve a channel that did not need it.
+ """
+ try:
+ info = slack.client.conversations_info(channel=channel)
+ conversation: dict[str, Any] = info.get("channel") or {}
+ return bool(conversation.get("is_ext_shared") or conversation.get("is_pending_ext_shared"))
+ except Exception:
+ logger.warning("slack_app_channel_info_failed", channel=channel)
+ return True
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 141f9e4372e8..13f0d6bea0ac 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -2,6 +2,7 @@ import re
from collections.abc import Callable
from dataclasses import dataclass, replace
from enum import StrEnum
+from functools import cached_property
from typing import TYPE_CHECKING, Any
from uuid import UUID
@@ -9,11 +10,24 @@ import structlog
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
+from posthog.dataclasses import frozen
from posthog.models.integration import Integration, SlackIntegration
from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
from products.slack_app.backend.analytics import capture_slack_event, slack_session_id
-from products.slack_app.backend.feature_flags import is_slack_app_forking_enabled
+from products.slack_app.backend.feature_flags import (
+ is_slack_app_forking_enabled,
+ is_slack_app_reply_suggestions_enabled,
+)
+from products.slack_app.backend.logic.reply_suggestions import (
+ ReplySuggestionAttribution,
+ SuggestedReply,
+ clear_open_suggestions,
+ remember_open_suggestions,
+ reply_suggestions_block,
+ reply_suggestions_fallback_text,
+ suggest_replies,
+)
from products.slack_app.backend.services.slack_messages import (
RunFooter,
app_home_url,
@@ -33,6 +47,8 @@ from products.slack_app.backend.services.slack_messages import (
)
if TYPE_CHECKING:
+ from posthog.models.user import User
+
from products.slack_app.backend.models import SlackThreadTaskMapping
logger = structlog.get_logger(__name__)
@@ -194,6 +210,20 @@ class SlackThreadContext:
)
+def _response_ts(response: Any) -> str | None:
+ ts = response.get("ts") if response is not None else None
+ return ts if isinstance(ts, str) else None
+
+
+@frozen
+class _PostedAnswer:
+ """The last message of a plain answer, kept so the reply buttons can join it after it is posted."""
+
+ ts: str
+ text: str
+ blocks: list[dict[str, Any]]
+
+
def _pr_buttons(pr_url: str, task_url: str | None) -> list[dict[str, Any]]:
buttons: list[dict[str, Any]] = [
{
@@ -235,6 +265,7 @@ class SlackThreadHandler:
self._client: WebClient | None = None
self._bot_user_id: str | None = None
self._fork_flag: bool | None = None
+ self._last_answer: _PostedAnswer | None = None
self.stream_ended = False
@classmethod
@@ -479,6 +510,7 @@ class SlackThreadHandler:
plan_title: str | None = None,
append_attachments: Callable[[], None] | None = None,
mention_sent: bool = False,
+ reply_suggestions_for: str | None = None,
) -> None:
"""Final flush: mark the last plan-block step complete, stream the answer, then chat.stopStream.
@@ -502,9 +534,15 @@ class SlackThreadHandler:
if self.stream_ended:
if final_markdown:
answer_delivered = self._post_answer_outside_stream(final_markdown)
+ if answer_delivered:
+ self.offer_reply_suggestions(reply_suggestions_for)
else:
self._close_stream(
- ts, final_markdown=final_markdown, mention_sent=mention_sent, append_attachments=append_attachments
+ ts,
+ final_markdown=final_markdown,
+ mention_sent=mention_sent,
+ append_attachments=append_attachments,
+ reply_suggestions_for=reply_suggestions_for if answer_delivered else None,
)
# A turn stopped before it answered still closes its stream, which then holds only status lines.
if final_markdown or mention_sent:
@@ -517,12 +555,14 @@ class SlackThreadHandler:
final_markdown: str | None,
mention_sent: bool,
append_attachments: Callable[[], None] | None,
+ reply_suggestions_for: str | None = None,
) -> None:
if append_attachments is not None:
try:
append_attachments()
except Exception as e:
logger.warning("slack_app_status_stream_attachments_failed", error=str(e))
+ placed = self._append_reply_suggestions(ts, reply_suggestions_for) if reply_suggestions_for else []
final_chunks: list[dict[str, Any]] = []
recipient = self.actor_slack_user_id
@@ -536,6 +576,8 @@ class SlackThreadHandler:
if footer:
self._append_trailing_blocks(ts)
self._stop_stream(ts)
+ if placed:
+ self._record_suggestions_placed(ts, placed, placement="answer")
def _stop_stream(self, ts: str) -> None:
if self.stream_ended:
@@ -799,7 +841,11 @@ class SlackThreadHandler:
footer = self._footer_block() if with_footer and fits_in_a_block else None
blocks = self._answer_blocks(text, footer, markdown=markdown)
try:
- return self._post_in_thread(text=text, blocks=blocks) is not None
+ response = self._post_in_thread(text=text, blocks=blocks)
+ ts = _response_ts(response)
+ if footer and blocks and ts:
+ self._last_answer = _PostedAnswer(ts=ts, text=text, blocks=blocks)
+ return response is not None
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.
@@ -922,6 +968,105 @@ class SlackThreadHandler:
logger.exception("slack_completion_post_failed", error=str(e))
return False
+ def _session_id(self) -> str:
+ return slack_session_id(self._get_integration().integration_id, self.context.channel, self.context.thread_ts)
+
+ @cached_property
+ def _actor_posthog_user(self) -> "User | None":
+ # Deferred: api.py imports the temporal.ai workflows, which this module's importers do not otherwise load.
+ from products.slack_app.backend.api import resolve_posthog_user_from_event # noqa: PLC0415
+
+ if not self.actor_slack_user_id:
+ return None
+ integration = self._get_integration()
+ try:
+ return resolve_posthog_user_from_event(
+ slack_user_id=self.actor_slack_user_id,
+ probe_integration=integration,
+ candidate_integrations=[integration],
+ )
+ except Exception:
+ logger.warning("slack_app_actor_lookup_failed", exc_info=True)
+ return None
+
+ def _suggestions_block(self, answer_markdown: str) -> tuple[list[SuggestedReply], dict[str, Any]] | None:
+ integration = self._get_integration()
+ if not is_slack_app_reply_suggestions_enabled(integration):
+ return None
+ posthog_user = self._actor_posthog_user
+ attribution = ReplySuggestionAttribution(
+ trace_id=self.turn_trace_id,
+ session_id=self._session_id(),
+ distinct_id=posthog_user.distinct_id if posthog_user else None,
+ task_id=self.run_footer.task_id,
+ run_id=self.run_footer.run_id,
+ )
+ suggestions = suggest_replies(answer_markdown, attribution)
+ if not suggestions:
+ return None
+ return suggestions, reply_suggestions_block(integration.id, suggestions, self.turn_trace_id)
+
+ def _append_reply_suggestions(self, ts: str, answer_markdown: str) -> list[SuggestedReply]:
+ """Add the buttons to an open stream, under the answer and its attachments and above the footer."""
+ offered = self._suggestions_block(answer_markdown)
+ if offered is None:
+ return []
+ suggestions, block = offered
+ # An append of its own, so a block Slack rejects costs the buttons alone, never the footer.
+ appended = self._append_chunks(
+ ts, [{"type": "blocks", "blocks": [block]}], "slack_app_reply_suggestions_append_failed"
+ )
+ return suggestions if appended else []
+
+ def offer_reply_suggestions(self, answer_markdown: str | None) -> None:
+ """Add the buttons to the answer's last message, right under the answer text.
+
+ They post as a message of their own only when the answer has no message to extend:
+ a plain-text answer with no blocks, or an answer composed with chart cards.
+ """
+ offered = self._suggestions_block(answer_markdown) if answer_markdown else None
+ if offered is None:
+ return
+ suggestions, block = offered
+ answer = self._last_answer
+ if answer is not None:
+ try:
+ self._get_client().chat_update(
+ channel=self.context.channel,
+ ts=answer.ts,
+ text=answer.text,
+ blocks=[answer.blocks[0], block, *answer.blocks[1:]],
+ )
+ self._record_suggestions_placed(answer.ts, suggestions, placement="answer")
+ return
+ except Exception as e:
+ logger.warning("slack_app_reply_suggestions_update_failed", error=str(e))
+ try:
+ response = self._post_in_thread(text=reply_suggestions_fallback_text(suggestions), blocks=[block])
+ except Exception as e:
+ logger.warning("slack_app_reply_suggestions_post_failed", error=str(e))
+ return
+ ts = _response_ts(response)
+ if ts:
+ self._record_suggestions_placed(ts, suggestions, placement="separate")
+
+ def _record_suggestions_placed(self, message_ts: str, suggestions: list[SuggestedReply], *, placement: str) -> None:
+ integration = self._get_integration()
+ clear_open_suggestions(self._get_client(), integration.id, self.context.channel, self.context.thread_ts)
+ remember_open_suggestions(integration.id, self.context.channel, self.context.thread_ts, message_ts)
+ capture_slack_event(
+ integration,
+ "slack app reply suggestions posted",
+ slack_user_id=self.actor_slack_user_id,
+ posthog_user=self._actor_posthog_user,
+ suggestion_count=len(suggestions),
+ placement=placement,
+ slack_session_id=self._session_id(),
+ ai_trace_id=self.turn_trace_id,
+ task_id=self.run_footer.task_id,
+ run_id=self.run_footer.run_id,
+ )
+
def capture_reply_posted(self, reply_kind: ReplyKind, *, delivered: bool) -> None:
"""Capture a reply the run posted to this thread, so a mention can be followed to its answer.
@@ -929,26 +1074,15 @@ class SlackThreadHandler:
is the join between the two events. The reader is resolved the way the mention event resolves
it, so both events land on the same person.
"""
- # Deferred: api.py imports the temporal.ai workflows, which this module's importers do not otherwise load.
- from products.slack_app.backend.api import resolve_posthog_user_from_event # noqa: PLC0415
-
try:
- integration = self._get_integration()
- actor = self.actor_slack_user_id
capture_slack_event(
- integration,
+ self._get_integration(),
"slack app reply posted",
- slack_user_id=actor,
- posthog_user=resolve_posthog_user_from_event(
- slack_user_id=actor, probe_integration=integration, candidate_integrations=[integration]
- )
- if actor
- else None,
+ slack_user_id=self.actor_slack_user_id,
+ posthog_user=self._actor_posthog_user,
reply_kind=str(reply_kind),
delivered=delivered,
- slack_session_id=slack_session_id(
- integration.integration_id, self.context.channel, self.context.thread_ts
- ),
+ slack_session_id=self._session_id(),
task_id=self.run_footer.task_id,
run_id=self.run_footer.run_id,
)
diff --git a/products/slack_app/backend/tests/test_reply_suggestions.py b/products/slack_app/backend/tests/test_reply_suggestions.py
new file mode 100644
index 000000000000..c20c076c9a74
--- /dev/null
+++ b/products/slack_app/backend/tests/test_reply_suggestions.py
@@ -0,0 +1,318 @@
+import json
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase, TestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework.test import APIClient
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.slack_app.backend.logic.reply_suggestions import (
+ REPLY_SUGGESTIONS_BLOCK_ID,
+ ReplySuggestionAttribution,
+ SuggestedReply,
+ clear_open_suggestions,
+ remember_open_suggestions,
+ reply_suggestions_block,
+ suggest_replies,
+)
+from products.slack_app.backend.services.slack_messages import RunFooter
+from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
+from products.slack_app.backend.tests.helpers import sign_slack_request
+
+ANSWER_BLOCK = {"type": "markdown", "text": "Should I open a pull request?"}
+FOOTER_BLOCK = {"type": "context", "elements": [{"type": "mrkdwn", "text": "Claude Opus 5"}]}
+OPEN_PR = SuggestedReply(label="Yes, open the PR", reply="Yes, open the pull request with the fix")
+KEEP_LOCAL = SuggestedReply(label="No, keep it local", reply="No, keep the change local for now")
+
+
+def _suggestion(label: str, reply: str) -> dict[str, str]:
+ return {"label": label, "reply": reply}
+
+
+def _completion(content: str) -> MagicMock:
+ response = MagicMock()
+ response.choices = [MagicMock(message=MagicMock(content=content))]
+ return response
+
+
+class TestSuggestReplies(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "keeps_order_and_caps_count",
+ json.dumps(
+ {
+ "suggestions": [
+ _suggestion(OPEN_PR.label, OPEN_PR.reply),
+ _suggestion(KEEP_LOCAL.label, KEEP_LOCAL.reply),
+ _suggestion("Add tests", "Add tests for the empty case too"),
+ _suggestion("Use option 2", "Use option 2"),
+ ]
+ }
+ ),
+ [OPEN_PR, KEEP_LOCAL, SuggestedReply(label="Add tests", reply="Add tests for the empty case too")],
+ ),
+ (
+ # Slack rejects the whole message for one label over 75 characters.
+ "drops_overlong_and_duplicate_labels",
+ json.dumps(
+ {
+ "suggestions": [
+ _suggestion("x" * 76, "x"),
+ _suggestion(OPEN_PR.label, OPEN_PR.reply),
+ _suggestion("Yes, open the PR", "Yes, open it"),
+ _suggestion("", "No label"),
+ ]
+ }
+ ),
+ [OPEN_PR],
+ ),
+ (
+ "a_missing_reply_sends_the_label",
+ json.dumps({"suggestions": [_suggestion("Use option 2", "")]}),
+ [SuggestedReply(label="Use option 2", reply="Use option 2")],
+ ),
+ ("answer_asks_nothing", json.dumps({"suggestions": []}), []),
+ ("prose_instead_of_json", "Sure, here are some ideas", []),
+ ("wrong_shape", json.dumps({"suggestions": "Yes"}), []),
+ ]
+ )
+ def test_suggestions_from_model_reply(self, _name: str, content: str, expected: list[SuggestedReply]) -> None:
+ with patch("products.slack_app.backend.logic.reply_suggestions.build_openai_client") as build:
+ build.return_value.with_options.return_value.chat.completions.create.return_value = _completion(content)
+ assert suggest_replies("Should I open a PR?", ReplySuggestionAttribution()) == expected
+
+ def test_generation_carries_what_online_evaluations_scope_and_join_on(self) -> None:
+ attribution = ReplySuggestionAttribution(
+ trace_id="trace-1", session_id="T1:C1:1.0", distinct_id="user-1", task_id="task-1", run_id="run-1"
+ )
+ with patch("products.slack_app.backend.logic.reply_suggestions.build_openai_client") as build:
+ build.return_value.with_options.return_value.chat.completions.create.return_value = _completion(
+ json.dumps({"suggestions": []})
+ )
+ suggest_replies("Should I open a PR?", attribution)
+
+ assert build.call_args.kwargs == {
+ "product": "slack_app_routing",
+ "ai_product": "slack_app_routing",
+ "trace_id": "trace-1",
+ "session_id": "T1:C1:1.0",
+ "distinct_id": "user-1",
+ "properties": {"slack_app_classifier": "reply_suggestions", "task_id": "task-1", "run_id": "run-1"},
+ }
+ create = build.return_value.with_options.return_value.chat.completions.create
+ assert create.call_args.kwargs["user"] == "user-1"
+
+ def test_model_failure_offers_nothing(self) -> None:
+ with patch("products.slack_app.backend.logic.reply_suggestions.build_openai_client") as build:
+ build.return_value.with_options.return_value.chat.completions.create.side_effect = TimeoutError()
+ assert suggest_replies("Should I open a PR?", ReplySuggestionAttribution()) == []
+
+
+@override_settings(DEBUG=True)
+@patch("products.slack_app.backend.api.SlackIntegration")
+class TestReplySuggestionClick(TestCase):
+ signing_secret = "posthog-code-test-secret"
+ slack_team_id = "T12345"
+ channel = "C001"
+ thread_ts = "1000.0000"
+ message_ts = "1005.0000"
+
+ def setUp(self) -> None:
+ cache.clear()
+ self.client = APIClient()
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.member_user = User.objects.create(email="[email protected]", distinct_id="user-member")
+ OrganizationMembership.objects.create(user=self.member_user, organization=self.organization)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id=self.slack_team_id,
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ def _click(self, slack_user_id: str, index: int = 0) -> Any:
+ block = reply_suggestions_block(self.integration.id, [OPEN_PR, KEEP_LOCAL], "trace-1")
+ action = block["elements"][index]
+ payload = {
+ "type": "block_actions",
+ "team": {"id": self.slack_team_id},
+ "user": {"id": slack_user_id},
+ "container": {
+ "type": "message",
+ "channel_id": self.channel,
+ "message_ts": self.message_ts,
+ "thread_ts": self.thread_ts,
+ },
+ "message": {
+ "ts": self.message_ts,
+ "thread_ts": self.thread_ts,
+ "text": "Should I open a pull request?",
+ "blocks": [ANSWER_BLOCK, block, FOOTER_BLOCK],
+ },
+ "actions": [{"action_id": action["action_id"], "block_id": block["block_id"], "value": action["value"]}],
+ }
+ body_str = f"payload={json.dumps(payload)}"
+ signed = sign_slack_request(body_str.encode(), self.signing_secret)
+ return self.client.post(
+ "/slack/interactivity-callback/",
+ data=body_str,
+ content_type="application/x-www-form-urlencoded",
+ headers={"x-slack-signature": signed.signature, "x-slack-request-timestamp": signed.timestamp},
+ )
+
+ def _as_slack_user(self, email: str) -> Any:
+ return patch(
+ "products.slack_app.backend.api.get_slack_user_info",
+ return_value={"user": {"profile": {"email": email}}},
+ )
+
+ def test_click_sends_the_reply_to_the_agent_once(self, mock_slack_cls: MagicMock) -> None:
+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ slack_client = mock_slack_cls.return_value.client
+ slack_client.conversations_info.return_value = {"channel": {"is_ext_shared": False}}
+ slack_client.chat_postMessage.return_value = {"ts": "1006.0000"}
+
+ with (
+ self._as_slack_user(self.member_user.email),
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ patch("products.slack_app.backend.api.capture_slack_event") as mock_capture,
+ ):
+ first = self._click("U_BOB", index=1)
+ second = self._click("U_CAROL", index=0)
+
+ assert first.status_code == second.status_code == 200
+ mock_start.assert_called_once()
+ assert mock_start.call_args.args[0] == {
+ "type": "message",
+ "user": "U_BOB",
+ "channel": self.channel,
+ "ts": "1006.0000",
+ "thread_ts": self.thread_ts,
+ "text": KEEP_LOCAL.reply,
+ }
+ # Without both, the click would face the classifier or start a new task in a thread with none.
+ assert mock_start.call_args.kwargs["untagged_followup"] is True
+ assert mock_start.call_args.kwargs["untagged_followup_confirmed"] is True
+ # The trace id joins the click to the generation that suggested it.
+ mock_capture.assert_called_once()
+ assert mock_capture.call_args.kwargs["ai_trace_id"] == "trace-1"
+ # The reply is its own message in the thread, carrying the full text the label stood for.
+ posted = slack_client.chat_postMessage.call_args.kwargs
+ assert posted["thread_ts"] == self.thread_ts
+ assert KEEP_LOCAL.reply in posted["text"]
+
+ @parameterized.expand(
+ [
+ ("someone_outside_the_project", "[email protected]", False),
+ # A typed reply here is dropped, so a click must not become the way around the approval.
+ ("unapproved_slack_connect_channel", "[email protected]", True),
+ ]
+ )
+ def test_click_that_must_not_reach_the_agent(
+ self, mock_slack_cls: MagicMock, _name: str, email: str, ext_shared: bool
+ ) -> None:
+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ slack_client = mock_slack_cls.return_value.client
+ slack_client.conversations_info.return_value = {"channel": {"is_ext_shared": ext_shared}}
+
+ with (
+ self._as_slack_user(email),
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ response = self._click("U_CLICKER")
+
+ assert response.status_code == 200
+ mock_start.assert_not_called()
+ slack_client.chat_postMessage.assert_not_called()
+ slack_client.chat_postEphemeral.assert_called_once()
+
+ def test_a_failed_dispatch_leaves_the_buttons_usable(self, mock_slack_cls: MagicMock) -> None:
+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ slack_client = mock_slack_cls.return_value.client
+ slack_client.conversations_info.return_value = {"channel": {"is_ext_shared": False}}
+ slack_client.chat_postMessage.return_value = {"ts": "1006.0000"}
+
+ with (
+ self._as_slack_user(self.member_user.email),
+ patch(
+ "products.slack_app.backend.api._start_mention_workflow", side_effect=[RuntimeError("temporal"), None]
+ ) as mock_start,
+ ):
+ with self.assertRaises(RuntimeError):
+ self._click("U_BOB")
+ self._click("U_BOB")
+
+ assert mock_start.call_count == 2
+ # The reply that never reached the agent does not stay in the thread.
+ slack_client.chat_delete.assert_called_once_with(channel=self.channel, ts="1006.0000")
+
+
+class TestReplySuggestionPlacement(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ @patch("products.slack_app.backend.slack_thread.capture_slack_event")
+ @patch("products.slack_app.backend.slack_thread.suggest_replies", return_value=[OPEN_PR])
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_reply_suggestions_enabled", return_value=True)
+ @patch.object(SlackThreadHandler, "_actor_posthog_user", None)
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_plain_answer_gets_the_buttons_under_its_text(
+ self, mock_get_client, mock_get_integration, *_mocks: MagicMock
+ ) -> None:
+ mock_client = MagicMock()
+ mock_client.chat_postMessage.return_value = {"ts": "2.0"}
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(id=7, config={}, integration_id="T1")
+ handler = SlackThreadHandler(
+ SlackThreadContext(integration_id=7, channel="C001", thread_ts="1.0"), RunFooter(model="claude-opus-5")
+ )
+
+ handler.post_thread_message("Should I open a pull request?", with_footer=True, markdown=True)
+ handler.offer_reply_suggestions("Should I open a pull request?")
+
+ posted = mock_client.chat_postMessage.call_args.kwargs["blocks"]
+ mock_client.chat_postMessage.assert_called_once()
+ update = mock_client.chat_update.call_args.kwargs
+ assert update["ts"] == "2.0"
+ assert update["blocks"][0] == posted[0]
+ assert update["blocks"][1]["block_id"] == REPLY_SUGGESTIONS_BLOCK_ID
+ assert update["blocks"][2:] == posted[1:]
+
+
+class TestClearOpenSuggestions(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ @parameterized.expand(
+ [
+ ("buttons_in_the_answer", [ANSWER_BLOCK, "buttons", FOOTER_BLOCK], [ANSWER_BLOCK, FOOTER_BLOCK]),
+ ("buttons_alone", ["buttons"], None),
+ ]
+ )
+ def test_a_newer_message_removes_only_the_buttons(self, _name: str, blocks: list, kept: list | None) -> None:
+ buttons = reply_suggestions_block(7, [OPEN_PR], None)
+ message = {"ts": "2.0", "text": "answer", "blocks": [buttons if b == "buttons" else b for b in blocks]}
+ client = MagicMock()
+ client.conversations_replies.return_value = {"messages": [message]}
+ remember_open_suggestions(7, "C001", "1.0", "2.0")
+
+ clear_open_suggestions(client, 7, "C001", "1.0")
+ clear_open_suggestions(client, 7, "C001", "1.0")
+
+ client.conversations_replies.assert_called_once()
+ if kept is None:
+ client.chat_delete.assert_called_once_with(channel="C001", ts="2.0")
+ client.chat_update.assert_not_called()
+ else:
+ client.chat_update.assert_called_once_with(channel="C001", ts="2.0", text="answer", blocks=kept)
diff --git a/products/slack_app/evals/eval_reply_suggestions.py b/products/slack_app/evals/eval_reply_suggestions.py
new file mode 100644
index 000000000000..7cffe192a852
--- /dev/null
+++ b/products/slack_app/evals/eval_reply_suggestions.py
@@ -0,0 +1,167 @@
+"""Which agent answers get one-click reply buttons, and are the buttons ones a person would press?
+
+Each case prompt is the agent's answer, not a user request. Watch `no_unasked_buttons` first,
+for the reason `suggest_replies` gives, then `reply_offer`, then `suggested_replies_fit`.
+
+To run:
+ hogli evals eval_reply_suggestions
+ hogli evals eval_reply_suggestions --eval rhetorical_question
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from products.posthog_ai.eval_harness.config import BaseEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind
+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval
+from products.slack_app.backend.logic import reply_suggestions
+from products.slack_app.evals.scorers import REPLY_OFFER_KEY, NoUnaskedButtons, ReplyOfferMatch, SuggestedRepliesFit
+
+SUITE_KIND = SuiteKind.ONE_SHOT
+
+
+def _offer(offer: bool) -> dict:
+ return {REPLY_OFFER_KEY: {"offer": offer}}
+
+
+# Longer than the clip window, with the question only in the tail.
+_MIGRATION_STEP = (
+ "Step {n}: the backfill reads one day of `signed_up` events, writes them to the new table, "
+ "and checks that the row counts match before it moves on. A mismatch stops the run and "
+ "logs the day, so a rerun starts from that day and not from the beginning.\n\n"
+)
+LONG_ANSWER = (
+ "I wrote the plan for the backfill. It runs one day at a time:\n\n"
+ + "".join(_MIGRATION_STEP.format(n=n) for n in range(1, 31))
+ + "The whole run takes about two hours. Should I start it now, or wait until tonight?"
+)
+
+WAITING_CASES = [
+ BaseEvalCase(
+ name="permission_to_open_pr",
+ prompt=(
+ "I found the cause. The retry loop resets its counter on every attempt, so it never stops "
+ "after a failure. The fix is two lines in `relay.py`. Should I open a pull request with it?"
+ ),
+ expected=_offer(True),
+ ),
+ BaseEvalCase(
+ name="choice_between_options",
+ prompt=(
+ "Here are two layouts for the pricing table:\n\n"
+ "1. **Plans as columns**: easy to compare, but tight on small screens.\n"
+ "2. **Plans as cards**: roomier, but the features do not line up.\n\n"
+ "Which one do you want?"
+ ),
+ expected=_offer(True),
+ ),
+ BaseEvalCase(
+ name="offer_of_a_next_step",
+ prompt=(
+ "Signups went up 12% last week compared to the week before. Most of the rise came on Tuesday. "
+ "I can break this down by acquisition source if that helps."
+ ),
+ expected=_offer(True),
+ ),
+ BaseEvalCase(
+ name="plan_to_confirm",
+ prompt=(
+ "Here is my plan:\n\n"
+ "1. Add a `retries` column to the export table.\n"
+ "2. Retry a failed export up to three times.\n"
+ "3. Alert the owner after the third failure.\n\n"
+ "Does this plan look right before I start?"
+ ),
+ expected=_offer(True),
+ ),
+ BaseEvalCase(
+ name="question_after_a_long_answer",
+ prompt=LONG_ANSWER,
+ expected=_offer(True),
+ ),
+ # One option is complete, the other needs a name only the person knows, so its buttons
+ # must not guess the name or say the same thing twice.
+ BaseEvalCase(
+ name="open_question_beside_a_choice",
+ prompt=(
+ "The `orders` table has no rows, so I can't count last month's revenue. "
+ "Is there another table I should use, or should I help you connect your Stripe source first?"
+ ),
+ expected=_offer(True),
+ ),
+ BaseEvalCase(
+ name="permission_in_german",
+ prompt=(
+ "Ich habe den Fehler gefunden: Der Export bricht ab, wenn eine Datei leer ist. "
+ "Soll ich den Fix als Pull Request öffnen?"
+ ),
+ expected=_offer(True),
+ ),
+]
+
+# Each one is a lure: a question mark, a polite invitation, or a request only the person can fill.
+BARE_CASES = [
+ BaseEvalCase(
+ name="plain_result",
+ prompt="There were 4,212 pageviews yesterday, about the same as the day before.",
+ expected=_offer(False),
+ ),
+ BaseEvalCase(
+ name="explanation",
+ prompt=(
+ "The `beta-dashboards` flag turns on the new dashboard layout. It is on for 20% of users "
+ "in the Hedgebox organization, and the rollout has not changed since last month."
+ ),
+ expected=_offer(False),
+ ),
+ BaseEvalCase(
+ name="work_reported_done",
+ prompt="I opened the pull request: https://github.com/example/app/pull/42. CI is running now.",
+ expected=_offer(False),
+ ),
+ BaseEvalCase(
+ name="rhetorical_question",
+ prompt=(
+ "Why did the nightly export fail? The bucket policy blocked the write. "
+ "I updated the policy and ran the export again, and it finished."
+ ),
+ expected=_offer(False),
+ ),
+ BaseEvalCase(
+ name="polite_sign_off",
+ prompt="Done. The alert now fires at 5% instead of 10%. Let me know if you need anything else.",
+ expected=_offer(False),
+ ),
+ # Only the person can answer this, and a button would have to guess the repository.
+ BaseEvalCase(
+ name="asks_for_a_value_only_the_person_knows",
+ prompt="I couldn't find the export settings in any connected repository. Which repository are they in?",
+ expected=_offer(False),
+ ),
+]
+
+
+async def eval_reply_suggestions(ctx: EvalContext) -> None:
+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
+ model = reply_suggestions.SUGGESTIONS_MODEL
+ try:
+ # Sync and blocking on the gateway, so off the event loop to keep cases concurrent.
+ suggestions = await asyncio.to_thread(
+ reply_suggestions.request_reply_suggestions,
+ case.prompt,
+ reply_suggestions.ReplySuggestionAttribution(),
+ )
+ except Exception as error:
+ return {"model": model, "suggestions": None, "error": f"{type(error).__name__}: {error}"}
+ offered = [{"label": s.label, "reply": s.reply} for s in suggestions]
+ return {"model": model, "suggestions": offered, "last_message": f"{model}: {offered}"}
+
+ await OneShotPublicEval(
+ experiment_name="slack-app-reply-suggestions",
+ cases=[*WAITING_CASES, *BARE_CASES],
+ scorers=[ReplyOfferMatch(), NoUnaskedButtons(), SuggestedRepliesFit()],
+ task=task,
+ ctx=ctx,
+ )
diff --git a/products/slack_app/evals/scorers.py b/products/slack_app/evals/scorers.py
index 944f01b2d04f..e2533bcde4f7 100644
--- a/products/slack_app/evals/scorers.py
+++ b/products/slack_app/evals/scorers.py
@@ -349,3 +349,103 @@ class NoUnaskedWake(Scorer):
score=0.0 if (output or {}).get("agent_directed") else 1.0,
metadata={"actual": (output or {}).get("agent_directed")},
)
+
+
+# ---------------------------------------------------------------------------
+# Reply suggestions
+# ---------------------------------------------------------------------------
+
+REPLY_OFFER_KEY = "reply_offer"
+
+
+class ReplyOfferMatch(Scorer):
+ """Did buttons appear exactly when the answer waits for the reader?"""
+
+ def _name(self) -> str:
+ return REPLY_OFFER_KEY
+
+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:
+ want = (expected or {}).get(REPLY_OFFER_KEY) or {}
+ if "offer" not in want:
+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})
+ if output and output.get("error"):
+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})
+
+ suggestions = (output or {}).get("suggestions") or []
+ return Score(
+ name=self._name(),
+ score=1.0 if bool(suggestions) == want["offer"] else 0.0,
+ metadata={"expected_offer": want["offer"], "suggestions": suggestions},
+ )
+
+
+class NoUnaskedButtons(Scorer):
+ """Buttons under an answer that asks nothing. Skips cases that wait for the reader, so the score is a rate."""
+
+ def _name(self) -> str:
+ return "no_unasked_buttons"
+
+ def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:
+ want = (expected or {}).get(REPLY_OFFER_KEY) or {}
+ if want.get("offer", True):
+ return Score(name=self._name(), score=None, metadata={"reason": "Case waits for the reader"})
+ if output and output.get("error"):
+ # A failed call offers nothing, this scorer's passing answer.
+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})
+
+ suggestions = (output or {}).get("suggestions") or []
+ return Score(name=self._name(), score=0.0 if suggestions else 1.0, metadata={"suggestions": suggestions})
+
+
+class SuggestedRepliesFit(JudgedScorer):
+ """Binary: would the reader send every offered reply as it is?
+
+ Grades only cases that offered replies; ``reply_offer`` already scores a missing offer.
+ """
+
+ def _prepare(self, output, expected) -> dict[str, Any] | Score:
+ want = (expected or {}).get(REPLY_OFFER_KEY) or {}
+ if not want.get("offer"):
+ return Score(name=self._name(), score=None, metadata={"reason": "Case expects no replies"})
+ suggestions = (output or {}).get("suggestions") or []
+ if not suggestions:
+ return Score(name=self._name(), score=None, metadata={"reason": "No replies to grade"})
+ return {
+ "output": {
+ "answer": (output or {}).get("prompt", ""),
+ "replies": "\n".join(f'- button "{s["label"]}" sends "{s["reply"]}"' for s in suggestions),
+ }
+ }
+
+ def __init__(self, **kwargs):
+ super().__init__(
+ name="suggested_replies_fit",
+ prompt_template="""
+You are evaluating reply buttons in a Slack thread. The PostHog agent posted the answer below. A person who reads it can send one of the replies to the agent with one click.
+
+Agent's answer:
+<answer>
+{{output.answer}}
+</answer>
+
+Offered replies:
+<replies>
+{{output.replies}}
+</replies>
+
+Each reply has a short button label and the full text the button sends. Every reply must:
+- have a label that means the same as the text it sends
+- be written by the person, to the agent, as their next message in the thread
+- make sense on its own, without the person typing more
+- ask only for actions the answer names or clearly implies
+- not guess information the answer asks the person for, such as a name, a value or a repository
+- be in the same language as the answer
+- mean something different from every other reply
+
+Answer `yes` if every reply follows all of these rules. Answer `no` if one reply breaks one rule.
+""".strip(),
+ choice_scores=BINARY_CHOICE_SCORES,
+ model=JUDGE_MODEL,
+ max_completion_tokens=256,
+ **kwargs,
+ )
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 032108bb937e..b4854de0099a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5859,6 +5859,7 @@ def relay_task_run_message(
delete_progress=True,
message_id=message_id,
trace_id=trace_id,
+ offer_reply_suggestions=True,
)
except Exception:
logger.exception("task_run_relay_message_enqueue_failed", extra={"run_id": str(run.id)})
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 40476dc2665c..77b975cf3f87 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -678,6 +678,7 @@ def execute_posthog_code_agent_relay_workflow(
reaction_emoji: str | None = None,
message_id: str | None = None,
trace_id: str | None = None,
+ offer_reply_suggestions: bool = False,
) -> str:
relay_id = relay_id or str(uuid.uuid4())
workflow_id = f"posthog-code-agent-relay-{run_id}-{relay_id}"
@@ -695,6 +696,7 @@ def execute_posthog_code_agent_relay_workflow(
reaction_emoji=reaction_emoji,
message_id=message_id,
trace_id=trace_id,
+ offer_reply_suggestions=offer_reply_suggestions,
),
id=workflow_id,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index feb21886d7e2..81a4f775bb87 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -257,6 +257,7 @@ def _enqueue_pending_reply_relay(task_run: Any, user_message_ts: str | None, com
reply_text = _extract_assistant_text_from_command_result(
command_result_data
) or _extract_recent_assistant_text_from_logs(task_run)
+ is_agent_answer = bool(reply_text)
if not reply_text and _has_recent_question_tool_failure(task_run):
reply_text = "I need clarification before continuing. Please reply in this thread with your preferred option."
@@ -270,6 +271,7 @@ def _enqueue_pending_reply_relay(task_run: Any, user_message_ts: str | None, com
text=reply_text,
user_message_ts=user_message_ts,
trace_id=_extract_trace_id_from_command_result(command_result_data),
+ offer_reply_suggestions=is_agent_answer,
)
except Exception:
logger.exception("forward_pending_message_relay_enqueue_failed", run_id=str(task_run.id))
diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
index 672a9aaf3231..2b89944b63d4 100644
--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
@@ -73,6 +73,9 @@ class StopSlackAgentDesignStreamInput:
# The stream opened with the answer, which already carried the @-mention.
mention_sent: bool = False
actor_slack_user_id: Optional[str] = None
+ # The turn's whole answer, which `final_markdown` omits when the stream opened with it. Set only
+ # for a finished turn, because a stopped turn waits for nothing from the reader.
+ answer_markdown: Optional[str] = None
def _rewrite_object_tags(text: Optional[str], project_url: str) -> Optional[str]:
@@ -189,6 +192,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> No
plan_title=input.plan_title,
append_attachments=_append_attachments,
mention_sent=input.mention_sent,
+ reply_suggestions_for=input.answer_markdown,
)
for delivery in deliveries:
if task_run is not None:
diff --git a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
index e21f5675c2e3..95641a9df2b5 100644
--- a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
@@ -482,6 +482,7 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):
plan_title=self._closing_plan_title(),
mention_sent=mention_sent,
actor_slack_user_id=self._stream.actor_slack_user_id,
+ answer_markdown=final_answer if self._turn_complete else None,
),
# Attachments upload inside this activity. One attempt, because a retry would
# append the answer a second time.
diff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
index d03bfc00114b..73cbae6d67ab 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
@@ -367,6 +367,7 @@ class TestForwardPendingUserMessage(TestCase):
text="Which license should I use?",
user_message_ts="1234.5",
trace_id="f960aead-b2af-4ee0-b0eb-630109a1b2a0",
+ offer_reply_suggestions=True,
)
run.refresh_from_db()
assert "pending_user_message" not in run.state
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index e299403fceb8..8bbd685404f9 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -189,6 +189,8 @@ class RelaySlackMessageInput:
# Gateway trace id of the turn that produced this answer. Trailing and defaulted so a
# relay enqueued before this field existed still decodes.
trace_id: str | None = None
+ # Set only for the agent's own answer, so a notice or a placeholder never gets reply buttons.
+ offer_reply_suggestions: bool = False
@activity.defn
@@ -310,3 +312,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
if input.reaction_emoji is not None:
handler.update_reaction(input.reaction_emoji)
+
+ # Last, because the model call behind it is the slowest step and the answer must not wait for it.
+ if answer_delivered and input.offer_reply_suggestions:
+ handler.offer_reply_suggestions(text)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 9d256bbe7f6c..2bcac8c9fc84 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -8683,6 +8683,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
delete_progress=True,
message_id=None,
trace_id=expected_trace_id,
+ offer_reply_suggestions=True,
)
@parameterized.expand(
@@ -8737,6 +8738,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
delete_progress=True,
message_id=None,
trace_id=None,
+ offer_reply_suggestions=True,
)
@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")