Skip to content

fix(worker): run comment-triggered private flows on the DM conversation - #1105

Merged
sung17 merged 1 commit into
mainfrom
fix/comment-automation-private-flow-dm-conversation
Sep 6, 2026
Merged

sung17 merged 1 commit into
mainfrom
fix/comment-automation-private-flow-dm-conversation

Conversation

@sung17

@sung17 sung17 commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

Fixes #1063.

The bug

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 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 to automatedResponse.

Root cause

# Where What happens
1 received-message.ts:974 A comment anchors the contact to the post: sourceConversationId: commentData.postId
2 received-message.ts:1425 incomingContact.sourceConversationId ?? null → comment yields conversation A (sourceId = postId), a DM yields conversation B (sourceId IS NULL)
3 private-reply.ts The flow branch enqueued sendFlow with ctx.conversationId — conversation A
4 send-flow-step.ts:675-676, updateChallenge Flow state (currentStep, additionalAttributes.challenge) lands on A
5 worker.ts:130-140 → routing.ts:31-36 The reply arrives on B; resolveIncomingTextRouting reads the challenge off B, finds none, and routes to automatedResponse instead of challenge

The 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

resolveDirectMessageConversationId resolves the DM conversation before enqueueing the flow — conversationService.findDMByContact, falling back to findOrCreate({ sourceId: null }) for a contact whose first ever interaction is the comment. commentAnchor is 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.conversationId rather 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.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, without re-broadcasting conversationCreated.

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:

Only when a person responds to the private message can you continue the conversation within the 24-hour messaging window.

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 (remainingAnchor in flow.ts:374, anchorAvailable in flow.ts:543-613) — and this change does not touch it.

Two intended behaviour changes

  1. Human takeover now applies. ensureActive consults the DM conversation's botEnabled / 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 always botEnabled = true.
  2. Duplicate message rows should stop. Echo dedup is conversation-scoped (findBySourceId(sourceId, conversationId, …), and the isEchoOfOwnSend fallback scopes to conversation.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/business full suite — 1727 passed (3 new findOrCreate race tests)
  • pnpm --filter worker check-types, pnpm --filter @chatbotx.io/business check-types — clean
  • pnpm lint — clean

No migration.

Production sanity after deploy: comment the keyword on a post with Private reply = Flow from a fresh contact, reply to the DM, and confirm the flow advances — ContactCustomField populated, tag applied, and the flow state on the sourceId IS NULL row rather than the sourceId = postId one.

🤖 Generated with Claude Code

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

1 participant