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): attribute workflow-driven ticket changes in activity log (#67740)

Abigail477e836f19a7
diff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.ts
index d5c1d80baa5e..4d534bb9be00 100644
--- a/nodejs/src/cdp/async-functions/conversations.ts
+++ b/nodejs/src/cdp/async-functions/conversations.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'
+import { HogFlow } from '~/cdp/schema/hogflow'
import { registerAsyncFunction } from '../async-function-registry'
@@ -91,15 +92,27 @@ registerAsyncFunction('postHogUpdateTicket', {
throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)
}
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${updateTeam.secret_api_token}`,
+ }
+
+ // Present only when running inside a HogFlow (spread onto the synthesized invocation);
+ // forward the workflow id so the ticket activity log can attribute and link to it. Only
+ // the id is sent — the display name is resolved from the workflow on the frontend so it
+ // can't be spoofed through this header. Typed as an optional HogFlow so a rename of its
+ // id shape breaks compilation here.
+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow
+ if (hogFlow?.id) {
+ headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id
+ }
+
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
url: `${context.siteUrl}/api/conversations/external/ticket/${ticketId}`,
method: 'PATCH',
body: JSON.stringify(updates),
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${updateTeam.secret_api_token}`,
- },
+ headers,
})
},
diff --git a/products/conversations/backend/api/external.py b/products/conversations/backend/api/external.py
index d0cc304255f7..334193fde734 100644
--- a/products/conversations/backend/api/external.py
+++ b/products/conversations/backend/api/external.py
@@ -23,7 +23,7 @@ from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
from posthog.models import Tag, Team
-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
from posthog.models.tag import tagify
from products.conversations.backend.api.tickets import assign_ticket
@@ -145,6 +145,58 @@ def _validate_ticket_id(ticket_id: str | uuid.UUID) -> Response | None:
return None
+# Header a HogFlow workflow step forwards so activity entries can attribute the change to it.
+HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"
+
+
+def _workflow_trigger_from_request(request: Request) -> Trigger | None:
+ """Build an activity-log Trigger when the request originates from a HogFlow workflow step.
+
+ Only the workflow id is taken from the (caller-supplied) header, and only as a well-formed
+ UUID. The display name is resolved from the workflow itself on the frontend, so a token
+ holder can't spoof an arbitrary workflow name into the audit log. Module boundaries keep
+ conversations independent of workflows, so we can't validate id ownership here; the endpoint
+ is team-token authenticated, so the worst case is a token holder pointing attribution at
+ another workflow id within its own team — no cross-team or privilege impact.
+ """
+ hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)
+ if not hog_flow_id:
+ return None
+ try:
+ uuid.UUID(hog_flow_id)
+ except (ValueError, TypeError):
+ return None
+ return Trigger(job_type="hog_flow", job_id=hog_flow_id, payload={})
+
+
+def _log_ticket_tag_removals(ticket: Ticket, team: Team, removed_tags: set[str], trigger: Trigger | None) -> None:
+ """Mirror tag removals onto the ticket's activity stream.
+
+ Tag *additions* go through ``TaggedItem`` saves that fire the model activity signal,
+ which already logs them to the ticket. Removals use a bulk queryset delete that bypasses
+ that signal, so they would otherwise leave no trace — this fills that gap (and, when a
+ workflow made the change, attributes it via ``trigger``).
+ """
+ if not removed_tags:
+ return
+ changes = [
+ Change(type="Ticket", field="tag", action="deleted", before=tag_name) for tag_name in sorted(removed_tags)
+ ]
+ try:
+ log_activity(
+ organization_id=team.organization_id,
+ team_id=team.id,
+ user=None,
+ was_impersonated=False,
+ item_id=str(ticket.id),
+ scope="Ticket",
+ activity="updated",
+ detail=Detail(name=f"Ticket #{ticket.ticket_number}", changes=changes, trigger=trigger),
+ )
+ except Exception as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
+
+
class ExternalTicketView(APIView):
"""
GET /api/conversations/external/ticket/<ticket_id> — Fetch ticket data
@@ -229,6 +281,10 @@ class ExternalTicketView(APIView):
assert team is not None
+ # When a HogFlow workflow step makes the change, it forwards its identity via
+ # headers so the activity log can attribute (and link to) the workflow.
+ workflow_trigger = _workflow_trigger_from_request(request)
+
if error := _validate_ticket_id(ticket_id):
return error
@@ -378,6 +434,7 @@ class ExternalTicketView(APIView):
detail=Detail(
name=f"Ticket #{ticket.ticket_number}",
changes=changes,
+ trigger=workflow_trigger,
),
)
except Exception as e:
@@ -392,6 +449,7 @@ class ExternalTicketView(APIView):
user=None,
team_id=team.id,
was_impersonated=False,
+ trigger=workflow_trigger,
)
except Exception as e:
capture_exception(e, {"ticket_id": str(ticket.id)})
@@ -400,12 +458,19 @@ class ExternalTicketView(APIView):
if "tags" in serializer.validated_data:
try:
tags_mode = serializer.validated_data.get("tags_mode", "add")
- normalized_tags = list({tagify(t) for t in serializer.validated_data["tags"]})
+ normalized_tags = {tagify(t) for t in serializer.validated_data["tags"]}
+ existing_tags = set(ticket.tagged_items.values_list("tag__name", flat=True))
+
+ # Additions log themselves via the TaggedItem model activity signal; only bulk
+ # deletes bypass it, so we track removals to log them explicitly below.
+ removed_tags: set[str] = set()
if tags_mode == "remove":
+ removed_tags = existing_tags & normalized_tags
ticket.tagged_items.filter(tag__name__in=normalized_tags).delete()
Tag.objects.filter(team_id=team.id, tagged_items__isnull=True).delete()
elif tags_mode == "set":
+ removed_tags = existing_tags - normalized_tags
for tag_name in normalized_tags:
tag_instance, _ = Tag.objects.get_or_create(name=tag_name, team_id=team.id)
ticket.tagged_items.get_or_create(tag_id=tag_instance.id)
@@ -419,4 +484,11 @@ class ExternalTicketView(APIView):
capture_exception(e, {"ticket_id": str(ticket.id)})
return Response({"error": "Failed to update tags"}, status=status.HTTP_400_BAD_REQUEST)
+ _log_ticket_tag_removals(
+ ticket=ticket,
+ team=team,
+ removed_tags=removed_tags,
+ trigger=workflow_trigger,
+ )
+
return Response({"ok": True})
diff --git a/products/conversations/backend/api/tests/test_external.py b/products/conversations/backend/api/tests/test_external.py
index 60851b4c8603..f8d6b7c3549f 100644
--- a/products/conversations/backend/api/tests/test_external.py
+++ b/products/conversations/backend/api/tests/test_external.py
@@ -6,7 +6,7 @@ from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
-from posthog.models import Team
+from posthog.models import ActivityLog, Team
from posthog.models.utils import generate_random_token_secret
from products.conversations.backend.models import Ticket
@@ -524,3 +524,109 @@ class TestExternalTicketAPI(BaseTest):
self.url, {"status": "resolved"}, content_type="application/json", **self._auth_headers()
)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
+
+ # -- Workflow (HogFlow) attribution -----------------------------------
+
+ def _workflow_headers(self, flow_id="0191d3e0-0000-7000-8000-000000000001", token=None):
+ return {
+ **self._auth_headers(token),
+ "HTTP_X_POSTHOG_HOG_FLOW_ID": flow_id,
+ }
+
+ def _latest_ticket_activity(self, activity="updated"):
+ return (
+ ActivityLog.objects.filter(
+ team_id=self.team.id, scope="Ticket", item_id=str(self.ticket.id), activity=activity
+ )
+ .order_by("-created_at")
+ .first()
+ )
+
+ @parameterized.expand(
+ [
+ ("status", {"status": Status.RESOLVED}),
+ ("priority", {"priority": Priority.HIGH}),
+ ]
+ )
+ def test_patch_records_workflow_trigger(self, _name, payload):
+ flow_id = "0191d3e0-0000-7000-8000-000000000001"
+ response = self.client.patch(
+ self.url,
+ payload,
+ content_type="application/json",
+ **self._workflow_headers(flow_id=flow_id),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ activity = self._latest_ticket_activity()
+ assert activity is not None
+ trigger = activity.detail.get("trigger")
+ assert trigger is not None
+ self.assertEqual(trigger["job_type"], "hog_flow")
+ self.assertEqual(trigger["job_id"], flow_id)
+ # Only the id is stored; the display name is resolved from the workflow on the frontend.
+ self.assertNotIn("name", trigger["payload"])
+
+ def test_patch_without_workflow_header_has_no_trigger(self):
+ response = self.client.patch(
+ self.url,
+ {"status": Status.RESOLVED},
+ content_type="application/json",
+ **self._auth_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ activity = self._latest_ticket_activity()
+ assert activity is not None
+ self.assertIsNone(activity.detail.get("trigger"))
+
+ def test_patch_ignores_malformed_workflow_id(self):
+ # A non-UUID header id is rejected so we never store a job_id that can't resolve to a link.
+ response = self.client.patch(
+ self.url,
+ {"status": Status.RESOLVED},
+ content_type="application/json",
+ **self._workflow_headers(flow_id="not-a-uuid"),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ activity = self._latest_ticket_activity()
+ assert activity is not None
+ self.assertIsNone(activity.detail.get("trigger"))
+
+ def test_patch_tag_remove_logs_activity_with_workflow_trigger(self):
+ # Removals use a bulk delete that bypasses the TaggedItem activity signal, so without
+ # explicit logging they leave no trace. Assert the gap is filled and workflow-attributed.
+ from posthog.models import Tag
+
+ existing_tag = Tag.objects.create(name="bug", team_id=self.team.id)
+ self.ticket.tagged_items.create(tag=existing_tag)
+
+ response = self.client.patch(
+ self.url,
+ {"tags": ["bug"], "tags_mode": "remove"},
+ content_type="application/json",
+ **self._workflow_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ activity = self._latest_ticket_activity()
+ assert activity is not None
+ tag_change = next((c for c in activity.detail.get("changes", []) if c["field"] == "tag"), None)
+ assert tag_change is not None
+ self.assertEqual(tag_change["action"], "deleted")
+ self.assertEqual(tag_change["before"], "bug")
+ self.assertEqual(activity.detail["trigger"]["job_type"], "hog_flow")
+
+ def test_patch_assignee_records_workflow_trigger(self):
+ response = self.client.patch(
+ self.url,
+ {"assignee": {"type": "user", "id": self.user.id}},
+ content_type="application/json",
+ **self._workflow_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ activity = self._latest_ticket_activity(activity="assigned")
+ assert activity is not None
+ self.assertEqual(activity.detail["trigger"]["job_type"], "hog_flow")
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index d00b5ef261be..c984d2d1e73e 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -31,7 +31,7 @@ from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership
-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
from posthog.models.comment import Comment
from posthog.models.person.person import Person
from posthog.models.person.util import get_person_by_distinct_id, get_persons_by_distinct_ids
@@ -1264,7 +1264,9 @@ def validate_assignee_membership(assignee, organization) -> None:
raise serializers.ValidationError({"assignee": "role does not belong to this organization"})
-def assign_ticket(ticket: Ticket, assignee, organization, user, team_id, was_impersonated):
+def assign_ticket(
+ ticket: Ticket, assignee, organization, user, team_id, was_impersonated, trigger: Trigger | None = None
+):
"""
Assign a ticket to a user or role.
@@ -1275,6 +1277,7 @@ def assign_ticket(ticket: Ticket, assignee, organization, user, team_id, was_imp
user: The user making the change
team_id: The team ID
was_impersonated: Whether the session is impersonated
+ trigger: Optional Trigger identifying an automated source (e.g. a workflow) that made the change
"""
validate_assignee(assignee)
validate_assignee_membership(assignee, organization)
@@ -1318,6 +1321,7 @@ def assign_ticket(ticket: Ticket, assignee, organization, user, team_id, was_imp
action="changed",
)
],
+ trigger=trigger,
),
)
diff --git a/products/conversations/frontend/WorkflowActivityLink.test.tsx b/products/conversations/frontend/WorkflowActivityLink.test.tsx
new file mode 100644
index 000000000000..bf60f2aff25d
--- /dev/null
+++ b/products/conversations/frontend/WorkflowActivityLink.test.tsx
@@ -0,0 +1,37 @@
+import { render } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { workflowsLogic } from 'products/workflows/frontend/Workflows/workflowsLogic'
+
+import { WorkflowActivityLink } from './WorkflowActivityLink'
+
+describe('WorkflowActivityLink', () => {
+ let logic: ReturnType<typeof workflowsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = workflowsLogic()
+ logic.mount()
+ // Populate via the loader success so the on-mount effect doesn't fire a real request.
+ logic.actions.loadWorkflowsSuccess([
+ { id: 'flow-1', name: 'Escalation workflow' },
+ { id: 'flow-2', name: 'Billing workflow' },
+ ] as any)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('renders the current workflow name resolved by id, not from the log', () => {
+ const { container } = render(<WorkflowActivityLink id="flow-1" />)
+ expect(container.textContent).toContain('Escalation workflow')
+ expect(container.querySelector('a')?.getAttribute('href')).toContain('flow-1')
+ })
+
+ it('falls back to a generic label when the workflow is not found', () => {
+ const { container } = render(<WorkflowActivityLink id="missing" />)
+ expect(container.textContent).toContain('A workflow')
+ })
+})
diff --git a/products/conversations/frontend/WorkflowActivityLink.tsx b/products/conversations/frontend/WorkflowActivityLink.tsx
new file mode 100644
index 000000000000..fb492370dde7
--- /dev/null
+++ b/products/conversations/frontend/WorkflowActivityLink.tsx
@@ -0,0 +1,30 @@
+import { useActions, useValues } from 'kea'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { workflowsLogic } from 'products/workflows/frontend/Workflows/workflowsLogic'
+
+// Renders the workflow that made a ticket change as a link, resolving the current name from the
+// workflow itself (by id) rather than from the activity-log payload — the name is never trusted
+// from the caller-supplied header, so it can't be spoofed. Falls back to a generic label when the
+// workflow can't be resolved (e.g. it was deleted).
+export function WorkflowActivityLink({ id }: { id: string }): JSX.Element {
+ const { workflows, hasLoadedWorkflows } = useValues(workflowsLogic)
+ const { loadWorkflows } = useActions(workflowsLogic)
+
+ useOnMountEffect(() => {
+ if (!hasLoadedWorkflows) {
+ loadWorkflows()
+ }
+ })
+
+ const name = workflows.find((workflow) => workflow.id === id)?.name
+
+ return (
+ <strong>
+ <Link to={urls.workflow(id, 'workflow')}>{name || 'A workflow'}</Link>
+ </strong>
+ )
+}
diff --git a/products/conversations/frontend/activityDescriber.test.tsx b/products/conversations/frontend/activityDescriber.test.tsx
index d0390788c75d..1fda17e49237 100644
--- a/products/conversations/frontend/activityDescriber.test.tsx
+++ b/products/conversations/frontend/activityDescriber.test.tsx
@@ -6,6 +6,12 @@ import { ActivityScope } from '~/types'
import { ticketActivityDescriber } from './activityDescriber'
+// WorkflowActivityLink resolves the workflow name from workflowsLogic; stub it so the describer
+// tests stay pure. Its own name-resolution behavior is covered in WorkflowActivityLink.test.tsx.
+jest.mock('./WorkflowActivityLink', () => ({
+ WorkflowActivityLink: ({ id }: { id: string }) => <span>workflow-actor:{id}</span>,
+}))
+
const getTextContent = (describer: { description: JSX.Element | string | null }): string => {
if (!describer.description || typeof describer.description === 'string') {
return (describer.description as string) || ''
@@ -24,6 +30,13 @@ const ticketLogItem = (overrides: Partial<ActivityLogItem>): ActivityLogItem =>
})
describe('ticketActivityDescriber', () => {
+ const statusChange: ActivityChange = {
+ type: ActivityScope.TICKET,
+ action: 'changed',
+ field: 'status',
+ before: 'new',
+ after: 'open',
+ }
const snoozeCleared: ActivityChange = {
type: ActivityScope.TICKET,
action: 'changed',
@@ -39,6 +52,50 @@ describe('ticketActivityDescriber', () => {
after: 'open',
}
+ it('attributes a workflow-triggered change to the workflow, not PostHog', () => {
+ const result = ticketActivityDescriber(
+ ticketLogItem({
+ detail: {
+ merge: null,
+ name: 'Ticket #2043',
+ changes: [statusChange],
+ trigger: { job_type: 'hog_flow', job_id: 'flow-123', payload: {} },
+ },
+ })
+ )
+ const text = getTextContent(result)
+ expect(text).toContain('workflow-actor:flow-123')
+ expect(text).toContain('changed status')
+ expect(text).not.toContain('PostHog')
+ })
+
+ it('attributes a non-workflow change to the acting user', () => {
+ const result = ticketActivityDescriber(
+ ticketLogItem({
+ user: { email: '[email protected]', first_name: 'Max', last_name: 'AI' },
+ detail: { merge: null, trigger: null, name: 'Ticket #2043', changes: [statusChange] },
+ })
+ )
+ expect(getTextContent(result)).toContain('Max AI')
+ })
+
+ it('describes a workflow-driven snooze clear as "removed snooze", not "snooze expired"', () => {
+ const result = ticketActivityDescriber(
+ ticketLogItem({
+ detail: {
+ merge: null,
+ name: 'Ticket #2043',
+ changes: [snoozeCleared],
+ trigger: { job_type: 'hog_flow', job_id: 'flow-123', payload: {} },
+ },
+ })
+ )
+ const text = getTextContent(result)
+ expect(text).toContain('workflow-actor:flow-123')
+ expect(text).toContain('removed snooze')
+ expect(text).not.toContain('snooze expired')
+ })
+
it('describes a manual unsnooze (user present) as "removed snooze"', () => {
const result = ticketActivityDescriber(
ticketLogItem({
diff --git a/products/conversations/frontend/activityDescriber.tsx b/products/conversations/frontend/activityDescriber.tsx
index 2a2fdfb07bb0..abbaedfd26ac 100644
--- a/products/conversations/frontend/activityDescriber.tsx
+++ b/products/conversations/frontend/activityDescriber.tsx
@@ -11,6 +11,8 @@ import { TZLabel } from 'lib/components/TZLabel'
import { Link } from 'lib/lemon-ui/Link'
import { urls } from 'scenes/urls'
+import { WorkflowActivityLink } from './WorkflowActivityLink'
+
const nameOrLinkToTicket = (
ticketNumber: string | undefined,
name: string | null | undefined
@@ -105,11 +107,13 @@ const ticketActionsMapping: Record<
}
}
if (before && !after) {
- // The same set→null change happens for a manual unsnooze and the system
- // wake task auto-expiring the snooze — tell them apart by actor. Only claim
- // "reopened" when the expiry actually flipped the ticket back to open; a
- // snooze on an already-resolved ticket clears without reopening it.
- if (logItem?.user) {
+ // The same set→null change happens for a deliberate unsnooze and the system
+ // wake task auto-expiring the snooze — tell them apart by actor. A workflow
+ // clearing the snooze is deliberate too (it has a trigger but no user), so only
+ // a change with neither a user nor a trigger is a genuine auto-expiry. Only claim
+ // "reopened" when the expiry actually flipped the ticket back to open; a snooze
+ // on an already-resolved ticket clears without reopening it.
+ if (logItem?.user || logItem?.detail?.trigger?.job_type === 'hog_flow') {
return { description: [<>removed snooze</>] }
}
const reopened = (logItem?.detail?.changes ?? []).some((c) => c.field === 'status' && c.after === 'open')
@@ -154,7 +158,16 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotification
return { description: null }
}
- const user = <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
+ // When a HogFlow workflow step made the change, attribute it to (and link to) the workflow
+ // instead of the generic "PostHog" system actor. The workflow name is resolved live by id
+ // (never trusted from the log payload), so it can't be spoofed via the update headers.
+ const trigger = logItem.detail.trigger
+ const actor =
+ trigger?.job_type === 'hog_flow' && trigger.job_id ? (
+ <WorkflowActivityLink id={trigger.job_id} />
+ ) : (
+ <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
+ )
const ticketNumber = logItem.detail.name?.replace(/^Ticket #/, '')
const ticketLink = nameOrLinkToTicket(ticketNumber, logItem.detail.name)
@@ -162,7 +175,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotification
return {
description: (
<>
- {user} created {ticketLink}
+ {actor} created {ticketLink}
</>
),
}
@@ -179,7 +192,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotification
return {
description: (
<>
- {user} assigned {ticketLink} to <strong>{formatAssignee(after)}</strong>
+ {actor} assigned {ticketLink} to <strong>{formatAssignee(after)}</strong>
</>
),
}
@@ -204,7 +217,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotification
return {
description: (
<>
- {user} {allChanges[0]} on {ticketLink}
+ {actor} {allChanges[0]} on {ticketLink}
</>
),
}
@@ -214,7 +227,7 @@ export function ticketActivityDescriber(logItem: ActivityLogItem, asNotification
return {
description: (
<>
- {user} made changes to {ticketLink}:
+ {actor} made changes to {ticketLink}:
<ul className="bullet-list">
{allChanges.map((desc, i) => (
<li key={i}>{desc}</li>