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): post only the final agent turn text to Slack (#67297)

Vojta Bartoš23c67fc29129
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7f2c3074767a..9466070a7b53 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2015,13 +2015,34 @@ def capture_relay_command_telemetry(
# --- Task run relay (Slack) ---
+def _pick_relay_text(*, text: str, text_parts: list[str] | None) -> str:
+ """Pick the text to post. If ``text_parts`` has any non-empty entries,
+ the last one wins (that's the post-last-tool-use answer). Otherwise fall
+ back to the joined ``text`` field."""
+ if text_parts:
+ for part in reversed(text_parts):
+ if isinstance(part, str) and part.strip():
+ return part
+ return text
+
+
def relay_task_run_message(
- run_id: str | UUID, task_id: str | UUID, team_id: int, *, text: str
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ text: str,
+ text_parts: list[str] | None = None,
) -> tuple[str, str | None]:
"""Queue a Slack relay workflow for a run message.
Returns ``(status, relay_id)`` where status is ``"accepted"`` (relay_id set), ``"skipped"``
(run not found / terminal / no Slack mapping / empty text), or ``"failed"``.
+
+ When ``text_parts`` is provided the last non-empty entry is used — it's the
+ post-last-tool-use answer, and posting only that keeps the interim narration
+ ("Let me check…") out of the Slack thread. Older callers still send just
+ ``text`` and get the previous behavior unchanged.
"""
from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
SlackThreadTaskMapping,
@@ -2036,7 +2057,8 @@ def relay_task_run_message(
if not SlackThreadTaskMapping.objects.filter(task_run=run).exists():
return "skipped", None
- trimmed = text.strip()
+ posted_text = _pick_relay_text(text=text, text_parts=text_parts)
+ trimmed = posted_text.strip()
if not trimmed:
return "skipped", None
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index a54fd7515bf7..5d4f296664c4 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -530,7 +530,17 @@ class TaskRunRelayMessageResponseSerializer(serializers.Serializer):
class TaskRunRelayMessageRequestSerializer(serializers.Serializer):
- text = serializers.CharField(max_length=10000)
+ text = serializers.CharField(
+ max_length=10000,
+ help_text="Joined message body. Used when text_parts is absent.",
+ )
+ # Kept optional for forward/backward compatibility during rollout; will be aligned once deployed.
+ text_parts = serializers.ListField(
+ child=serializers.CharField(max_length=10000, allow_blank=True),
+ required=False,
+ allow_empty=True,
+ help_text="Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.",
+ )
class TaskRunArtifactUploadSerializer(serializers.Serializer):
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 3693bd35b81e..7f06421a6ced 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1025,7 +1025,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def relay_message(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
relay_status, relay_id = tasks_facade.relay_task_run_message(
- pk, task_id, self.team_id, text=request.validated_data["text"]
+ pk,
+ task_id,
+ self.team_id,
+ text=request.validated_data["text"],
+ text_parts=request.validated_data.get("text_parts"),
)
if relay_status == "failed":
return Response(
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index 1abfe1e8db86..e02cc9a562bd 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -222,8 +222,13 @@ def _extract_text_from_message_payload(message: dict[str, Any]) -> str | None:
return content.strip()
if isinstance(content, list):
+ # Only text after the last tool_use is the final answer; text before it is interim narration.
+ last_tool_use = -1
+ for i, part in enumerate(content):
+ if isinstance(part, dict) and part.get("type") == "tool_use":
+ last_tool_use = i
text_parts: list[str] = []
- for part in content:
+ for part in content[last_tool_use + 1 :]:
if not isinstance(part, dict):
continue
if part.get("type") == "text" and isinstance(part.get("text"), str):
diff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
index 52a77210800a..2b27f3f179b4 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from django.apps import apps
from django.test import TestCase
+from parameterized import parameterized
from prometheus_client import REGISTRY
from posthog.models.integration import Integration
@@ -290,3 +291,72 @@ class TestForwardPendingUserMessage(TestCase):
mock_enqueue_relay.assert_called_once()
assert "couldn't fetch the reply text" in mock_enqueue_relay.call_args.kwargs["text"]
+
+
+_extract_text_from_message_payload = _module._extract_text_from_message_payload
+
+
+class TestExtractTextFromMessagePayload(TestCase):
+ """Guards the ``text-after-last-tool_use`` rule that keeps interim narrative
+ ("Let me pull DAU…") out of the Slack reply while preserving the final answer."""
+
+ @parameterized.expand(
+ [
+ (
+ "string_content_returned_as_is",
+ {"content": "final answer"},
+ "final answer",
+ ),
+ (
+ "no_tool_use_joins_every_text_part",
+ {
+ "content": [
+ {"type": "text", "text": "part one"},
+ {"type": "text", "text": "part two"},
+ ]
+ },
+ "part one\npart two",
+ ),
+ (
+ "drops_text_before_the_only_tool_use",
+ {
+ "content": [
+ {"type": "text", "text": "I'll pull DAU."},
+ {"type": "tool_use", "name": "hogql_query"},
+ {"type": "text", "text": "Here's your answer."},
+ ]
+ },
+ "Here's your answer.",
+ ),
+ (
+ "keeps_only_text_after_the_last_of_many_tool_uses",
+ {
+ "content": [
+ {"type": "text", "text": "step 1 setup"},
+ {"type": "tool_use", "name": "a"},
+ {"type": "text", "text": "step 2 setup"},
+ {"type": "tool_use", "name": "b"},
+ {"type": "text", "text": "final answer"},
+ ]
+ },
+ "final answer",
+ ),
+ (
+ "no_text_after_last_tool_use_returns_none",
+ {
+ "content": [
+ {"type": "text", "text": "I'll do stuff"},
+ {"type": "tool_use", "name": "x"},
+ ]
+ },
+ None,
+ ),
+ (
+ "falls_back_to_top_level_text_when_content_absent",
+ {"text": "hello"},
+ "hello",
+ ),
+ ]
+ )
+ def test_extract(self, _name: str, message: dict, expected: str | None) -> None:
+ assert _extract_text_from_message_payload(message) == expected
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 937808b2d0eb..11ff33d52568 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -3888,6 +3888,58 @@ class TestTaskRunAPI(BaseTaskAPITest):
delete_progress=True,
)
+ @parameterized.expand(
+ [
+ (
+ "prefers_last_non_empty_text_part",
+ {
+ "text": "I'll pull DAU.\n\nHere's your answer.",
+ "text_parts": ["I'll pull DAU.", "Here's your answer."],
+ },
+ "Here's your answer.",
+ ),
+ (
+ "falls_back_to_text_when_parts_only_blank",
+ {"text": "actual message", "text_parts": ["", " "]},
+ "actual message",
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
+ def test_relay_message_text_selection(self, _name, payload, expected_posted_text, mock_execute_relay):
+ from posthog.models.integration import Integration
+
+ from products.slack_app.backend.models import SlackThreadTaskMapping
+
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ mock_execute_relay.return_value = "relay-selected"
+
+ integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})
+ SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=integration,
+ slack_workspace_id="T_SLACK",
+ channel="C123",
+ thread_ts="1234.5678",
+ task=task,
+ task_run=run,
+ mentioning_slack_user_id="U123",
+ )
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",
+ payload,
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_execute_relay.assert_called_once_with(
+ run_id=str(run.id),
+ text=expected_posted_text,
+ delete_progress=True,
+ )
+
@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
def test_relay_message_skips_when_no_slack_mapping(self, mock_execute_relay):
task = self.create_task()
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 65690bb41b38..4d00e7efbd50 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1637,8 +1637,16 @@ export interface ConnectionTokenResponseApi {
}
export interface TaskRunRelayMessageRequestApi {
- /** @maxLength 10000 */
+ /**
+ * Joined message body. Used when text_parts is absent.
+ * @maxLength 10000
+ */
text: string
+ /**
+ * Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.
+ * @items.maxLength 10000
+ */
+ text_parts?: string[]
}
export interface TaskRunRelayMessageResponseApi {
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index d1886cf875df..969ae634bed4 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1445,8 +1445,17 @@ export const TasksRunsCommandCreateBody = /* @__PURE__ */ zod
*/
export const tasksRunsRelayMessageCreateBodyTextMax = 10000
+export const tasksRunsRelayMessageCreateBodyTextPartsItemMax = 10000
+
export const TasksRunsRelayMessageCreateBody = /* @__PURE__ */ zod.object({
- text: zod.string().max(tasksRunsRelayMessageCreateBodyTextMax),
+ text: zod
+ .string()
+ .max(tasksRunsRelayMessageCreateBodyTextMax)
+ .describe('Joined message body. Used when text_parts is absent.'),
+ text_parts: zod
+ .array(zod.string().max(tasksRunsRelayMessageCreateBodyTextPartsItemMax))
+ .optional()
+ .describe('Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.'),
})
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 108a5d52238f..a5f53b782fe3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -51951,8 +51951,16 @@ export namespace Schemas {
}
export interface TaskRunRelayMessageRequest {
- /** @maxLength 10000 */
+ /**
+ * Joined message body. Used when text_parts is absent.
+ * @maxLength 10000
+ */
text: string;
+ /**
+ * Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.
+ * @items.maxLength 10000
+ */
+ text_parts?: string[];
}
export interface TaskRunRelayMessageResponse {