Repository navigation
fix(worker): run comment-triggered private flows on the DM conversation - #1105
Merged
Merged
Conversation
A comment automation with `Private reply = Flow` enqueued `sendFlow` on the
comment-anchored conversation (`Conversation.sourceId = postId`). The flow's
first message was delivered, but its state — `currentStep` and
`additionalAttributes.challenge` — was written there, while the contact's reply
arrived on the DM conversation (`sourceId IS NULL`). `resolveIncomingTextRouting`
found no challenge on that conversation and fell through to `automatedResponse`,
so the flow never advanced past its first waiting step. Nothing threw: no queue
error, no `sendError`.
Resolve the DM conversation before enqueueing the flow, falling back to
`findOrCreate({ sourceId: null })` for a contact whose first interaction is the
comment. `commentAnchor` is untouched — it travels on the job and still delivers
the first message through the comment_id-anchored Send API and its 7-day window.
The public branch deliberately keeps the comment-anchored conversation: a public
flow is answered on the post, and the contact's next comment resolves back to
that same conversation.
Also make `conversationService.findOrCreate` race-safe. It was a plain
find-then-insert against two partial unique indexes
(`Conversation_contactId_dm_key`, `Conversation_contactId_sourceId_key`), so a
concurrent writer — the message echo webhook opening the same DM — could make it
throw. It now uses `onConflictDoNothing()` and re-reads the winner's row.
Two intended behaviour changes: a flow no longer resumes when an agent has taken
over the DM (`ensureActive` now consults the DM conversation's `botEnabled`),
and the duplicate message rows caused by conversation-scoped echo dedup should
stop, since the outgoing row and its echo now share one conversation.
Fixes #1063
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1063.
The bug
A comment automation with Private reply = Flow enqueued
sendFlowon the comment-anchored conversation (Conversation.sourceId = postId). The flow's first message was delivered, but its state was written there — while the contact's reply arrives on the DM conversation (sourceId IS NULL). The two never meet, so the flow never advances past its first waiting step.Nothing fails: no queue error, no
sendError. The routing simply finds no challenge and falls through toautomatedResponse.Root cause
received-message.ts:974sourceConversationId: commentData.postIdreceived-message.ts:1425incomingContact.sourceConversationId ?? null→ comment yields conversation A (sourceId = postId), a DM yields conversation B (sourceId IS NULL)private-reply.tsflowbranch enqueuedsendFlowwithctx.conversationId— conversation Asend-flow-step.ts:675-676,updateChallengecurrentStep,additionalAttributes.challenge) lands on Aworker.ts:130-140→routing.ts:31-36resolveIncomingTextRoutingreads the challenge off B, finds none, and routes toautomatedResponseinstead ofchallengeThe post anchoring itself is intentional and stays: it lets the flow's first message go out through Meta's comment_id-anchored Send API (7-day comment window) instead of a DM gated by the 24-hour window. That is a delivery concern. The bug is that state rode along with it.
The fix
resolveDirectMessageConversationIdresolves the DM conversation before enqueueing the flow —conversationService.findDMByContact, falling back tofindOrCreate({ sourceId: null })for a contact whose first ever interaction is the comment.commentAnchoris untouched: it travels on the job and still delivers the first message through the comment-anchored API.If the lookup throws, it logs and falls back to
ctx.conversationIdrather than rethrowing — a throw would mark the dispatch failed, skip the dedup row, and let a job retry post the public reply a second time.The public branch deliberately keeps the comment-anchored conversation. A public flow is answered on the post, and the contact's next comment resolves back to that same conversation through
receiveComment. There is a regression test pinning this so the two branches are not "unified" later.Also makes
conversationService.findOrCreaterace-safe. It was a plain find-then-insert against two partial unique indexes (Conversation_contactId_dm_key,Conversation_contactId_sourceId_key), so a concurrent writer — the message echo webhook opening the same DM — could make it throw. It now usesonConflictDoNothing()and re-reads the winner's row, without re-broadcastingconversationCreated.Why this matches the platform
Meta's private-reply docs, for both Messenger and Instagram, say the private reply lands in the recipient's Inbox (or Request folder) — the standard DM thread, not a comment-bound one:
So the continuation happens in the DM thread, which is exactly where the flow's state now lives.
Meta also allows only one private reply per comment. The existing anchor hand-off already honours that — the first message-producing step claims the anchor and clears it (
remainingAnchorinflow.ts:374,anchorAvailableinflow.ts:543-613) — and this change does not touch it.Two intended behaviour changes
ensureActiveconsults the DM conversation'sbotEnabled/botResumeAt, so a flow no longer resumes when an agent has taken over the DM. This is correct and matches a keyword-triggered flow in a DM, but it differs from the old path, where the freshly created comment conversation was alwaysbotEnabled = true.findBySourceId(sourceId, conversationId, …), and theisEchoOfOwnSendfallback scopes toconversation.id), so an outgoing row on A could never dedup against its echo on B — the duplicate copies visible in the issue's evidence. Both now share the DM conversation.One minor trade-off: for a first-time commenter the DM conversation is created at enqueue time rather than when the echo lands, so a flow send that fails outright leaves an empty DM conversation. It sorts last in the inbox (
lastActivityAt IS NULL), and the conversation would have been created a second later anyway on success.Verification
comment-automation.test.ts+read-receipts.test.ts— 57 passed (6 new tests: existing DM, first-interaction create, lookup failure still dispatches and still writes dedup, public branch unchanged)packages/businessfull suite — 1727 passed (3 newfindOrCreaterace tests)pnpm --filter worker check-types,pnpm --filter @chatbotx.io/business check-types— cleanpnpm lint— cleanNo migration.
Production sanity after deploy: comment the keyword on a post with
Private reply = Flowfrom a fresh contact, reply to the DM, and confirm the flow advances —ContactCustomFieldpopulated, tag applied, and the flow state on thesourceId IS NULLrow rather than thesourceId = postIdone.🤖 Generated with Claude Code