:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack-app): rate an agent answer from the reply menu (#92540)
Vojta Bartoš6f252c3bca93
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 0aea0f0fbbd9..1c9db9ae65a2 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -64,7 +64,7 @@ from products.slack_app.backend.feature_flags import ()from products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, UntaggedFollowupMode-from products.slack_app.backend.services import inbox_interactivity+from products.slack_app.backend.services import inbox_interactivity, turn_feedbackfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,format_project_candidate_list,@@ -83,7 +83,11 @@ from products.slack_app.backend.services.slack_app_home import (handle_app_home_view_submission as _handle_app_home_view_submission,)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, post_slack_thread_reply+from products.slack_app.backend.services.slack_messages import (+ FORK_THREAD_ACTION_ID,+ TURN_FEEDBACK_ACTION_ID,+ post_slack_thread_reply,+)from products.slack_app.backend.services.slack_settings import resolve_untagged_followup_modefrom products.slack_app.backend.services.slack_user_info import (clear_workspace_profile_cache,@@ -4751,7 +4755,14 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:dismiss_integration_id = _extract_dismiss_hints(payload)alert_snooze_uuid = _extract_alert_snooze_hints(payload)inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)- fork_menu_integration_id, _ = _extract_action_value_hints(payload, FORK_THREAD_ACTION_ID)+ # 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.+ 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)+ )requesting_user = payload.get("user", {}).get("id", "")slack_team_id = payload.get("team", {}).get("id")@@ -4808,12 +4819,14 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:kind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,).exists()- elif slack_team_id and fork_menu_integration_id:- # The fork menu rides on a bot reply anyone in the thread can see, so any- # reader may use it. Routing only claims the workspace; who the fork runs as,- # and whether they may, is settled in the fork activity.+ elif slack_team_id and reply_control_integration_id:+ # The fork menu and the thumbs ride on a bot reply anyone in the thread can see, so+ # any reader may use them, and the same goes for the modal a thumbs-down opens.+ # Routing only claims the workspace; who the fork runs as, and whether they may, is+ # settled in the fork activity, and a rating is matched to its run in the feedback+ # handler.local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team- id=fork_menu_integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ id=reply_control_integration_id, # nosemgrep: idor-taint-user-input-to-model-getkind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,).exists()@@ -4888,8 +4901,11 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_repo_picker_options(payload)if payload_type == "view_submission":- if payload.get("view", {}).get("callback_id") == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:+ callback_id = payload.get("view", {}).get("callback_id")+ if callback_id == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:return _handle_insight_alert_snooze_modal_submit(payload)+ if callback_id == turn_feedback.TURN_FEEDBACK_MODAL_CALLBACK_ID:+ return turn_feedback.handle_turn_feedback_modal_submit(payload)return _handle_app_home_view_submission(payload)if payload_type == "block_actions":@@ -4902,6 +4918,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_no_repo_needed_submit(payload)if action_id == FORK_THREAD_ACTION_ID:return _handle_fork_thread_submit(payload)+ if action_id == TURN_FEEDBACK_ACTION_ID:+ return turn_feedback.handle_turn_feedback_click(payload)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.pyindex bd7906a1c363..2e6b6c0616f4 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -35,6 +35,7 @@ logger = structlog.get_logger(__name__)SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_FORKING_FLAG = "slack-app-forking"+SLACK_APP_TURN_FEEDBACK_FLAG = "slack-app-turn-feedback"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -52,23 +53,17 @@ def _region_properties() -> dict[str, str]:return {"region": get_instance_region() or "dev"}-def is_slack_app_oauth_enabled(integration: Integration) -> bool:- """Gate for the Slack user-identity OAuth link feature, covering both backend- (offering the invite button, accepting the link callback, listing/starting- from settings) and frontend (rendering the Slack card in Personal- integrations) decisions. Linking resolves the Slack profile and its email,- so the install must hold the identity scopes."""- return has_scopes(integration, OAUTH_REQUIRED_SCOPES)-+def _workspace_flag_enabled(flag: str, integration: Integration, *, failure_log_key: str) -> bool:+ """Evaluate one workspace-keyed gate under the settings this module documents.-def is_slack_app_agent_design_enabled(integration: Integration) -> bool:- """Gate for the agent-design plan-block streaming surface on Slack task runs.- Posts through the ``chat:write`` the mention flow already requires, so this is the- flag alone. Keyed on the Slack workspace + PostHog org."""+ The uniformity the docstring above promises is only real if there is one place that+ spells it out. A gate that needs more than a flag — scopes, say — checks that itself+ and calls this for the flag half.+ """try:return bool(posthoganalytics.feature_enabled(- SLACK_APP_AGENT_DESIGN_FLAG,+ flag,f"slack_workspace:{integration.integration_id}",groups={"organization": str(integration.team.organization_id)},person_properties=_region_properties(),@@ -77,13 +72,30 @@ def is_slack_app_agent_design_enabled(integration: Integration) -> bool:))except Exception:- logger.exception(- "slack_app_agent_design_feature_flag_check_failed",- integration_id=integration.id,- )+ logger.exception(failure_log_key, integration_id=integration.id)return False+def is_slack_app_oauth_enabled(integration: Integration) -> bool:+ """Gate for the Slack user-identity OAuth link feature, covering both backend+ (offering the invite button, accepting the link callback, listing/starting+ from settings) and frontend (rendering the Slack card in Personal+ integrations) decisions. Linking resolves the Slack profile and its email,+ so the install must hold the identity scopes."""+ return has_scopes(integration, OAUTH_REQUIRED_SCOPES)+++def is_slack_app_agent_design_enabled(integration: Integration) -> bool:+ """Gate for the agent-design plan-block streaming surface on Slack task runs.+ Posts through the ``chat:write`` the mention flow already requires, so this is the+ flag alone. Keyed on the Slack workspace + PostHog org."""+ return _workspace_flag_enabled(+ SLACK_APP_AGENT_DESIGN_FLAG,+ integration,+ failure_log_key="slack_app_agent_design_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 surfacecalls — ``im:history`` in particular, without which the assistant would answer@@ -91,6 +103,21 @@ def is_slack_app_assistant_enabled(integration: Integration) -> bool:return has_scopes(integration, ASSISTANT_REQUIRED_SCOPES)+def is_slack_app_turn_feedback_enabled(integration: Integration) -> bool:+ """Gate for the thumbs under an agent answer.++ Posts through the ``chat:write`` the mention flow already requires, so this is the+ flag alone. Keyed on the Slack workspace like its neighbours: the thumbs hang off a+ reply, and a workspace connected to two projects would otherwise show them on some+ replies and not others.+ """+ return _workspace_flag_enabled(+ SLACK_APP_TURN_FEEDBACK_FLAG,+ integration,+ failure_log_key="slack_app_turn_feedback_feature_flag_check_failed",+ )++def is_slack_app_forking_enabled(integration: Integration) -> bool:"""Gate for the "Fork to DM" menu under a reply.@@ -106,17 +133,8 @@ def is_slack_app_forking_enabled(integration: Integration) -> bool:"""if not has_scopes(integration, ASSISTANT_REQUIRED_SCOPES):return False- try:- return bool(- posthoganalytics.feature_enabled(- SLACK_APP_FORKING_FLAG,- f"slack_workspace:{integration.integration_id}",- groups={"organization": str(integration.team.organization_id)},- person_properties=_region_properties(),- only_evaluate_locally=False,- send_feature_flag_events=False,- )- )- except Exception:- logger.exception("slack_app_forking_feature_flag_check_failed", integration_id=integration.id)- return False+ return _workspace_flag_enabled(+ SLACK_APP_FORKING_FLAG,+ integration,+ failure_log_key="slack_app_forking_feature_flag_check_failed",+ )diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 3fc79c122bf7..270cf6768632 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -473,17 +473,23 @@ UNFURL_OPT_OUT_PARAM = "unfurl"@dataclass(frozen=True)class RunFooter:- """What a reply can say about the run behind it.+ """What a reply knows about the run behind it.Constant for the life of a handler, so it is supplied once at construction ratherthan threaded through every posting method. An empty instance is the "say nothing"case, which is what every caller outside the footer rollout gets.++ ``run_id`` and ``task_id`` are what the run *is* rather than what the footer says+ about it: the thumbs under an answer report against them, and they ride here because+ a reply that can describe its run is exactly a reply that has one to rate."""task_url: str | None = Nonedesktop_url: str | None = Nonemodel: str | None = Nonereasoning_effort: str | None = None+ run_id: str | None = None+ task_id: str | None = Nonedef has_content(self) -> bool:"""Whether this would render as anything.@@ -491,6 +497,7 @@ class RunFooter:A caller checks it to skip the flag lookups behind a footer that can't appear.Spelled out rather than given as ``__bool__`` so that ``footer or RunFooter()``keeps meaning "None-coalesce" and cannot silently discard a partial instance.+ The ids are not part of the answer — they say nothing on their own."""return any((self.task_url, self.desktop_url, self.model))@@ -518,6 +525,8 @@ def load_run_footer(run_id: str | UUID | None) -> RunFooter:return RunFooter()state = parse_run_state(run.state)return RunFooter(+ run_id=str(run.id),+ task_id=str(run.task_id),task_url=_task_url(run.team_id, run.task_id, run.id),# The web bridge page, not the raw `posthog-code://` scheme: it redirects into the# desktop app when installed and offers a download when not, so a reader without@@ -595,6 +604,42 @@ def fork_menu_element(integration_id: int) -> dict[str, Any]:}+TURN_FEEDBACK_ACTION_ID = "slack_app_turn_feedback"+++def turn_feedback_block(integration_id: int, run_id: str) -> dict[str, Any]:+ """The thumbs a reader rates one agent answer with.++ Slack's own feedback element rather than a pair of buttons: it renders as the two+ small icons a reader already knows from other AI apps. Whether Slack marks the+ clicked thumb afterwards is its own business and is not documented either way; we+ store no rating and never rewrite the reply to show one.++ Both buttons carry the same run plus their own sentiment, because Slack sends back+ 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.+ """+ target = {"integration_id": integration_id, "run_id": run_id}+ return {+ "type": "context_actions",+ "elements": [+ {+ "type": "feedback_buttons",+ "action_id": TURN_FEEDBACK_ACTION_ID,+ "positive_button": {+ "text": {"type": "plain_text", "text": "Good response"},+ "value": json.dumps({**target, "sentiment": "positive"}),+ },+ "negative_button": {+ "text": {"type": "plain_text", "text": "Bad response"},+ "value": json.dumps({**target, "sentiment": "negative"}),+ },+ }+ ],+ }++def thread_permalink(slack: SlackIntegration, channel: str, thread_ts: str) -> str | None:"""Permalink for a thread, or `None` if Slack won't give us one.diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.pynew file mode 100644index 000000000000..b3d43cb948d1--- /dev/null+++ b/products/slack_app/backend/services/turn_feedback.py@@ -0,0 +1,336 @@+"""What a reader's rating of an agent answer becomes.++Rating is analytics only: it changes nothing about the run, and a reader who picks the+other rating later simply sends a second event. What a pick produces is the pair of+events AI observability already understands, ``$ai_metric`` for the rating and+``$ai_feedback`` for the reason, tagged with the same ``ai_product`` the run's own+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.+"""++from __future__ import annotations++import json+from typing import Any, Literal+from uuid import UUID++from django.http import HttpResponse, JsonResponse++import structlog+import posthoganalytics++from posthog.dataclasses import frozen+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++logger = structlog.get_logger(__name__)++SLACK_INTEGRATION_KIND = "slack"++TURN_FEEDBACK_MODAL_CALLBACK_ID = "slack_app_turn_feedback_modal"+_MODAL_TEXT_BLOCK_ID = "feedback_text"+_MODAL_TEXT_ACTION_ID = "text"++# What the run's own generations are already tagged with, so a rating joins them: a+# Slack-origin run resolves to this gateway product (`_ORIGIN_TO_GATEWAY_PRODUCT` in+# `products/tasks/backend/temporal/process_task/ai_gateway_token.py`) and the gateway+# stamps it onto every `$ai_generation`. The other clients make the same match — desktop+# sends `posthog_code`, web sends `posthog_ai` — which is what puts all PostHog AI+# feedback on one metric, split by this property.+AI_PRODUCT = "slack_app"++# Slack's own cap on a `plain_text_input`, and Slack rejects the whole view past it, so the+# modal would not open at all. Below the desktop client's 4000 on purpose: a reason typed+# into this modal can never be longer, so one number serves the field and the truncation.+FEEDBACK_TEXT_MAX_LENGTH = 3000++_RATINGS: dict[str, Literal["good", "bad"]] = {"positive": "good", "negative": "bad"}+++@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.+ """++ integration: Integration+ run_id: str+ task_id: str | None+ turn_id: str | None+ slack_user_id: str+++def _parse_action_value(raw: Any) -> dict[str, Any]:+ if not isinstance(raw, str) or not raw:+ return {}+ try:+ value = json.loads(raw)+ except json.JSONDecodeError:+ return {}+ return value if isinstance(value, dict) else {}+++def clicked_feedback_value(payload: dict) -> dict[str, Any]:+ """The thumb that was clicked, as its value. Empty when this click is not a rating.++ Slack sends back only the button the reader pressed, so the value alone says which+ thumb it was.+ """+ action = next(+ (a for a in payload.get("actions", []) or () if a.get("action_id") == TURN_FEEDBACK_ACTION_ID),+ None,+ )+ return _parse_action_value(action.get("value")) if action else {}+++def _modal_metadata(payload: dict) -> dict[str, Any]:+ view = payload.get("view")+ if not isinstance(view, dict) or view.get("callback_id") != TURN_FEEDBACK_MODAL_CALLBACK_ID:+ return {}+ return _parse_action_value(view.get("private_metadata"))+++def extract_modal_hint(payload: dict) -> int | None:+ """The integration id the reason modal carries, for region-ownership routing.++ Only the modal needs its own extractor. A clicked thumb carries the id in the+ button's ``value``, which the router's generic action-value hint already reads; a+ view submission carries no action at all, so the id rides in ``private_metadata``.+ """+ integration_id = _modal_metadata(payload).get("integration_id")+ 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``.++ 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.+ """+ # 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):+ return None+ try:+ UUID(run_id)+ except (ValueError, AttributeError, TypeError):+ return None++ integration = (+ 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.+ .select_related("team__organization")+ .first()+ )+ if integration is None:+ return None++ run = get_task_run(run_id, team_id=integration.team_id)+ if run is None:+ logger.info("slack_app_turn_feedback_unknown_run", integration_id=integration.id, run_id=run_id)+ return None++ return _FeedbackTarget(+ integration=integration,+ run_id=str(run.id),+ task_id=str(run.task_id),+ turn_id=turn_id,+ slack_user_id=slack_user_id,+ )+++def _turn_id(payload: dict) -> str | None:+ """The rated answer's Slack timestamp, which is what identifies one turn in a thread.++ Stable for the life of the message, so a reader who changes their mind reports+ against the same turn and the later event is the one that counts.+ """+ message_ts = (payload.get("message") or {}).get("ts")+ if isinstance(message_ts, str) and message_ts:+ return message_ts+ container_ts = (payload.get("container") or {}).get("message_ts")+ return container_ts if isinstance(container_ts, str) and container_ts else None+++def _distinct_id(target: _FeedbackTarget) -> str:+ """Who the feedback is attributed to.++ The PostHog user behind the Slack identity when there is one, so a rating joins that+ person's feedback from the web and desktop clients. An unlinked reader is attributed to+ the project instead of minting a person keyed on a Slack id; ``slack_user_id`` rides on+ the event either way, so the click is still traceable to someone we can follow up with.+ """+ from products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user # noqa: PLC0415++ try:+ user = find_linked_posthog_user(+ slack_user_id=target.slack_user_id,+ slack_team_id=target.integration.integration_id or "",+ candidate_org_ids={target.integration.team.organization_id},+ )+ if user is not None and user.distinct_id:+ return user.distinct_id+ except Exception:+ logger.warning("slack_app_turn_feedback_user_lookup_failed", integration_id=target.integration.id)+ return str(target.integration.team.uuid)+++def _event_context(target: _FeedbackTarget) -> dict[str, Any]:+ """The properties both events share.++ The workspace half comes from ``slack_event_props``, the bundle every Slack app event+ carries, so a rating can be joined against the rest of them.++ ``$ai_session_id`` is the task id because every ``$ai_generation`` of a run carries it+ as ``task_id``, which is the same bargain the desktop client makes. ``$ai_trace_id`` is+ absent until the sandbox exposes per-turn trace ids; adding it here is what will attach+ a rating to the exact generation rather than to the run.+ """+ return slack_event_props(+ target.integration,+ slack_user_id=target.slack_user_id,+ **{+ "$ai_session_id": target.task_id,+ "ai_product": AI_PRODUCT,+ "agent_runtime": "sandbox",+ "task_id": target.task_id,+ "task_run_id": target.run_id,+ "turn_id": target.turn_id,+ },+ )+++def _capture(target: _FeedbackTarget, event: str, properties: dict[str, Any]) -> None:+ """Send one feedback event. Best-effort: analytics never breaks the click."""+ try:+ team = target.integration.team+ posthoganalytics.capture(+ distinct_id=_distinct_id(target),+ event=event,+ properties={**_event_context(target), **properties},+ groups=groups(team.organization, team),+ )+ except Exception:+ # NB: structlog's first positional arg is named `event`, so the captured event+ # rides under a different key rather than colliding with it.+ logger.warning("slack_app_turn_feedback_capture_failed", captured_event=event, exc_info=True)+++def _render_reason_modal(private_metadata: str) -> dict[str, Any]:+ return {+ "type": "modal",+ "callback_id": TURN_FEEDBACK_MODAL_CALLBACK_ID,+ "private_metadata": private_metadata,+ "title": {"type": "plain_text", "text": "Feedback"},+ "submit": {"type": "plain_text", "text": "Send"},+ "close": {"type": "plain_text", "text": "Cancel"},+ "blocks": [+ {+ "type": "input",+ "block_id": _MODAL_TEXT_BLOCK_ID,+ "label": {"type": "plain_text", "text": "What went wrong?"},+ "element": {+ "type": "plain_text_input",+ "action_id": _MODAL_TEXT_ACTION_ID,+ "multiline": True,+ "max_length": FEEDBACK_TEXT_MAX_LENGTH,+ "placeholder": {"type": "plain_text", "text": "What did you expect instead?"},+ },+ }+ ],+ }+++def _open_reason_modal(payload: dict, target: _FeedbackTarget) -> None:+ """Ask a bad rating for its reason. Best-effort: the rating is already recorded."""+ trigger_id = payload.get("trigger_id")+ if not trigger_id:+ return+ private_metadata = json.dumps(+ {+ "integration_id": target.integration.id,+ "run_id": target.run_id,+ "turn_id": target.turn_id,+ }+ )+ try:+ SlackIntegration(target.integration).client.views_open(+ trigger_id=trigger_id, view=_render_reason_modal(private_metadata)+ )+ except Exception:+ logger.warning("slack_app_turn_feedback_modal_open_failed", run_id=target.run_id, exc_info=True)+++def handle_turn_feedback_click(payload: dict) -> HttpResponse:+ """Record a clicked thumb, and ask a thumbs-down what went wrong.++ The reply is left as it is. A rating is one reader's view of an answer the whole+ thread can see, so rewriting the message would report it to everyone; the modal is+ what tells a thumbs-down that the click landed.+ """+ value = clicked_feedback_value(payload)+ sentiment = value.get("sentiment")+ rating = _RATINGS.get(sentiment) if isinstance(sentiment, str) else None+ if rating is None:+ logger.info("slack_app_turn_feedback_unknown_sentiment", sentiment=sentiment)+ return HttpResponse(status=200)++ target = _resolve_target(payload, value, _turn_id(payload))+ if target is None:+ return HttpResponse(status=200)++ # The modal goes first. Its trigger expires seconds after the click, while the capture+ # 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})+ return HttpResponse(status=200)+++def handle_turn_feedback_modal_submit(payload: dict) -> HttpResponse:+ """Record the reason typed into the bad-rating modal.++ The rating itself went out when the option was picked, so an abandoned modal costs+ nothing: this only adds the text.+ """+ metadata = _modal_metadata(payload)+ if not metadata:+ return HttpResponse(status=200)++ values = payload.get("view", {}).get("state", {}).get("values", {})+ raw_text = values.get(_MODAL_TEXT_BLOCK_ID, {}).get(_MODAL_TEXT_ACTION_ID, {}).get("value") or ""+ text = raw_text.strip()[:FEEDBACK_TEXT_MAX_LENGTH]+ if not text:+ # A submission error keeps the modal open with the message under the field.+ 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)+ if target is None:+ return HttpResponse(status=200)++ _capture(target, "$ai_feedback", {"$ai_feedback_text": text, "feedback_type": "bad"})+ return HttpResponse(status=200)diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex eb66d8c90ba0..324ef34a97df 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -8,7 +8,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integration, SlackIntegration-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_turn_feedback_enabledfrom products.slack_app.backend.services.model_catalogue import describe_run_modelfrom products.slack_app.backend.services.slack_messages import (RunFooter,@@ -21,6 +21,7 @@ from products.slack_app.backend.services.slack_messages import (post_slack_thread_reply,reply_footer_block,slack_message_exists,+ turn_feedback_block,viewer_has_code_access,)@@ -144,6 +145,7 @@ class SlackThreadHandler:self._client: WebClient | None = Noneself._bot_user_id: str | None = Noneself._fork_flag: bool | None = None+ self._feedback_flag: bool | None = Noneself._code_access: bool | None = Nonedef _get_integration(self) -> Integration:@@ -212,25 +214,48 @@ class SlackThreadHandler:return Nonereturn fork_menu_element(integration.id)- def _append_fork_menu(self, ts: str) -> None:- """Add the fork menu to a streamed reply, which has no section to hang it on.+ def _feedback_block(self) -> dict[str, Any] | None:+ """The thumbs for this reply, or `None` when there is nothing to rate.- Its own call on purpose: Slack documents no block-type restriction on a streamed- `blocks` chunk but does not confirm interactive blocks are allowed either, and- the answer rides the append before this one — a rejected request must cost the- menu, never the reply.+ A reply with no run behind it — a note, a card posted before the run existed —+ has nothing a rating could be attributed to, which is what keeps those replies+ off the flag lookup here."""+ run_id = self.run_footer.run_id+ if not run_id:+ return None+ integration = self._get_integration()+ if self._feedback_flag is None:+ self._feedback_flag = is_slack_app_turn_feedback_enabled(integration)+ if not self._feedback_flag:+ return None+ return turn_feedback_block(integration.id, run_id)++ def _append_trailing_blocks(self, ts: str) -> None:+ """Add the fork menu and the thumbs to a streamed reply, which has no section to+ hang either on.++ One append per block, and both after the answer's: a request Slack rejects must+ cost that control alone, never the reply and never its sibling.+ """+ for block, failure in (+ (self._fork_menu_actions_block(), "slack_app_fork_menu_append_failed"),+ (self._feedback_block(), "slack_app_feedback_buttons_append_failed"),+ ):+ if not block:+ continue+ try:+ self._get_client().chat_appendStream(+ channel=self.context.channel,+ ts=ts,+ chunks=[{"type": "blocks", "blocks": [block]}],+ )+ except Exception as e:+ logger.warning(failure, error=str(e))++ def _fork_menu_actions_block(self) -> dict[str, Any] | None:menu = self._fork_menu()- if not menu:- return- try:- self._get_client().chat_appendStream(- channel=self.context.channel,- ts=ts,- chunks=[{"type": "blocks", "blocks": [fork_menu_actions_block(menu)]}],- )- except Exception as e:- logger.warning("slack_app_fork_menu_append_failed", error=str(e))+ return fork_menu_actions_block(menu) if menu else Nonedef _get_bot_user_id(self) -> str | None:if self._bot_user_id is None:@@ -401,7 +426,7 @@ class SlackThreadHandler:except Exception as e:logger.warning("slack_app_status_stream_final_append_failed", error=str(e))if footer:- self._append_fork_menu(ts)+ self._append_trailing_blocks(ts)try:self._get_client().chat_stopStream(channel=self.context.channel,@@ -544,6 +569,9 @@ class SlackThreadHandler:menu = self._fork_menu()if menu:blocks.append(fork_menu_actions_block(menu))+ feedback = self._feedback_block()+ if feedback:+ blocks.append(feedback)try:self._post_in_thread(text=footer["elements"][0]["text"], blocks=blocks)except Exception as e:@@ -558,7 +586,9 @@ class SlackThreadHandler:ordinary message stays a plain-text post."""# A section block caps at 3000 characters; over that, dropping the footer costs a- # line of provenance, while keeping it would cost the whole message.+ # line of provenance, while keeping it would cost the whole message. The menu and+ # the thumbs go with it: an answer that long can only be posted as plain text,+ # which carries no blocks at all.footer = self._footer_block() if with_footer and len(text) <= _SECTION_TEXT_LIMIT else None# No footer means no blocks at all, so an ordinary message stays the plain-text# post it has always been. `expand` keeps the answer fully visible: a section@@ -573,6 +603,11 @@ class SlackThreadHandler:if menu:answer["accessory"] = menublocks = [answer, footer]+ # The thumbs close the message, below the footer, where a reader of any other+ # AI app already looks for them.+ feedback = self._feedback_block()+ if feedback:+ blocks.append(feedback)try:self._post_in_thread(text=text, blocks=blocks)except SlackApiError as e:diff --git a/products/slack_app/backend/tests/test_turn_feedback.py b/products/slack_app/backend/tests/test_turn_feedback.pynew file mode 100644index 000000000000..eb55f225cfd8--- /dev/null+++ b/products/slack_app/backend/tests/test_turn_feedback.py@@ -0,0 +1,176 @@+import json++from unittest.mock import patch++from django.apps import apps+from django.test import 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+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.turn_feedback import (+ _MODAL_TEXT_ACTION_ID,+ _MODAL_TEXT_BLOCK_ID,+ FEEDBACK_TEXT_MAX_LENGTH,+ TURN_FEEDBACK_MODAL_CALLBACK_ID,+)+from products.slack_app.backend.tests.helpers import sign_slack_request+++@override_settings(DEBUG=True)+class TestTurnFeedback(TestCase):+ """A rating is only worth collecting if it lands on the run it was given about, so these+ drive the real thumbs the reply carries rather than a hand-written payload: producer and+ consumer sit in different modules and would otherwise drift apart unnoticed."""++ signing_secret = "posthog-code-test-secret"+ slack_team_id = "T12345"++ def setUp(self):+ self.client = APIClient()+ self.org = Organization.objects.create(name="TestOrg")+ self.team = Team.objects.create(organization=self.org, name="TestTeam")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-member")+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id=self.slack_team_id, config={}+ )++ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ self.task = Task.objects.create(+ team=self.team,+ title="Fix the broken dashboard export",+ description="desc",+ origin_product=Task.OriginProduct.SLACK,+ created_by=self.user,+ repository="org/repo",+ )+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.IN_PROGRESS)++ config = patch(+ "products.slack_app.backend.api.SlackIntegration.slack_config",+ return_value={"SLACK_APP_SIGNING_SECRET": self.signing_secret},+ )+ config.start()+ self.addCleanup(config.stop)+ slack = patch("products.slack_app.backend.services.turn_feedback.SlackIntegration")+ self.mock_slack = slack.start()+ self.addCleanup(slack.stop)+ analytics = patch("products.slack_app.backend.services.turn_feedback.posthoganalytics")+ self.mock_analytics = analytics.start()+ self.addCleanup(analytics.stop)++ def _post(self, payload: dict):+ body = f"payload={json.dumps(payload)}"+ signed = sign_slack_request(body.encode(), self.signing_secret)+ return self.client.post(+ "/slack/interactivity-callback/",+ data=body,+ content_type="application/x-www-form-urlencoded",+ HTTP_X_SLACK_SIGNATURE=signed.signature,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,+ )++ def _thumb_value(self, sentiment: str, run_id: str | None = None) -> str:+ element = turn_feedback_block(self.integration.id, run_id or str(self.task_run.id))["elements"][0]+ button = "positive_button" if sentiment == "positive" else "negative_button"+ return element[button]["value"]++ def test_the_modal_input_fits_slack_cap(self):+ # Slack caps a plain_text_input at 3000 and rejects the whole view past it, so the+ # modal never opens and a thumbs-down collects no reason. Raising this to match+ # another client's limit is the mistake this guards.+ assert FEEDBACK_TEXT_MAX_LENGTH <= 3000++ def _pick(self, value: str):+ return self._post(+ {+ "type": "block_actions",+ "team": {"id": self.slack_team_id},+ "user": {"id": "U_ALICE"},+ "channel": {"id": "C_SOURCE"},+ "message": {"ts": "222.1", "thread_ts": "111.1"},+ "trigger_id": "trigger-1",+ "actions": [+ {"type": "button", "action_id": TURN_FEEDBACK_ACTION_ID, "value": value},+ ],+ }+ )++ @parameterized.expand([("positive", "good", False), ("negative", "bad", True)])+ def test_picking_a_rating_reports_it_against_the_run(self, sentiment, rating, asks_for_a_reason):+ response = self._pick(self._thumb_value(sentiment))++ assert response.status_code == 200+ 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+ # Must match what the gateway stamps on the run's own generations, or a rating+ # cannot be joined to the turn it rates.+ assert properties["ai_product"] == "slack_app"+ assert properties["task_run_id"] == str(self.task_run.id)+ 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 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):+ other_org = Organization.objects.create(name="OtherOrg")+ other_team = Team.objects.create(organization=other_org, name="OtherTeam")+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ other_task = Task.objects.create(+ team=other_team, title="Someone else's task", description="desc", repository="org/repo"+ )+ other_run = TaskRun.objects.create(task=other_task, team=other_team, status=TaskRun.Status.IN_PROGRESS)++ response = self._pick(self._thumb_value("negative", run_id=str(other_run.id)))++ assert response.status_code == 200+ self.mock_analytics.capture.assert_not_called()++ def _submit_reason(self, text: str):+ return self._post(+ {+ "type": "view_submission",+ "team": {"id": self.slack_team_id},+ "user": {"id": "U_ALICE"},+ "view": {+ "callback_id": TURN_FEEDBACK_MODAL_CALLBACK_ID,+ "private_metadata": json.dumps(+ {+ "integration_id": self.integration.id,+ "run_id": str(self.task_run.id),+ "turn_id": "222.1",+ }+ ),+ "state": {"values": {_MODAL_TEXT_BLOCK_ID: {_MODAL_TEXT_ACTION_ID: {"value": text}}}},+ },+ }+ )++ def test_the_reason_is_reported_against_the_same_run(self):+ response = self._submit_reason(" it answered about the wrong dashboard ")++ assert response.status_code == 200+ self.mock_analytics.capture.assert_called_once()+ kwargs = self.mock_analytics.capture.call_args.kwargs+ assert kwargs["event"] == "$ai_feedback"+ assert kwargs["properties"]["$ai_feedback_text"] == "it answered about the wrong dashboard"+ assert kwargs["properties"]["task_run_id"] == str(self.task_run.id)+ assert kwargs["properties"]["turn_id"] == "222.1"++ def test_an_empty_reason_keeps_the_modal_open(self):+ response = self._submit_reason(" ")++ assert response.json()["response_action"] == "errors"+ self.mock_analytics.capture.assert_not_called()