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(conversations): Include a quote from first_message_text in CSAT request emails (#93884)

posthog[bot]d23828801e5a
diff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.ts
index 5a5885f876f6..cbae0b07f77a 100644
--- a/nodejs/src/cdp/async-functions/conversations.ts
+++ b/nodejs/src/cdp/async-functions/conversations.ts
@@ -21,7 +21,7 @@ async function callInternalTicketApi(
context: AsyncFunctionContext,
result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
ticketId: string,
- options: { method: 'GET' | 'PATCH'; body?: string; extraHeaders?: Record<string, string> }
+ options: { method: 'GET' | 'PATCH'; query?: string; body?: string; extraHeaders?: Record<string, string> }
): Promise<void> {
// The ticket id becomes a URL segment and a token claim, so only a UUID may pass — Hog
// code controls this value. Lowercased because Django's <uuid:> converter and the claim
@@ -30,11 +30,12 @@ async function callInternalTicketApi(
throw new Error(`[HogFunction] - ticket_id must be a UUID, got '${ticketId}'`)
}
const canonicalTicketId = ticketId.toLowerCase()
+ const { query, ...rest } = options
await callInternalApi(context, result, {
jwt: context.conversationsTicketsJwt,
- path: `/api/projects/${context.invocation.teamId}/internal/conversations/tickets/${canonicalTicketId}`,
+ path: `/api/projects/${context.invocation.teamId}/internal/conversations/tickets/${canonicalTicketId}${query ?? ''}`,
entityClaims: { ticket_id: canonicalTicketId },
- ...options,
+ ...rest,
})
}
@@ -47,10 +48,15 @@ registerAsyncFunction('postHogGetTicket', {
throw new Error("[HogFunction] - postHogGetTicket call missing 'ticket_id' property")
}
+ // Opt-in preview of the customer's first message. Only appended when the workflow enabled
+ // it, so the default fetch keeps the same URL, response size, and query cost it had.
+ const query =
+ opts?.include_first_customer_message_text === true ? '?include_first_customer_message_text=true' : ''
+
if (context.conversationsTicketsJwt.enabled) {
// No team fetch and no secret_api_token requirement: teams that never minted the
// legacy key can use ticket actions once the JWT secret is provisioned.
- await callInternalTicketApi(context, result, ticketId, { method: 'GET' })
+ await callInternalTicketApi(context, result, ticketId, { method: 'GET', query })
return
}
@@ -58,7 +64,7 @@ registerAsyncFunction('postHogGetTicket', {
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
- url: `${context.siteUrl}/api/conversations/external/ticket/${ticketId}`,
+ url: `${context.siteUrl}/api/conversations/external/ticket/${ticketId}${query}`,
method: 'GET',
headers: { Authorization: `Bearer ${team.secret_api_token}` },
})
@@ -84,15 +90,20 @@ registerAsyncFunction('postHogGetTicket', {
status: 'new',
priority: null,
channel_source: 'widget',
+ channel_detail: null,
distinct_id: 'mock-distinct-id',
created_at: DateTime.now().toISO(),
updated_at: DateTime.now().toISO(),
message_count: 0,
last_message_at: null,
last_message_text: null,
+ // The real ticket API omits this field unless the caller opts in, so only include
+ // it here when the workflow asked for it, keeping a mocked preview true to runtime.
+ ...(args[0]?.include_first_customer_message_text === true ? { first_customer_message_text: null } : {}),
unread_team_count: 0,
unread_customer_count: 0,
sla: null,
+ snoozed_until: null,
assignee: null,
url: null,
slack_channel_id: null,
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts
index 2e3185976648..ec15b73c4a04 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-get-ticket.template.ts
@@ -19,7 +19,10 @@ if (empty(inputs.ticket_id)) {
throw Error('Ticket ID is required')
}
-let response := postHogGetTicket({'ticket_id': inputs.ticket_id})
+let response := postHogGetTicket({
+ 'ticket_id': inputs.ticket_id,
+ 'include_first_customer_message_text': inputs.include_first_customer_message_text
+})
if (response.status != 200) {
throw Error(f'Failed to fetch ticket ({response.status}): {apiErrorMessage(response)}')
@@ -37,5 +40,15 @@ return response.body
default: '{event.properties.ticket_id}',
description: 'The UUID of the ticket to fetch. Available from trigger event properties.',
},
+ {
+ key: 'include_first_customer_message_text',
+ type: 'boolean',
+ label: 'Include first customer message text',
+ secret: false,
+ required: false,
+ default: false,
+ description:
+ "Add a short preview of the customer's first message to the response. Off by default, since it runs an extra query. Turn it on to remind the customer which ticket a message is about.",
+ },
],
}
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts
index 19df10f0e573..819f27b42457 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-tickets.template.test.ts
@@ -54,4 +54,27 @@ describe('posthog conversations ticket templates', () => {
expect(response.execResult).toEqual({ id: 'ticket-1', status: 'new' })
})
})
+
+ describe('get ticket first_customer_message_text opt-in', () => {
+ const tester = new TemplateTester(getTicketTemplate)
+
+ beforeEach(async () => {
+ await tester.beforeEach()
+ })
+
+ const fetchUrl = (response: Awaited<ReturnType<TemplateTester['invoke']>>): string =>
+ (response.invocation.queueParameters as { url: string }).url
+
+ it('does not request the field by default', async () => {
+ const response = await tester.invoke({ ticket_id: 'ticket-1' })
+ expect(fetchUrl(response)).not.toContain('include_first_customer_message_text')
+ })
+
+ it('appends the query param when opted in', async () => {
+ const response = await tester.invoke({ ticket_id: 'ticket-1', include_first_customer_message_text: true })
+ expect(fetchUrl(response)).toContain(
+ '/api/conversations/external/ticket/ticket-1?include_first_customer_message_text=true'
+ )
+ })
+ })
})
diff --git a/nodejs/tests/fixtures/hog-bytecode/f6c862bef5c9da62051ab27d7dd506aa01e9429dfc6c518935250427621ac1c6.json b/nodejs/tests/fixtures/hog-bytecode/f6c862bef5c9da62051ab27d7dd506aa01e9429dfc6c518935250427621ac1c6.json
new file mode 100644
index 000000000000..2d5a1cfa070c
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/f6c862bef5c9da62051ab27d7dd506aa01e9429dfc6c518935250427621ac1c6.json
@@ -0,0 +1 @@
+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"ticket_id",32,"inputs",1,2,2,"empty",1,40,6,32,"Ticket ID is required",2,"Error",1,49,32,"ticket_id",32,"ticket_id",32,"inputs",1,2,32,"include_first_customer_message_text",32,"include_first_customer_message_text",32,"inputs",1,2,42,2,2,"postHogGetTicket",1,33,200,36,1,32,"status",45,12,40,22,32,"Failed to fetch ticket (",36,1,32,"status",45,32,"): ",36,1,36,0,54,1,2,"concat",4,2,"Error",1,49,36,1,32,"body",45,38,35,35]
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index 231e0cb980bc..40f81a1a0f2a 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -22,7 +22,11 @@ from rest_framework.views import APIView
from posthog.models import Team
-from products.conversations.backend.api.ticket_actions import handle_ticket_get, handle_ticket_patch
+from products.conversations.backend.api.ticket_actions import (
+ handle_ticket_get,
+ handle_ticket_patch,
+ wants_first_customer_message_text,
+)
from products.conversations.backend.metrics import TICKET_ACTION_AUTH_COUNTER
@@ -89,7 +93,9 @@ class ExternalTicketView(APIView):
assert team is not None
- return handle_ticket_get(team, ticket_id)
+ return handle_ticket_get(
+ team, ticket_id, include_first_customer_message_text=wants_first_customer_message_text(request)
+ )
def patch(self, request: Request, ticket_id: str) -> Response:
team, error = _authenticate_team(request)
diff --git a/products/conversations/backend/api/internal.py b/products/conversations/backend/api/internal.py
index 534d8cc04bc5..f60c072c6450 100644
--- a/products/conversations/backend/api/internal.py
+++ b/products/conversations/backend/api/internal.py
@@ -22,7 +22,11 @@ from posthog.jwt import PosthogJwtAudience
from posthog.models import Team
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
-from products.conversations.backend.api.ticket_actions import handle_ticket_get, handle_ticket_patch
+from products.conversations.backend.api.ticket_actions import (
+ handle_ticket_get,
+ handle_ticket_patch,
+ wants_first_customer_message_text,
+)
from products.conversations.backend.metrics import TICKET_ACTION_AUTH_COUNTER
CONVERSATIONS_TICKETS_PURPOSE = ScopedServiceJwtPurpose(
@@ -54,7 +58,9 @@ class InternalTicketView(APIView):
return error
assert team is not None
TICKET_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="get").inc()
- return handle_ticket_get(team, ticket_id)
+ return handle_ticket_get(
+ team, ticket_id, include_first_customer_message_text=wants_first_customer_message_text(request)
+ )
def patch(self, request: Request, team_id: str, ticket_id: uuid.UUID) -> Response:
team, error = _check_ticket_access(request, ticket_id)
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 17a38cb0b479..dc23a1c7e62c 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -1,18 +1,28 @@
import uuid
+from datetime import timedelta
from posthog.test.base import BaseTest
+from django.db import connection
+from django.test import SimpleTestCase
+from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
+
from parameterized import parameterized
from prometheus_client import REGISTRY
from rest_framework import status
from rest_framework.test import APIClient
-from posthog.models import ActivityLog, Team
+from posthog.models import ActivityLog, Comment, Team
from posthog.models.utils import generate_random_token_secret
+from products.conversations.backend.api.ticket_actions import _truncate_bytes
from products.conversations.backend.models import Ticket
from products.conversations.backend.models.constants import Priority, Status
+# Shaped like the markdown _build_content_with_attachments appends for an inbound email image.
+_IMAGE_ATTACHMENT = "![image001.png](https://us.posthog.com/uploaded_media/0199a0b1-2c3d-4e5f-8a9b-0c1d2e3f4a5b)"
+
class TestExternalTicketAPI(BaseTest):
def setUp(self):
@@ -96,6 +106,8 @@ class TestExternalTicketAPI(BaseTest):
self.assertEqual(data["message_count"], 0)
self.assertIsNone(data["last_message_at"])
self.assertIsNone(data["last_message_text"])
+ # first_customer_message_text is opt-in, so it is absent unless the caller asks for it.
+ self.assertNotIn("first_customer_message_text", data)
self.assertEqual(data["unread_team_count"], 0)
self.assertEqual(data["unread_customer_count"], 0)
self.assertIsNone(data["sla"])
@@ -403,6 +415,186 @@ class TestExternalTicketAPI(BaseTest):
self.assertEqual(data["email_to"], "[email protected]")
self.assertEqual(data["cc_participants"], ["[email protected]", "[email protected]"])
+ # -- GET first_customer_message_text ----------------------------------
+
+ def _create_message(
+ self,
+ content: str | None,
+ *,
+ minutes_ago: int,
+ item_context: dict | None = None,
+ deleted: bool = False,
+ ) -> Comment:
+ comment = Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(self.ticket.id),
+ content=content,
+ item_context=item_context,
+ deleted=deleted,
+ )
+ # created_at is auto_now_add, so pin it after the fact to keep ordering deterministic.
+ Comment.objects.filter(pk=comment.pk).update(created_at=timezone.now() - timedelta(minutes=minutes_ago))
+ return comment
+
+ def _get_first_customer_message_text(self):
+ """GET the ticket with the opt-in flag and return the first_customer_message_text value."""
+ response = self.client.get(self.url, {"include_first_customer_message_text": "true"}, **self._auth_headers())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ return response.json()["first_customer_message_text"]
+
+ @parameterized.expand(
+ [
+ ("team_authored", {"is_private": False, "author_type": "support"}, False, "Second message"),
+ ("soft_deleted", {"author_type": "customer"}, True, "Second message"),
+ ("no_item_context", None, False, "Second message"),
+ ("customer_missing_is_private_key", {"author_type": "customer"}, False, "First message"),
+ ("customer_not_private", {"is_private": False, "author_type": "customer"}, False, "First message"),
+ ]
+ )
+ def test_get_ticket_first_message_only_quotes_the_customer(self, _name, item_context, deleted, expected):
+ self._create_message("First message", minutes_ago=10, item_context=item_context, deleted=deleted)
+ self._create_message("Second message", minutes_ago=5, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), expected)
+
+ @parameterized.expand(
+ [
+ ("empty_string", ""),
+ ("null", None),
+ ("whitespace_only", "\n\n "),
+ # An inbound email carrying only a screenshot has no body text at all.
+ ("image_attachment_only", _IMAGE_ATTACHMENT),
+ # Enough inline images to run past the scan window, so the window cuts the last one
+ # in half. The fragment left behind must not become the preview.
+ ("images_past_the_scan_window", _IMAGE_ATTACHMENT * 30),
+ ]
+ )
+ def test_get_ticket_first_message_skips_messages_with_nothing_to_quote(self, _name, unquotable):
+ self._create_message(unquotable, minutes_ago=10, item_context={"author_type": "customer"})
+ self._create_message("Actual question", minutes_ago=5, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), "Actual question")
+
+ @parameterized.expand(
+ [
+ ("image_stripped", "Why is this broken?\n\n![shot.png](/uploaded_media/abc)", "Why is this broken?"),
+ ("file_label_kept", "See\n\n[report.pdf](/uploaded_media/abc)", "See report.pdf"),
+ ("prose_kept_when_images_run_past_the_scan_window", "It broke\n\n" + _IMAGE_ATTACHMENT * 30, "It broke"),
+ # Brackets are ordinary in a support message, so nothing here may be treated as a
+ # severed attachment.
+ ("bracketed_prose_kept", "[2026-01-01] ERROR failed on a[0]", "[2026-01-01] ERROR failed on a[0]"),
+ ]
+ )
+ def test_get_ticket_first_message_strips_attachment_markdown(self, _name, content, expected):
+ self._create_message(content, minutes_ago=10, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), expected)
+
+ @parameterized.expand(
+ [
+ # The widget escapes the customer's punctuation on the way in; the preview shows it as
+ # the customer typed it. These are the stored strings, with the escaping the widget adds.
+ ("parentheses_and_period", "Please don't tag it \\(yet\\)\\.", "Please don't tag it (yet)."),
+ ("emphasis_chars_the_customer_typed", "2 \\* 3 \\* 4", "2 * 3 * 4"),
+ # A backslash the customer actually typed is stored doubled, so it comes back single.
+ ("typed_backslash_survives", "path C:\\\\Users", "path C:\\Users"),
+ # Link-shaped text the customer typed is stored escaped, so the attachment strip does
+ # not treat it as a link; unescaping runs after that strip and restores it intact.
+ ("typed_link_shaped_text_survives", "see \\[the docs\\]\\(here\\)", "see [the docs](here)"),
+ ]
+ )
+ def test_get_ticket_first_message_unescapes_widget_markdown(self, _name, content, expected):
+ self._create_message(content, minutes_ago=10, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), expected)
+
+ @parameterized.expand([("email",), ("slack",), ("teams",)])
+ def test_get_ticket_first_message_keeps_backslashes_for_non_widget_channels(self, channel_source):
+ # Only the widget editor escapes the customer's punctuation on input. On other channels a
+ # backslash is the customer's own, so a regex or a UNC path must survive the preview intact.
+ ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=str(uuid.uuid4()),
+ distinct_id=f"user-{channel_source}-1",
+ channel_source=channel_source,
+ status=Status.NEW,
+ )
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="Match \\. and path \\\\server\\share",
+ item_context={"author_type": "customer"},
+ )
+
+ response = self.client.get(
+ f"/api/conversations/external/ticket/{ticket.id}",
+ {"include_first_customer_message_text": "true"},
+ **self._auth_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["first_customer_message_text"], "Match \\. and path \\\\server\\share")
+
+ def test_get_ticket_first_message_keeps_bracketed_prose_in_a_body_long_enough_to_cut(self):
+ # Only a body past the scan window reaches the severed-attachment strip, so a shorter
+ # message cannot show whether that strip leaves a customer's own brackets alone.
+ self._create_message(
+ "[2026-01-01] ERROR failed on a[0]. " + "Padding sentence. " * 200,
+ minutes_ago=10,
+ item_context={"author_type": "customer"},
+ )
+
+ self.assertTrue(self._get_first_customer_message_text().startswith("[2026-01-01] ERROR failed on a[0]."))
+
+ @parameterized.expand(
+ [
+ # A cut message ends with an ellipsis in place of its last three characters, so the
+ # 200-byte result is 197 "x" plus "...".
+ ("ascii", "x" * 900, "x" * 197 + "..."),
+ # 3 bytes per character, so the cap lands at 66 characters (198 bytes); the ellipsis
+ # replaces the last three, leaving 63 characters plus "...". A character-based cap
+ # would emit 600 bytes against the workflow variable budget.
+ ("multibyte", "あ" * 300, "あ" * 63 + "..."),
+ ]
+ )
+ def test_get_ticket_truncates_first_message_to_200_bytes(self, _name, content, expected):
+ self._create_message(content, minutes_ago=10, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), expected)
+
+ def test_get_ticket_first_message_that_fits_has_no_ellipsis(self):
+ # The ellipsis only marks a cut, so a message inside the budget is returned unchanged.
+ self._create_message("All done, thanks!", minutes_ago=10, item_context={"author_type": "customer"})
+
+ self.assertEqual(self._get_first_customer_message_text(), "All done, thanks!")
+
+ def test_get_ticket_omits_first_customer_message_text_without_opt_in(self):
+ # A customer message exists, but a caller that does not ask for the preview must not get
+ # the field at all, so an existing Get ticket node keeps its response shape and cost.
+ self._create_message("Hello there", minutes_ago=10, item_context={"author_type": "customer"})
+
+ response = self.client.get(self.url, **self._auth_headers())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn("first_customer_message_text", response.json())
+
+ def test_get_ticket_first_customer_message_text_is_null_when_no_customer_message(self):
+ # Opted in, but nothing quotable from the customer: the field is present and null so the
+ # workflow can tell "asked for, none found" apart from "did not ask".
+ self.assertIsNone(self._get_first_customer_message_text())
+
+ def test_default_get_skips_the_first_customer_message_query(self):
+ # The opt-in exists to keep the extra message lookup off every Get ticket call. Pin that:
+ # the opted-in path runs the lookup, the default path must not.
+ self._create_message("Hello there", minutes_ago=10, item_context={"author_type": "customer"})
+ # Warm per-connection caches so the comparison reflects only the opt-in query.
+ self.client.get(self.url, **self._auth_headers())
+ with CaptureQueriesContext(connection) as default_queries:
+ self.client.get(self.url, **self._auth_headers())
+ with CaptureQueriesContext(connection) as opted_in_queries:
+ self.client.get(self.url, {"include_first_customer_message_text": "true"}, **self._auth_headers())
+ self.assertLess(len(default_queries), len(opted_in_queries))
+
def test_get_ticket_returns_tags(self):
from posthog.models import Tag
@@ -715,3 +907,17 @@ class TestExternalTicketAPI(BaseTest):
).count(),
1,
)
+
+
+class TestTruncateBytes(SimpleTestCase):
+ def test_drops_a_joiner_the_cut_left_dangling(self):
+ # The cut lands inside the emoji following a joiner, so errors="ignore" drops the
+ # partial character and would otherwise end the preview on the joiner itself.
+ truncated = _truncate_bytes("xxx" + "👨‍👩‍👧" * 20, 200)
+
+ self.assertFalse(truncated.endswith("‍"))
+ self.assertTrue(truncated.endswith("..."))
+ self.assertLessEqual(len(truncated.encode("utf-8")), 200)
+
+ def test_returns_text_within_budget_unchanged(self):
+ self.assertEqual(_truncate_bytes("short enough", 200), "short enough")
diff --git a/products/conversations/backend/api/tests/test_internal.py b/products/conversations/backend/api/tests/test_internal.py
index 9fec790dd277..68bb751dc44d 100644
--- a/products/conversations/backend/api/tests/test_internal.py
+++ b/products/conversations/backend/api/tests/test_internal.py
@@ -11,6 +11,7 @@ from rest_framework import status
from rest_framework.test import APIClient
from posthog.jwt import PosthogJwtAudience
+from posthog.models import Comment
from posthog.models.utils import generate_random_token_secret
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
@@ -60,6 +61,20 @@ class TestInternalTicketAPI(BaseTest):
self.assertEqual(data["status"], "new")
self.assertEqual(data["distinct_id"], "user-int-123")
+ def test_get_returns_first_customer_message_text_when_opted_in(self):
+ # The field is shared with the external route but gated behind a query param, so confirm
+ # the JWT route reads that param and returns the preview through the same handler.
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(self.ticket.id),
+ content="How do I export my data?",
+ item_context={"author_type": "customer"},
+ )
+ response = self.client.get(self.url, {"include_first_customer_message_text": "true"}, **self._headers())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["first_customer_message_text"], "How do I export my data?")
+
def test_patch_updates_ticket(self):
response = self.client.patch(
self.url, {"status": "resolved"}, content_type="application/json", **self._headers()
diff --git a/products/conversations/backend/api/ticket_actions.py b/products/conversations/backend/api/ticket_actions.py
index a4d96386e1ad..c424bb62df79 100644
--- a/products/conversations/backend/api/ticket_actions.py
+++ b/products/conversations/backend/api/ticket_actions.py
@@ -6,9 +6,11 @@ Two routes wrap these handlers with different authentication: the public externa
by config presence (#82564), so the two must behave identically.
"""
+import re
import uuid
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+from django.db.models.functions import Substr
from django.utils import timezone
from rest_framework import serializers, status
@@ -24,7 +26,8 @@ from posthog.models.tag import tagify
from products.conversations.backend.api.tickets import assign_ticket
from products.conversations.backend.cache import invalidate_unread_count_cache
from products.conversations.backend.models import Ticket
-from products.conversations.backend.models.constants import Priority, Status
+from products.conversations.backend.models.constants import Channel, Priority, Status
+from products.conversations.backend.services.messages import visible_ticket_messages
from products.conversations.backend.services.sla import WEEKDAYS, compute_sla_deadline
@@ -119,8 +122,141 @@ def workflow_trigger_from_request(request: Request) -> Trigger | None:
return Trigger(job_type="hog_flow", job_id=hog_flow_id, payload={})
-def handle_ticket_get(team: Team, ticket_id: str | uuid.UUID) -> Response:
- """Fetch a ticket's data for an already-authenticated team."""
+# The CDP worker spreads this whole response into workflow variables and rejects the step once
+# their combined size passes 5KB, so this preview has to stay small enough to be a rounding
+# error against that budget. The bound counts UTF-8 bytes rather than characters so that
+# multibyte text cannot quietly cost several times its length. The worker measures the budget
+# after JSON encoding, which escapes quotes, newlines and control characters, so a quote-heavy
+# message can still cost roughly twice the figure below.
+FIRST_MESSAGE_PREVIEW_BYTES = 200
+
+# How far down the thread to look for a message with something quotable in it. Bounded so a
+# ticket that opens with a run of attachments cannot turn this into a scan of the whole thread.
+FIRST_MESSAGE_CANDIDATES = 5
+
+# Attachments arrive as markdown appended to the message body, and an inbound email carrying
+# only a screenshot has no other text at all. A truncated image URL identifies nothing, so drop
+# image markdown outright and keep only the label of a file or link. The label stops at a
+# bracket, so a run of unclosed ones cannot restart a walk of the rest of the window at every
+# one. That costs no stripping ability: sanitize_attachment_filename removes brackets from
+# every inbound filename, so a label we render ourselves never holds one.
+_IMAGE_MARKDOWN = re.compile(r"!\[[^\[\]]*\]\([^)]*\)")
+_LINK_MARKDOWN = re.compile(r"\[([^\[\]]*)\]\([^)]*\)")
+
+# How much of a message body those regexes are allowed to scan. They are linear on ordinary
+# prose, but a crafted run of `![](` still rescans the remaining window for a closing bracket
+# and parenthesis at every one, and an inbound email may carry 50,000 characters of them. This
+# ceiling is an order of magnitude wider than the preview it feeds.
+FIRST_MESSAGE_SCAN_CHARS = 2000
+
+# The database fetches one character more than the scan window, never the whole body. The extra
+# character is what lets `_quotable_text` still tell a cut body from a whole one: a body at or
+# under the scan window comes back untouched, and only a longer one comes back at this length,
+# which is strictly greater than the window. Fetch exactly the window and that test can no
+# longer fire. Keep this one above FIRST_MESSAGE_SCAN_CHARS.
+FIRST_MESSAGE_DB_FETCH_CHARS = FIRST_MESSAGE_SCAN_CHARS + 1
+
+# Taking that window can cut an attachment in half, and a fragment like `![shot.png](/uploaded`
+# no longer matches the patterns above, so it would survive into the preview. This drops the
+# unterminated construct a cut leaves behind. The run cannot cross a bracket, so a closed
+# bracket with text after it is left alone and a log line pasted as "[2026-01-01] ERROR ..."
+# survives. A window ending on the bracket itself still matches, which is why the caller
+# applies this only when the body was long enough to be cut.
+_PARTIAL_MARKDOWN_TAIL = re.compile(r"!?\[[^\[\]]*(?:\](?:\([^)]*)?)?$")
+
+# The support widget stores the customer's message as markdown, so it backslash-escapes the
+# customer's own punctuation (a typed "(yet)" is stored as "\(yet\)"). The preview is quoted back
+# to the customer as prose, often in an email that does not render markdown, so those backslashes
+# would show. Reverse the escaping. This is the inverse of the widget editor's escapeMarkdown, and
+# matches the same character set the outbound Slack formatter unescapes (posthog/comment/formatting.py).
+_MARKDOWN_ESCAPE = re.compile(r"\\([\\`*_{}\[\]()#+\-.!|])")
+
+
+def _quotable_text(content: str, *, unescape_markdown: bool) -> str:
+ window = content[:FIRST_MESSAGE_SCAN_CHARS]
+ # Only a window that actually cut the body can hold a severed construct. Applying this to a
+ # whole short message would eat a trailing bracket the customer meant to type.
+ if len(content) > FIRST_MESSAGE_SCAN_CHARS:
+ window = _PARTIAL_MARKDOWN_TAIL.sub("", window)
+ text = _LINK_MARKDOWN.sub(r"\1", _IMAGE_MARKDOWN.sub("", window))
+ # Only the widget editor escapes the customer's punctuation on the way in (its escapeMarkdown),
+ # so only a widget message is unescaped here. Email, Slack, Teams and imports store the text as
+ # typed, where a backslash is the customer's own and must survive into the preview.
+ if unescape_markdown:
+ text = _MARKDOWN_ESCAPE.sub(r"\1", text)
+ return " ".join(text.split())
+
+
+def _truncate_bytes(text: str, max_bytes: int) -> str:
+ encoded = text.encode("utf-8")
+ if len(encoded) <= max_bytes:
+ return text
+ # Slicing encoded bytes can land inside a character, so errors="ignore" drops the partial
+ # trailing one. That can also expose the joiner of a split emoji sequence, which renders as
+ # a dangling glyph, so strip any joiner the cut left at the end.
+ truncated = encoded[:max_bytes].decode("utf-8", errors="ignore").rstrip("‍")
+ # The message was longer than the budget, so end it with an ellipsis to show it was cut.
+ # Replacing the last three characters keeps the result within max_bytes: dropping three
+ # characters frees at least three bytes and "..." adds exactly three.
+ return (truncated[:-3] if len(truncated) > 3 else "") + "..."
+
+
+def _first_customer_message_text(team_id: int, ticket_id: str, *, unescape_markdown: bool) -> str | None:
+ """
+ Preview of what the customer first asked, so a workflow can remind them which ticket it
+ is writing about on channels that carry no email subject.
+
+ Only the customer's own messages qualify, because a ticket can open with a team message
+ such as an agent composing outbound mail or a teammate's Slack post that seeded the
+ ticket, and quoting that back to the customer as "what you asked us" would be wrong.
+
+ author_type must say "customer" explicitly. Display code elsewhere treats a missing value
+ as the customer's, but a wrong guess here is emailed out, so an unlabelled message is left
+ out and the workflow renders no reminder instead.
+
+ unescape_markdown is on only for a widget ticket, whose editor markdown-escapes the customer's
+ punctuation. Other channels store the text as typed and must keep their backslashes.
+ """
+ candidates = (
+ visible_ticket_messages(team_id, ticket_id)
+ .filter(item_context__author_type="customer")
+ .exclude(content__isnull=True)
+ .exclude(content="")
+ # Fetch only the scan window plus one character, so a 50,000-character email never
+ # crosses the wire in full. The preview keeps the same value it would from the whole
+ # body: the strip and truncation below never look past the window anyway.
+ .annotate(content_preview=Substr("content", 1, FIRST_MESSAGE_DB_FETCH_CHARS))
+ # Zendesk-imported messages carry second-resolution timestamps, so created_at alone can
+ # tie. Tie-breaking on id keeps the preview stable from one call to the next.
+ .order_by("created_at", "id")
+ .values_list("content_preview", flat=True)[:FIRST_MESSAGE_CANDIDATES]
+ )
+ for content in candidates:
+ quotable = _quotable_text(content or "", unescape_markdown=unescape_markdown)
+ if quotable:
+ return _truncate_bytes(quotable, FIRST_MESSAGE_PREVIEW_BYTES) or None
+ return None
+
+
+def wants_first_customer_message_text(request: Request) -> bool:
+ """True when the caller opted into first_customer_message_text with ?include_...=true.
+
+ The CDP async function only appends the parameter when the workflow enabled it, so it
+ arrives as the literal "true" or not at all. Parsing both routes the same way keeps them
+ identical.
+ """
+ return request.query_params.get("include_first_customer_message_text", "").lower() == "true"
+
+
+def handle_ticket_get(
+ team: Team, ticket_id: str | uuid.UUID, *, include_first_customer_message_text: bool = False
+) -> Response:
+ """Fetch a ticket's data for an already-authenticated team.
+
+ first_customer_message_text is opt-in: it runs an extra query, so a caller that does not ask
+ for it (the default) pays nothing and gets the response shape it always got. Only the CSAT
+ workflows request it.
+ """
if error := validate_ticket_id(ticket_id):
return error
@@ -148,36 +284,41 @@ def handle_ticket_get(team: Team, ticket_id: str | uuid.UUID) -> Response:
# APIViews without scope_object), so the schema-drift risk behind the rule cannot occur,
# and the wire shape must stay identical to the legacy external route while the worker
# migrates between them (a serializer would re-format datetimes).
- return Response( # nosemgrep: api-response-must-match-schema
- {
- "id": str(ticket.id),
- "number": ticket.ticket_number,
- "status": ticket.status,
- "priority": ticket.priority,
- "channel_source": ticket.channel_source,
- "channel_detail": ticket.channel_detail,
- "distinct_id": ticket.distinct_id,
- "created_at": ticket.created_at.isoformat(),
- "updated_at": ticket.updated_at.isoformat(),
- "message_count": ticket.message_count,
- "last_message_at": ticket.last_message_at.isoformat() if ticket.last_message_at else None,
- "last_message_text": ticket.last_message_text,
- "unread_team_count": ticket.unread_team_count,
- "unread_customer_count": ticket.unread_customer_count,
- "sla": ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
- "snoozed_until": ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
- "assignee": assignee,
- "url": session_context.get("current_url"),
- "slack_channel_id": ticket.slack_channel_id,
- "slack_thread_ts": ticket.slack_thread_ts,
- "slack_team_id": ticket.slack_team_id,
- "email_subject": ticket.email_subject,
- "email_from": ticket.email_from,
- "email_to": ticket.email_config.from_email if ticket.email_config else None,
- "cc_participants": ticket.cc_participants,
- "tags": tags,
- }
- )
+ payload = {
+ "id": str(ticket.id),
+ "number": ticket.ticket_number,
+ "status": ticket.status,
+ "priority": ticket.priority,
+ "channel_source": ticket.channel_source,
+ "channel_detail": ticket.channel_detail,
+ "distinct_id": ticket.distinct_id,
+ "created_at": ticket.created_at.isoformat(),
+ "updated_at": ticket.updated_at.isoformat(),
+ "message_count": ticket.message_count,
+ "last_message_at": ticket.last_message_at.isoformat() if ticket.last_message_at else None,
+ "last_message_text": ticket.last_message_text,
+ "unread_team_count": ticket.unread_team_count,
+ "unread_customer_count": ticket.unread_customer_count,
+ "sla": ticket.sla_due_at.isoformat() if ticket.sla_due_at else None,
+ "snoozed_until": ticket.snoozed_until.isoformat() if ticket.snoozed_until else None,
+ "assignee": assignee,
+ "url": session_context.get("current_url"),
+ "slack_channel_id": ticket.slack_channel_id,
+ "slack_thread_ts": ticket.slack_thread_ts,
+ "slack_team_id": ticket.slack_team_id,
+ "email_subject": ticket.email_subject,
+ "email_from": ticket.email_from,
+ "email_to": ticket.email_config.from_email if ticket.email_config else None,
+ "cc_participants": ticket.cc_participants,
+ "tags": tags,
+ }
+
+ if include_first_customer_message_text:
+ payload["first_customer_message_text"] = _first_customer_message_text(
+ team.id, str(ticket.id), unescape_markdown=ticket.channel_source == Channel.WIDGET
+ )
+
+ return Response(payload) # nosemgrep: api-response-must-match-schema
def handle_ticket_patch(request: Request, team: Team, ticket_id: str | uuid.UUID) -> Response:
diff --git a/products/conversations/backend/services/messages.py b/products/conversations/backend/services/messages.py
new file mode 100644
index 000000000000..ad9f4c5b082b
--- /dev/null
+++ b/products/conversations/backend/services/messages.py
@@ -0,0 +1,30 @@
+from django.db.models import Q, QuerySet
+
+from posthog.models.comment import Comment
+
+# Ticket messages are stored as comments under this scope.
+TICKET_MESSAGE_SCOPE = "conversations_ticket"
+
+
+def visible_ticket_messages(team_id: int, ticket_id: str) -> QuerySet[Comment]:
+ """
+ Messages on a ticket that the customer is allowed to read: not soft-deleted, and not a
+ private team note. Getting this predicate wrong shows a private team note to a customer,
+ so callers should reuse it rather than write their own.
+
+ The isnull arm keeps comments whose item_context has no is_private key, because `~Q` alone
+ drops them when the JSONB lookup returns SQL NULL rather than false. That matches the
+ identity check in signals._is_private_message, which treats anything but boolean True as
+ public.
+
+ widget.py keeps its own copy of the predicate. It filters on a Team object, which
+ RootTeamQuerySet does not rewrite, where this helper filters on an id, which it does.
+ The two agree while no team sets parent_team. If environments ship they diverge, and this
+ helper is the correct form, because RootTeamMixin.save stores comments on the root team.
+ """
+ return Comment.objects.filter(
+ team_id=team_id,
+ scope=TICKET_MESSAGE_SCOPE,
+ item_id=ticket_id,
+ deleted=False,
+ ).filter(~Q(item_context__is_private=True) | Q(item_context__is_private__isnull=True))
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index e11121e826de..2f742d6e6087 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -2,7 +2,7 @@ from email.utils import make_msgid
from typing import Any, cast
from django.db import transaction
-from django.db.models import F, Q
+from django.db.models import F
from django.db.models.functions import Greatest
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
@@ -20,6 +20,7 @@ from .cache import invalidate_identity_tickets_cache, invalidate_messages_cache,
from .events import capture_message_received, capture_message_sent, capture_private_message_sent, capture_ticket_created
from .models import EmailOutboxMessage, SigningSecret, Ticket
from .models.constants import Channel
+from .services.messages import visible_ticket_messages
from .tasks.email import send_email_reply
from .tasks.github import post_reply_to_github
from .tasks.slack import post_reply_to_slack
@@ -262,18 +263,8 @@ def handle_comment_soft_delete(sender, instance: Comment, **kwargs):
Ticket.objects.filter(id=item_id, team_id=team_id).update(**update_fields)
# Recalculate last_message from remaining non-private messages
- # Use exclude + isnull to match _is_private_message() identity check:
- # - Exclude only exact boolean True
- # - Include everything else (False, None, missing key, weird values)
- # The isnull handles SQL NULL semantics where ~Q alone would exclude missing keys
last_comment = (
- Comment.objects.filter(
- team_id=team_id,
- scope="conversations_ticket",
- item_id=item_id,
- deleted=False,
- )
- .filter(~Q(item_context__is_private=True) | Q(item_context__is_private__isnull=True))
+ visible_ticket_messages(team_id, item_id)
.exclude(pk=comment_pk) # Exclude the one being deleted
.order_by("-created_at")
.first()
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index b5f0897997b9..3880b97efb52 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -2751,6 +2751,7 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
['channel_source', 'Channel source'],
['last_message_at', 'Last message at'],
['last_message_text', 'Last message text'],
+ ['first_customer_message_text', 'First customer message text'],
['unread_team_count', 'Unread team'],
['unread_customer_count', 'Unread customer'],
['sla', 'SLA'],