: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(customer-analytics): auditable message counts in channel summaries (#75778)
Arthur Moreira de Deusf9361ad66adb
diff --git a/products/conversations/backend/temporal/channel_summary/summarize.py b/products/conversations/backend/temporal/channel_summary/summarize.pyindex 62aac2c39f60..4256156ef33f 100644--- a/products/conversations/backend/temporal/channel_summary/summarize.py+++ b/products/conversations/backend/temporal/channel_summary/summarize.py@@ -7,7 +7,7 @@ from temporalio.exceptions import ApplicationErrorwith workflow.unsafe.imports_passed_through():import reimport asyncio- from datetime import datetime, timedelta+ from datetime import UTC, datetime, timedeltafrom uuid import uuid5import structlog@@ -68,7 +68,8 @@ One bullet per unresolved request or commitment: who asked, what they need. WritRules:- Be factual and specific. No filler, no speculation.- Cover every distinct thread or topic in the transcript at least briefly before going deep on any one.-- For a thread marked as started before this period, write one bullet for the original message with its date in parentheses, then indented sub-bullets under it summarizing only this period's replies. Do not present the original message as new activity.+- For each thread, write one bullet for the original message, then indented sub-bullets under it summarizing the replies. Never write sibling top-level bullets for messages that belong to the same thread.+- For a thread marked as started before this period, add the original message's date in parentheses and summarize only this period's replies. Do not present the original message as new activity.- Back every claim with a citation: a markdown link on a short phrase pointing to the source message's link from the transcript, like [asked about SSO](https://...). Every bullet needs at least one citation.- When the transcript contains a GitHub URL for a PR or issue you mention, also hyperlink its number to that URL, like [PR #123](https://github.com/...). Never invent a GitHub URL; a reference with no URL in the transcript stays plain text.- Do not use em-dashes.@@ -197,10 +198,16 @@ def _message_line(client: WebClient, channel_id: str, message: dict, tz, cache:def _build_transcript(- client: WebClient, team: Team, channel_id: str, threads: list[tuple[dict, list[dict]]], period_start: float-) -> str:+ client: WebClient,+ team: Team,+ channel_id: str,+ threads: list[tuple[dict, list[dict]]],+ period_start: float,+ cache: dict[str, str],+) -> tuple[str, list[tuple[dict, list[dict]]]]:+ """The transcript plus the threads that actually made it in — count and audit refs+ must come from the returned threads, or a truncated transcript overclaims coverage."""tz = team.timezone_info- cache: dict[str, str] = {}blocks: list[str] = []for parent, replies in threads:lines = [_message_line(client, channel_id, parent, tz, cache, "")]@@ -212,6 +219,7 @@ def _build_transcript(# Keep the newest threads when over budget: recent context matters most for the# open-asks section, and the truncation is disclosed to the model.kept: list[str] = []+ kept_thread_count = 0total = 0for block in reversed(blocks):total += len(block) + 2@@ -219,11 +227,24 @@ def _build_transcript(kept.append("(earlier messages omitted: transcript truncated)")breakkept.append(block)- return "\n\n".join(reversed(kept))+ kept_thread_count += 1+ return "\n\n".join(reversed(kept)), threads[len(threads) - kept_thread_count :]-def _message_count(threads: list[tuple[dict, list[dict]]]) -> int:- return sum(1 + len(replies) for _, replies in threads)+def _message_refs(+ client: WebClient, channel_id: str, threads: list[tuple[dict, list[dict]]], cache: dict[str, str]+) -> list[dict]:+ """Metadata (never text) for every message the summary covered, in transcript order —+ the stored audit trail behind the summary's message count."""+ return [+ {+ "author": _display_name(client, message["user"], cache) if message.get("user") else "unknown",+ "sent_at": datetime.fromtimestamp(float(message["ts"]), tz=UTC).isoformat(),+ "permalink": _slack_permalink(channel_id, message["ts"], message.get("thread_ts")),+ }+ for parent, replies in threads+ for message in (parent, *replies)+ ]async def _summarize(input: ChannelSummaryInput) -> ChannelSummaryOutput:@@ -278,9 +299,17 @@ async def _summarize(input: ChannelSummaryInput) -> ChannelSummaryOutput:)return ChannelSummaryOutput(summary_id=None, message_count=0)- transcript = await asyncio.to_thread(- _build_transcript, client, team, input.slack_channel_id, threads, period_start.timestamp()- )+ # One shared name cache: after the transcript resolves every author, the refs pass+ # is lookup-free. Both stay off the event loop — cache misses call Slack. Refs come+ # from the threads the transcript kept, so a truncated transcript never overclaims.+ def build_transcript_and_refs() -> tuple[str, list[dict]]:+ cache: dict[str, str] = {}+ transcript, covered_threads = _build_transcript(+ client, team, input.slack_channel_id, threads, period_start.timestamp(), cache+ )+ return transcript, _message_refs(client, input.slack_channel_id, covered_threads, cache)++ transcript, message_refs = await asyncio.to_thread(build_transcript_and_refs)user_content = (f"Slack channel activity for account {input.account_name!r} "@@ -310,12 +339,13 @@ async def _summarize(input: ChannelSummaryInput) -> ChannelSummaryOutput:period_start=period_start,period_end=period_end,content=content,- message_count=_message_count(threads),+ message_count=len(message_refs),+ messages=message_refs,model_name=SUMMARY_MODEL,),thread_sensitive=False,)()- return ChannelSummaryOutput(summary_id=summary_id, message_count=_message_count(threads))+ return ChannelSummaryOutput(summary_id=summary_id, message_count=len(message_refs))@activity.defndiff --git a/products/conversations/backend/temporal/tests/test_channel_summary.py b/products/conversations/backend/temporal/tests/test_channel_summary.pyindex 8e7001b049ee..43ea43b87f25 100644--- a/products/conversations/backend/temporal/tests/test_channel_summary.py+++ b/products/conversations/backend/temporal/tests/test_channel_summary.py@@ -1,6 +1,6 @@from __future__ import annotations-from datetime import datetime+from datetime import UTC, datetimefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -9,8 +9,10 @@ from parameterized import parameterizedfrom products.conversations.backend.temporal.channel_summary.coordinator import _collect_due_channelsfrom products.conversations.backend.temporal.channel_summary.summarize import (+ _build_transcript,_fetch_period_messages,_include_message,+ _message_refs,_resolve_mentions,_slack_permalink,)@@ -115,6 +117,46 @@ class TestSummarizeHelpers:def test_include_message(self, _name, message, expected):assert _include_message(message) is expected+ def test_truncated_transcript_returns_only_the_kept_threads(self):+ # Audit refs and message_count come from the returned threads: a thread the+ # transcript dropped must drop out of the audit too, or the count overclaims.+ old_thread: tuple[dict, list[dict]] = ({"text": "x" * 300, "ts": "100.0", "user": "U1"}, [])+ new_thread: tuple[dict, list[dict]] = ({"text": "y" * 300, "ts": "200.0", "user": "U1"}, [])+ client = MagicMock()+ team = MagicMock()+ team.timezone_info = UTC++ with patch("products.conversations.backend.temporal.channel_summary.summarize.MAX_TRANSCRIPT_CHARS", 400):+ transcript, covered = _build_transcript(+ client, team, "C1", [old_thread, new_thread], period_start=50.0, cache={"U1": "alice"}+ )++ assert covered == [new_thread]+ assert "(earlier messages omitted: transcript truncated)" in transcript+ assert "yyy" in transcript and "xxx" not in transcript++ def test_message_refs_cover_every_message_with_metadata_only(self):+ parent = {"text": "secret question", "ts": "1721999999.123456", "thread_ts": "1721999999.123456", "user": "U1"}+ reply = {"text": "secret answer", "ts": "1722000010.000200", "thread_ts": "1721999999.123456", "user": "U2"}+ client = MagicMock()+ client.users_info.return_value = {"user": {"profile": {"display_name": "alice", "real_name": "Alice A"}}}++ refs = _message_refs(client, "C1", [(parent, [reply])], cache={"U2": "bob"})++ assert refs == [+ {+ "author": "alice",+ "sent_at": "2024-07-26T13:19:59.123456+00:00",+ "permalink": "https://posthog.slack.com/archives/C1/p1721999999123456",+ },+ {+ "author": "bob",+ "sent_at": "2024-07-26T13:20:10.000200+00:00",+ "permalink": "https://posthog.slack.com/archives/C1/p1722000010000200?thread_ts=1721999999.123456&cid=C1",+ },+ ]+ assert not any("secret" in str(ref) for ref in refs)+def test_thread_replies_after_the_period_are_excluded(self):parent = {"text": "question", "ts": "100.0", "thread_ts": "100.0", "user": "U1", "reply_count": 2}in_window_reply = {"text": "answer", "ts": "150.0", "thread_ts": "100.0", "user": "U2"}diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex a647276ee53e..fb8c13fee352 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -2371,6 +2371,7 @@ def _to_channel_summary_view(summary: AccountChannelSummary) -> contracts.Accounperiod_end=summary.period_end,content=summary.content,message_count=summary.message_count,+ messages=summary.messages,generated_at=summary.generated_at,)@@ -2448,10 +2449,14 @@ def record_channel_summary(period_end: datetime,content: str,message_count: int,+ messages: list[dict] | None = None,model_name: str = "",) -> str | None:"""Store a finished channel summary pushed in by the conversations pipeline.+ ``messages`` is the per-message audit metadata ([{author, sent_at, permalink}]),+ never message text.+Idempotent on ``(team, account, cadence, period_start)``: a retry or overlapping runresolves to the existing row's id instead of double-writing. Returns None when theaccount no longer exists (deleted mid-flight) — the period's summary is simply dropped.@@ -2471,6 +2476,7 @@ def record_channel_summary(period_end=period_end,content=content,message_count=message_count,+ messages=messages or [],model_name=model_name,)except IntegrityError:diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 346b4eb35e39..61203bbd9b59 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -130,6 +130,8 @@ class AccountChannelSummaryView:period_end: datetimecontent: strmessage_count: int+ # [{author, sent_at, permalink}] per covered message — metadata only, never text.+ messages: list[dict]generated_at: datetimediff --git a/products/customer_analytics/backend/migrations/0028_accountchannelsummary_messages.py b/products/customer_analytics/backend/migrations/0028_accountchannelsummary_messages.pynew file mode 100644index 000000000000..ba6049fabd86--- /dev/null+++ b/products/customer_analytics/backend/migrations/0028_accountchannelsummary_messages.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0027_accountchannelsummary_validate_fks"),+ ]++ operations = [+ migrations.AddField(+ model_name="accountchannelsummary",+ name="messages",+ field=models.JSONField(default=list),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 878996e2952b..47db7f4d92f9 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0027_accountchannelsummary_validate_fks+0028_accountchannelsummary_messagesdiff --git a/products/customer_analytics/backend/models/account_channel_summary.py b/products/customer_analytics/backend/models/account_channel_summary.pyindex eb88b18e0d3d..6ba93bdf03fc 100644--- a/products/customer_analytics/backend/models/account_channel_summary.py+++ b/products/customer_analytics/backend/models/account_channel_summary.py@@ -15,9 +15,9 @@ class SlackSummaryCadence(models.TextChoices):class AccountChannelSummary(TeamScopedRootMixin, UUIDModel):"""An AI summary of one closed period of an account's bound Slack channel.- Written by the conversations summary pipeline through the facade. The channel- messages themselves are never persisted — only this summary, which cites them- with permalinks.+ Written by the conversations summary pipeline through the facade. Message text is+ never persisted — only this summary (which cites messages with permalinks) and+ per-message metadata in ``messages`` backing the audit trail."""all_teams = models.Manager() # noqa: DJ012@@ -34,6 +34,9 @@ class AccountChannelSummary(TeamScopedRootMixin, UUIDModel):period_end = models.DateTimeField()content = models.TextField()message_count = models.PositiveIntegerField(default=0)+ # Audit trail behind message_count: [{author, sent_at, permalink}] per covered+ # message, in transcript order. Metadata only, never message text.+ messages = models.JSONField(default=list)model_name = models.CharField(max_length=100, blank=True, default="")generated_at = models.DateTimeField(auto_now_add=True)diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex cd2efb3a970a..4353f2de47f9 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -307,6 +307,14 @@ class AccountNoteSerializer(DataclassSerializer):fields = ["short_id", "title", "created_at", "last_modified_at", "account_id", "account_name", "created_by"]+class ChannelSummaryMessageSerializer(serializers.Serializer):+ """Metadata for one message a channel summary covered — never the message text."""++ author = serializers.CharField(read_only=True, help_text="Display name of the message author.")+ sent_at = serializers.DateTimeField(read_only=True, help_text="When the message was sent.")+ permalink = serializers.CharField(read_only=True, help_text="Slack permalink to the message.")++class AccountChannelSummarySerializer(DataclassSerializer):"""An AI summary of one closed period of the account's bound Slack channel (read-only)."""@@ -327,6 +335,11 @@ class AccountChannelSummarySerializer(DataclassSerializer):message_count = serializers.IntegerField(read_only=True, help_text="Number of channel messages the summary covered.")+ messages = ChannelSummaryMessageSerializer(+ many=True,+ read_only=True,+ help_text="The messages the summary covered, in transcript order — metadata only, no message text.",+ )generated_at = serializers.DateTimeField(read_only=True, help_text="When the summary was generated.")class Meta:@@ -340,6 +353,7 @@ class AccountChannelSummarySerializer(DataclassSerializer):"period_end","content","message_count",+ "messages","generated_at",]diff --git a/products/customer_analytics/backend/test/test_channel_summaries.py b/products/customer_analytics/backend/test/test_channel_summaries.pyindex fbff214776e9..5c692df375c7 100644--- a/products/customer_analytics/backend/test/test_channel_summaries.py+++ b/products/customer_analytics/backend/test/test_channel_summaries.py@@ -149,6 +149,16 @@ class TestRecordChannelSummary(BaseTest):}return facade.record_channel_summary(**{**kwargs, **overrides})+ def test_persists_message_metadata(self):+ account = create_account(team_id=self.team.id)+ refs = [{"author": "alice", "sent_at": "2026-07-27T10:00:00+00:00", "permalink": "https://slack/1"}]++ summary_id = self._record(account, messages=refs)++ assert summary_id is not None+ summary = AccountChannelSummary.objects.unscoped().get(id=summary_id)+ assert summary.messages == refs+def test_duplicate_write_resolves_to_the_existing_row(self):account = create_account(team_id=self.team.id)@@ -185,6 +195,7 @@ class TestAccountSummariesEndpoint(APIBaseTest):period_end=period_start,content=f"summary for {period_start.date()}",message_count=1,+ messages=[{"author": "alice", "sent_at": "2026-07-25T10:00:00+00:00", "permalink": "https://slack/1"}],)def test_lists_summaries_newest_period_first_paginated(self):@@ -199,6 +210,9 @@ class TestAccountSummariesEndpoint(APIBaseTest):assert [row["id"] for row in data["results"]] == [str(newer.id), str(older.id)]assert data["results"][0]["content"] == "summary for 2026-07-27"assert data["results"][0]["cadence"] == "daily"+ assert data["results"][0]["messages"] == [+ {"author": "alice", "sent_at": "2026-07-25T10:00:00+00:00", "permalink": "https://slack/1"}+ ]def test_other_teams_account_is_404(self):other_team = Team.objects.create(organization=self.organization)diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsxindex f5ebfd9fab8a..02ba993580bc 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx@@ -2,7 +2,7 @@ import clsx from 'clsx'import { useActions, useValues } from 'kea'import { ReactNode } from 'react'-import { LemonSelect, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'+import { LemonDropdown, LemonSelect, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'import { BigLeaguesHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'@@ -63,6 +63,43 @@ function periodLabel(summary: AccountChannelSummaryApi): string {return summary.cadence === 'daily' ? start : `${start} to ${summary.period_end.slice(0, 10)}`}+function MessageCountBadge({ summary }: { summary: AccountChannelSummaryApi }): JSX.Element {+ const label = `${summary.message_count} message${summary.message_count === 1 ? '' : 's'}`+ if (!summary.messages?.length) {+ return <span>{label}</span>+ }+ return (+ // The wrapper span keeps clicks on the badge from toggling the card.+ <span onClick={(e) => e.stopPropagation()}>+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="flex flex-col max-h-80 overflow-y-auto py-1">+ {summary.messages.map((message, index) => (+ <Link+ key={index}+ to={message.permalink}+ target="_blank"+ className="px-2 py-1 whitespace-nowrap"+ >+ {message.author} · <TZLabel time={message.sent_at} />+ </Link>+ ))}+ </div>+ }+ >+ <span+ role="button"+ className="underline decoration-dotted cursor-pointer"+ data-attr="account-summary-message-count"+ >+ {label}+ </span>+ </LemonDropdown>+ </span>+ )+}+function SummaryCard({summary,expanded,@@ -86,8 +123,7 @@ function SummaryCard({<LemonTag type="default">{summary.cadence}</LemonTag><span className="font-semibold">{periodLabel(summary)}</span><span className="text-muted text-xs ml-auto flex items-center gap-1">- {summary.message_count} message{summary.message_count === 1 ? '' : 's'} · generated{' '}- <TZLabel time={summary.generated_at} />+ <MessageCountBadge summary={summary} /> · generated <TZLabel time={summary.generated_at} /></span></div>{expanded && (diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex a5b3b97625a3..fc0731a8d05f 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -462,6 +462,18 @@ export interface PatchedAccountApi {readonly updated_at?: string | null}+/**+ * Metadata for one message a channel summary covered — never the message text.+ */+export interface ChannelSummaryMessageApi {+ /** Display name of the message author. */+ readonly author: string+ /** When the message was sent. */+ readonly sent_at: string+ /** Slack permalink to the message. */+ readonly permalink: string+}+/*** An AI summary of one closed period of the account's bound Slack channel (read-only).*/@@ -484,6 +496,8 @@ export interface AccountChannelSummaryApi {readonly content: string/** Number of channel messages the summary covered. */readonly message_count: number+ /** The messages the summary covered, in transcript order — metadata only, no message text. */+ readonly messages: readonly ChannelSummaryMessageApi[]/** When the summary was generated. */readonly generated_at: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 215031f3075a..d00d67823b6e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -240,6 +240,18 @@ export namespace Schemas {readonly email: string;}+ /**+ * Metadata for one message a channel summary covered — never the message text.+ */+ export interface ChannelSummaryMessage {+ /** Display name of the message author. */+ readonly author: string;+ /** When the message was sent. */+ readonly sent_at: string;+ /** Slack permalink to the message. */+ readonly permalink: string;+ }+/*** An AI summary of one closed period of the account's bound Slack channel (read-only).*/@@ -262,6 +274,8 @@ export namespace Schemas {readonly content: string;/** Number of channel messages the summary covered. */readonly message_count: number;+ /** The messages the summary covered, in transcript order — metadata only, no message text. */+ readonly messages: readonly ChannelSummaryMessage[];/** When the summary was generated. */readonly generated_at: string;}