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(workflows): add a send message action for support tickets (#105105)

Alex V2daecc7a65e3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 501d024e887e..6e26fef28548 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6927,7 +6927,7 @@ snapshots:
products-workflows-editor-graph--add-on-promotion-emails--dark:
hash: v1.k794b7964.4e05cc89e810a0658cc3a95ad89ad3818b663f032294a768bf31dd45f255e229.wkYlcGi9vkdpW7HMrEMsxh4gMxH0ZiJSHwidbTkxC7A
products-workflows-editor-graph--add-on-promotion-emails--light:
- hash: v1.k794b7964.0df096512fda16f0d1fa1ebfed25fd9df287e7cf273d7bd56a93b3d5a316b2eb.0Td6CXL_NV0F9bNlH2sKu6FEJ3bi-WFQMYYeSV3LBY8
+ hash: v1.k794b7964.c3b9e6f838e5ceaf19f55e5ed259191679ef528ac20a93917ad67712ce2a400a.Otx1cNHaX_Y2tWHQE146ky7_pFZ3TOPd0DuqQKWimXE
products-workflows-editor-graph--customer-onboarding-and-retention--dark:
hash: v1.k794b7964.9c165882088a94a60c3f278c5ac933e19deea0799e2f178773b9562a06d5b587.T17LeudaJGjY7lpzSaWm3Vstubn72J6YmRirV14ZZGQ
products-workflows-editor-graph--customer-onboarding-and-retention--light:
@@ -6935,19 +6935,19 @@ snapshots:
products-workflows-editor-graph--new-workflow--dark:
hash: v1.k794b7964.7ba2d7e983927e8e8375e47d0c949b93943fd66aae376f98e125d683dd4ffd99.YZb3PzvlCIEGiDRA-lVQffhm1K7TV_CXi-VCWJpzbLc
products-workflows-editor-graph--new-workflow--light:
- hash: v1.k794b7964.a4626c7c6687ecfce8b18483f3023e63d6fea340afe537c77ac3b54b9806ec7a.yLmzRxJrZgQVkxgPOef_FH4ALnTa2GGJYnO-5Hxodn0
+ hash: v1.k794b7964.db428c9f9a07f95469995f3f6e2d70160b5b1c9883a470d21a34f8aed9c730e7.jWXaKUQj_Iyc8_JcnU56uRgQcYoaOFMQvl6HN6BIz4M
products-workflows-editor-graph--pending-ticket-cleanup--dark:
hash: v1.k794b7964.50a685ff409fb1d3bb91bcca26cc519dbac7448245365e0fb83395ce34373116.RXLJNJWCGBCN2FsWZkjCZMOaglz9nNSYEbyPcTXWzec
products-workflows-editor-graph--pending-ticket-cleanup--light:
- hash: v1.k794b7964.4af1b3ca8104f959250ec3c225c86ef68f36009ce8a0fc4569356e9e8491ff7b.PVlHcgjmjoOtUTvUiSfkcjhxoaWESCG0-iNbC-nm_2g
+ hash: v1.k794b7964.8a28c5eca9e95f1b6170a7e97cfecd7dc59af90dbe90c175226420931b4dd841.A8w0Sz2VUnYMz5xA-cNvdPONFGEs0QiBpGm2QCH2zXs
products-workflows-editor-graph--renewal-window-alerts--dark:
hash: v1.k794b7964.e262932c316a84d6e05ad90bae8c5cedc77bdb9d5b39804aa6b48ebcc0603581._vvGJVTaEGD2tI4GdyktkuUZ2mXbWetsfgJ9m_Z0QQY
products-workflows-editor-graph--renewal-window-alerts--light:
- hash: v1.k794b7964.fab81e2858c6ee5f4f670f1d274901a1346302f174bc933d8ab098c124cf5555.ORDicecK-aPejsEHWHeQZimUJ2B0P6wBOM12IsLwC54
+ hash: v1.k794b7964.bb2d7c26dce2e0db78eccc6ae66b4f3780f156c26dc70af43ebfd7ffb6a09349.m74JFK2zZNeUxlNjDWkwzXyozyN1Yvd9cF6bIVn5pvo
products-workflows-editor-graph--support-sla-routing--dark:
hash: v1.k794b7964.7c60c3d139d5b5dabbd7fb974f621f135149176f1c86184aed079c6deaef414e.AkijMDM4cBxIWBu4E8V7VThp1fwVqHJcfVB24fcGK0Y
products-workflows-editor-graph--support-sla-routing--light:
- hash: v1.k794b7964.96264d77ca9e5d4897c48f8552d051ab6a414675e9a5d62b1878c40955e60a12.veQ0qlbkuVu45XgikLqMm6GhiTqaU-iYLBAUuvq-W_o
+ hash: v1.k794b7964.185cabd282f05ff0599ff324858eeeb5a81eeeb8fffd0b072ca9d5c0d7807243.YHPb3_b2-Ub_stRNprVNr30-LC_kXEkREvdFFEMknkw
products-workflows-editor-tree--add-on-promotion-emails--dark:
hash: v1.k794b7964.f28f743921b108a3d7ce5c5f7f373407609e4f131790261d27afd7107909381f.Ji6HKS277Nou8dc2Ow4IG0TDdXKMQOCiNg6StWNB1Kc
products-workflows-editor-tree--add-on-promotion-emails--light:
diff --git a/nodejs/src/cdp/async-functions/conversations.ts b/nodejs/src/cdp/async-functions/conversations.ts
index e1c7b37d71c9..9ec2f1de65e7 100644
--- a/nodejs/src/cdp/async-functions/conversations.ts
+++ b/nodejs/src/cdp/async-functions/conversations.ts
@@ -5,6 +5,7 @@ import { HogFlow } from '~/cdp/schema/hogflow'
import { AsyncFunctionContext } from '../async-function-registry'
import { registerAsyncFunction } from '../async-function-registry'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
+import { workflowStepDispatchKeyFromInvocation } from '../utils/workflow-step-dispatch-key'
import { UUID_RE, callInternalApi } from './internal-api-call'
const TICKET_ACTIONS = 'ticket workflow actions'
@@ -18,7 +19,13 @@ async function callInternalTicketApi(
context: AsyncFunctionContext,
result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
ticketId: string,
- options: { method: 'GET' | 'PATCH'; query?: string; body?: string; extraHeaders?: Record<string, string> }
+ options: {
+ method: 'GET' | 'PATCH' | 'POST'
+ query?: string
+ body?: string
+ extraHeaders?: Record<string, string>
+ retriableStatuses?: number[]
+ }
): Promise<void> {
// Reaches the operator verbatim in the workflow logs. Keep it free of square brackets,
// which the log viewer parses as entity chips and would swallow.
@@ -153,3 +160,54 @@ registerAsyncFunction('postHogUpdateTicket', {
}
},
})
+
+registerAsyncFunction('postHogSendTicketMessage', {
+ execute: async (args, context, result) => {
+ const [opts] = args as [Record<string, any> | undefined]
+ const ticketId = opts?.ticket_id
+ const message = typeof opts?.message === 'string' ? opts.message.trim() : ''
+
+ if (!ticketId || typeof ticketId !== 'string') {
+ throw new Error("[HogFunction] - postHogSendTicketMessage call missing 'ticket_id' property")
+ }
+ if (!message) {
+ throw new Error("[HogFunction] - postHogSendTicketMessage call missing 'message' property")
+ }
+
+ const idempotencyKey = workflowStepDispatchKeyFromInvocation(context.invocation)
+ if (!idempotencyKey) {
+ throw new Error('[HogFunction] - postHogSendTicketMessage only runs inside a workflow')
+ }
+
+ await callInternalTicketApi(context, result, ticketId, {
+ method: 'POST',
+ body: JSON.stringify({
+ message,
+ is_private: opts?.is_private === true,
+ idempotency_key: idempotencyKey,
+ }),
+ retriableStatuses: [409],
+ })
+ },
+
+ mock: (args, logs) => {
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `Async function 'postHogSendTicketMessage' was mocked with arguments:`,
+ })
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `postHogSendTicketMessage(${JSON.stringify(args[0], null, 2)})`,
+ })
+
+ return {
+ status: 201,
+ body: {
+ id: 'mock-message-id',
+ is_private: args[0]?.is_private === true,
+ },
+ }
+ },
+})
diff --git a/nodejs/src/cdp/async-functions/internal-api-call.ts b/nodejs/src/cdp/async-functions/internal-api-call.ts
index 90f4fba540e5..eb6f99ac055c 100644
--- a/nodejs/src/cdp/async-functions/internal-api-call.ts
+++ b/nodejs/src/cdp/async-functions/internal-api-call.ts
@@ -42,9 +42,10 @@ export async function callInternalApi(
entityClaims: Record<string, string>
body?: string
extraHeaders?: Record<string, string>
+ retriableStatuses?: number[]
}
): Promise<void> {
- const { jwt, path, method, entityClaims, body, extraHeaders } = options
+ const { jwt, path, method, entityClaims, body, extraHeaders, retriableStatuses = [] } = options
const startedAt = performance.now()
// Counts once per handler call, not per retry attempt below: the retries are all one
@@ -90,7 +91,9 @@ export async function callInternalApi(
fetchError = err as Error
}
- const succeeded = fetchError === null && status !== null && !RETRIABLE_STATUSES.includes(status)
+ const shouldRetry =
+ status !== null && (RETRIABLE_STATUSES.includes(status) || retriableStatuses.includes(status))
+ const succeeded = fetchError === null && status !== null && !shouldRetry
if (succeeded) {
const parsedBody = parseBody(text)
if (status! >= 400) {
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index e9d79bf4c9d3..bd0392f0a3a4 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -720,6 +720,36 @@ describe('Hog Executor', () => {
expect(result.invocation.queueParameters).toBeUndefined()
})
+ it('postHogSendTicketMessage posts the message and only marks a private note when the flag is true', async () => {
+ const fetchSpy = jest
+ .spyOn(requestModule, 'internalFetch')
+ .mockResolvedValueOnce(mockInternalResponse(409, { error: 'Message is still being created' }))
+ .mockResolvedValue(mockInternalResponse(201, { id: 'message-1', is_private: true }))
+
+ mockExecHogForAsyncFunction('postHogSendTicketMessage', [
+ { ticket_id: TICKET_UUID, message: ' Internal only ', is_private: true },
+ ])
+ const invocation = createTicketInvocation()
+ invocation.state.actionId = 'send_message'
+ invocation.state.actionStepCount = 0
+ const result = await executor.execute(invocation)
+
+ expect(fetchSpy).toHaveBeenCalledTimes(2)
+ const [url, options] = fetchSpy.mock.calls[1] as unknown as [string, FetchOptions]
+ expect(url).toEqual(
+ `${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/conversations/tickets/${TICKET_UUID}`
+ )
+ expect(options.method).toEqual('POST')
+ expect(parseJSON(options.body as string)).toEqual({
+ message: 'Internal only',
+ is_private: true,
+ idempotency_key: `${invocation.id}:send_message:0`,
+ })
+ expect(result.invocation.state.vmState!.stack).toEqual([
+ { status: 201, body: { id: 'message-1', is_private: true } },
+ ])
+ })
+
it('postHogUpdateTicket forwards the updates body and workflow attribution header', async () => {
const fetchSpy = jest
.spyOn(requestModule, 'internalFetch')
@@ -895,11 +925,34 @@ describe('Hog Executor', () => {
})
})
- it.each(['postHogGetTicket', 'postHogUpdateTicket'])('%s errors when ticket_id is missing', async (name) => {
- mockExecHogForAsyncFunction(name, [name === 'postHogUpdateTicket' ? { updates: { status: 'new' } } : {}])
+ it.each(['postHogGetTicket', 'postHogUpdateTicket', 'postHogSendTicketMessage'])(
+ '%s errors when ticket_id is missing',
+ async (name) => {
+ const args =
+ name === 'postHogUpdateTicket'
+ ? [{ updates: { status: 'new' } }]
+ : name === 'postHogSendTicketMessage'
+ ? [{ message: 'hello' }]
+ : [{}]
+ mockExecHogForAsyncFunction(name, args)
+
+ const result = await executor.execute(createTicketInvocation())
+ expect(result.error).toContain("missing 'ticket_id'")
+ }
+ )
+
+ it('postHogSendTicketMessage errors when message is missing', async () => {
+ mockExecHogForAsyncFunction('postHogSendTicketMessage', [{ ticket_id: TICKET_UUID, message: ' ' }])
+
+ const result = await executor.execute(createTicketInvocation())
+ expect(result.error).toContain("missing 'message'")
+ })
+
+ it('postHogSendTicketMessage errors outside a workflow step', async () => {
+ mockExecHogForAsyncFunction('postHogSendTicketMessage', [{ ticket_id: TICKET_UUID, message: 'hello' }])
const result = await executor.execute(createTicketInvocation())
- expect(result.error).toContain("missing 'ticket_id'")
+ expect(result.error).toContain('only runs inside a workflow')
})
})
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-send-ticket-message.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-send-ticket-message.template.ts
new file mode 100644
index 000000000000..efafa71794b3
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/posthog_conversations/posthog-send-ticket-message.template.ts
@@ -0,0 +1,67 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+import { hogApiErrorMessageFn } from '../../hog-helpers'
+
+export const template: HogFunctionTemplate = {
+ free: true,
+ status: 'hidden',
+ type: 'destination',
+ id: 'template-posthog-send-ticket-message',
+ name: 'Send conversation ticket message',
+ description: 'Post a reply on a ticket, or save it as a private note',
+ icon_url: '/static/posthog-icon.svg',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
+${hogApiErrorMessageFn}
+
+if (empty(inputs.ticket_id)) {
+ throw Error('Ticket ID is required')
+}
+
+if (empty(inputs.message)) {
+ throw Error('Message is required')
+}
+
+let response := postHogSendTicketMessage({
+ 'ticket_id': inputs.ticket_id,
+ 'message': inputs.message,
+ 'is_private': inputs.is_private
+})
+
+if (response.status >= 400) {
+ throw Error(f'Failed to send message ({response.status}): {apiErrorMessage(response)}')
+}
+
+return response.body
+`,
+ inputs_schema: [
+ {
+ key: 'ticket_id',
+ type: 'string',
+ label: 'Ticket ID',
+ secret: false,
+ required: true,
+ default: '{event.properties.ticket_id}',
+ description: 'The UUID of the ticket to post on. Available from trigger event properties.',
+ },
+ {
+ key: 'message',
+ type: 'string',
+ label: 'Message',
+ secret: false,
+ required: true,
+ description: 'Text to post on the ticket. You can use variables.',
+ },
+ {
+ key: 'is_private',
+ type: 'boolean',
+ label: 'Send as a private note',
+ secret: false,
+ required: false,
+ default: false,
+ description:
+ 'Keep this message internal. The customer does not see it, and it is not delivered on the ticket channel.',
+ },
+ ],
+}
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 70a29f1f17ff..a5efcdb6afbe 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
@@ -1,5 +1,8 @@
+import { parseJSON } from '~/common/utils/json-parse'
+
import { TemplateTester } from '../../test/test-helpers'
import { template as getTicketTemplate } from './posthog-get-ticket.template'
+import { template as sendTicketMessageTemplate } from './posthog-send-ticket-message.template'
import { template as updateTicketTemplate } from './posthog-update-ticket.template'
const TICKET_UUID = '0198a5c1-2f6e-7c3a-9b41-b6d21c0aa111'
@@ -11,16 +14,25 @@ describe('posthog conversations ticket templates', () => {
template: getTicketTemplate,
inputs: { ticket_id: TICKET_UUID },
failurePrefix: 'Failed to fetch ticket (401):',
+ actionId: undefined,
},
{
name: 'update ticket',
template: updateTicketTemplate,
inputs: { ticket_id: TICKET_UUID, status: 'new' },
failurePrefix: 'Failed to update ticket (401):',
+ actionId: undefined,
+ },
+ {
+ name: 'send message',
+ template: sendTicketMessageTemplate,
+ inputs: { ticket_id: TICKET_UUID, message: 'We are on it.' },
+ failurePrefix: 'Failed to send message (401):',
+ actionId: 'send_message',
},
]
- describe.each(cases)('$name', ({ template, inputs, failurePrefix }) => {
+ describe.each(cases)('$name', ({ template, inputs, failurePrefix, actionId }) => {
const tester = new TemplateTester(template)
beforeEach(async () => {
@@ -32,7 +44,11 @@ describe('posthog conversations ticket templates', () => {
// the bare status code alone gave the customer nothing to act on.
tester.mockInternalFetchResponse({ status: 401, body: { error: 'Invalid API key' } })
- let response = await tester.invoke(inputs)
+ let response = await tester.invoke(
+ inputs,
+ undefined,
+ actionId ? { actionId, actionStepCount: 0 } : undefined
+ )
expect(response.error).toBeUndefined()
response = await tester.resumeInvocation(response.invocation)
@@ -42,7 +58,11 @@ describe('posthog conversations ticket templates', () => {
it('returns the ticket body on success', async () => {
tester.mockInternalFetchResponse({ status: 200, body: { id: TICKET_UUID, status: 'new' } })
- let response = await tester.invoke(inputs)
+ let response = await tester.invoke(
+ inputs,
+ undefined,
+ actionId ? { actionId, actionStepCount: 0 } : undefined
+ )
response = await tester.resumeInvocation(response.invocation)
expect(response.error).toBeUndefined()
@@ -51,6 +71,44 @@ describe('posthog conversations ticket templates', () => {
})
})
+ describe('send message', () => {
+ const tester = new TemplateTester(sendTicketMessageTemplate)
+
+ beforeEach(async () => {
+ await tester.beforeEach()
+ tester.mockInternalFetchResponse({ status: 201, body: { id: 'message-1', is_private: false } })
+ })
+
+ const postedBody = (): { message: string; is_private: boolean; idempotency_key: string } => {
+ const [, options] = tester.mockInternalFetch.mock.calls[0] as unknown as [string, { body: string }]
+ return parseJSON(options.body)
+ }
+
+ it('posts a public reply by default and treats 201 as success', async () => {
+ let response = await tester.invoke({ ticket_id: TICKET_UUID, message: 'We are on it.' }, undefined, {
+ actionId: 'send_message',
+ actionStepCount: 0,
+ })
+ response = await tester.resumeInvocation(response.invocation)
+
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toBe(true)
+ expect(postedBody()).toEqual({
+ message: 'We are on it.',
+ is_private: false,
+ idempotency_key: expect.stringMatching(/:send_message:0$/),
+ })
+ })
+
+ it('sends the private-note flag when the checkbox is on', async () => {
+ await tester.invoke({ ticket_id: TICKET_UUID, message: 'Internal only', is_private: true }, undefined, {
+ actionId: 'send_message',
+ actionStepCount: 0,
+ })
+ expect(postedBody().is_private).toBe(true)
+ })
+ })
+
describe('get ticket first_customer_message_text opt-in', () => {
const tester = new TemplateTester(getTicketTemplate)
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index e785f0cb41ef..8799346e970b 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -25,6 +25,7 @@ import { template as posthogCaptureTemplate } from './_destinations/posthog_capt
import { template as posthogGroupIdentifyTemplate } from './_destinations/posthog_capture/posthog-group-identify.template'
import { template as posthogUpdatePersonPropertiesTemplate } from './_destinations/posthog_capture/posthog-update-person-properties.template'
import { template as posthogGetTicketTemplate } from './_destinations/posthog_conversations/posthog-get-ticket.template'
+import { template as posthogSendTicketMessageTemplate } from './_destinations/posthog_conversations/posthog-send-ticket-message.template'
import { template as posthogUpdateTicketTemplate } from './_destinations/posthog_conversations/posthog-update-ticket.template'
import { template as posthogCreateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-create-account.template'
import { template as posthogCreateCustomerTaskTemplate } from './_destinations/posthog_customer_analytics/posthog-create-customer-task.template'
@@ -102,6 +103,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
posthogUpdatePersonPropertiesTemplate,
posthogSetHogflowVariableTemplate,
posthogGetTicketTemplate,
+ posthogSendTicketMessageTemplate,
posthogUpdateTicketTemplate,
posthogCreateTaskTemplate,
posthogRunScoutTemplate,
diff --git a/nodejs/tests/fixtures/hog-bytecode/2b4b245e98e19f5f18ec7031c2ccf12e5e431349d37092b537dbad5d2175c045.json b/nodejs/tests/fixtures/hog-bytecode/2b4b245e98e19f5f18ec7031c2ccf12e5e431349d37092b537dbad5d2175c045.json
new file mode 100644
index 000000000000..ba5abd7ad1bc
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/2b4b245e98e19f5f18ec7031c2ccf12e5e431349d37092b537dbad5d2175c045.json
@@ -0,0 +1 @@
+["_H",1,32,"We are on it.",38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/3fcb664b1cac4a584433d2313a5764d4e3e5028ed5dd6477515f962968a97126.json b/nodejs/tests/fixtures/hog-bytecode/3fcb664b1cac4a584433d2313a5764d4e3e5028ed5dd6477515f962968a97126.json
new file mode 100644
index 000000000000..2458d7eda0c4
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/3fcb664b1cac4a584433d2313a5764d4e3e5028ed5dd6477515f962968a97126.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,"message",32,"inputs",1,2,2,"empty",1,40,6,32,"Message is required",2,"Error",1,49,32,"ticket_id",32,"ticket_id",32,"inputs",1,2,32,"message",32,"message",32,"inputs",1,2,32,"is_private",32,"is_private",32,"inputs",1,2,42,3,2,"postHogSendTicketMessage",1,33,400,36,1,32,"status",45,14,40,22,32,"Failed to send message (",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/nodejs/tests/fixtures/hog-bytecode/ce7dd5eb0e9f52ac388f7a87f7520d55219322e893989f7be7b15abb15dd74ce.json b/nodejs/tests/fixtures/hog-bytecode/ce7dd5eb0e9f52ac388f7a87f7520d55219322e893989f7be7b15abb15dd74ce.json
new file mode 100644
index 000000000000..a3f3049f86eb
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/ce7dd5eb0e9f52ac388f7a87f7520d55219322e893989f7be7b15abb15dd74ce.json
@@ -0,0 +1 @@
+["_H",1,32,"Internal only",38]
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index bfc509884e43..252da3a98d48 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -216,6 +216,7 @@ def register_supported_function(name: str) -> None:
register_supported_function("postHogGetTicket")
register_supported_function("postHogUpdateTicket")
+register_supported_function("postHogSendTicketMessage")
register_supported_function("postHogGetAccount")
register_supported_function("postHogUpdateAccount")
register_supported_function("postHogSetAccountProperties")
diff --git a/products/conversations/backend/api/internal.py b/products/conversations/backend/api/internal.py
index f60c072c6450..90581625f8f1 100644
--- a/products/conversations/backend/api/internal.py
+++ b/products/conversations/backend/api/internal.py
@@ -11,6 +11,7 @@ does not expose, so the route is unreachable from the public internet.
import uuid
from typing import Any, cast
+from drf_spectacular.utils import extend_schema
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
@@ -23,7 +24,10 @@ from posthog.models import Team
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from products.conversations.backend.api.ticket_actions import (
+ TicketActionMessageResponseSerializer,
+ TicketActionMessageSerializer,
handle_ticket_get,
+ handle_ticket_message,
handle_ticket_patch,
wants_first_customer_message_text,
)
@@ -43,6 +47,7 @@ class InternalTicketView(APIView):
"""
GET /api/projects/<team_id>/internal/conversations/tickets/<ticket_id> — Fetch ticket data
PATCH /api/projects/<team_id>/internal/conversations/tickets/<ticket_id> — Update ticket fields
+ POST /api/projects/<team_id>/internal/conversations/tickets/<ticket_id> — Post a reply or private note
JWT-only from birth: there is no legacy-token fallback here, so this route never
accepts secret_api_token. The auth class binds the request to the token's team and
@@ -70,6 +75,21 @@ class InternalTicketView(APIView):
TICKET_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="patch").inc()
return handle_ticket_patch(request, team, ticket_id)
+ @extend_schema(
+ request=TicketActionMessageSerializer,
+ responses={
+ status.HTTP_200_OK: TicketActionMessageResponseSerializer,
+ status.HTTP_201_CREATED: TicketActionMessageResponseSerializer,
+ },
+ )
+ def post(self, request: Request, team_id: str, ticket_id: uuid.UUID) -> Response:
+ team, error = _check_ticket_access(request, ticket_id)
+ if error:
+ return error
+ assert team is not None
+ TICKET_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="post").inc()
+ return handle_ticket_message(request, team, ticket_id)
+
def _check_ticket_access(request: Request, ticket_id: uuid.UUID) -> tuple[Team, None] | tuple[None, Response]:
"""Enforce the per-entity claim and the product gate after JWT authentication.
diff --git a/products/conversations/backend/api/tests/test_internal.py b/products/conversations/backend/api/tests/test_internal.py
index 68bb751dc44d..6d0ee077c935 100644
--- a/products/conversations/backend/api/tests/test_internal.py
+++ b/products/conversations/backend/api/tests/test_internal.py
@@ -17,7 +17,7 @@ from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from products.conversations.backend.api.internal import CONVERSATIONS_TICKETS_PURPOSE
from products.conversations.backend.models import Ticket
-from products.conversations.backend.models.constants import Status
+from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_NAME, WORKFLOW_AUTHOR_TYPE, Status
# Signed with this route's key but carrying another surface's audience — a token minted for a
# different purpose must never authenticate here even when the signing key checks out.
@@ -75,6 +75,88 @@ class TestInternalTicketAPI(BaseTest):
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_post_sends_a_public_message(self):
+ response = self.client.post(
+ self.url,
+ {"message": " We are on it. ", "idempotency_key": "run-1:send:0"},
+ content_type="application/json",
+ **self._headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ body = response.json()
+ self.assertEqual(body["is_private"], False)
+ comment = Comment.objects.get(id=body["id"], team_id=self.team.id)
+ self.assertEqual(comment.content, "We are on it.")
+ self.assertEqual(comment.item_id, str(self.ticket.id))
+ self.assertIsNone(comment.created_by_id)
+ item_context = comment.item_context
+ assert item_context is not None
+ self.assertEqual(item_context["author_type"], WORKFLOW_AUTHOR_TYPE)
+ self.assertEqual(item_context["author_name"], WORKFLOW_AUTHOR_NAME)
+ self.assertFalse(item_context["is_private"])
+
+ def test_post_private_note(self):
+ response = self.client.post(
+ self.url,
+ {"message": "Internal only", "is_private": True, "idempotency_key": "run-1:note:0"},
+ content_type="application/json",
+ **self._headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertTrue(response.json()["is_private"])
+ comment = Comment.objects.get(id=response.json()["id"], team_id=self.team.id)
+ item_context = comment.item_context
+ assert item_context is not None
+ self.assertTrue(item_context["is_private"])
+ self.assertEqual(item_context["author_type"], WORKFLOW_AUTHOR_TYPE)
+
+ def test_post_deduplicates_by_workflow_step_execution(self):
+ payload = {"message": "We are on it.", "is_private": False, "idempotency_key": "run-1:send:0"}
+ first = self.client.post(self.url, payload, content_type="application/json", **self._headers())
+ second = self.client.post(
+ self.url,
+ {**payload, "message": "Changed after retry"},
+ content_type="application/json",
+ **self._headers(),
+ )
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(second.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.json()["id"], first.json()["id"])
+ self.assertEqual(Comment.objects.filter(team_id=self.team.id, item_id=str(self.ticket.id)).count(), 1)
+
+ next_run = self.client.post(
+ self.url,
+ {"message": "We are on it.", "is_private": False, "idempotency_key": "run-2:send:0"},
+ content_type="application/json",
+ **self._headers(),
+ )
+ self.assertEqual(next_run.status_code, status.HTTP_201_CREATED)
+ self.assertNotEqual(next_run.json()["id"], first.json()["id"])
+ self.assertEqual(Comment.objects.filter(team_id=self.team.id, item_id=str(self.ticket.id)).count(), 2)
+
+ def test_post_rejects_blank_message(self):
+ response = self.client.post(
+ self.url,
+ {"message": " ", "idempotency_key": "run-1:send:0"},
+ content_type="application/json",
+ **self._headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Comment.objects.filter(team_id=self.team.id, item_id=str(self.ticket.id)).exists())
+
+ def test_post_unknown_ticket_creates_nothing(self):
+ missing = uuid.uuid4()
+ url = f"/api/projects/{self.team.id}/internal/conversations/tickets/{missing}"
+ headers = self._headers({"team_id": self.team.id, "ticket_id": str(missing)})
+ response = self.client.post(
+ url,
+ {"message": "hello", "idempotency_key": "run-1:send:0"},
+ content_type="application/json",
+ **headers,
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertFalse(Comment.objects.filter(team_id=self.team.id, item_id=str(missing)).exists())
+
def test_patch_updates_ticket(self):
response = self.client.patch(
self.url, {"status": "resolved"}, content_type="application/json", **self._headers()
@@ -126,8 +208,13 @@ class TestInternalTicketAPI(BaseTest):
self.assertEqual(get_response.status_code, expected_status)
patch_response = self.client.patch(self.url, {"status": "resolved"}, content_type="application/json", **headers)
self.assertEqual(patch_response.status_code, expected_status)
+ post_response = self.client.post(
+ self.url, {"message": "should not land"}, content_type="application/json", **headers
+ )
+ self.assertEqual(post_response.status_code, expected_status)
self.ticket.refresh_from_db()
self.assertEqual(self.ticket.status, Status.NEW)
+ self.assertFalse(Comment.objects.filter(team_id=self.team.id, item_id=str(self.ticket.id)).exists())
def test_unprovisioned_secret_rejects_even_a_well_formed_token(self):
headers = self._headers()
@@ -140,6 +227,11 @@ class TestInternalTicketAPI(BaseTest):
self.team.save(update_fields=["conversations_enabled"])
response = self.client.get(self.url, **self._headers())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ post_response = self.client.post(
+ self.url, {"message": "should not land"}, content_type="application/json", **self._headers()
+ )
+ self.assertEqual(post_response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Comment.objects.filter(team_id=self.team.id, item_id=str(self.ticket.id)).exists())
def test_authenticated_get_increments_the_scoped_jwt_counter(self):
labels = {"auth_method": "scoped_jwt", "http_method": "get"}
diff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.py
index 2336f6257673..8055ebe8b5de 100644
--- a/products/conversations/backend/api/tests/test_signals.py
+++ b/products/conversations/backend/api/tests/test_signals.py
@@ -80,6 +80,26 @@ class TestTicketMessageSignals(BaseTest):
assert self.ticket.updated_at == comment.created_at
assert self.ticket.unread_customer_count == 0 # Customer messages don't increment this
+ @patch("products.conversations.backend.signals.capture_message_received")
+ @patch("products.conversations.backend.signals.capture_message_sent")
+ def test_public_workflow_message_counts_without_emitting_a_trigger_event(
+ self, mock_sent, mock_received, mock_on_commit
+ ):
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(self.ticket.id),
+ content="Automated reply",
+ item_context={"author_type": "workflow", "is_private": False},
+ )
+
+ self.ticket.refresh_from_db()
+ assert self.ticket.message_count == 1
+ assert self.ticket.last_message_text == "Automated reply"
+ assert self.ticket.unread_customer_count == 1
+ mock_sent.assert_not_called()
+ mock_received.assert_not_called()
+
def test_team_message_updates_stats_and_unread(self, mock_on_commit):
comment = self._create_team_message("Response from team")
@@ -641,6 +661,7 @@ class TestEmailReplySignalGuard(BaseTest):
("inbound_team_email_blocked", "support", True, True, 0),
("in_app_agent_reply_sent", "support", False, True, 1),
("customer_email_blocked", "customer", True, True, 0),
+ ("workflow_public_reply_sent", "workflow", False, False, 1),
]
)
def test_email_outbox_guard(self, _mock_on_commit, _name, author_type, from_email, has_created_by, expected_count):
@@ -665,6 +686,8 @@ class TestIsOutboundReply:
[
("private_ai_note", {"author_type": "AI", "is_private": True}, None, False),
("public_ai_reply", {"author_type": "AI", "is_private": False}, None, True),
+ ("public_workflow_reply", {"author_type": "workflow", "is_private": False}, None, True),
+ ("private_workflow_note", {"author_type": "workflow", "is_private": True}, None, False),
("human_team_reply", {"author_type": "support", "is_private": False}, 42, True),
("private_human_note", {"author_type": "support", "is_private": True}, 42, False),
("customer_message", {"author_type": "customer", "is_private": False}, None, False),
diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.py
index cecdf03d8f4d..b55edf0fdaf3 100644
--- a/products/conversations/backend/api/tests/test_widget.py
+++ b/products/conversations/backend/api/tests/test_widget.py
@@ -307,6 +307,39 @@ class TestWidgetAPI(BaseTest):
self.assertEqual(len(response.json()["messages"]), 2)
self.assertEqual(response.json()["messages"][0]["content"], "First message")
+ def test_get_messages_shows_a_workflow_reply_as_staff(self):
+ ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=self.widget_session_id,
+ distinct_id=self.distinct_id,
+ channel_source="widget",
+ )
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="We are on it.",
+ item_context={"author_type": "workflow", "author_name": "Workflow", "is_private": False},
+ )
+ Comment.objects.create(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="Internal only",
+ item_context={"author_type": "workflow", "is_private": True},
+ )
+
+ response = self.client.get(
+ f"/api/conversations/v1/widget/messages/{ticket.id}?widget_session_id={self.widget_session_id}",
+ **self._get_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ messages = response.json()["messages"]
+ self.assertEqual(len(messages), 1)
+ self.assertEqual(messages[0]["content"], "We are on it.")
+ self.assertEqual(messages[0]["author_type"], "support")
+ self.assertEqual(messages[0]["author_name"], "Support")
+
def test_get_messages_excludes_private(self):
ticket = Ticket.objects.create_with_number(
team=self.team,
diff --git a/products/conversations/backend/api/ticket_actions.py b/products/conversations/backend/api/ticket_actions.py
index e592718d2364..5cb82729902f 100644
--- a/products/conversations/backend/api/ticket_actions.py
+++ b/products/conversations/backend/api/ticket_actions.py
@@ -1,15 +1,17 @@
"""Shared implementation of the ticket API called by CDP workflow actions.
-Two routes wrap these handlers with different authentication: the public external route
-(legacy Team.secret_api_token bearer, api/external.py) and the internal service route
-(scoped service JWT, api/internal.py). The worker selects between them per environment
-by config presence (#82564), so the two must behave identically.
+Two routes wrap the get and patch handlers with different authentication: the public
+external route (legacy Team.secret_api_token bearer, api/external.py) and the internal
+service route (scoped service JWT, api/internal.py). The worker selects between them per
+environment by config presence (#82564), so those two handlers must behave identically.
+Sending a message is JWT-only. The legacy route does not expose it.
"""
import re
import uuid
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+from django.db import connection, transaction
from django.db.models.functions import Substr
from django.utils import timezone
@@ -21,12 +23,26 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Tag, Team
from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
from posthog.models.activity_logging.model_activity import ActivityTriggerContext
+from posthog.models.comment import Comment
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 Channel, Priority, Status
+from products.conversations.backend.models.constants import (
+ WORKFLOW_AUTHOR_NAME,
+ WORKFLOW_AUTHOR_TYPE,
+ WORKFLOW_DISPATCH_KEY,
+ Channel,
+ Priority,
+ Status,
+)
+from products.conversations.backend.reply_dedupe import (
+ REPLY_IN_PROGRESS_DETAIL,
+ CreateOutcome,
+ ReplyFingerprint,
+ create_deduplicated,
+)
from products.conversations.backend.services.messages import visible_ticket_messages
from products.conversations.backend.services.sla import WEEKDAYS, compute_sla_deadline
@@ -85,6 +101,36 @@ class TicketActionUpdateSerializer(serializers.Serializer):
return attrs
+class TicketActionMessageSerializer(serializers.Serializer):
+ message = serializers.CharField(
+ max_length=5000,
+ help_text="Reply text in markdown. The same limit as a reply posted from the ticket.",
+ )
+ is_private = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="When true, store an internal note. The customer does not see it and it is not delivered.",
+ )
+ idempotency_key = serializers.CharField(
+ max_length=500,
+ help_text="Stable identity of this workflow step execution.",
+ )
+
+ def validate_message(self, value: str) -> str:
+ stripped = value.strip()
+ if not stripped:
+ raise serializers.ValidationError("Message content is required.")
+ return stripped
+
+
+class TicketActionMessageResponseSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="UUID of the created or replayed ticket message.")
+ is_private = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether the message is an internal note hidden from the customer.",
+ )
+
+
def validate_ticket_id(ticket_id: str | uuid.UUID) -> Response | None:
"""Return an error Response if ticket_id is not a valid UUID, else None."""
# Django's <uuid:ticket_id> converter passes uuid.UUID; uuid.UUID(uuid_obj)
@@ -536,3 +582,70 @@ def handle_ticket_patch(request: Request, team: Team, ticket_id: str | uuid.UUID
return Response({"error": "Failed to update tags"}, status=status.HTTP_400_BAD_REQUEST)
return Response({"ok": True})
+
+
+def handle_ticket_message(request: Request, team: Team, ticket_id: str | uuid.UUID) -> Response:
+ """Post a workflow reply or private note on an already-authenticated ticket.
+
+ author_type is workflow, with no created_by. Delivery only sends a public reply when the
+ author is AI or workflow, so a support author here would be stored and never emailed.
+ """
+ if error := validate_ticket_id(ticket_id):
+ return error
+
+ serializer = TicketActionMessageSerializer(data=request.data)
+ if not serializer.is_valid():
+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
+
+ try:
+ ticket = Ticket.objects.get(id=ticket_id, team_id=team.id)
+ except Ticket.DoesNotExist:
+ return Response({"error": "Ticket not found"}, status=status.HTTP_404_NOT_FOUND)
+
+ is_private = serializer.validated_data["is_private"]
+ content = serializer.validated_data["message"]
+ idempotency_key = serializer.validated_data["idempotency_key"]
+ item_context = {
+ "author_type": WORKFLOW_AUTHOR_TYPE,
+ "author_name": WORKFLOW_AUTHOR_NAME,
+ "is_private": is_private,
+ WORKFLOW_DISPATCH_KEY: idempotency_key,
+ }
+
+ def create_comment() -> Comment:
+ # ATOMIC_REQUESTS is off. The email outbox row is written in the comment post_save signal,
+ # so it has to share this transaction with the comment.
+ with transaction.atomic():
+ return Comment.objects.create(
+ team=team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content=content,
+ item_context=item_context,
+ )
+
+ # The worker retries a dropped response. Without this, that retry delivers the message again.
+ fingerprint = ReplyFingerprint.for_workflow(
+ team_id=team.id,
+ item_id=str(ticket.id),
+ content=content,
+ item_context=item_context,
+ idempotency_key=idempotency_key,
+ )
+ # Redis fails open, so serialize the persisted-match check and insert in Postgres too.
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
+ [f"conversations-workflow-message:{team.id}:{idempotency_key}"],
+ )
+ guarded = create_deduplicated(fingerprint, create_comment)
+ comment = guarded.comment
+ if guarded.outcome is CreateOutcome.CONFLICT or comment is None:
+ return Response({"error": REPLY_IN_PROGRESS_DETAIL}, status=status.HTTP_409_CONFLICT)
+
+ created = guarded.outcome is CreateOutcome.CREATED
+ return Response(
+ TicketActionMessageResponseSerializer({"id": comment.id, "is_private": is_private}).data,
+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
+ )
diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.py
index 0a291f9c7582..53481c0fd9b6 100644
--- a/products/conversations/backend/api/widget.py
+++ b/products/conversations/backend/api/widget.py
@@ -55,7 +55,7 @@ from products.conversations.backend.cache import (
set_cached_tickets,
)
from products.conversations.backend.models import SigningSecret, Ticket
-from products.conversations.backend.models.constants import ChannelDetail
+from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPE, ChannelDetail
from products.conversations.backend.services.identity import (
canonicalize_claim_value,
identity_claim_has_expired,
@@ -571,6 +571,9 @@ class WidgetMessagesView(APIView):
message_list = []
for m in messages:
author_type = m.item_context.get("author_type", "customer") if m.item_context else "customer"
+ # Widget clients branch on customer and AI. A workflow reply is a staff message.
+ if author_type == WORKFLOW_AUTHOR_TYPE:
+ author_type = "support"
# Get author name
if m.created_by:
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index 5f3d53e49052..485568431b65 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -55,6 +55,7 @@ from products.conversations.backend.models import (
Status,
Ticket,
)
+from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPE
from products.conversations.backend.services.messages import public_human_ticket_replies
from products.conversations.backend.slack import get_slack_client
from products.conversations.backend.support_slack import get_support_slack_bot_token
@@ -461,6 +462,7 @@ def _support_ticket_last_message(ticket: Ticket, comment: Comment | None) -> Con
"AI",
"human",
"support",
+ WORKFLOW_AUTHOR_TYPE,
}
context_name = _get_first_string(
context,
diff --git a/products/conversations/backend/models/constants.py b/products/conversations/backend/models/constants.py
index 6c5229ea6093..eeb3524e9f45 100644
--- a/products/conversations/backend/models/constants.py
+++ b/products/conversations/backend/models/constants.py
@@ -52,3 +52,11 @@ class OrganizationIdSource(models.TextChoices):
class RuleType(models.TextChoices):
TONE = "tone", "Tone"
ESCALATION = "escalation", "Escalation"
+
+
+# Workflow "Send message" posts with no PostHog user. Delivery treats this like an AI reply
+# (outbound, no created_by). The name is what agents see on the ticket; channel delivery
+# uses the support identity instead, so a customer never sees this label.
+WORKFLOW_AUTHOR_TYPE = "workflow"
+WORKFLOW_AUTHOR_NAME = "Workflow"
+WORKFLOW_DISPATCH_KEY = "workflow_dispatch_key"
diff --git a/products/conversations/backend/reply_dedupe.py b/products/conversations/backend/reply_dedupe.py
index 66bb4793a1f9..1084e02441be 100644
--- a/products/conversations/backend/reply_dedupe.py
+++ b/products/conversations/backend/reply_dedupe.py
@@ -34,6 +34,7 @@ from posthog.models.comment import Comment
from posthog.redis import get_client
from products.conversations.backend.models import Channel, Ticket
+from products.conversations.backend.models.constants import WORKFLOW_DISPATCH_KEY
logger = structlog.get_logger(__name__)
@@ -124,11 +125,12 @@ class ReplyFingerprint:
team_id: int
scope: str
item_id: str
- created_by_id: int
+ created_by_id: int | None
source_comment_id: str | None
content: str
rich_content: Any
item_context: dict[str, Any]
+ idempotency_key: str | None
@classmethod
def build(
@@ -169,12 +171,42 @@ class ReplyFingerprint:
content=content,
rich_content=rich_content,
item_context=item_context,
+ idempotency_key=None,
+ )
+
+ @classmethod
+ def for_workflow(
+ cls,
+ *,
+ team_id: int,
+ item_id: str,
+ content: str,
+ item_context: dict[str, Any],
+ idempotency_key: str,
+ ) -> "ReplyFingerprint":
+ """Fingerprint a workflow step by its stable dispatch key."""
+ return cls(
+ team_id=team_id,
+ scope=SUPPORT_TICKET_SCOPE,
+ item_id=str(item_id),
+ created_by_id=None,
+ source_comment_id=None,
+ content=content,
+ rich_content=None,
+ item_context=item_context,
+ idempotency_key=idempotency_key,
)
@property
def key(self) -> str:
- canonical = json.dumps(
+ identity = (
{
+ "team_id": self.team_id,
+ "scope": self.scope,
+ "idempotency_key": self.idempotency_key,
+ }
+ if self.idempotency_key is not None
+ else {
"team_id": self.team_id,
"scope": self.scope,
"item_id": self.item_id,
@@ -183,7 +215,10 @@ class ReplyFingerprint:
"content": self.content,
"rich_content": self.rich_content,
"item_context": self.item_context,
- },
+ }
+ )
+ canonical = json.dumps(
+ identity,
sort_keys=True,
separators=(",", ":"),
default=str,
@@ -195,6 +230,14 @@ class ReplyFingerprint:
"""Whether this persisted comment is the message this request asked for."""
if comment.deleted or comment.version != 0:
return False
+ if self.idempotency_key is not None:
+ context = comment.item_context or {}
+ return (
+ comment.team_id == self.team_id
+ and comment.scope == self.scope
+ and comment.item_id == self.item_id
+ and context.get(WORKFLOW_DISPATCH_KEY) == self.idempotency_key
+ )
if (
comment.team_id != self.team_id
or comment.scope != self.scope
@@ -222,11 +265,14 @@ class ReplyFingerprint:
scope=self.scope,
item_id=self.item_id,
created_by_id=self.created_by_id,
- content=self.content,
deleted=False,
version=0,
- created_at__gte=created_after,
- ).order_by("-created_at")[:20]
+ )
+ if self.idempotency_key is not None:
+ candidates = candidates.filter(item_context__workflow_dispatch_key=self.idempotency_key)
+ else:
+ candidates = candidates.filter(content=self.content, created_at__gte=created_after)
+ candidates = candidates.order_by("-created_at")[:20]
return next((comment for comment in candidates if self.matches(comment)), None)
def load_replay_target(self, comment_id: str | None) -> Comment | None:
diff --git a/products/conversations/backend/services/delivery.py b/products/conversations/backend/services/delivery.py
index 2bada758211e..e46438b56a72 100644
--- a/products/conversations/backend/services/delivery.py
+++ b/products/conversations/backend/services/delivery.py
@@ -28,7 +28,7 @@ from products.conversations.backend.models import (
ConversationDeliveryPart,
TeamConversationsSlackConfig,
)
-from products.conversations.backend.models.constants import Channel
+from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPE, Channel
from products.conversations.backend.models.delivery import (
DELIVERY_ERROR_MAX_LENGTH,
DeliverySnapshotTooLargeError,
@@ -195,7 +195,10 @@ def _author_for_comment(comment: Comment, team: Team) -> CommentAuthor:
return CommentAuthor(name=name, email=created_by.email or "")
settings_dict = team.conversations_settings or {}
bot_name = settings_dict.get("slack_bot_display_name")
- return CommentAuthor(name=bot_name if isinstance(bot_name, str) and bot_name else "AI assistant", email="")
+ context = comment.item_context if isinstance(comment.item_context, dict) else {}
+ # A workflow reply is not the assistant. Fall back to Support when the team has no bot name.
+ fallback = "Support" if context.get("author_type") == WORKFLOW_AUTHOR_TYPE else "AI assistant"
+ return CommentAuthor(name=bot_name if isinstance(bot_name, str) and bot_name else fallback, email="")
def _ticket_belongs_to_comment_team(ticket: Ticket, comment: Comment) -> bool:
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index 88c824080ac2..21b73d07bb43 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -20,7 +20,7 @@ from .ai.human_outcome import maybe_record_human_outcome
from .cache import invalidate_identity_tickets_cache, invalidate_messages_cache, invalidate_tickets_cache
from .events import capture_message_received, capture_message_sent, capture_private_message_sent, capture_ticket_created
from .models import ConversationDeliveryPart, EmailOutboxMessage, SigningSecret, Ticket
-from .models.constants import Channel
+from .models.constants import WORKFLOW_AUTHOR_TYPE, Channel
from .services.delivery import enqueue_slack_body_delivery
from .services.messages import visible_ticket_messages
from .tasks.email import send_email_reply
@@ -57,11 +57,25 @@ def _is_outbound_reply(item_context: dict | None, created_by_id: int | None) ->
author_type = item_context.get("author_type")
if created_by_id and author_type != "customer":
return True
- if author_type == "AI":
+ # No created_by: only these authors are team replies. A workflow message with any other
+ # type would be stored and never delivered.
+ if author_type in ("AI", WORKFLOW_AUTHOR_TYPE):
return True
return False
+def _unattributed_author_name(item_context: dict | None) -> str:
+ """Name shown to the customer when a reply has no PostHog user.
+
+ A workflow reply is not the assistant. Using the AI bot name here would tell the
+ customer the assistant wrote a message a workflow sent.
+ """
+ author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
+ if author_type == WORKFLOW_AUTHOR_TYPE:
+ return "Support"
+ return AI_BOT_DISPLAY_NAME
+
+
AI_BOT_DISPLAY_NAME = "AI assistant"
@@ -163,7 +177,7 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)
# New message: update denormalized stats
is_team_message = (created_by_id and author_type != "customer") or (
- author_type == "AI" and not _is_private_message(item_context)
+ author_type in ("AI", WORKFLOW_AUTHOR_TYPE) and not _is_private_message(item_context)
)
update_fields = {
@@ -201,10 +215,10 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)
capture_exception(e, {"ticket_id": item_id})
# Customer-facing analytics (to customer's project)
- if is_team_message:
+ if is_team_message and author_type != WORKFLOW_AUTHOR_TYPE:
author = User.objects.filter(id=created_by_id).first() if created_by_id else None
capture_message_sent(ticket, comment_id, content or "", author=author)
- else:
+ elif not is_team_message:
author = None
capture_message_received(ticket, comment_id, content or "")
@@ -283,7 +297,7 @@ def handle_comment_soft_delete(sender, instance: Comment, **kwargs):
# (private messages weren't counted in the first place)
if not is_private:
author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- is_team_message = created_by_id and author_type != "customer"
+ is_team_message = (created_by_id and author_type != "customer") or author_type == WORKFLOW_AUTHOR_TYPE
# Use Greatest to prevent negative counts from race conditions or data inconsistencies
update_fields = {"message_count": Greatest(F("message_count") - 1, 0)}
@@ -484,7 +498,7 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
else:
- author_name = AI_BOT_DISPLAY_NAME
+ author_name = _unattributed_author_name(item_context)
# Shared channels are written to via Graph (the bot connector can't post
# there); standard channels keep using the bot connector reply path.
@@ -572,7 +586,7 @@ def post_github_reply_on_team_message(sender, instance: Comment, created: bool,
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
else:
- author_name = AI_BOT_DISPLAY_NAME
+ author_name = _unattributed_author_name(item_context)
cast(Any, post_reply_to_github).delay(
ticket_id=str(ticket.id),
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
index fa0d2313e338..d0f62db1740e 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
@@ -256,6 +256,28 @@ describe('supportTicketSceneLogic chatMessages mapping', () => {
expect(logic.values.chatMessages[0].authorName).toBe(expectedName)
})
+ it('shows a workflow reply as a teammate message named Workflow', () => {
+ logic.actions.setMessages([
+ {
+ id: 'msg-workflow',
+ content: 'We are on it.',
+ scope: 'conversations_ticket',
+ item_id: 'ticket-1',
+ item_context: { author_type: 'workflow', author_name: 'Workflow', is_private: false },
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ } as unknown as CommentType,
+ ])
+
+ expect(logic.values.chatMessages[0]).toEqual(
+ expect.objectContaining({
+ authorType: 'human',
+ authorName: 'Workflow',
+ isPrivate: false,
+ })
+ )
+ })
+
it('loads the full email when the inbound message retained one', async () => {
logic.actions.setMessages([makeCustomerComment('msg-1', { has_full_email_content: true })])
expect(logic.values.chatMessages[0].hasFullEmailContent).toBe(true)
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 18ce371f04d3..9ea943637031 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -1130,7 +1130,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
id: message.id,
content: message.content || '',
richContent: message.rich_content,
- authorType: authorType === 'support' ? 'human' : authorType,
+ authorType: authorType === 'support' || authorType === 'workflow' ? 'human' : authorType,
authorName: displayName,
createdBy: message.created_by,
createdAt: message.created_at,
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/conversations.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/conversations.ts
index 63a9572aa588..3804f7cc1536 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/conversations.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/conversations.ts
@@ -16,5 +16,11 @@ registerActionNodeCategory({
description: 'Update a conversation ticket status or priority.',
config: { template_id: 'template-posthog-update-ticket', inputs: {} },
},
+ {
+ type: 'function',
+ name: 'Send message',
+ description: 'Post a reply on a ticket, or save it as a private note.',
+ config: { template_id: 'template-posthog-send-ticket-message', inputs: {} },
+ },
],
})