Instagram & Messenger DMs
How Instagram and Facebook Messenger DMs and Instagram comments reach the inbox, become leads, and get AI or staff replies, including the identity limits of social chats.
11 min read
Overview
Kagami reads and answers Instagram DMs, Facebook Messenger DMs and Instagram post comments for a brand. One Meta webhook receives all three, stores each message in the same inbox tables as WhatsApp, turns the sender into a lead, and (if the brand's AI agent is on) lets the AI answer. Staff can reply or take over from the same inbox.

The big difference from WhatsApp: Meta gives only a page-scoped id, never a phone number. The AI cannot look up, change or cancel a client's appointments, and cannot read wallet balances, in these chats. See the Identity limits section below.
Related: communications.md (WhatsApp inbox), ai.md, reputation.md, settings.md, ai-whatsapp-agent.md, messaging-delivery.md.
Message flow
| Step | What happens | Code |
|---|---|---|
| 1 | Meta POSTs to /api/webhooks/meta. |
src/app/api/webhooks/meta/route.ts |
| 2 | Signature verified (see below). | verifyMetaSignature in src/lib/messaging/meta-dm.ts |
| 3 | Body flattened to DmEvents by parseDmWebhook. |
meta-dm.ts |
| 4 | Each event runs inside serializeTurns("dm:<entryId>:<senderId>") so one sender's messages are handled in order. |
src/lib/ai/turn-queue.ts |
| 5 | processDmEvent: map entry to brand, resolve client, store message, notify, CAPI lead, AI. |
src/lib/messaging/meta-dm-ingest.ts |
| 6 | routeDmToAi decides whether the AI answers. |
src/lib/messaging/meta-dm-ai.ts |
The handler always answers 200 once the signature passes (a non-200 makes Meta retry the whole delivery). Per-event errors go to captureError with tag meta_webhook.inbound_dm. Bad JSON after a valid signature returns 400.
serializeTurns is an in-process Map, so ordering is per server instance, not across the two production servers. Duplicates are still caught by the unique provider_message_id.
Webhook security
| Item | Value |
|---|---|
| Verify (GET) | hub.mode=subscribe and hub.verify_token equal to env META_WEBHOOK_VERIFY_TOKEN; echoes hub.challenge with 200, else 403. A missing env var always gives 403. |
| Signature header | x-hub-signature-256, format sha256=<hex> |
| Algorithm | HMAC-SHA256 of the raw body keyed with env META_APP_SECRET, constant-time compare (timingSafeEqual) |
| Fails closed | Missing secret, missing header, or length/value mismatch returns 403 Forbidden; nothing is parsed or stored. |
| Failure log | [meta_webhook] rejected: <signature mismatch / no signature header> (META_APP_SECRET not set), plus object, entry ids and field names. Never the body. |
| Why strict | Each DM can trigger a paid AI turn (comment in route.ts). |
| Dropped events | A signed body that yields 0 events logs [meta_webhook] dropped: 0 DM events parsed. |
META_APP_SECRET is shared with the WhatsApp webhook and with the Connect Instagram flow (it also seals the OAuth cookies, meta-connect.ts). Env var values are never shown in the UI.
What the parser accepts
| Source | Accepted | Skipped |
|---|---|---|
object: "page" |
Messenger text DMs | echoes (is_echo), reactions, reads, postbacks, no mid, sender equal to the entry id |
object: "instagram" messaging |
IG text DMs | same as above |
object: "instagram" changes[field=comments] |
comments with at least one letter or digit | our own replies (sender equals entry id, a loop guard), emoji-only comments |
| Attachment-only message | stored as placeholder text "[Attachment received. Open it in the Instagram or Messenger app.]" |
Any other object returns no events. Comment events get mid = igc_<commentId> and the text prefix [Commented on our Instagram post] so staff and the AI know it was public.
24-hour messaging window
Meta allows a free-form reply only within 24h of the customer's last message. DM_REPLY_WINDOW_MS = 24h (meta-dm.ts).
| Path | Behaviour |
|---|---|
| Staff reply in the inbox | sendInboxReplyAction (src/lib/inbox/actions.ts) reads the newest inbound_messages.received_at for the thread (from_phone = "<channel>:<senderId>"). If none or older than 24h, returns OUTSIDE_WINDOW_ERROR and sends nothing: "Meta only allows replies within 24 hours of the customer's last message ... or reach them on WhatsApp." A failed window lookup returns "Could not check the 24-hour reply window: ...". |
| AI reply | No explicit window check: the AI only answers the message that just arrived, so it is always inside the window. |
| Proactive AI messages | None for DMs. The cold-chat follow-up cron (src/app/api/cron/ai-chat-recovery/route.ts) only selects channel = whatsapp. |
| Meta rejects anyway | Graph codes 10 or 551 map to OUTSIDE_WINDOW_ERROR. |
| Instagram comment private reply | Meta allows one private reply per comment, within 7 days (comment in sendMetaDm). The code does not check the 7 days itself; Meta's rejection surfaces as a generic send error. |
Identity limits
Instagram and Messenger senders are known only by a page-scoped id (senderId). No phone, no email, no real name.
Lead ingestion (resolveDmClient)
- Look up
client_channel_idsby(brand_id, channel, external_id = senderId). - If the message text contains an Indian-style mobile number (
extractPhone: optional+91, 10 digits starting 6-9), find the brand's most recently visitedclientsrow whose phone ends with those 10 digits. - If a link exists and a phone match points to a different client, the link is re-pointed to the phone-matched client.
- If no link and no phone match, a new
clientsrow is inserted:display_name = "Instagram user <last 4 of id>"(or "Messenger user ..."),phone = shared number or null,status = active, taggedLead(LEAD_TAGfromsrc/lib/ai/whatsapp-lead.ts). - The link is upserted into
client_channel_ids(unique(brand_id, channel, external_id)). - Any error returns
null: the message is still stored, just unlinked (meta_dm.resolve_client).
Storage (migration 0278_meta_dm_channels.sql): DM threads reuse inbound_messages / outbound_messages. The thread key instagram:<id> / messenger:<id> goes in from_phone / to_phone; the raw id goes in inbound_messages.channel_user_id. client_channel_ids is writable only through the service role (webhook); members can read it. Duplicate deliveries are dropped by upsert on provider_message_id.
Every inbound DM is attached to the brand's oldest location (order by created_at), because DM chats have no store picker. If the brand has no location, location_id is null and the AI stays silent.
What the AI can and cannot do in a social DM
| Capability | Instagram / Messenger | Source |
|---|---|---|
| Answer questions, prices, hours, address | Yes | src/lib/ai/gateway.ts |
| Check availability, propose and book | Allowed, using a phone the model collected in chat | workflows/appointments.ts (book) |
get_client_appointments |
Blocked: not_verified ("I can't look up appointments in this chat") |
workflows/appointments.ts |
| Cancel / reschedule | Blocked: not_verified |
resolveVerifiedClient in workflows/helpers.ts |
| Wallet balance | Blocked: not_verified |
workflows/wallet.ts |
| Greet by name, use client history | No: both are loaded for whatsapp only |
gateway.ts (historyPromise, clientName) |
Interactive buttons (present_choices) |
Removed (text only) | gateway.ts (interactive) |
switch_store |
Removed (WhatsApp only) | gateway.ts |
| Save store preference | Skipped (needs a phone) | saveStorePreference in tools.ts |
resolveVerifiedClient only trusts channel of whatsapp or phone. The AI tells the customer it cannot look this up and offers handoff_to_human.
Even when a DM sender is linked to a CRM client by a shared phone, that link affects only the inbox display name and staff context. It does not unlock the AI's lookup tools.
AI replies
One setting controls the AI across channels: ai_agent_settings.is_enabled for the brand (Settings > AI agent, "Booking agent" switch, ai-agent-editor.tsx). routeDmToAi checks that same row; there is no separate Instagram or Messenger toggle. The editor copy mentions WhatsApp only. When it is off, the DM is stored and staff are notified but the AI sends nothing (the "offline message" is not sent for DMs).
routeDmToAi returns silently (no reply, no alert) when:
| Condition | Note |
|---|---|
No locationId |
no store to ground the agent |
is_enabled is false or no settings row |
|
Chat is handed_off and still inside the pause window |
isHandoffPaused (src/lib/ai/handoff-pause.ts) |
| Pause lookup errored | fails closed, logged meta_dm.pause_lookup |
checkSenderRateLimit is not ok |
per sender key <channel>:<id>: 6/min, 40/hour, 80/day, plus 1,500/day per brand (whatsapp-turn-queue.ts). The WhatsApp "pause" notice is not sent to DMs. |
Turn was held (reply jury) or the reply is empty |
held draft goes to the inbox hold list with an empty phone |
If the Page id or access token is missing it throws "Instagram is not fully connected for this brand: Page id or access token missing in Settings > Social." Any thrown error sends staff the ai_agent_failed alert ("AI assistant could not reply on Instagram ... Please reply to this Instagram chat directly.") linking to /dashboard/inbox.
AI turns use getOrCreateConversation(..., channel, senderId) with no phone, so ai_conversations.client_id and user_identifier stay null. Conversation enum values instagram and messenger were added in 0279_conversation_channel_dm.sql.
Handoff and staff takeover in DMs
| Event | Behaviour |
|---|---|
AI hands off (handoff) |
sendAlert key ai_agent_handoff ("AI assistant handed over a chat", linking to /dashboard/inbox) fires first, then the reply is still sent. The WhatsApp-only escalating handoff alert (openHandoffAlert) is not used for Meta DMs (gateway.ts, channel === "whatsapp" && clientPhone). |
| Staff replies from the inbox | After sending, pauseAfterStaffReply marks the conversation handed_off with reason staff_replied for 2h (STAFF_REPLY_PAUSE_MS). Other handoffs pause 12h (HANDOFF_PAUSE_MS). |
| "Take over" / "Resume AI" buttons | Not available for DM threads. Sending a staff reply pauses the AI for that chat. |
Comment replies (Instagram only)
Comments arrive as entry.changes[field=comments]. For each accepted comment:
- Stored as an inbound message with the
[Commented on our Instagram post]prefix, and a lead resolved like a DM (the commenter id is the sender id). - The AI answers it privately:
sendMetaDmis called withrecipient: { comment_id }(Instagram private reply). The AI-reply path is the same as a DM, so the same toggle, pause and rate limits apply. - After the private reply succeeds, a public reply is posted under the comment:
@<username> Thank you! We've sent you a DM with the detailsplus a speech-balloon emoji (replyToIgComment,POST /<commentId>/replies, 2,200 char cap). The detail goes private so no prices or personal data appear on a public post. - If the answer does not fit one message, only the part that fits is sent plus "Reply to this message and I'll send the rest." (
COMMENT_REPLY_MORE), because Meta allows a single private reply per comment. The customer's reply then opens a normal DM chat.
If the private reply fails, the public reply is not posted (it runs after the send in the same try block) and staff get the ai_agent_failed alert. Comment replies depend on the instagram_manage_comments permission; a missing permission gives "Instagram refused the comment reply: the app is missing the instagram_manage_comments permission."
Comments are only answered when the AI is enabled. Staff cannot send a public comment reply from the inbox.
Reply format
Meta shows Markdown literally, so replies are converted and split (toDmText, splitDmText, SALO-2571).
| Rule | Detail |
|---|---|
| Markdown stripped | **bold** loses markers, [text](url) becomes text: url, # headings lose markers, - / * bullets become • |
| Instagram limit | 1,000 UTF-8 bytes per message (₹ is 3 bytes, an emoji 4) |
| Messenger limit | 2,000 characters |
| Split | Long text is split at line breaks, then spaces, then graphemes (never inside an emoji). Nothing is dropped. Parts are sent in order. |
| Partial failure | If part 2+ fails the error is "Only N of M message parts were delivered: ..." |
| Stored copy | outbound_messages.body stores the exact text the customer received |
| Send API | Graph v21.0 POST /<pageId>/messages, messaging_type: RESPONSE, 10s timeout, Bearer page token. Instagram sends also go through the linked Page id. |
Outbound rows are written with channel instagram or messenger, message_type = custom, status = sent. AI replies leave sent_by null; staff replies set it. The inbox shows an "Instagram" or "Messenger" badge on the thread.
Connecting channels
Owners and brand managers (super_admin, org_owner, brand_manager; INSTAGRAM_CONNECT_ROLES) use Settings > Social profiles > Instagram & Facebook (/dashboard/settings/social).
| Step | Detail |
|---|---|
| Start | "Connect Instagram" goes to /api/integrations/meta/connect, which sets a sealed, user-bound state cookie (AES-256-GCM, 10 min) and redirects to Meta's login. |
| Scopes | pages_show_list, pages_read_engagement, pages_manage_metadata, pages_messaging, instagram_basic, instagram_manage_messages, instagram_manage_comments |
| Callback | /api/integrations/meta/callback checks state, exchanges the code for a long-lived user token, checks every scope was granted, lists up to 100 Pages. Only Pages with a linked Instagram Business account qualify. |
| Several Pages | The owner picks one (selectInstagramPageAction); names only reach the browser. |
| Save | connectPage writes social_settings.fb_page_id, ig_account_id, fb_page_access_token (one row per brand), then subscribes the Page to the app webhook with fields messages,messaging_postbacks,feed. |
| Disconnect | Unsubscribes the Page (best effort, a warning is shown on failure) and clears the three columns. |
| Manual option | The Social settings form still has fields for the Facebook Page id, an access token and the Instagram account id (used for post publishing and also matched by the webhook). A saved token is never sent back to the browser. |
| Env | NEXT_PUBLIC_META_APP_ID, META_APP_SECRET, META_WEBHOOK_VERIFY_TOKEN, optional NEXT_PUBLIC_APP_URL |
Webhook routing: Messenger events carry the Page id (matched to social_settings.fb_page_id), Instagram events carry the Instagram business account id (matched to ig_account_id). An id with no matching brand logs meta_dm.unmapped_entry and the message is dropped. The Page token is stored as plain text in social_settings (no encryption in the code or migration); RLS allows org members, writes go through the service role.
Page tokens derived from the long-lived user token do not expire (comment in meta-connect.ts). Error code 190 shows "access token expired or revoked. Reconnect it in Settings > Social."
Meta lead event
The first message from a new sender (no earlier inbound_messages for that brand, channel and sender) sends a CAPI LeadSubmitted event, action_source = business_messaging, with page-scoped ids instead of hashed PII (sendMetaDmLead in src/lib/integrations/meta-capi.ts). It is a no-op when the brand has no CAPI credentials. See marketing.md.
Troubleshooting / where to look
| Symptom | Check |
|---|---|
| No DMs arrive | Server log for [meta_webhook] rejected (secret or signature) or dropped: 0 DM events parsed; meta_dm.unmapped_entry means no social_settings row has that id; Settings > Social shows "subscribe_failed" or a token warning. |
| Webhook setup fails in Meta | META_WEBHOOK_VERIFY_TOKEN must equal the string typed in the Meta app. |
| AI does not answer | Brand's Booking agent switch; brand has a location; chat is not handed_off; rate limit counters (rate_limit_hit keys wa-ai:...). |
| Staff reply refused | Message is older than 24h, or the Page is not connected. |
| "Advanced Access" error | Meta has not approved the app for Instagram messaging, so replies only reach people with a role on the app (ADVANCED_ACCESS_ERROR). |
| Alert "AI assistant could not reply" | Alert body carries the real cause; also meta_dm.ai_turn in error monitoring. |
| Duplicate or missing lead | client_channel_ids for the sender; clients tagged Lead. |
Tests: src/app/api/webhooks/meta/route.test.ts, src/lib/messaging/meta-dm.test.ts, meta-dm-ingest.test.ts, src/lib/integrations/meta-connect.test.ts.