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): record thumbs reactions on agent replies as turn feedback (#93147)

Vojta Bartoš19db3edbd67d
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.md
index d691fa7dcc4b..22eb39bde1fc 100644
--- a/docs/internal/slack-local-setup-guide.md
+++ b/docs/internal/slack-local-setup-guide.md
@@ -108,6 +108,7 @@ oauth_config:
- chat:write
- canvases:write
- files:write
+ - reactions:read
- reactions:write
- users:read
- users:read.email
@@ -122,6 +123,7 @@ settings:
- app_mention
- app_home_opened
- message.channels
+ - reaction_added
interactivity:
is_enabled: true
request_url: https://<you>-posthog.ngrok.dev/slack/interactivity-callback
@@ -142,6 +144,9 @@ Django must be up at that moment.
> the second redirect URL (`/complete/slack-link/`). Drop those if you don't want either feature
> locally — they're behind the `slack-app-home` and `slack-app-oauth` flags.
+> `reaction_added` + `reactions:read` power thumbs-reaction feedback on agent replies. Without
+> them a 👍/👎 reaction on a reply records nothing, again with no error.
+
> `message.channels` is what makes Slack deliver plain channel messages. Without it you get
> `app_mention` only, so `@PostHog` works and everything driven by an untagged message —
> workflow Slack triggers, untagged thread follow-ups — receives nothing. There is no error:
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 1c9db9ae65a2..e1d5ed187e09 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -85,6 +85,7 @@ from products.slack_app.backend.services.slack_app_home import (
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,
+ SLACK_WEBHOOK_TIMEOUT_SECONDS,
TURN_FEEDBACK_ACTION_ID,
post_slack_thread_reply,
)
@@ -92,6 +93,7 @@ from products.slack_app.backend.services.slack_settings import resolve_untagged_
from products.slack_app.backend.services.slack_user_info import (
clear_workspace_profile_cache,
get_cached_bot_user_id,
+ get_cached_workspace_bot_user_id,
get_slack_user_info,
normalize_slack_response,
persist_slack_user_info,
@@ -120,6 +122,7 @@ HANDLED_EVENT_TYPES = [
"assistant_thread_context_changed",
"app_home_opened",
"app_uninstalled",
+ "reaction_added",
]
# The notifications Slack app (`slack`) install carries every scope the coding-agent flow
@@ -150,10 +153,6 @@ ROUTE_NO_INTEGRATION = "no_integration"
# covers mentions that got far enough to resolve an integration.
SLACK_MENTION_DROPPED_EVENT = "posthog code slack mention dropped"
-# Ceiling on a feedback post made from inside the webhook request path, matching
-# _count_session_thread_messages. Slack's retry window is what we're protecting.
-SLACK_FEEDBACK_TIMEOUT_SECONDS = 3
-
PICKER_TOKEN_SALT = "posthog_code_repo_picker"
PICKER_TOKEN_MAX_AGE_SECONDS = 900
@@ -351,7 +350,7 @@ def _post_slack_user_ephemeral(
# builds a fresh WebClient on every access, so the client has to be held in a local
# for the timeout to apply to the instance that makes the request.
client = slack.client
- client.timeout = SLACK_FEEDBACK_TIMEOUT_SECONDS
+ client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
try:
client.chat_postEphemeral(channel=channel, user=slack_user_id, thread_ts=thread_ts, text=text)
except Exception:
@@ -2043,6 +2042,68 @@ def _route_app_home_opened(
return ROUTE_HANDLED_LOCALLY
+def _route_reaction_added(
+ request: HttpRequest,
+ event: dict,
+ slack_team_id: str,
+ *,
+ proxied: bool,
+ other_domain: str,
+) -> str:
+ """Turn a thumbs reaction on an agent reply into turn feedback, in the owning region.
+
+ The event names only a channel and a message ts, so which region owns the run is not
+ known until the handler reads the message back and finds the reply's own integration
+ id. The gate here is therefore two-step: no local integration for the workspace defers
+ the whole event, and a fetched integration id belonging to the other region defers it
+ after the fetch. The US-precedence rule for dual-owned workspaces does not apply,
+ because the embedded integration id is definitive.
+ """
+ # Everything up to the workspace lookup is free, and most reactions fail it: only a
+ # thumb on a message is a rating candidate.
+ item = event.get("item") or {}
+ channel = item.get("channel")
+ message_ts = item.get("ts")
+ if turn_feedback.reaction_sentiment(event.get("reaction")) is None or item.get("type") != "message":
+ return ROUTE_HANDLED_LOCALLY
+
+ # The reacted message's author rides on the event, and the bot's user id is the same
+ # for every install of the workspace, so a warm workspace cache rejects a thumb on a
+ # human message here, before the first database query. A miss falls through: the
+ # handler re-checks against the integration-scoped lookup, which also warms this cache.
+ workspace_bot_user_id = get_cached_workspace_bot_user_id(slack_team_id)
+ if workspace_bot_user_id is not None and event.get("item_user") != workspace_bot_user_id:
+ return ROUTE_HANDLED_LOCALLY
+
+ # Same candidate loading as the mention pipeline: broken-token installs are filtered
+ # out (with none left the event defers to the other region, whose healthy install can
+ # still serve a rating this region cannot), and the resolver ladder picks the install
+ # the same way a mention would. A reaction carries no thread_ts, so the message ts
+ # stands in; it only matches a thread mapping when the reacted message opened the
+ # thread, and the resolver falls through to the defaults otherwise.
+ workspace_result = load_integrations(
+ slack_team_id=slack_team_id,
+ kinds=[SLACK_INTEGRATION_KIND],
+ slack_user_id=str(event.get("user") or ""),
+ channel=channel if isinstance(channel, str) else None,
+ thread_ts=message_ts if isinstance(message_ts, str) else None,
+ )
+ workspace_integration = workspace_result.resolved_or_first()
+ if workspace_integration is None:
+ return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
+
+ outcome = turn_feedback.handle_reaction_added(event, slack_team_id, workspace_integration)
+ if outcome == turn_feedback.REACTION_NOT_LOCAL:
+ if not proxied and cross_region_routing_enabled():
+ return _proxy_event_and_return_route(request, other_domain)
+ logger.warning(
+ "slack_app_reaction_feedback_not_local",
+ slack_team_id=slack_team_id,
+ incoming_host=request.get_host(),
+ )
+ return ROUTE_HANDLED_LOCALLY
+
+
def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:
"""Drop the workspace's cached Slack profiles so a reinstall resolves users from
fresh ``users.info`` data instead of emails cached under the previous install.
@@ -2092,6 +2153,15 @@ def route_posthog_code_event_to_relevant_region(
if event_type == "app_uninstalled":
return _handle_app_uninstalled(request, slack_team_id)
+ if event_type == "reaction_added":
+ return _route_reaction_added(
+ request,
+ event,
+ slack_team_id,
+ proxied=proxied,
+ other_domain=other_domain,
+ )
+
# App Home tab: published per-user when they open the Home tab. The view is
# rendered against the workspace's integration row, which only the owning
# region holds, so this takes the same region gate as every other surface.
@@ -2649,7 +2719,7 @@ def _count_session_thread_messages(integration: Integration, channel: str | None
return None
try:
client = SlackIntegration(integration).client
- client.timeout = 3
+ client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
response = client.conversations_replies(channel=channel, ts=thread_ts, limit=200)
return len(response.get("messages", []))
except Exception:
diff --git a/products/slack_app/backend/facade/api.py b/products/slack_app/backend/facade/api.py
index 962d6bac9059..e69030953f09 100644
--- a/products/slack_app/backend/facade/api.py
+++ b/products/slack_app/backend/facade/api.py
@@ -13,8 +13,11 @@ without breaking their callers.
from __future__ import annotations
+from posthog.models.integration import Integration
+
from products.slack_app.backend.models import SlackChannel
from products.slack_app.backend.services.slack_auth import invalidate_auth_state
+from products.slack_app.backend.services.slack_user_info import invalidate_workspace_bot_user_id
def invalidate_slack_integration_auth_state(integration_id: int) -> None:
@@ -22,9 +25,22 @@ def invalidate_slack_integration_auth_state(integration_id: int) -> None:
Call from core's OAuth completion path so a freshly-reconnected Slack
install doesn't get pinned to the stale ``ok=false`` state we wrote when
- its previous token was revoked.
+ its previous token was revoked. The workspace-level bot id mirror goes with
+ it: a reinstall can mint a new bot user, and the reaction router's author
+ gate must not keep judging the new bot's replies against the old id.
"""
invalidate_auth_state(integration_id)
+ # Cache invalidation on the caller's own row, id straight from core's OAuth completion
+ # path rather than user input; only the Slack workspace id is read off it.
+ slack_team_id = (
+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team
+ id=integration_id, kind="slack"
+ )
+ .values_list("integration_id", flat=True)
+ .first()
+ )
+ if slack_team_id:
+ invalidate_workspace_bot_user_id(slack_team_id)
def slack_channel_is_approved(slack_workspace_id: str, slack_channel_id: str) -> bool:
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index d3040d4976ac..c2f32bfb2f3a 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -50,6 +50,10 @@ logger = structlog.get_logger(__name__)
# fetch without the cache.
THREAD_REPLIES_CACHE_TTL_SECONDS = 10
+# Ceiling on a Slack call made from inside the webhook request path. Slack's retry window
+# is the budget: a slow or rate-limited response must not eat into it before we return.
+SLACK_WEBHOOK_TIMEOUT_SECONDS = 3
+
def resolve_user_mentions_text(
slack: SlackIntegration,
@@ -641,6 +645,11 @@ def turn_feedback_block(integration_id: int, run_id: str) -> dict[str, Any]:
only the button that was clicked. The integration rides along so the cross-region
interactivity router can tell whose click this is, the same way the fork menu's
option value does. The task is not carried: it is read back from the run row.
+
+ The block's shape is also a read contract, not only a render: the reaction feedback
+ path fetches the posted message back from Slack and finds the run through this
+ element's action id and button value (``turn_feedback._feedback_value_from_message``).
+ Renaming the element's keys silently kills reaction feedback.
"""
target = {"integration_id": integration_id, "run_id": run_id}
return {
diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.py
index bcd722f8838f..b6acb4b53962 100644
--- a/products/slack_app/backend/services/slack_user_info.py
+++ b/products/slack_app/backend/services/slack_user_info.py
@@ -20,6 +20,7 @@ keeps `api.py` focused on routes.
from datetime import timedelta
from typing import Any
+from django.core.cache import cache
from django.db.utils import DatabaseError
from django.utils import timezone
@@ -30,6 +31,7 @@ from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, Sla
from products.slack_app.backend.models import SlackUserProfileCache
from products.slack_app.backend.services.slack_auth import (
+ SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
classify_slack_api_error,
get_cached_auth_state,
write_auth_state_broken,
@@ -231,6 +233,50 @@ def clear_workspace_profile_cache(slack_team_id: str) -> int:
return deleted
+def _workspace_bot_user_cache_key(slack_team_id: str) -> str:
+ return f"slack_app:workspace_bot_user_id:{slack_team_id}"
+
+
+def get_cached_workspace_bot_user_id(slack_team_id: str) -> str | None:
+ """The workspace's bot user id, if some install resolved it recently. Cheap.
+
+ One Slack install serves every integration row a workspace has, in both regions, so
+ the id is workspace-level data. Written as a side effect of ``get_cached_bot_user_id``,
+ which is what lets a surface that has not loaded an integration yet (the reaction
+ router) reject a reaction on a non-bot message before its first database query. A miss
+ proves nothing: callers fall through to the integration-scoped path, which is also why
+ a cache outage degrades to that path rather than raising into a webhook.
+ """
+ try:
+ value = cache.get(_workspace_bot_user_cache_key(slack_team_id))
+ except Exception:
+ logger.warning("slack_app_workspace_bot_user_cache_read_failed", slack_team_id=slack_team_id)
+ return None
+ return value if isinstance(value, str) and value else None
+
+
+def cache_workspace_bot_user_id(slack_team_id: str, bot_user_id: str) -> None:
+ """Best-effort: this cache only saves work, so a write failure must not fail the
+ caller, which sits on the mention pipeline's hot path."""
+ try:
+ cache.set(_workspace_bot_user_cache_key(slack_team_id), bot_user_id, SLACK_AUTH_STATE_CACHE_TTL_SECONDS)
+ except Exception:
+ logger.warning("slack_app_workspace_bot_user_cache_write_failed", slack_team_id=slack_team_id)
+
+
+def invalidate_workspace_bot_user_id(slack_team_id: str) -> None:
+ """Drop the workspace-level bot id so the next resolution re-derives it.
+
+ Called on OAuth reconnect: a reinstall can mint a new bot user, and the reaction
+ router's author gate must not keep rejecting the new bot's replies against the old id
+ for the cache TTL.
+ """
+ try:
+ cache.delete(_workspace_bot_user_cache_key(slack_team_id))
+ except Exception:
+ logger.warning("slack_app_workspace_bot_user_cache_delete_failed", slack_team_id=slack_team_id)
+
+
def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:
"""Return the bot's Slack user id for ``integration``, populating the
shared auth-state cache as a side effect.
@@ -249,6 +295,8 @@ def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) ->
cached = get_cached_auth_state(integration.id)
if cached is not None:
if cached.ok and cached.bot_user_id is not None:
+ if integration.integration_id:
+ cache_workspace_bot_user_id(integration.integration_id, cached.bot_user_id)
return cached.bot_user_id
if not cached.ok:
return None
@@ -281,4 +329,6 @@ def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) ->
if not isinstance(bot_user_id, str) or not bot_user_id:
return None
write_auth_state_ok(integration.id, bot_user_id)
+ if integration.integration_id:
+ cache_workspace_bot_user_id(integration.integration_id, bot_user_id)
return bot_user_id
diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.py
index b3d43cb948d1..2d7ee1bc700a 100644
--- a/products/slack_app/backend/services/turn_feedback.py
+++ b/products/slack_app/backend/services/turn_feedback.py
@@ -7,8 +7,13 @@ events AI observability already understands, ``$ai_metric`` for the rating and
generations carry so Slack feedback sits beside the web and desktop clients' rather than
in a surface of its own.
-Kept out of ``api.py`` so that module stays the interactivity router: it imports the hint
-extractor for region ownership and the two handler entrypoints.
+A rating arrives two ways: a click on the reply's thumbs, or a thumbs emoji reacted onto
+the reply. Both become the same ``$ai_metric``, split by ``feedback_source``; only a
+clicked thumbs-down can ask for a reason, because a reaction carries no ``trigger_id`` to
+open a modal with.
+
+Kept out of ``api.py`` so that module stays the interactivity/event router: it imports
+the hint extractor for region ownership and the handler entrypoints.
"""
from __future__ import annotations
@@ -27,7 +32,8 @@ from posthog.event_usage import groups
from posthog.models.integration import Integration, SlackIntegration
from products.slack_app.backend.analytics import slack_event_props
-from products.slack_app.backend.services.slack_messages import TURN_FEEDBACK_ACTION_ID
+from products.slack_app.backend.services.slack_messages import SLACK_WEBHOOK_TIMEOUT_SECONDS, TURN_FEEDBACK_ACTION_ID
+from products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id
logger = structlog.get_logger(__name__)
@@ -52,15 +58,33 @@ FEEDBACK_TEXT_MAX_LENGTH = 3000
_RATINGS: dict[str, Literal["good", "bad"]] = {"positive": "good", "negative": "bad"}
+# Slack sends a reaction as its emoji name, with any skin tone appended after ``::``.
+# ``+1``/``-1`` are the canonical names for the thumbs; ``thumbsup``/``thumbsdown`` are
+# their standing aliases, kept here in case a client sends the alias form.
+_REACTION_SENTIMENTS: dict[str, str] = {
+ "+1": "positive",
+ "thumbsup": "positive",
+ "-1": "negative",
+ "thumbsdown": "negative",
+}
+
+# The outcomes ``handle_reaction_added`` reports to the event router. ``not_local`` means
+# the reacted reply belongs to an integration the other region owns, so the router should
+# forward the event there.
+ReactionOutcome = Literal["handled", "not_local"]
+REACTION_HANDLED: ReactionOutcome = "handled"
+REACTION_NOT_LOCAL: ReactionOutcome = "not_local"
+
@frozen
class _FeedbackTarget:
"""The run a rating is about, resolved against the workspace that owns it.
- Built only by ``_resolve_target``, which is what makes every field here trusted: the
- integration is matched on the Slack team the click came from, and the run is looked up
- scoped to that integration's project, so a forged ``run_id`` resolves to nothing rather
- than attributing feedback to another team's run.
+ Built only by ``_resolve_target`` on an integration ``_local_integration`` matched,
+ which is what makes every field here trusted: the integration is matched on the Slack
+ team the rating came from, and the run is looked up scoped to that integration's
+ project, so a forged ``run_id`` resolves to nothing rather than attributing feedback
+ to another team's run.
"""
integration: Integration
@@ -111,41 +135,51 @@ def extract_modal_hint(payload: dict) -> int | None:
return integration_id if isinstance(integration_id, int) else None
-def _resolve_target(payload: dict, value: dict[str, Any], turn_id: str | None) -> _FeedbackTarget | None:
- """Match the click's workspace and run, or answer ``None``.
+def _local_integration(integration_id: Any, slack_team_id: str | None) -> Integration | None:
+ """The integration a rating names, if this region owns it for that Slack team.
- Two lookups, both scoped: the integration must belong to the Slack team the click came
- from, and the run must belong to that integration's project. Anyone who can read the
- reply may rate it, so this is not an authorization check; it is what keeps a rating
- from landing on a run the clicker's workspace has nothing to do with.
+ Scoped to the Slack team the rating came from, so a forged id resolves to nothing
+ rather than crossing workspaces. ``None`` also covers an id whose row lives in the
+ other region's database, which the reaction path forwards on.
"""
- # Deferred so the tasks product stays off this module's import path, matching
- # `slack_messages.load_run_footer`.
- from products.tasks.backend.facade.api import get_task_run # noqa: PLC0415
-
- slack_team_id = payload.get("team", {}).get("id")
- integration_id = value.get("integration_id")
- run_id = value.get("run_id")
- slack_user_id = payload.get("user", {}).get("id", "")
- if not slack_team_id or not isinstance(integration_id, int) or not isinstance(run_id, str):
+ if not slack_team_id or not isinstance(integration_id, int):
return None
- try:
- UUID(run_id)
- except (ValueError, AttributeError, TypeError):
- return None
-
- integration = (
+ return (
Integration.objects.filter( # nosemgrep: idor-lookup-without-team
id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get
kind=SLACK_INTEGRATION_KIND,
integration_id=slack_team_id,
)
# The event properties and the capture's groups both read through to the team and
- # its organization, and Slack gives the click three seconds.
+ # its organization, and Slack gives the interaction three seconds.
.select_related("team__organization")
.first()
)
- if integration is None:
+
+
+def _resolve_target(
+ value: dict[str, Any],
+ *,
+ integration: Integration,
+ slack_user_id: str,
+ turn_id: str | None,
+) -> _FeedbackTarget | None:
+ """Match the rating's run within ``integration``'s project, or answer ``None``.
+
+ Anyone who can read the reply may rate it, so this is not an authorization check; the
+ project scope is what keeps a rating from landing on a run the rater's workspace has
+ nothing to do with.
+ """
+ # Deferred so the tasks product stays off this module's import path, matching
+ # `slack_messages.load_run_footer`.
+ from products.tasks.backend.facade.api import get_task_run # noqa: PLC0415
+
+ run_id = value.get("run_id")
+ if not isinstance(run_id, str):
+ return None
+ try:
+ UUID(run_id)
+ except (ValueError, AttributeError, TypeError):
return None
run = get_task_run(run_id, team_id=integration.team_id)
@@ -233,9 +267,18 @@ def _capture(target: _FeedbackTarget, event: str, properties: dict[str, Any]) ->
properties={**_event_context(target), **properties},
groups=groups(team.organization, team),
)
- except Exception:
+ # The one positive trace on this path: without it, a rating that quietly went
+ # nowhere is indistinguishable in the logs from a reaction we ignored on purpose.
# NB: structlog's first positional arg is named `event`, so the captured event
# rides under a different key rather than colliding with it.
+ logger.info(
+ "slack_app_turn_feedback_captured",
+ captured_event=event,
+ feedback_source=properties.get("feedback_source"),
+ run_id=target.run_id,
+ turn_id=target.turn_id,
+ )
+ except Exception:
logger.warning("slack_app_turn_feedback_capture_failed", captured_event=event, exc_info=True)
@@ -298,7 +341,17 @@ def handle_turn_feedback_click(payload: dict) -> HttpResponse:
logger.info("slack_app_turn_feedback_unknown_sentiment", sentiment=sentiment)
return HttpResponse(status=200)
- target = _resolve_target(payload, value, _turn_id(payload))
+ integration = _local_integration(value.get("integration_id"), payload.get("team", {}).get("id"))
+ target = (
+ _resolve_target(
+ value,
+ integration=integration,
+ slack_user_id=payload.get("user", {}).get("id", ""),
+ turn_id=_turn_id(payload),
+ )
+ if integration
+ else None
+ )
if target is None:
return HttpResponse(status=200)
@@ -306,7 +359,11 @@ def handle_turn_feedback_click(payload: dict) -> HttpResponse:
# resolves the clicker's identity against the database on its way out.
if sentiment == "negative":
_open_reason_modal(payload, target)
- _capture(target, "$ai_metric", {"$ai_metric_name": "quality", "$ai_metric_value": rating})
+ _capture(
+ target,
+ "$ai_metric",
+ {"$ai_metric_name": "quality", "$ai_metric_value": rating, "feedback_source": "button"},
+ )
return HttpResponse(status=200)
@@ -328,9 +385,147 @@ def handle_turn_feedback_modal_submit(payload: dict) -> HttpResponse:
return JsonResponse({"response_action": "errors", "errors": {_MODAL_TEXT_BLOCK_ID: "Tell us what went wrong."}})
turn_id = metadata.get("turn_id")
- target = _resolve_target(payload, metadata, turn_id if isinstance(turn_id, str) else None)
+ integration = _local_integration(metadata.get("integration_id"), payload.get("team", {}).get("id"))
+ target = (
+ _resolve_target(
+ metadata,
+ integration=integration,
+ slack_user_id=payload.get("user", {}).get("id", ""),
+ turn_id=turn_id if isinstance(turn_id, str) else None,
+ )
+ if integration
+ else None
+ )
if target is None:
return HttpResponse(status=200)
- _capture(target, "$ai_feedback", {"$ai_feedback_text": text, "feedback_type": "bad"})
+ _capture(
+ target,
+ "$ai_feedback",
+ {"$ai_feedback_text": text, "feedback_type": "bad", "feedback_source": "button"},
+ )
return HttpResponse(status=200)
+
+
+def _reaction_base(reaction: str) -> str:
+ """The emoji name without its skin-tone modifier.
+
+ A skin-toned thumb arrives as ``+1::skin-tone-3``. The tone changes nothing about the
+ rating, and it must not reach the captured event either: it is a person's routine
+ default on every emoji they send, so storing it would record a proxy for a protected
+ attribute against an identified user.
+ """
+ return reaction.split("::", 1)[0]
+
+
+def reaction_sentiment(reaction: Any) -> str | None:
+ """The rating a reaction stands for, or ``None`` for any other emoji."""
+ if not isinstance(reaction, str):
+ return None
+ return _REACTION_SENTIMENTS.get(_reaction_base(reaction))
+
+
+def _fetch_reacted_message(workspace_integration: Integration, channel: str, message_ts: str) -> dict[str, Any] | None:
+ """The reacted message, read back from Slack so its blocks can say which run it is.
+
+ ``conversations.replies`` accepts the ts of any message in a thread, and agent replies
+ always live in threads.
+ """
+ try:
+ client = SlackIntegration(workspace_integration).client
+ client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
+ # `oldest` and `latest` pin the window to exactly the reacted message, so the one
+ # returned row is that message whatever order Slack ranges the thread in.
+ response = client.conversations_replies(
+ channel=channel, ts=message_ts, oldest=message_ts, latest=message_ts, inclusive=True, limit=1
+ )
+ messages = response.get("messages") or []
+ except Exception:
+ logger.warning(
+ "slack_app_reaction_feedback_fetch_failed",
+ integration_id=workspace_integration.id,
+ channel=channel,
+ message_ts=message_ts,
+ exc_info=True,
+ )
+ return None
+ return next((m for m in messages if isinstance(m, dict) and m.get("ts") == message_ts), None)
+
+
+def _feedback_value_from_message(message: dict[str, Any]) -> dict[str, Any]:
+ """The thumbs' target, read off the reacted reply's own blocks.
+
+ Only agent replies carry the feedback element, so finding it is also the gate: a
+ reaction on any other bot message resolves to nothing. Both buttons carry the same
+ integration and run, so either value serves.
+ """
+ for block in message.get("blocks") or []:
+ if not isinstance(block, dict):
+ continue
+ for element in block.get("elements") or []:
+ if isinstance(element, dict) and element.get("action_id") == TURN_FEEDBACK_ACTION_ID:
+ return _parse_action_value((element.get("positive_button") or {}).get("value"))
+ return {}
+
+
+def handle_reaction_added(event: dict, slack_team_id: str, workspace_integration: Integration) -> ReactionOutcome:
+ """Record a thumbs reaction on an agent reply as a rating.
+
+ ``workspace_integration`` is any of this region's integrations for the Slack team; its
+ token is what reads the reacted message back. The reply's own button value then names
+ the integration the run belongs to, and ``REACTION_NOT_LOCAL`` reports that row living
+ in the other region so the event router can forward the event there. Everything this
+ handler ignores, including reactions that are not a thumb, is ``REACTION_HANDLED``.
+ """
+ reaction = event.get("reaction")
+ sentiment = reaction_sentiment(reaction)
+ rating = _RATINGS.get(sentiment) if sentiment else None
+ item = event.get("item") or {}
+ channel = item.get("channel")
+ message_ts = item.get("ts")
+ if (
+ rating is None
+ or not isinstance(reaction, str)
+ or item.get("type") != "message"
+ or not isinstance(channel, str)
+ or not isinstance(message_ts, str)
+ ):
+ return REACTION_HANDLED
+
+ # Most thumbs in a channel land on human messages; the author check keeps those from
+ # each costing a Slack fetch. `get_cached_bot_user_id` settles a cold cache itself, so
+ # `None` means the token is broken or Slack is failing. A rating is best-effort
+ # analytics, so skip it then rather than pay a doomed fetch per reaction.
+ bot_user_id = get_cached_bot_user_id(SlackIntegration(workspace_integration), workspace_integration)
+ if bot_user_id is None or event.get("item_user") != bot_user_id:
+ return REACTION_HANDLED
+
+ message = _fetch_reacted_message(workspace_integration, channel, message_ts)
+ value = _feedback_value_from_message(message) if message else {}
+ if not isinstance(value.get("integration_id"), int):
+ return REACTION_HANDLED
+
+ integration = _local_integration(value.get("integration_id"), slack_team_id)
+ if integration is None:
+ return REACTION_NOT_LOCAL
+
+ target = _resolve_target(
+ value,
+ integration=integration,
+ slack_user_id=str(event.get("user") or ""),
+ turn_id=message_ts,
+ )
+ if target is None:
+ return REACTION_HANDLED
+
+ _capture(
+ target,
+ "$ai_metric",
+ {
+ "$ai_metric_name": "quality",
+ "$ai_metric_value": rating,
+ "feedback_source": "reaction",
+ "reaction": _reaction_base(reaction),
+ },
+ )
+ return REACTION_HANDLED
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 9b189a80cbea..d247423e50dc 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -124,7 +124,8 @@ class TestPostHogCodeEventHandler(SimpleTestCase):
("member_joined_channel_routes", "member_joined_channel", "handled_locally", 202, True),
("message_dm_routes", "message", "handled_locally", 202, True),
("app_uninstalled_routes", "app_uninstalled", "handled_locally", 202, True),
- ("non_handled_event_type_skips_routing", "reaction_added", "handled_locally", 202, False),
+ ("reaction_added_routes", "reaction_added", "handled_locally", 202, True),
+ ("non_handled_event_type_skips_routing", "emoji_changed", "handled_locally", 202, False),
]
)
@patch("products.slack_app.backend.api.route_posthog_code_event_to_relevant_region")
@@ -1683,7 +1684,7 @@ class TestPostSlackUserEphemeral(SimpleTestCase):
# the timeout on one access and calling on another leaves the request on the SDK
# default. Nothing about the app's behavior changes when that happens, so only an
# assertion on the client instance catches it.
- from products.slack_app.backend.api import SLACK_FEEDBACK_TIMEOUT_SECONDS, _post_slack_user_ephemeral
+ from products.slack_app.backend.api import SLACK_WEBHOOK_TIMEOUT_SECONDS, _post_slack_user_ephemeral
built_clients: list[MagicMock] = []
@@ -1697,7 +1698,7 @@ class TestPostSlackUserEphemeral(SimpleTestCase):
assert posted is True
assert len(built_clients) == 1
- assert built_clients[0].timeout == SLACK_FEEDBACK_TIMEOUT_SECONDS
+ assert built_clients[0].timeout == SLACK_WEBHOOK_TIMEOUT_SECONDS
built_clients[0].chat_postEphemeral.assert_called_once()
def test_failed_delivery_is_reported_as_not_replied(self):
diff --git a/products/slack_app/backend/tests/test_turn_feedback.py b/products/slack_app/backend/tests/test_turn_feedback.py
index eb55f225cfd8..7e377c89d176 100644
--- a/products/slack_app/backend/tests/test_turn_feedback.py
+++ b/products/slack_app/backend/tests/test_turn_feedback.py
@@ -14,6 +14,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.slack_app.backend.services.slack_messages import TURN_FEEDBACK_ACTION_ID, turn_feedback_block
+from products.slack_app.backend.services.slack_user_info import cache_workspace_bot_user_id
from products.slack_app.backend.services.turn_feedback import (
_MODAL_TEXT_ACTION_ID,
_MODAL_TEXT_BLOCK_ID,
@@ -65,6 +66,12 @@ class TestTurnFeedback(TestCase):
analytics = patch("products.slack_app.backend.services.turn_feedback.posthoganalytics")
self.mock_analytics = analytics.start()
self.addCleanup(analytics.stop)
+ bot_id = patch("products.slack_app.backend.services.turn_feedback.get_cached_bot_user_id", return_value="U_BOT")
+ bot_id.start()
+ self.addCleanup(bot_id.stop)
+ # The router's early author gate reads the workspace-level cache; pin it so the
+ # reaction tests exercise that gate whatever earlier tests left in the cache.
+ cache_workspace_bot_user_id(self.slack_team_id, "U_BOT")
def _post(self, payload: dict):
body = f"payload={json.dumps(payload)}"
@@ -121,6 +128,7 @@ class TestTurnFeedback(TestCase):
assert properties["task_id"] == str(self.task.id)
# The rated answer's own message, so a thread of answers stays separable.
assert properties["turn_id"] == "222.1"
+ assert properties["feedback_source"] == "button"
assert self.mock_slack.return_value.client.views_open.called is asks_for_a_reason
def test_a_run_from_another_project_is_not_rated(self):
@@ -174,3 +182,90 @@ class TestTurnFeedback(TestCase):
assert response.json()["response_action"] == "errors"
self.mock_analytics.capture.assert_not_called()
+
+ def _react(self, reaction: str, item_user: str = "U_BOT"):
+ body = json.dumps(
+ {
+ "type": "event_callback",
+ "team_id": self.slack_team_id,
+ "event_id": "Ev123",
+ "event": {
+ "type": "reaction_added",
+ "user": "U_ALICE",
+ "reaction": reaction,
+ "item_user": item_user,
+ "item": {"type": "message", "channel": "C_SOURCE", "ts": "222.1"},
+ },
+ }
+ ).encode()
+ signed = sign_slack_request(body, self.signing_secret)
+ return self.client.post(
+ "/slack/event-callback/",
+ data=body,
+ content_type="application/json",
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
+ )
+
+ def _reacted_message(self, blocks: list[dict]) -> None:
+ self.mock_slack.return_value.client.conversations_replies.return_value = {
+ "messages": [{"ts": "222.1", "blocks": blocks}]
+ }
+
+ @parameterized.expand(
+ [
+ ("+1", "good", "+1"),
+ ("+1::skin-tone-3", "good", "+1"),
+ ("thumbsup", "good", "thumbsup"),
+ ("-1", "bad", "-1"),
+ ("-1::skin-tone-5", "bad", "-1"),
+ ("thumbsdown", "bad", "thumbsdown"),
+ ]
+ )
+ def test_a_thumb_reaction_reports_a_rating(self, reaction, rating, stored_reaction):
+ self._reacted_message([turn_feedback_block(self.integration.id, str(self.task_run.id))])
+
+ response = self._react(reaction)
+
+ assert response.status_code == 202
+ # The window must pin exactly the reacted message: with an open lower bound Slack
+ # ranges the whole thread and one returned row could be a different message.
+ fetch_kwargs = self.mock_slack.return_value.client.conversations_replies.call_args.kwargs
+ assert fetch_kwargs["oldest"] == fetch_kwargs["latest"] == fetch_kwargs["ts"] == "222.1"
+ assert fetch_kwargs["inclusive"] is True
+ self.mock_analytics.capture.assert_called_once()
+ kwargs = self.mock_analytics.capture.call_args.kwargs
+ assert kwargs["event"] == "$ai_metric"
+ properties = kwargs["properties"]
+ assert properties["$ai_metric_name"] == "quality"
+ assert properties["$ai_metric_value"] == rating
+ assert properties["feedback_source"] == "reaction"
+ # The skin-tone modifier never reaches the event: it is a proxy for a protected
+ # attribute on an identified person, and the metric does not need it.
+ assert properties["reaction"] == stored_reaction
+ assert properties["task_run_id"] == str(self.task_run.id)
+ assert properties["turn_id"] == "222.1"
+ # A reaction carries no trigger_id, so a bad rating cannot be asked for a reason.
+ assert not self.mock_slack.return_value.client.views_open.called
+
+ def test_a_non_thumb_reaction_costs_no_slack_fetch(self):
+ response = self._react("eyes")
+
+ assert response.status_code == 202
+ assert not self.mock_slack.return_value.client.conversations_replies.called
+ self.mock_analytics.capture.assert_not_called()
+
+ def test_a_thumb_on_a_human_message_costs_no_slack_fetch(self):
+ response = self._react("+1", item_user="U_SOMEONE_ELSE")
+
+ assert response.status_code == 202
+ assert not self.mock_slack.return_value.client.conversations_replies.called
+ self.mock_analytics.capture.assert_not_called()
+
+ def test_a_thumb_on_a_bot_message_without_thumbs_is_not_a_rating(self):
+ self._reacted_message([{"type": "section", "text": {"type": "mrkdwn", "text": "Working on it"}}])
+
+ response = self._react("+1")
+
+ assert response.status_code == 202
+ self.mock_analytics.capture.assert_not_called()