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): pass the question to reply suggestions and fix labels (#118344)

Vojta Bartoš5b2cba2f6da6
diff --git a/products/slack_app/backend/logic/reply_suggestions.py b/products/slack_app/backend/logic/reply_suggestions.py
index d569befd9436..6005e09f5433 100644
--- a/products/slack_app/backend/logic/reply_suggestions.py
+++ b/products/slack_app/backend/logic/reply_suggestions.py
@@ -12,6 +12,7 @@ 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
+from posthog.slack.channels import clip_text
logger = structlog.get_logger(__name__)
@@ -29,7 +30,7 @@ MAX_SUGGESTIONS = 3
MAX_LABEL_CHARS = 75
MAX_REPLY_CHARS = 300
-SUGGESTIONS_MODEL = "gpt-5.6-luna"
+SUGGESTIONS_MODEL = "gpt-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.
@@ -38,48 +39,72 @@ 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
+# A person's message is short, and a long one is a pasted log the answer already covers.
+PERSON_MESSAGE_CHARS = 2000
# 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.
+You write reply buttons for a Slack thread. The next message holds the PostHog agent's answer in \
+<agent_answer>. When it is known, the message that the person sent before the answer is in \
+<person_message>. The person who reads the answer can send one of your replies with one click.
+
+Use the person's message to see what they want, who decides, and which reply they will most likely send. \
+Write replies only to what the answer asks or offers, not to the person's message.
+
+First decide if the answer waits for the person. It does when it asks for permission, offers a next step, \
+or asks the person to choose or to confirm. If the answer only reports a result, explains something, or asks \
+nothing, return an empty list. If the next step waits for someone other than the person, such as another \
+team, or for an event that has not happened yet, 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: the messages the person will most likely type next.
+
+Write each reply the way a person types a short Slack message to a colleague:
+- The person sees only the label, under a long answer, so the label is the whole reply at a glance. \
+Name the choice in its own words, never by its number or letter alone. Not "Option 2" or "Use option 2", \
+but "Stacked rows" or "Go with stacked rows".
+- Vary the form. Do not put the same word in front of every label, such as "Use" or "Yes". When the \
+choices are parallel, a label can be the name of the choice alone. A good set reads like three different \
+people answering, not like a form.
+- Make each reply a different choice. Do not offer two replies that mean the same thing.
+- Put the most likely reply first. When the answer recommends a choice, that reply is the most likely.
+- Write in the language of the answer.
-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".
+Keep to what the answer offers:
- Offer only actions that the answer names or clearly implies. Do not invent new work.
-- If the answer offers to investigate or check something first and then make a change, such as a pull \
-request or a code or config change, keep the two steps apart. Put first a reply that asks only for the \
-investigation, so the agent reports what it finds and waits. A reply that also makes the change is a \
-separate choice. Ask for a pull request or a change only in a reply that the person picks for that change.
+- If the answer asks two or more separate questions, do not write a reply for each combination of \
+answers. Write a reply only if it answers every question with a combination that the answer recommends. \
+If there is none, return an empty list.
+- If the answer offers to check something first and then make a change, such as a pull request or a code \
+or config change, keep the two steps apart. Put first a reply that asks only for the check, so the agent \
+reports what it finds and waits. A reply that also makes the change is a separate choice.
- 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.
-- If the answer offers to fix a bug or an error, use "Fix it, make no mistakes" as the label of the reply \
-that accepts the fix. Its reply starts with "Fix it, make no mistakes." and can add the step that the answer \
-names, for example "Fix it, make no mistakes. Open the pull request with the fix." Do not also offer a plain \
-"Yes, fix it" reply. If the answer is not in English, translate this reply.
+- If the answer offers to fix a bug or an error, the reply that accepts the fix has the label \
+"Fix it, make no mistakes". Its reply starts with "Fix it, make no mistakes." and can add the step that the \
+answer names. Do not also offer a plain "Yes, fix it" reply. If the answer is not in English, translate the \
+label and the reply word for word, such as "Beheb es, ohne Fehler" in German, and do not reword them.
+- Do not use em dashes. Use a comma or a full stop.
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.
+It means the same as the label and can add the detail the label leaves out, such as the option number.
+
+Examples of good sets:
+- The answer asks "Should I open a pull request with the fix?": \
+[{"label": "Yes, open the PR", "reply": "Yes, open the pull request with the fix"}, \
+{"label": "Show me the diff first", "reply": "Show me the diff first, before you open anything"}]
+- The answer lists three layouts and asks which one: \
+[{"label": "Stacked rows", "reply": "Go with stacked rows (option 2)"}, \
+{"label": "The card with toggles", "reply": "The card with toggles (option 1), please"}, \
+{"label": "Persona tabs", "reply": "Persona tabs (option 3)"}]
+- The answer says "I can also break this down by acquisition source": \
+[{"label": "Break it down by source", "reply": "Yes, break it down by acquisition source"}, \
+{"label": "No need, this is enough", "reply": "No need, this is enough for now"}]
-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"}]}."""
+Answer only with JSON, for example {"suggestions": [{"label": "...", "reply": "..."}]}."""
@frozen
@@ -136,6 +161,14 @@ def _clip_answer(answer: str) -> str:
return f"{answer[:ANSWER_HEAD_CHARS]}\n…\n{answer[-ANSWER_TAIL_CHARS:]}"
+def _user_content(answer_markdown: str, person_message: str | None) -> str:
+ answer = f"<agent_answer>\n{_clip_answer(answer_markdown)}\n</agent_answer>"
+ message = clip_text(" ".join((person_message or "").split()), PERSON_MESSAGE_CHARS)
+ if not message:
+ return answer
+ return f"<person_message>\n{message}\n</person_message>\n\n{answer}"
+
+
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):
@@ -154,7 +187,9 @@ def _clean_suggestions(raw: object) -> list[SuggestedReply]:
return suggestions[:MAX_SUGGESTIONS]
-def request_reply_suggestions(answer_markdown: str, attribution: ReplySuggestionAttribution) -> list[SuggestedReply]:
+def request_reply_suggestions(
+ answer_markdown: str, attribution: ReplySuggestionAttribution, person_message: str | None = None
+) -> 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 []
@@ -176,7 +211,7 @@ def request_reply_suggestions(answer_markdown: str, attribution: ReplySuggestion
model=SUGGESTIONS_MODEL,
messages=[
{"role": "system", "content": REPLY_SUGGESTIONS_INSTRUCTIONS},
- {"role": "user", "content": _clip_answer(answer_markdown)},
+ {"role": "user", "content": _user_content(answer_markdown, person_message)},
],
max_completion_tokens=SUGGESTIONS_MAX_COMPLETION_TOKENS,
response_format=_RESPONSE_FORMAT,
@@ -188,11 +223,13 @@ def request_reply_suggestions(answer_markdown: str, attribution: ReplySuggestion
return _clean_suggestions(parsed.get("suggestions"))
-def suggest_replies(answer_markdown: str, attribution: ReplySuggestionAttribution) -> list[SuggestedReply]:
+def suggest_replies(
+ answer_markdown: str, attribution: ReplySuggestionAttribution, person_message: str | None = None
+) -> 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)
+ return request_reply_suggestions(answer_markdown, attribution, person_message)
except Exception:
logger.warning("slack_app_reply_suggestions_failed", exc_info=True)
return []
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 2e44919cb7dc..0e0ef47e7d9b 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -174,6 +174,8 @@ class SlackThreadContext:
thread_ts: str
user_message_ts: str | None = None
mentioning_slack_user_id: str | None = None
+ # The mention that opened the run. Only the run's first turn answers it.
+ person_message: str | None = None
def to_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {
@@ -185,6 +187,8 @@ class SlackThreadContext:
d["user_message_ts"] = self.user_message_ts
if self.mentioning_slack_user_id is not None:
d["mentioning_slack_user_id"] = self.mentioning_slack_user_id
+ if self.person_message is not None:
+ d["person_message"] = self.person_message
return d
@classmethod
@@ -195,6 +199,7 @@ class SlackThreadContext:
thread_ts=data["thread_ts"],
user_message_ts=data.get("user_message_ts"),
mentioning_slack_user_id=data.get("mentioning_slack_user_id"),
+ person_message=data.get("person_message"),
)
@classmethod
@@ -252,12 +257,15 @@ class SlackThreadHandler:
run_footer: RunFooter | None = None,
actor_slack_user_id: str | None = None,
turn_trace_id: str | None = None,
+ turn_person_message: str | None = None,
) -> None:
self.context = context
self.run_footer = run_footer or RunFooter()
# Beside the footer rather than in it: a trace id belongs to one turn, and the
# next turn in the same thread has its own.
self.turn_trace_id = turn_trace_id
+ # What the person said to start this turn, so reply suggestions know what they asked for.
+ self.turn_person_message = turn_person_message
# Who this reply is for, which can differ from the task creator because a thread
# outlives its opener.
self.actor_slack_user_id = actor_slack_user_id or context.mentioning_slack_user_id
@@ -276,6 +284,7 @@ class SlackThreadHandler:
*,
actor_slack_user_id: str | None = None,
turn_trace_id: str | None = None,
+ turn_person_message: str | None = None,
) -> "SlackThreadHandler":
"""A handler whose footer describes ``run_id``.
@@ -287,6 +296,7 @@ class SlackThreadHandler:
load_run_footer(run_id, integration_id=context.integration_id),
actor_slack_user_id=actor_slack_user_id,
turn_trace_id=turn_trace_id,
+ turn_person_message=turn_person_message,
)
def _get_integration(self) -> Integration:
@@ -1003,7 +1013,7 @@ class SlackThreadHandler:
task_id=self.run_footer.task_id,
run_id=self.run_footer.run_id,
)
- suggestions = suggest_replies(answer_markdown, attribution)
+ suggestions = suggest_replies(answer_markdown, attribution, self.turn_person_message)
if not suggestions:
return None
return suggestions, reply_suggestions_block(integration.id, suggestions, self.turn_trace_id)
diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.py
index 4af7082aaf95..267a0ea4d5ba 100644
--- a/products/slack_app/backend/temporal/activities/task_creation.py
+++ b/products/slack_app/backend/temporal/activities/task_creation.py
@@ -691,6 +691,7 @@ def create_posthog_code_task_for_repo_activity(
thread_ts=thread_ts,
user_message_ts=user_message_ts,
mentioning_slack_user_id=slack_user_id,
+ person_message=title_text or None,
)
# Points at the thread the agent answers in — the DM for a fork, not the thread
@@ -988,9 +989,12 @@ def forward_posthog_code_followup_activity(
from products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415
collect_thread_messages,
decode_slack_event_text,
+ labeled_mentions_to_display_names,
)
user_text = decode_slack_event_text(slack, integration, event_text)
+ # Taken before the thread digest and the speaker prefix join it, so it holds only this person's words.
+ person_message = labeled_mentions_to_display_names(user_text) or None
bot_token = get_slack_bot_token(slack, integration)
event_files = parse_slack_file_refs(inputs.event.get("files"))
# Shared with the thread fetch below, so the reply and the catch-up files draw on one
@@ -1094,6 +1098,7 @@ def forward_posthog_code_followup_activity(
actor_user_id=actor_user.id if actor_user and actor_user.id else None,
message_id=_slack_followup_message_id(channel, user_message_ts, thread_ts),
actor_slack_user_id=slack_user_id,
+ person_message=person_message,
)
if signal_result is not True:
logger.warning(
@@ -1349,13 +1354,17 @@ def _resume_task_with_new_run(
model_override: SlackAppModelOverride | None = None,
) -> bool:
"""Create a new run on the same task when a follow-up arrives after the previous run completed."""
- from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415
+ from products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415
+ decode_slack_event_text,
+ labeled_mentions_to_display_names,
+ )
from products.slack_app.backend.slack_thread import SlackThreadContext
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.temporal import dispatch_task_processing_workflow
integration = slack.integration
user_text = decode_slack_event_text(slack, integration, event_text)
+ person_message = labeled_mentions_to_display_names(user_text) or None
prepared_attachments = prepare_slack_file_artifacts(
parse_slack_file_refs(inputs.event.get("files")), get_slack_bot_token(slack, integration)
)
@@ -1507,6 +1516,7 @@ def _resume_task_with_new_run(
thread_ts=thread_ts,
user_message_ts=user_message_ts,
mentioning_slack_user_id=slack_user_id,
+ person_message=person_message,
)
try:
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 7ecb0c809c33..f2a99290df78 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -1141,6 +1141,8 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
assert mock_signal.call_args.args == (self.task_run.id, self.task.id, self.team.id)
signal_kwargs = mock_signal.call_args.kwargs
assert signal_kwargs["content"] == "Bob: please retry the build"
+ # Reply suggestions get the person's own words, without the speaker prefix the agent needs.
+ assert signal_kwargs["person_message"] == "please retry the build"
assert signal_kwargs["actor_user_id"] == bob.id
assert signal_kwargs["message_id"] is not None
# No "Only the person who started" denial; the message went through.
diff --git a/products/slack_app/backend/tests/test_reply_suggestions.py b/products/slack_app/backend/tests/test_reply_suggestions.py
index c20c076c9a74..bbbfe000a568 100644
--- a/products/slack_app/backend/tests/test_reply_suggestions.py
+++ b/products/slack_app/backend/tests/test_reply_suggestions.py
@@ -116,6 +116,18 @@ class TestSuggestReplies(SimpleTestCase):
build.return_value.with_options.return_value.chat.completions.create.side_effect = TimeoutError()
assert suggest_replies("Should I open a PR?", ReplySuggestionAttribution()) == []
+ def test_the_person_message_reaches_the_model_apart_from_the_answer(self) -> None:
+ with patch("products.slack_app.backend.logic.reply_suggestions.build_openai_client") as build:
+ create = build.return_value.with_options.return_value.chat.completions.create
+ create.return_value = _completion(json.dumps({"suggestions": []}))
+ suggest_replies("Should I open a PR?", ReplySuggestionAttribution(), "Why does the retry never stop?")
+
+ content = create.call_args.kwargs["messages"][1]["content"]
+ assert content == (
+ "<person_message>\nWhy does the retry never stop?\n</person_message>\n\n"
+ "<agent_answer>\nShould I open a PR?\n</agent_answer>"
+ )
+
@override_settings(DEBUG=True)
@patch("products.slack_app.backend.api.SlackIntegration")
@@ -268,14 +280,16 @@ class TestReplySuggestionPlacement(SimpleTestCase):
@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
+ self, mock_get_client, mock_get_integration, _mock_enabled, mock_suggest, _mock_capture
) -> 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")
+ SlackThreadContext(integration_id=7, channel="C001", thread_ts="1.0"),
+ RunFooter(model="claude-opus-5"),
+ turn_person_message="why does the retry never stop?",
)
handler.post_thread_message("Should I open a pull request?", with_footer=True, markdown=True)
@@ -288,6 +302,7 @@ class TestReplySuggestionPlacement(SimpleTestCase):
assert update["blocks"][0] == posted[0]
assert update["blocks"][1]["block_id"] == REPLY_SUGGESTIONS_BLOCK_ID
assert update["blocks"][2:] == posted[1:]
+ assert mock_suggest.call_args.args[2] == "why does the retry never stop?"
class TestClearOpenSuggestions(SimpleTestCase):
diff --git a/products/slack_app/evals/eval_reply_suggestions.py b/products/slack_app/evals/eval_reply_suggestions.py
index 154c24dc4e19..eb80eca083e9 100644
--- a/products/slack_app/evals/eval_reply_suggestions.py
+++ b/products/slack_app/evals/eval_reply_suggestions.py
@@ -22,6 +22,10 @@ from products.slack_app.evals.scorers import REPLY_OFFER_KEY, NoUnaskedButtons,
SUITE_KIND = SuiteKind.ONE_SHOT
+# The person's last message, when a case needs it to show who decides or what they want.
+PERSON_MESSAGE_KEY = "person_message"
+
+
def _offer(offer: bool) -> dict:
return {REPLY_OFFER_KEY: {"offer": offer}}
@@ -46,6 +50,7 @@ WAITING_CASES = [
"after a failure. The fix is two lines in `relay.py`. Should I open a pull request with it?"
),
expected=_offer(True),
+ metadata={PERSON_MESSAGE_KEY: "Why does the relay keep retrying after the export fails?"},
),
BaseEvalCase(
name="choice_between_options",
@@ -102,6 +107,18 @@ WAITING_CASES = [
),
expected=_offer(True),
),
+ # Buttons for every mix of the two answers would differ by one word each and leave a mix out.
+ BaseEvalCase(
+ name="two_separate_questions",
+ prompt=(
+ "The weekly digest is ready. Two things to decide:\n\n"
+ "1. **Channel:** email reaches everyone, and Slack reaches only the team that joined the "
+ "`#digest` channel. I recommend Slack, because the email list has many old addresses.\n"
+ "2. **Day:** Monday or Friday. I suggest Monday, so the numbers are fresh for the week.\n\n"
+ "Which channel and which day do you want?"
+ ),
+ expected=_offer(True),
+ ),
BaseEvalCase(
name="permission_in_german",
prompt=(
@@ -145,6 +162,17 @@ BARE_CASES = [
prompt="Done. The alert now fires at 5% instead of 10%. Let me know if you need anything else.",
expected=_offer(False),
),
+ # The reader cannot make this decision, so a button would commit to a choice for another team.
+ BaseEvalCase(
+ name="decision_waits_for_another_team",
+ prompt=(
+ "The billing team is choosing between monthly and yearly usage caps. If they pick monthly caps, "
+ "I can open the pull request for the new limit. If they pick yearly caps, the current branch is "
+ "ready to merge as it is."
+ ),
+ expected=_offer(False),
+ metadata={PERSON_MESSAGE_KEY: "What is left before we can ship the usage caps?"},
+ ),
# 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",
@@ -157,17 +185,24 @@ BARE_CASES = [
async def eval_reply_suggestions(ctx: EvalContext) -> None:
async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
model = reply_suggestions.SUGGESTIONS_MODEL
+ person_message = case.metadata.get(PERSON_MESSAGE_KEY)
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(),
+ person_message,
)
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}"}
+ return {
+ "model": model,
+ "suggestions": offered,
+ "person_message": person_message,
+ "last_message": f"{model}: {offered}",
+ }
await OneShotPublicEval(
experiment_name="slack-app-reply-suggestions",
diff --git a/products/slack_app/evals/scorers.py b/products/slack_app/evals/scorers.py
index 2b88cac4813c..8e238c3a0236 100644
--- a/products/slack_app/evals/scorers.py
+++ b/products/slack_app/evals/scorers.py
@@ -413,6 +413,7 @@ class SuggestedRepliesFit(JudgedScorer):
return {
"output": {
"answer": (output or {}).get("prompt", ""),
+ "person_message": (output or {}).get("person_message") or "(not known)",
"replies": "\n".join(f'- button "{s["label"]}" sends "{s["reply"]}"' for s in suggestions),
}
}
@@ -423,6 +424,11 @@ class SuggestedRepliesFit(JudgedScorer):
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.
+The person's last message before the answer:
+<person_message>
+{{output.person_message}}
+</person_message>
+
Agent's answer:
<answer>
{{output.answer}}
@@ -435,6 +441,9 @@ Offered 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
+- have a label that names the choice in words, not only by its number or letter, such as "Option 2"
+- read like a short message a person typed, and not every label starts with the same word, such as "Use" or "Yes"
+- if the answer asks more than one question, answer every question, and not offer near-copies that change one part of a combination
- 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
@@ -443,6 +452,8 @@ Each reply has a short button label and the full text the button sends. Every re
- mean something different from every other reply
- if the answer offers to check something first and then make a change, such as a pull request, not ask for the check and the change together unless another reply asks for the check alone
+One reply is fixed on purpose. When the answer offers to fix a bug or an error, the reply that accepts the fix has the label "Fix it, make no mistakes", or its translation, and its text starts with the same words. "Make no mistakes" is not an extra action. The label stands for the fix and for the step that its text adds, such as opening a pull request.
+
Answer `yes` if every reply follows all of these rules. Answer `no` if one reply breaks one rule.
""".strip(),
choice_scores=BINARY_CHOICE_SCORES,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index d0953945589d..caf5b46a88b2 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5470,6 +5470,7 @@ def signal_task_run_user_message(
actor_user_id: int | None = None,
message_id: str | None = None,
actor_slack_user_id: str | None = None,
+ person_message: str | None = None,
steer: bool = False,
rpc_timeout: timedelta | None = None,
workflow_id: str | None = None,
@@ -5513,7 +5514,8 @@ def signal_task_run_user_message(
raise ComputeBillingLimitError({"team_id": team_id, "task_id": str(task_id), "run_id": str(run_id)}, reason)
accepted_at = django_timezone.now()
try:
- context = {"actor_slack_user_id": actor_slack_user_id} if actor_slack_user_id else None
+ context_values = {"actor_slack_user_id": actor_slack_user_id, "person_message": person_message}
+ context = {key: value for key, value in context_values.items() if value} or None
signal_task_followup_message(
workflow_id or run.workflow_id,
content,
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index 7571a3d94817..96364162feef 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -55,7 +55,7 @@ from products.tasks.backend.temporal.process_task.utils import (
mark_sandbox_github_identity,
mark_sandbox_mcp_session,
mcp_exclude_tools_from_state,
- record_message_actor,
+ record_delivered_message,
sandbox_identity_scope,
upgrade_run_to_user_authorship,
)
@@ -442,8 +442,14 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
)
raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)
- if input.message_id and actor_slack_user_id:
- record_message_actor(input.run_id, input.message_id, actor_slack_user_id)
+ if input.message_id:
+ person_message = (input.context or {}).get("person_message")
+ record_delivered_message(
+ input.run_id,
+ input.message_id,
+ actor_slack_user_id=actor_slack_user_id,
+ person_message=person_message if isinstance(person_message, str) else None,
+ )
result = send_user_message(
task_run,
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 2b89944b63d4..fd063eb547cb 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
@@ -76,6 +76,10 @@ class StopSlackAgentDesignStreamInput:
# 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
+ # The message this turn answers, and, on the run's first turn only, the mention that opened the
+ # run. One of them says what the person asked, for the reply suggestions.
+ message_id: Optional[str] = None
+ mention: Optional[str] = None
def _rewrite_object_tags(text: Optional[str], project_url: str) -> Optional[str]:
@@ -163,6 +167,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> No
stream_pending_slack_attachments,
)
from products.tasks.backend.models import TaskRun
+ from products.tasks.backend.temporal.process_task.utils import turn_person_message
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
@@ -171,6 +176,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> No
input.run_id,
actor_slack_user_id=input.actor_slack_user_id,
turn_trace_id=input.trace_id,
+ turn_person_message=turn_person_message(input.run_id, input.message_id, mention=input.mention),
)
task_run = TaskRun.objects.get(id=input.run_id) if input.run_id else None
deliveries: list[SlackFileDeliveryResult] = []
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 95641a9df2b5..697cc024e782 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
@@ -76,6 +76,8 @@ class SlackAgentDesignRelayInput:
setup_title: Optional[str] = None
# The message this turn answers, so the reply tags its sender.
message_id: Optional[str] = None
+ # The mention that opened the run. Set only on the relay that streams the first turn.
+ person_message: Optional[str] = None
@workflow.defn(name="slack-agent-design-relay")
@@ -483,6 +485,8 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):
mention_sent=mention_sent,
actor_slack_user_id=self._stream.actor_slack_user_id,
answer_markdown=final_answer if self._turn_complete else None,
+ message_id=input.message_id,
+ mention=input.person_message,
),
# 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_slack_agent_design.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py
index 818e5bc3b231..2f97353ce4f6 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py
@@ -20,7 +20,7 @@ from products.tasks.backend.temporal.process_task.activities.slack_agent_design
start_slack_agent_design_stream,
stop_slack_agent_design_stream,
)
-from products.tasks.backend.temporal.process_task.utils import record_message_actor
+from products.tasks.backend.temporal.process_task.utils import record_delivered_message
PROJECT_URL = "https://us.posthog.com/project/7"
@@ -119,6 +119,52 @@ class TestSlackAgentDesignStream(TestCase):
assert mock_stop.call_args.args[0].turn_trace_id == trace_id
+ @parameterized.expand(
+ [
+ ("first_turn_answers_the_mention", None, "Why is the export slow?", "Why is the export slow?"),
+ ("follow_up_answers_its_own_message", "msg-2", None, "Add the index too"),
+ # The record expired, and the relay passes no mention past the first turn, so it gets nothing.
+ ("follow_up_without_a_record", "msg-3", None, None),
+ ]
+ )
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream", autospec=True)
+ def test_closing_the_stream_hands_the_suggestions_what_the_turn_answers(
+ self, _name, message_id, mention, expected, mock_stop
+ ) -> None:
+ record_delivered_message(
+ str(self.task_run.id), "msg-2", actor_slack_user_id=None, person_message="Add the index too"
+ )
+
+ stop_slack_agent_design_stream(
+ StopSlackAgentDesignStreamInput(
+ slack_thread_context={"integration_id": self.integration.id, "channel": "C1", "thread_ts": "1.0"},
+ ts="2.0",
+ final_markdown="Should I add the index?",
+ run_id=str(self.task_run.id),
+ message_id=message_id,
+ mention=mention,
+ )
+ )
+
+ assert mock_stop.call_args.args[0].turn_person_message == expected
+
+ @patch("products.tasks.backend.temporal.process_task.utils.get_tasks_cache", side_effect=RuntimeError("redis"))
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream", autospec=True)
+ def test_a_cache_failure_still_closes_the_stream(self, mock_stop, _mock_cache) -> None:
+ # The lookup only feeds the buttons, so it must not stop the answer and its attachments.
+ stop_slack_agent_design_stream(
+ StopSlackAgentDesignStreamInput(
+ slack_thread_context={"integration_id": self.integration.id, "channel": "C1", "thread_ts": "1.0"},
+ ts="2.0",
+ final_markdown="Should I add the index?",
+ run_id=str(self.task_run.id),
+ message_id="msg-2",
+ )
+ )
+
+ mock_stop.assert_called_once()
+ assert mock_stop.call_args.args[0].turn_person_message is None
+
@patch("products.tasks.backend.logic.services.living_artifacts.deliver_pending_slack_file_artifacts")
@patch.object(SlackThreadHandler, "_get_client")
def test_a_stream_slack_closed_still_delivers_the_turns_attachments(self, mock_get_client, mock_deliver) -> None:
@@ -154,7 +200,7 @@ class TestSlackAgentDesignStream(TestCase):
def test_opening_the_stream_tags_the_turns_sender_not_the_thread_creator(
self, _name, message_id, expected_target, mock_start
) -> None:
- record_message_actor(str(self.task_run.id), "msg-2", "U789")
+ record_delivered_message(str(self.task_run.id), "msg-2", actor_slack_user_id="U789", person_message=None)
stream = start_slack_agent_design_stream(
StartSlackAgentDesignStreamInput(
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index a4d82c92b7fd..192eaa7753d5 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -2576,13 +2576,20 @@ class TestProcessTaskWorkflowUnit:
monkeypatch.setattr(workflow, "_start_slack_agent_design_relay", start_slack_relay_mock)
monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
- result = await workflow.run(ProcessTaskInput(run_id="run-id", slack_thread_context={"channel": "C1"}))
+ result = await workflow.run(
+ ProcessTaskInput(
+ run_id="run-id", slack_thread_context={"channel": "C1", "person_message": "Why is the export slow?"}
+ )
+ )
assert result.success is True
relay_sandbox_events_mock.assert_not_called()
relay_agent_design_signals_mock.assert_called_once()
- # The plan shows while the sandbox provisions, so the relay starts before the first turn.
- start_slack_relay_mock.assert_awaited_once_with({"channel": "C1"}, setup_title="Setting up sandbox")
+ # The plan shows while the sandbox provisions, so the relay starts before the first turn. The
+ # mention goes with it alone, not with the context every later payload carries.
+ start_slack_relay_mock.assert_awaited_once_with(
+ {"channel": "C1"}, setup_title="Setting up sandbox", person_message="Why is the export slow?"
+ )
@pytest.mark.parametrize(
"early_relay_open, expected_starts",
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 35662dfa1013..71329c7ea7b5 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1742,28 +1742,55 @@ def get_git_identity_env_vars(task: Task, state: dict[str, Any] | None = None) -
}
-def _message_actor_cache_key(run_id: str, message_id: str) -> str:
- return f"tasks:followup-actor:{run_id}:{message_id}"
+def _message_record_key(kind: str, run_id: str, message_id: str) -> str:
+ return f"tasks:followup-{kind}:{run_id}:{message_id}"
# Bounds how long after delivery a turn can finish and still get exact
# per-message attribution; longer turns fall back to the run-state actors.
-MESSAGE_ACTOR_TTL_SECONDS = 2 * 60 * 60
+DELIVERED_MESSAGE_TTL_SECONDS = 2 * 60 * 60
-def record_message_actor(run_id: str, message_id: str, slack_user_id: str) -> None:
- """Correlate a delivered message with its sender's Slack id, so a relay
- echoing the message id can tag the exact speaker it answers. The sandbox
- only ever echoes an opaque id — resolution happens against actors this
- server recorded itself, so a compromised sandbox cannot pick an arbitrary
- mention target."""
- get_tasks_cache().set(
- _message_actor_cache_key(run_id, message_id), slack_user_id, timeout=MESSAGE_ACTOR_TTL_SECONDS
- )
+def record_delivered_message(
+ run_id: str, message_id: str, *, actor_slack_user_id: str | None, person_message: str | None
+) -> None:
+ """Correlate a delivered message with its sender's Slack id and the sender's own words, so a
+ relay echoing the message id can tag the exact speaker it answers and offer replies that fit
+ what they asked. The sandbox only ever echoes an opaque id — resolution happens against values
+ this server recorded itself, so a compromised sandbox cannot pick an arbitrary mention target."""
+ records = {
+ _message_record_key(kind, run_id, message_id): value
+ for kind, value in (("actor", actor_slack_user_id), ("person-message", person_message))
+ if value
+ }
+ if records:
+ get_tasks_cache().set_many(records, timeout=DELIVERED_MESSAGE_TTL_SECONDS)
def get_message_actor(run_id: str, message_id: str) -> str | None:
- return get_tasks_cache().get(_message_actor_cache_key(run_id, message_id))
+ return get_tasks_cache().get(_message_record_key("actor", run_id, message_id))
+
+
+def turn_person_message(run_id: str | None, message_id: str | None, *, mention: str | None = None) -> str | None:
+ """What the person said to start the turn that answers ``message_id``.
+
+ ``mention`` is the message that opened the run, and only the run's first turn passes it: a later
+ turn never falls back to it, because the mention is not what that turn answers.
+ """
+ if run_id and message_id:
+ # The answer must still go out when the cache is down; the buttons then come from the answer alone.
+ try:
+ recorded = get_tasks_cache().get(_message_record_key("person-message", run_id, message_id))
+ except Exception:
+ logger.warning(
+ "turn_person_message_lookup_failed",
+ extra={"run_id": run_id, "message_id": message_id},
+ exc_info=True,
+ )
+ recorded = None
+ if isinstance(recorded, str) and recorded:
+ return recorded
+ return mention or None
def slack_reply_target(task_run: TaskRun, mapping: SlackThreadTaskMapping | None, message_id: str | None) -> str | None:
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 77c390f84dd9..842fa1a1ba60 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -545,6 +545,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
def __init__(self) -> None:
self._context: Optional[TaskProcessingContext] = None
self._slack_thread_context: Optional[dict[str, Any]] = None
+ self._opening_person_message: Optional[str] = None
self._posthog_mcp_scopes: PosthogMcpScopes = "read_only"
self._sandbox_id_for_cleanup: Optional[str] = None
# Captured once the agent server is up, for handing to a continue_as_new continuation.
@@ -1320,6 +1321,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
run_id = input.run_id
self._sandbox_id_for_cleanup = None
self._slack_thread_context = input.slack_thread_context
+ # Taken off the context, so the mention rides in the first turn's relay only, not in every
+ # later payload that carries the context.
+ if self._slack_thread_context and "person_message" in self._slack_thread_context:
+ self._slack_thread_context = dict(self._slack_thread_context)
+ self._opening_person_message = self._slack_thread_context.pop("person_message")
self._prewarmed = input.prewarmed
credential_refresh_task: asyncio.Task[None] | None = None
permission_response_task: asyncio.Task[None] | None = None
@@ -1919,7 +1925,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await self._post_slack_update()
elif self._slack_thread_context:
# The first turn's relay starts now, so the plan shows while the sandbox provisions.
- await self._start_slack_agent_design_relay(self._slack_thread_context, setup_title=sandbox_label)
+ await self._start_slack_agent_design_relay(
+ self._slack_thread_context, setup_title=sandbox_label, person_message=self._opening_person_message
+ )
self._early_slack_relay_open = True
sandbox_output = await self._get_sandbox_for_repository()
@@ -3665,7 +3673,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await self._start_slack_agent_design_relay(slack_ctx, message_id=payload.get("message_id"))
async def _start_slack_agent_design_relay(
- self, slack_ctx: dict[str, Any], setup_title: Optional[str] = None, message_id: Optional[str] = None
+ self,
+ slack_ctx: dict[str, Any],
+ setup_title: Optional[str] = None,
+ message_id: Optional[str] = None,
+ person_message: Optional[str] = None,
) -> None:
relay_workflow_id = f"slack-agent-design-relay-{self.context.run_id}-{workflow.uuid4()}"
self._current_slack_relay_workflow_id = relay_workflow_id
@@ -3676,6 +3688,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
run_id=self.context.run_id,
setup_title=setup_title,
message_id=message_id,
+ person_message=person_message,
),
id=relay_workflow_id,
task_queue=workflow.info().task_queue,
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index 8bbd685404f9..9d91a96920f0 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -204,7 +204,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
)
from products.slack_app.backend.slack_thread import ReplyKind, SlackThreadContext, SlackThreadHandler
from products.tasks.backend.models import TaskRun
- from products.tasks.backend.temporal.process_task.utils import slack_reply_target
+ from products.tasks.backend.temporal.process_task.utils import slack_reply_target, turn_person_message
try:
task_run = TaskRun.objects.get(id=input.run_id)
@@ -250,8 +250,15 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
context = SlackThreadContext.from_mapping(mapping, user_message_ts=input.user_message_ts)
# Resolved before the handler, so the handler knows whoever this reply is for.
target = slack_reply_target(task_run, mapping, input.message_id)
-
- handler = SlackThreadHandler.for_run(context, task_run.id, actor_slack_user_id=target, turn_trace_id=input.trace_id)
+ person_message = turn_person_message(str(task_run.id), input.message_id)
+
+ handler = SlackThreadHandler.for_run(
+ context,
+ task_run.id,
+ actor_slack_user_id=target,
+ turn_trace_id=input.trace_id,
+ turn_person_message=person_message,
+ )
# The mention opens the answer, in the same line, so the reply reads as one message.
mention_prefix = leading_mention_prefix(text, target)
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 6f3fd015b79d..44dbb4d65313 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -57,7 +57,8 @@ Its caller is ReviewHog, which uses a shared gateway key and the product model p
No open-weight model is behind a per-model access flag now; the mechanism stays for the next rollout.
The Go catalog serves GLM 5.2 only, and Baseten on Go still depends on the provider deployment check below.
`gpt-6-astra` is also Python-only because the Go catalog does not serve it, while cloud agents require the Python product policy above.
-`claude-opus-5-5`, `gpt-6-sol` and `gpt-6-luna` stay Python-only for the same reason: the Go catalog does not serve them.
+`claude-opus-5-5` and `gpt-6-sol` stay Python-only for the same reason: the Go catalog does not serve them.
+The Go catalog serves `gpt-6-luna`, and the `slack_app_routing` route allows it too, so the Slack reply suggestions keep working in an environment that has only the Python gateway.
`gpt-6.1-sol` uses the Python product policies for Slack tasks and background agents.
These callers still require the OAuth application restrictions and product billing policies above, even when the Go catalog discovers the model.
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 60a3687fa1ce..6c134b3efb06 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -252,7 +252,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
),
"slack_app_routing": ProductConfig(
allowed_application_ids=None,
- allowed_models=frozenset({"claude-haiku-4-5", "gpt-5.6-luna"}),
+ allowed_models=frozenset({"claude-haiku-4-5", "gpt-5.6-luna", "gpt-6-luna"}),
allow_api_keys=True,
credit_bucket=CreditBucket.AI_CREDITS,
),
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index bb9ba8f52d4d..568f980fe661 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -382,8 +382,9 @@ class TestCheckProductAccess:
assert error is not None
assert "not allowed" in error
- def test_slack_app_routing_allows_claude_haiku_via_api_key(self):
- allowed, error = check_product_access("slack_app_routing", "personal_api_key", None, "claude-haiku-4-5")
+ @pytest.mark.parametrize("model", ["claude-haiku-4-5", "gpt-5.6-luna", "gpt-6-luna"])
+ def test_slack_app_routing_allows_its_models_via_api_key(self, model):
+ allowed, error = check_product_access("slack_app_routing", "personal_api_key", None, model)
assert allowed is True
assert error is None