: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): carry the rated turn's trace id on Slack feedback (#96353)
Vojta Bartošcc7daac52183
diff --git a/ee/hogai/sandbox/__init__.py b/ee/hogai/sandbox/__init__.pyindex 405c0e5a8f9b..6442452116c6 100644--- a/ee/hogai/sandbox/__init__.py+++ b/ee/hogai/sandbox/__init__.py@@ -1,3 +1,3 @@-from ee.hogai.sandbox.types import STOP_REASON_END_TURN, TURN_COMPLETE_METHOD, is_turn_complete+from ee.hogai.sandbox.types import STOP_REASON_END_TURN, TURN_COMPLETE_METHOD, is_turn_complete, turn_complete_trace_id-__all__ = ["STOP_REASON_END_TURN", "TURN_COMPLETE_METHOD", "is_turn_complete"]+__all__ = ["STOP_REASON_END_TURN", "TURN_COMPLETE_METHOD", "is_turn_complete", "turn_complete_trace_id"]diff --git a/ee/hogai/sandbox/types.py b/ee/hogai/sandbox/types.pyindex d9d723dbaf79..3fe46cea76ac 100644--- a/ee/hogai/sandbox/types.py+++ b/ee/hogai/sandbox/types.py@@ -30,6 +30,22 @@ def is_turn_complete(event: dict) -> bool:return isinstance(result, dict) and result.get("stopReason") == STOP_REASON_END_TURN+def turn_complete_trace_id(event: dict) -> str | None:+ """The finished turn's gateway trace id, when the agent reported one.++ Only the synthetic ``_posthog/turn_complete`` notification carries it; the agent+ derives it from the ``traceparent`` the CLI sends and the gateway stamps the same id+ on the turn's ``$ai_generation`` events. Absent for a turn that ran without the+ traceparent hook, and for the raw ACP prompt response, which has no such field.+ """+ notification = event.get("notification") or {}+ params = notification.get("params")+ if not isinstance(params, dict):+ return None+ trace_id = params.get("traceId")+ return trace_id if isinstance(trace_id, str) and trace_id else None++# Session update typesACP_SESSION_UPDATE_AGENT_MESSAGE_CHUNK = "agent_message_chunk"diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex 9e2c7933feea..6865e836a368 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -232,24 +232,27 @@ describe("PostHogAPIClient", () => {it.each([[- "includes message_id and text_parts when provided",+ "includes message_id, text_parts and trace_id when provided",["part one", "final answer"],"msg-1",+ "f960aead-b2af-4ee0-b0eb-630109a1b2a0",{text: "final answer",text_parts: ["part one", "final answer"],message_id: "msg-1",+ trace_id: "f960aead-b2af-4ee0-b0eb-630109a1b2a0",},],["omits optional fields when unknown",undefined,undefined,+ undefined,{ text: "final answer" },],])("relay_message body %s",- async (_label, textParts, messageId, expectedBody) => {+ async (_label, textParts, messageId, traceId, expectedBody) => {const client = new PostHogAPIClient({apiUrl: "https://app.posthog.com",getApiKey: vi.fn().mockResolvedValue("token"),@@ -267,6 +270,7 @@ describe("PostHogAPIClient", () => {"final answer",textParts,messageId,+ traceId,);expect(mockFetch).toHaveBeenCalledWith(diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex 9aee6b701cbe..d0ea2ba080d1 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -479,6 +479,7 @@ export class PostHogAPIClient {text: string,textParts?: string[],messageId?: string,+ traceId?: string | null,): Promise<void> {const teamId = this.getTeamId();// Send `text_parts` alongside the joined `text` so backends that understand@@ -486,7 +487,12 @@ export class PostHogAPIClient {// backends still get the flat `text` field they already handle.// `message_id` correlates the relay with the user message that initiated// the turn; it is omitted when no message id is known (e.g. boot prompt).- const body: { text: string; text_parts?: string[]; message_id?: string } = {+ const body: {+ text: string;+ text_parts?: string[];+ message_id?: string;+ trace_id?: string;+ } = {text,};if (textParts && textParts.length > 0) {@@ -495,6 +501,9 @@ export class PostHogAPIClient {if (messageId) {body.message_id = messageId;}+ if (traceId) {+ body.trace_id = traceId;+ }await this.apiRequest<{ status: string }>(`/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/relay_message/`,{diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex e0bd9eb7bbc3..5358e027f95c 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -1521,18 +1521,20 @@ export class AgentServer {}this.recordTurnUsage(result.usage);- this.broadcastTurnComplete(- result.stopReason,- this.promptResultTraceId(result),- );+ const turnTraceId = this.promptResultTraceId(result);+ this.broadcastTurnComplete(result.stopReason, turnTraceId);if (result.stopReason === "end_turn") {// Relay the response to Slack. For follow-ups this is the primary// delivery path — the HTTP caller only handles reactions. Echo the- // initiating message's id so the backend can attribute the answer.- this.relayAgentResponse(commandSession.payload, messageId).catch(- (err) =>- this.logger.debug("Failed to relay follow-up response", err),+ // initiating message's id so the backend can attribute the answer,+ // and the turn's trace id so a rating on the reply names the turn.+ this.relayAgentResponse(+ commandSession.payload,+ messageId,+ turnTraceId,+ ).catch((err) =>+ this.logger.debug("Failed to relay follow-up response", err),);}@@ -1557,6 +1559,9 @@ export class AgentServer {const outcome = {stopReason: result.stopReason,...(assistantMessage && { assistant_message: assistantMessage }),+ // The caller posts this answer itself when the relay above found no+ // message to send, so it needs the turn's trace id on the same terms.+ ...(turnTraceId && { trace_id: turnTraceId }),};resolveDelivery(outcome);return outcome;@@ -2837,13 +2842,11 @@ export class AgentServer {}this.recordTurnUsage(result.usage);- this.broadcastTurnComplete(- result.stopReason,- this.promptResultTraceId(result),- );+ const turnTraceId = this.promptResultTraceId(result);+ this.broadcastTurnComplete(result.stopReason, turnTraceId);if (result.stopReason === "end_turn") {- await this.relayAgentResponse(payload);+ await this.relayAgentResponse(payload, undefined, turnTraceId);}await this.finalizeRunTelemetry(payload);@@ -3226,13 +3229,11 @@ export class AgentServer {}this.recordTurnUsage(result.usage);- this.broadcastTurnComplete(- result.stopReason,- this.promptResultTraceId(result),- );+ const turnTraceId = this.promptResultTraceId(result);+ this.broadcastTurnComplete(result.stopReason, turnTraceId);if (result.stopReason === "end_turn") {- await this.relayAgentResponse(payload);+ await this.relayAgentResponse(payload, undefined, turnTraceId);}await this.finalizeRunTelemetry(payload);@@ -5426,6 +5427,7 @@ ${commonInstructions}private async relayAgentResponse(payload: JwtPayload,messageId?: string,+ traceId?: string | null,): Promise<void> {if (!this.session) {return;@@ -5471,6 +5473,7 @@ ${commonInstructions}message,messageParts,messageId,+ traceId,);} catch (error) {this.logger.debug("Failed to relay initial agent response to Slack", {diff --git a/products/desktop/packages/agent/src/server/question-relay.test.ts b/products/desktop/packages/agent/src/server/question-relay.test.tsindex 5da67a74ebeb..be53e1b54047 100644--- a/products/desktop/packages/agent/src/server/question-relay.test.ts+++ b/products/desktop/packages/agent/src/server/question-relay.test.ts@@ -39,6 +39,7 @@ interface TestableAgentServer {relayAgentResponse: (payload: Record<string, unknown>,messageId?: string,+ traceId?: string | null,) => Promise<void>;sendInitialTaskMessage: (payload: Record<string, unknown>,@@ -600,10 +601,11 @@ describe("Question relay", () => {"agent response",["first part", "agent response"],undefined,+ undefined,);});- it("passes the initiating message id through to relayMessage", async () => {+ it("passes the initiating message id and the turn's trace id through to relayMessage", async () => {const relaySpy = vi.spyOn(server.posthogAPI, "relayMessage").mockResolvedValue(undefined);@@ -619,7 +621,11 @@ describe("Question relay", () => {};server.questionRelayedToSlack = false;- await server.relayAgentResponse(TEST_PAYLOAD, "msg-123");+ await server.relayAgentResponse(+ TEST_PAYLOAD,+ "msg-123",+ "f960aead-b2af-4ee0-b0eb-630109a1b2a0",+ );expect(relaySpy).toHaveBeenCalledWith("test-task-id",@@ -627,6 +633,7 @@ describe("Question relay", () => {"agent response",["agent response"],"msg-123",+ "f960aead-b2af-4ee0-b0eb-630109a1b2a0",);});diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 90f74cb4189b..9aaa884bb4c0 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -751,7 +751,7 @@ 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]:+def turn_feedback_block(integration_id: int, run_id: str, trace_id: str | None = None) -> 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@@ -764,12 +764,19 @@ def turn_feedback_block(integration_id: int, run_id: str) -> dict[str, Any]:interactivity router can tell whose click this is, the same way the fork menu'soption value does. The task is not carried: it is read back from the run row.+ ``trace_id`` is the answering turn's gateway trace id, which nothing on the server+ can look up afterwards — it exists only in the turn that produced this reply — so the+ reply itself is where it has to be kept. Omitted when the turn reported none, which+ is what a rating with no ``$ai_trace_id`` then means.+The block's shape is also a read contract, not only a render: the reaction feedbackpath fetches the posted message back from Slack and finds the run through thiselement's action id and button value (``turn_feedback._feedback_value_from_message``).Renaming the element's keys silently kills reaction feedback."""- target = {"integration_id": integration_id, "run_id": run_id}+ target: dict[str, Any] = {"integration_id": integration_id, "run_id": run_id}+ if trace_id:+ target["trace_id"] = trace_idreturn {"type": "context_actions","elements": [diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.pyindex 2d7ee1bc700a..253a2db14372 100644--- a/products/slack_app/backend/services/turn_feedback.py+++ b/products/slack_app/backend/services/turn_feedback.py@@ -84,13 +84,15 @@ class _FeedbackTarget:which is what makes every field here trusted: the integration is matched on the Slackteam the rating came from, and the run is looked up scoped to that integration'sproject, so a forged ``run_id`` resolves to nothing rather than attributing feedback- to another team's run.+ to another team's run. ``trace_id`` names no row of ours and so cannot be matched that+ way; ``_trace_id`` says what stands behind it instead."""integration: Integrationrun_id: strtask_id: str | Noneturn_id: str | None+ trace_id: str | Noneslack_user_id: str@@ -192,10 +194,32 @@ def _resolve_target(run_id=str(run.id),task_id=str(run.task_id),turn_id=turn_id,+ trace_id=_trace_id(value),slack_user_id=slack_user_id,)+def _trace_id(value: dict[str, Any]) -> str | None:+ """The rated turn's gateway trace id, as carried by the reply we posted.++ Unlike the run, there is nothing to match it against: a trace id names an event in+ AI observability, not a row we own. What stands behind it instead is Slack's request+ signature — the value comes back from a block we wrote — and the shape check here,+ which is what keeps a malformed id from being stamped onto ``$ai_trace_id`` and+ joining nothing. The gateway renders the id as a UUID (``traceIdFromHookStderr`` in+ the agent), so anything else is not one of ours.+ """+ trace_id = value.get("trace_id")+ if not isinstance(trace_id, str):+ return None+ try:+ UUID(trace_id)+ except ValueError:+ logger.info("slack_app_turn_feedback_malformed_trace_id", run_id=value.get("run_id"))+ return None+ return trace_id++def _turn_id(payload: dict) -> str | None:"""The rated answer's Slack timestamp, which is what identifies one turn in a thread.@@ -239,15 +263,16 @@ def _event_context(target: _FeedbackTarget) -> dict[str, Any]: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.+ as ``task_id``, which is the same bargain the desktop client makes. ``$ai_trace_id``+ narrows that to the one turn the reader rated, and is ``None`` when the turn reported+ no trace id — the same null the web and desktop clients send rather than a guess."""return slack_event_props(target.integration,slack_user_id=target.slack_user_id,**{"$ai_session_id": target.task_id,+ "$ai_trace_id": target.trace_id,"ai_product": AI_PRODUCT,"agent_runtime": "sandbox","task_id": target.task_id,@@ -277,6 +302,9 @@ def _capture(target: _FeedbackTarget, event: str, properties: dict[str, Any]) ->feedback_source=properties.get("feedback_source"),run_id=target.run_id,turn_id=target.turn_id,+ # Absent here and present on the reply's buttons narrows a missing join to the+ # parse; absent in both puts it upstream, in the turn that never reported one.+ trace_id=target.trace_id,)except Exception:logger.warning("slack_app_turn_feedback_capture_failed", captured_event=event, exc_info=True)@@ -317,6 +345,7 @@ def _open_reason_modal(payload: dict, target: _FeedbackTarget) -> None:"integration_id": target.integration.id,"run_id": target.run_id,"turn_id": target.turn_id,+ "trace_id": target.trace_id,})try:diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex 355dd0c81c4e..15ddef6dab25 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -135,9 +135,13 @@ class SlackThreadHandler:context: SlackThreadContext,run_footer: RunFooter | None = None,actor_slack_user_id: str | None = None,+ turn_trace_id: str | None = None,) -> None:self.context = contextself.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# Who this reply is for. Links are gated on their access, not the task creator's:# a thread outlives its opener, and a link only helps the person looking at it.self.actor_slack_user_id = actor_slack_user_id or context.mentioning_slack_user_id@@ -222,7 +226,7 @@ class SlackThreadHandler:run_id = self.run_footer.run_idif not run_id:return None- return turn_feedback_block(self._get_integration().id, run_id)+ return turn_feedback_block(self._get_integration().id, run_id, self.turn_trace_id)def _append_trailing_blocks(self, ts: str) -> None:"""Add the fork menu and the thumbs to a streamed reply, which has no section todiff --git a/products/slack_app/backend/tests/test_turn_feedback.py b/products/slack_app/backend/tests/test_turn_feedback.pyindex 7e377c89d176..181f4e9fe35b 100644--- a/products/slack_app/backend/tests/test_turn_feedback.py+++ b/products/slack_app/backend/tests/test_turn_feedback.py@@ -84,8 +84,8 @@ class TestTurnFeedback(TestCase):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]+ def _thumb_value(self, sentiment: str, run_id: str | None = None, trace_id: str | None = None) -> str:+ element = turn_feedback_block(self.integration.id, run_id or str(self.task_run.id), trace_id)["elements"][0]button = "positive_button" if sentiment == "positive" else "negative_button"return element[button]["value"]@@ -129,8 +129,51 @@ class TestTurnFeedback(TestCase):# The rated answer's own message, so a thread of answers stays separable.assert properties["turn_id"] == "222.1"assert properties["feedback_source"] == "button"+ # A turn that reported no trace id sends the null the other clients send, never a+ # stand-in like the session id.+ assert properties["$ai_trace_id"] is Noneassert self.mock_slack.return_value.client.views_open.called is asks_for_a_reason+ def test_a_rating_names_the_turn_the_reply_answered(self):+ trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"++ response = self._pick(self._thumb_value("positive", trace_id=trace_id))++ assert response.status_code == 200+ assert self.mock_analytics.capture.call_args.kwargs["properties"]["$ai_trace_id"] == trace_id++ def test_a_trace_id_that_is_not_one_of_ours_is_dropped(self):+ # A trace id that is not the UUID the gateway mints would join nothing.+ response = self._pick(self._thumb_value("positive", trace_id="not-a-trace-id"))++ assert response.status_code == 200+ assert self.mock_analytics.capture.call_args.kwargs["properties"]["$ai_trace_id"] is None++ def test_the_reason_inherits_the_trace_id_of_the_thumb_that_asked_for_it(self):+ # The reason arrives in a second request carrying only what the modal was opened with.+ trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"+ self._pick(self._thumb_value("negative", trace_id=trace_id))+ view = self.mock_slack.return_value.client.views_open.call_args.kwargs["view"]+ self.mock_analytics.capture.reset_mock()++ response = self._post(+ {+ "type": "view_submission",+ "team": {"id": self.slack_team_id},+ "user": {"id": "U_ALICE"},+ "view": {+ "callback_id": view["callback_id"],+ "private_metadata": view["private_metadata"],+ "state": {"values": {_MODAL_TEXT_BLOCK_ID: {_MODAL_TEXT_ACTION_ID: {"value": "wrong dashboard"}}}},+ },+ }+ )++ assert response.status_code == 200+ kwargs = self.mock_analytics.capture.call_args.kwargs+ assert kwargs["event"] == "$ai_feedback"+ assert kwargs["properties"]["$ai_trace_id"] == trace_id+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")@@ -248,6 +291,16 @@ class TestTurnFeedback(TestCase):# A reaction carries no trigger_id, so a bad rating cannot be asked for a reason.assert not self.mock_slack.return_value.client.views_open.called+ def test_a_thumb_reaction_names_the_turn_the_reply_answered(self):+ # A reaction resolves its target by reading the posted reply's own blocks back.+ trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"+ self._reacted_message([turn_feedback_block(self.integration.id, str(self.task_run.id), trace_id)])++ response = self._react("+1")++ assert response.status_code == 202+ assert self.mock_analytics.capture.call_args.kwargs["properties"]["$ai_trace_id"] == trace_id+def test_a_non_thumb_reaction_costs_no_slack_fetch(self):response = self._react("eyes")diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2aa64b919cc6..71774ca87ec9 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -4498,6 +4498,7 @@ def relay_task_run_message(text: str,text_parts: list[str] | None = None,message_id: str | None = None,+ trace_id: str | None = None,) -> tuple[str, str | None]:"""Queue a Slack relay workflow for a run message, or under the agent-designflag signal the running task workflow to stream the text inline.@@ -4510,6 +4511,10 @@ def relay_task_run_message(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.++ ``trace_id`` is the gateway trace id of the turn that wrote this answer, which the+ posted reply keeps so a rating on it can name the turn. Absent when the sandbox+ reported none."""from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import pathSlackThreadTaskMapping,@@ -4546,6 +4551,7 @@ def relay_task_run_message(text=trimmed,delete_progress=True,message_id=message_id,+ trace_id=trace_id,)except Exception:logger.exception("task_run_relay_message_enqueue_failed", extra={"run_id": str(run.id)})diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 3281aba5f65b..a5da5398ed33 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1147,6 +1147,11 @@ class TaskRunRelayMessageRequestSerializer(serializers.Serializer):allow_empty=True,help_text="Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.",)+ trace_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="AI observability trace id of the turn that wrote this answer, when the sandbox reported one.",+ )class TaskRunArtifactUploadSerializer(serializers.Serializer):diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 9bb29d8179bd..48ba367388c6 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -2045,6 +2045,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def relay_message(self, request, pk=None, **kwargs):task_id = self._ensure_task_accessible()+ trace_id = request.validated_data.get("trace_id")relay_status, relay_id = tasks_facade.relay_task_run_message(pk,task_id,@@ -2052,6 +2053,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):text=request.validated_data["text"],text_parts=request.validated_data.get("text_parts"),message_id=request.validated_data.get("message_id"),+ # Validated as a UUID, carried on as the string form the events it ends up on use.+ trace_id=str(trace_id) if trace_id else None,)if relay_status == "failed":return Response(diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 8c936dd2b0c5..a4df0cc32b5a 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -641,6 +641,7 @@ def execute_posthog_code_agent_relay_workflow(delete_progress: bool = True,reaction_emoji: str | None = None,message_id: str | None = None,+ trace_id: str | None = None,) -> str:relay_id = relay_id or str(uuid.uuid4())workflow_id = f"posthog-code-agent-relay-{run_id}-{relay_id}"@@ -657,6 +658,7 @@ def execute_posthog_code_agent_relay_workflow(delete_progress=delete_progress,reaction_emoji=reaction_emoji,message_id=message_id,+ trace_id=trace_id,),id=workflow_id,id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.pyindex e3be94ffc8fc..1d41c220d6e1 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@@ -263,11 +263,23 @@ def _enqueue_pending_reply_relay(task_run: Any, user_message_ts: str | None, comrun_id=str(task_run.id),text=reply_text,user_message_ts=user_message_ts,+ trace_id=_extract_trace_id_from_command_result(command_result_data),)except Exception:logger.exception("forward_pending_message_relay_enqueue_failed", run_id=str(task_run.id))+def _extract_trace_id_from_command_result(command_result_data: Any) -> str | None:+ """The answering turn's gateway trace id, as the agent-server reports it.++ Absent for a turn that ran without the traceparent hook, and for any agent other+ than Claude, which is what a rating with no ``$ai_trace_id`` then reflects.+ """+ result = command_result_data.get("result") if isinstance(command_result_data, dict) else None+ trace_id = result.get("trace_id") if isinstance(result, dict) else None+ return trace_id if isinstance(trace_id, str) and trace_id else None++def _extract_assistant_text_from_command_result(command_result_data: Any) -> str | None:if not isinstance(command_result_data, dict):return Nonediff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex adce8b9fbdff..9c84ee00cbf0 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -44,7 +44,7 @@ from products.tasks.backend.temporal.process_task.utils import (is_slack_interaction_state,)-from ee.hogai.sandbox import is_turn_complete+from ee.hogai.sandbox import is_turn_complete, turn_complete_trace_idlogger = structlog.get_logger(__name__)@@ -501,7 +501,11 @@ async def _relay_loop(# turn_completed, which clears the parent's relay id and would# otherwise drop a delta that arrived after it.await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)- await _signal_safely(workflow_handle, "turn_completed")+ await _signal_safely(+ workflow_handle,+ "turn_completed",+ arg=turn_complete_trace_id(event_data),+ )final_text = final_message_tracker.end_turn()if final_text is not None and task_run is not None:await asyncio.to_thread(_persist_final_message, run_id, final_text)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.pyindex 7546a1a09098..65703793c02b 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@@ -11,6 +11,7 @@ from typing import Any, Optionalfrom temporalio import activity+from posthog.dataclasses import frozenfrom posthog.models.integration import Integrationfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections@@ -48,7 +49,7 @@ class AppendSlackAgentDesignStepsInput:markdown_text: Optional[str] = None-@dataclass+@frozenclass StopSlackAgentDesignStreamInput:slack_thread_context: dict[str, Any]ts: str@@ -60,6 +61,9 @@ class StopSlackAgentDesignStreamInput:# Sources the provenance footer. Optional so a relay started before this field# existed replays cleanly — it just closes without one.run_id: Optional[str] = None+ # Gateway trace id of the turn being closed, so the thumbs appended to the reply+ # report against that turn.+ trace_id: Optional[str] = Nonedef _rewrite_object_tags(text: Optional[str], integration_id: int) -> Optional[str]:@@ -124,7 +128,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> Notry:context = SlackThreadContext.from_dict(input.slack_thread_context)- handler = SlackThreadHandler(context)+ handler = SlackThreadHandler(context, turn_trace_id=input.trace_id)handler.run_footer = load_run_footer(input.run_id)handler.stop_status_stream(ts=input.ts,diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.pyindex c9e785057a53..fcd80bb932ca 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py@@ -26,7 +26,7 @@ from products.tasks.backend.logic.stream.redis_stream import ()from products.tasks.backend.models import TaskRun as TaskRunModel-from ee.hogai.sandbox import is_turn_complete+from ee.hogai.sandbox import is_turn_complete, turn_complete_trace_id# Reuse the ACP event helpers, signal dispatcher, and SSE reconnect tuning from relay_sandbox_events# so the two relays derive/emit signals and drive their SSE transport from identical logic.@@ -90,7 +90,10 @@ class SlackAgentDesignSignalEmitter:if is_turn_complete(event_data):if self._turn_active:self._turn_active = False- return [("turn_completed", None)]+ # The trace id rides the signal because this event is the only place it+ # appears: the reply the relay posts closes the turn, and the thumbs under+ # it report against that turn.+ return [("turn_completed", turn_complete_trace_id(event_data))]return []signals: list[tuple[str, Any]] = []diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.pyindex 7725ecb03881..784c37980255 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py@@ -40,8 +40,11 @@ def _tool_call(tool_call_id: str, tool_name: str, file_path: str) -> dict[str, A}-def _turn_complete() -> dict[str, Any]:- return {"type": "notification", "notification": {"method": TURN_COMPLETE_METHOD}}+def _turn_complete(trace_id: str | None = None) -> dict[str, Any]:+ notification: dict[str, Any] = {"method": TURN_COMPLETE_METHOD}+ if trace_id:+ notification["params"] = {"traceId": trace_id}+ return {"type": "notification", "notification": notification}def _session_prompt() -> dict[str, Any]:@@ -86,6 +89,16 @@ class TestSlackAgentDesignSignalEmitter:emitter.process(_text_chunk("hi"))assert emitter.process(_turn_complete()) == [("turn_completed", None)]+ def test_turn_completed_carries_the_turns_trace_id(self) -> None:+ # The closing reply carries the thumbs, and this event is the only place the id+ # appears, so a signal that drops it costs every rating on that answer its trace.+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("hi"))++ signals = emitter.process(_turn_complete("f960aead-b2af-4ee0-b0eb-630109a1b2a0"))++ assert signals == [("turn_completed", "f960aead-b2af-4ee0-b0eb-630109a1b2a0")]+def test_second_turn_reopens_after_idle_prompt(self) -> None:emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)emitter.process(_text_chunk("turn one"))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.pyindex 67dc30fa5163..728e289565fd 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,10 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):# Length of a narrative held back whole (an unfinished tag); a flush waits for it to grow.self._held_length: int = 0self._turn_complete: bool = False+ # Gateway trace id of the turn this relay is streaming, as ``complete_turn``+ # reports it. The closing reply carries the thumbs, so this is what a rating on+ # them names.+ self._trace_id: Optional[str] = None@workflow.signalasync def agent_status_update(self, payload: dict[str, Any] | str) -> None:@@ -110,8 +114,9 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):self._current_narrative += text@workflow.signal- async def complete_turn(self) -> None:+ async def complete_turn(self, trace_id: str | None = None) -> None:self._turn_complete = True+ self._trace_id = trace_iddef _build_transition_chunks(self, steps: list[PendingStep]) -> list[TaskUpdateChunk]:"""Previous step → complete, intermediates → complete, last → in_progress.@@ -318,6 +323,7 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):complete_task_details=self._current_task_details,final_markdown=final_for_stop,run_id=input.run_id,+ trace_id=self._trace_id,),start_to_close_timeout=timedelta(seconds=10),retry_policy=RetryPolicy(maximum_attempts=3),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.pyindex 22cf43d82a19..c833e9db5343 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@@ -328,15 +328,22 @@ class TestForwardPendingUserMessage(TestCase):mock_send.return_value = _command_result(success=True,status_code=200,- data={"result": {"assistant_message": "Which license should I use?"}},+ data={+ "result": {+ "assistant_message": "Which license should I use?",+ "trace_id": "f960aead-b2af-4ee0-b0eb-630109a1b2a0",+ }+ },)forward_pending_user_message(str(run.id))+ # The trace id exists only in the agent's answer, so dropping it here loses it.mock_enqueue_relay.assert_called_once_with(run_id=str(run.id),text="Which license should I use?",user_message_ts="1234.5",+ trace_id="f960aead-b2af-4ee0-b0eb-630109a1b2a0",)run.refresh_from_db()assert "pending_user_message" not in run.statediff --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.pyindex 73033280b74e..b3f3175a203a 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@@ -41,3 +41,20 @@ class TestSlackAgentDesignStream(TestCase):assert final_markdown == (f"The [checkout funnel](https://us.posthog.com/project/{self.team.id}/insights/9pQx3?unfurl=false) dropped.")++ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream", autospec=True)+ def test_closing_the_stream_hands_the_reply_the_turns_trace_id(self, mock_stop) -> None:+ # Closing the stream is what appends the thumbs, so a trace id dropped here leaves+ # every rating on a streamed answer with nothing to open.+ trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"++ 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="Done.",+ trace_id=trace_id,+ )+ )++ assert mock_stop.call_args.args[0].turn_trace_id == trace_iddiff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 2c578d62c08a..ed71e94240d9 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -3226,14 +3226,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):)@temporalio.workflow.signal- async def turn_completed(self) -> None:+ async def turn_completed(self, trace_id: str | None = None) -> None:if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:returnrelay_id = self._current_slack_relay_workflow_idself._current_slack_relay_workflow_id = Nonetry:handle = workflow.get_external_workflow_handle(relay_id)- await handle.signal(SlackAgentDesignRelayWorkflow.complete_turn)+ await handle.signal(SlackAgentDesignRelayWorkflow.complete_turn, trace_id)except Exception as e:workflow.logger.debug("slack_status_complete_failed",diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex 9266a70129e3..63564080c5d7 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -1,10 +1,10 @@import re-from dataclasses import dataclassfrom typing import Anyfrom markdown_to_mrkdwn import SlackMarkdownConverterfrom temporalio import activity+from posthog.dataclasses import frozenfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections@@ -349,7 +349,7 @@ def _split_markdown_for_slack(text: str, limit: int = SLACK_MESSAGE_TEXT_LIMIT)return chunks-@dataclass+@frozenclass RelaySlackMessageInput:run_id: strrelay_id: str@@ -360,6 +360,9 @@ class RelaySlackMessageInput:# Id of the user message this relay answers (agent-server echo), used to# tag the exact sender; None falls back to the run-state/mapping actors.message_id: str | None = None+ # Gateway trace id of the turn that produced this answer. Trailing and defaulted so a+ # relay enqueued before this field existed still decodes.+ trace_id: str | None = None@activity.defn@@ -448,7 +451,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:or mapping.mentioning_slack_user_id)- handler = SlackThreadHandler(context, actor_slack_user_id=target)+ handler = SlackThreadHandler(context, actor_slack_user_id=target, turn_trace_id=input.trace_id)handler.run_footer = load_run_footer(task_run.id)mention_prefix = f"<@{target}> " if target else ""diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex ed17693dc63b..1182de855c47 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -121,6 +121,20 @@ class TestRelaySlackMessage(TestCase):self.task_run.refresh_from_db()assert relay_id in self.task_run.state.get("slack_sent_relay_ids", [])+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message", autospec=True)+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")+ def test_relay_hands_the_reply_the_turns_trace_id(self, _mock_delete_progress, mock_post):+ # The posted reply is the only place the turn's trace id survives.+ trace_id = "f960aead-b2af-4ee0-b0eb-630109a1b2a0"++ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id), relay_id="relay-trace", text="Done.", trace_id=trace_id+ )+ )++ assert mock_post.call_args.args[0].turn_trace_id == trace_id+@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")def test_relay_does_not_post_when_claim_write_fails(self, mock_delete_progress, mock_post):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex dc68f979c77a..36795a183e7b 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -6424,8 +6424,20 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertNotIn("pending_user_message", run.state)self.assertNotIn("pending_user_artifact_ids", run.state)+ @parameterized.expand(+ [+ ("without_a_trace_id", {}, None),+ (+ "with_a_trace_id",+ {"trace_id": "f960aead-b2af-4ee0-b0eb-630109a1b2a0"},+ "f960aead-b2af-4ee0-b0eb-630109a1b2a0",+ ),+ ]+ )@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")- def test_relay_message_enqueues_slack_relay_workflow(self, mock_execute_relay):+ def test_relay_message_enqueues_slack_relay_workflow(+ self, _name, extra_body, expected_trace_id, mock_execute_relay+ ):from posthog.models.integration import Integrationfrom products.slack_app.backend.models import SlackThreadTaskMapping@@ -6449,7 +6461,7 @@ class TestTaskRunAPI(BaseTaskAPITest):response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",- {"text": "Which license should I use?"},+ {"text": "Which license should I use?", **extra_body},format="json",)@@ -6460,6 +6472,7 @@ class TestTaskRunAPI(BaseTaskAPITest):text="Which license should I use?",delete_progress=True,message_id=None,+ trace_id=expected_trace_id,)@parameterized.expand(@@ -6513,6 +6526,7 @@ class TestTaskRunAPI(BaseTaskAPITest):text=expected_posted_text,delete_progress=True,message_id=None,+ trace_id=None,)@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 8870374f83a4..36660abeae2c 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3935,6 +3935,11 @@ export interface TaskRunRelayMessageRequestApi {* @items.maxLength 10000*/text_parts?: string[]+ /**+ * AI observability trace id of the turn that wrote this answer, when the sandbox reported one.+ * @nullable+ */+ trace_id?: string | null}export interface TaskRunRelayMessageResponseApi {diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex ae79ff4af092..76cd4aa65223 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -3185,6 +3185,10 @@ export const TasksRunsRelayMessageCreateBody = /* @__PURE__ */ zod.object({.array(zod.string().max(tasksRunsRelayMessageCreateBodyTextPartsItemMax)).optional().describe('Ordered assistant text blocks. When present, the last non-empty entry is posted instead of text.'),+ trace_id: zod+ .uuid()+ .nullish()+ .describe('AI observability trace id of the turn that wrote this answer, when the sandbox reported one.'),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 78b242695c1a..b8e04561b7d3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -86750,6 +86750,11 @@ export namespace Schemas {* @items.maxLength 10000*/text_parts?: string[];+ /**+ * AI observability trace id of the turn that wrote this answer, when the sandbox reported one.+ * @nullable+ */+ trace_id?: string | null;}export interface TaskRunRelayMessageResponse {