From b245181740be1b130d226d44a4938f2a281c8ae7 Mon Sep 17 00:00:00 2001 From: Patrick Ng Date: Thu, 3 Dec 2026 22:28:08 +0000 Subject: [PATCH] Instagram step 3: replies from OpenChat reach the customer (ADR-0028) Same content as #213, which was merged into its stacked base branch by mistake instead of main. Signed-off-by: yatping Co-Authored-By: Claude Opus 5.5 --- apps/dashboard/src/i18n/de.ts | 9 +- apps/dashboard/src/i18n/en.ts | 9 +- apps/dashboard/src/i18n/es.ts | 9 +- apps/dashboard/src/i18n/fr.ts | 9 +- apps/dashboard/src/i18n/it.ts | 9 +- apps/dashboard/src/i18n/ja.ts | 9 +- apps/dashboard/src/i18n/ko.ts | 9 +- apps/dashboard/src/i18n/nl.ts | 9 +- apps/dashboard/src/i18n/pt.ts | 9 +- apps/dashboard/src/i18n/zh-hans.ts | 9 +- apps/dashboard/src/i18n/zh-hant.ts | 9 +- apps/dashboard/src/inbox/inbox-panel.tsx | 54 ++++---- docs/architecture/background-jobs.md | 2 +- docs/guide/admin.md | 2 +- docs/guide/inbox.md | 4 +- docs/known-issues.md | 3 +- packages/api-contracts/generated/openapi.json | 4 +- packages/api-contracts/src/routes.ts | 9 +- packages/core/src/instagram-inbound.ts | 42 +++++- packages/core/src/messaging.ts | 9 +- packages/core/src/messenger-inbound.ts | 5 +- packages/core/src/messenger-outbound.ts | 23 ++-- packages/core/src/whatsapp-outbound.ts | 27 +++- .../src/internal/message-statements.ts | 4 +- packages/database/src/messenger-outbound.ts | 21 +-- packages/database/src/repositories.ts | 2 +- services/api/src/dispatch.ts | 9 +- services/api/test/api.test.ts | 2 +- services/api/test/messenger.test.ts | 122 ++++++++++++++++-- 29 files changed, 350 insertions(+), 93 deletions(-) diff --git a/apps/dashboard/src/i18n/de.ts b/apps/dashboard/src/i18n/de.ts index e493123..a1128e6 100644 --- a/apps/dashboard/src/i18n/de.ts +++ b/apps/dashboard/src/i18n/de.ts @@ -714,5 +714,12 @@ export const de: Messages = { instagramEphemeral: 'Hat ein einmal anzeigbares Foto oder Video gesendet. Es ist nur in Instagram zu sehen.', instagramUnsent: 'Hat eine Nachricht in Instagram zurückgezogen', instagramUnsupported: 'Hat etwas gesendet, das OpenChat nicht anzeigen kann. Sie können es in Instagram sehen.', - instagramRepliesUnavailable: 'Antworten auf Instagram können noch nicht aus OpenChat gesendet werden. Antworten Sie in Instagram oder fügen Sie eine interne Notiz hinzu.', + sentFromInstagram: 'Aus Instagram gesendet', + instagramWindowOpen: 'Antworten erreichen die Person auf Instagram bis {time}.', + instagramWindowClosed: 'Seit der letzten Nachricht sind über 24 Stunden vergangen, daher erlaubt Instagram keine Antwort, bis die Person wieder schreibt. Sie können eine interne Notiz hinzufügen.', + instagramEchoUnsupported: 'Eine Datei oder anderer Inhalt wurde aus Instagram gesendet ({kind}). Es ist in Instagram zu sehen.', + instagramErrorUnavailable: 'Instagram war nicht erreichbar', + instagramErrorUndeliverable: 'die Person ist auf Instagram nicht erreichbar', + instagramErrorMeta: 'Instagram hat sie abgelehnt (Fehler {code})', + instagramErrorNotConnected: 'Instagram ist für diese Website ausgeschaltet oder ihre Facebook-Seite ist getrennt', }; diff --git a/apps/dashboard/src/i18n/en.ts b/apps/dashboard/src/i18n/en.ts index 586cf47..fd725a8 100644 --- a/apps/dashboard/src/i18n/en.ts +++ b/apps/dashboard/src/i18n/en.ts @@ -727,7 +727,14 @@ export const en = { instagramEphemeral: 'Sent a view-once photo or video. You can see it only in Instagram.', instagramUnsent: 'Unsent a message in Instagram', instagramUnsupported: 'Sent something OpenChat cannot show. You can see it in Instagram.', - instagramRepliesUnavailable: 'Replies on Instagram cannot be sent from OpenChat yet. Reply in Instagram, or add an internal note.', + sentFromInstagram: 'Sent from Instagram', + instagramWindowOpen: 'Replies reach the customer on Instagram until {time}.', + instagramWindowClosed: 'More than 24 hours have passed since the customer last wrote, so Instagram allows no reply until they write again. You can add an internal note.', + instagramEchoUnsupported: 'Sent a file or other content from Instagram ({kind}). You can see it in Instagram.', + instagramErrorUnavailable: 'Instagram could not be reached', + instagramErrorUndeliverable: 'the customer cannot be reached on Instagram', + instagramErrorMeta: 'Instagram refused it (error {code})', + instagramErrorNotConnected: 'Instagram is off for this website, or its Facebook Page is disconnected', }; export type Messages = Record; diff --git a/apps/dashboard/src/i18n/es.ts b/apps/dashboard/src/i18n/es.ts index c061fbc..5bb280e 100644 --- a/apps/dashboard/src/i18n/es.ts +++ b/apps/dashboard/src/i18n/es.ts @@ -714,5 +714,12 @@ export const es: Messages = { instagramEphemeral: 'Envió una foto o un vídeo de visualización única. Solo puedes verlo en Instagram.', instagramUnsent: 'Anuló el envío de un mensaje en Instagram', instagramUnsupported: 'Envió algo que OpenChat no puede mostrar. Puedes verlo en Instagram.', - instagramRepliesUnavailable: 'Las respuestas en Instagram aún no se pueden enviar desde OpenChat. Responde en Instagram o añade una nota interna.', + sentFromInstagram: 'Enviado desde Instagram', + instagramWindowOpen: 'Las respuestas llegan al cliente por Instagram hasta las {time}.', + instagramWindowClosed: 'Han pasado más de 24 horas desde el último mensaje del cliente, así que Instagram no permite responder hasta que vuelva a escribir. Puedes añadir una nota interna.', + instagramEchoUnsupported: 'Se envió un archivo u otro contenido desde Instagram ({kind}). Puedes verlo en Instagram.', + instagramErrorUnavailable: 'no se pudo contactar con Instagram', + instagramErrorUndeliverable: 'no se puede contactar con el cliente en Instagram', + instagramErrorMeta: 'Instagram lo rechazó (error {code})', + instagramErrorNotConnected: 'Instagram está desactivado para este sitio web o su página de Facebook está desconectada', }; diff --git a/apps/dashboard/src/i18n/fr.ts b/apps/dashboard/src/i18n/fr.ts index 2642e6e..62f4f7c 100644 --- a/apps/dashboard/src/i18n/fr.ts +++ b/apps/dashboard/src/i18n/fr.ts @@ -714,5 +714,12 @@ export const fr: Messages = { instagramEphemeral: 'A envoyé une photo ou une vidéo éphémère. Elle n’est visible que dans Instagram.', instagramUnsent: 'A annulé l’envoi d’un message dans Instagram', instagramUnsupported: 'A envoyé quelque chose qu’OpenChat ne peut pas afficher. Vous pouvez le voir dans Instagram.', - instagramRepliesUnavailable: 'Les réponses sur Instagram ne peuvent pas encore être envoyées depuis OpenChat. Répondez dans Instagram ou ajoutez une note interne.', + sentFromInstagram: 'Envoyé depuis Instagram', + instagramWindowOpen: 'Les réponses parviennent au client sur Instagram jusqu’à {time}.', + instagramWindowClosed: 'Plus de 24 heures se sont écoulées depuis le dernier message du client : Instagram n’autorise aucune réponse avant qu’il écrive à nouveau. Vous pouvez ajouter une note interne.', + instagramEchoUnsupported: 'Un fichier ou un autre contenu a été envoyé depuis Instagram ({kind}). Vous pouvez le voir dans Instagram.', + instagramErrorUnavailable: 'Instagram était injoignable', + instagramErrorUndeliverable: 'le client est injoignable sur Instagram', + instagramErrorMeta: 'Instagram l’a refusée (erreur {code})', + instagramErrorNotConnected: 'Instagram est désactivé pour ce site web, ou sa page Facebook est déconnectée', }; diff --git a/apps/dashboard/src/i18n/it.ts b/apps/dashboard/src/i18n/it.ts index 2fe3a3f..13c7d49 100644 --- a/apps/dashboard/src/i18n/it.ts +++ b/apps/dashboard/src/i18n/it.ts @@ -714,5 +714,12 @@ export const it: Messages = { instagramEphemeral: 'Ha inviato una foto o un video visualizzabile una sola volta. Puoi vederlo solo in Instagram.', instagramUnsent: 'Ha annullato l’invio di un messaggio in Instagram', instagramUnsupported: 'Ha inviato qualcosa che OpenChat non può mostrare. Puoi vederlo in Instagram.', - instagramRepliesUnavailable: 'Le risposte su Instagram non possono ancora essere inviate da OpenChat. Rispondi in Instagram o aggiungi una nota interna.', + sentFromInstagram: 'Inviato da Instagram', + instagramWindowOpen: 'Le risposte arrivano al cliente su Instagram fino alle {time}.', + instagramWindowClosed: 'Sono passate più di 24 ore dall’ultimo messaggio del cliente, quindi Instagram non consente risposte finché non scrive di nuovo. Puoi aggiungere una nota interna.', + instagramEchoUnsupported: 'È stato inviato un file o un altro contenuto da Instagram ({kind}). Puoi vederlo in Instagram.', + instagramErrorUnavailable: 'Instagram non era raggiungibile', + instagramErrorUndeliverable: 'il cliente non è raggiungibile su Instagram', + instagramErrorMeta: 'Instagram l’ha rifiutata (errore {code})', + instagramErrorNotConnected: 'Instagram è disattivato per questo sito web, oppure la sua pagina Facebook è scollegata', }; diff --git a/apps/dashboard/src/i18n/ja.ts b/apps/dashboard/src/i18n/ja.ts index 2a7dccf..4982133 100644 --- a/apps/dashboard/src/i18n/ja.ts +++ b/apps/dashboard/src/i18n/ja.ts @@ -714,5 +714,12 @@ export const ja: Messages = { instagramEphemeral: '1回だけ表示できる写真または動画を送信しました。Instagram でのみ確認できます。', instagramUnsent: 'Instagram でメッセージの送信を取り消しました', instagramUnsupported: 'OpenChat で表示できないものを送信しました。Instagram で確認できます。', - instagramRepliesUnavailable: 'Instagram への返信はまだ OpenChat から送信できません。Instagram で返信するか、内部メモを追加してください。', + sentFromInstagram: 'Instagram から送信', + instagramWindowOpen: '{time}まで、返信はInstagramでお客様に届きます。', + instagramWindowClosed: 'お客様の最後のメッセージから24時間以上が経過したため、お客様が再度メッセージを送るまでInstagramでは返信できません。社内メモは追加できます。', + instagramEchoUnsupported: 'Instagram からファイルなどが送信されました({kind})。Instagram で確認できます。', + instagramErrorUnavailable: 'Instagramに接続できませんでした', + instagramErrorUndeliverable: 'お客様に Instagram で連絡できません', + instagramErrorMeta: 'Instagram に拒否されました(エラー {code})', + instagramErrorNotConnected: 'このウェブサイトでは Instagram がオフになっているか、Facebook ページの接続が解除されています', }; diff --git a/apps/dashboard/src/i18n/ko.ts b/apps/dashboard/src/i18n/ko.ts index 0cbf65a..b2c97ca 100644 --- a/apps/dashboard/src/i18n/ko.ts +++ b/apps/dashboard/src/i18n/ko.ts @@ -714,5 +714,12 @@ export const ko: Messages = { instagramEphemeral: '한 번만 볼 수 있는 사진 또는 동영상을 보냈습니다. Instagram에서만 볼 수 있습니다.', instagramUnsent: 'Instagram에서 메시지 전송을 취소했습니다', instagramUnsupported: 'OpenChat에서 표시할 수 없는 것을 보냈습니다. Instagram에서 볼 수 있습니다.', - instagramRepliesUnavailable: 'Instagram 답장은 아직 OpenChat에서 보낼 수 없습니다. Instagram에서 답장하거나 내부 메모를 추가하세요.', + sentFromInstagram: 'Instagram에서 보냄', + instagramWindowOpen: '{time}까지 답장이 Instagram로 고객에게 전달됩니다.', + instagramWindowClosed: '고객의 마지막 메시지 후 24시간이 지나 고객이 다시 메시지를 보낼 때까지 Instagram에서 답장할 수 없습니다. 내부 메모는 추가할 수 있습니다.', + instagramEchoUnsupported: 'Instagram에서 파일 등을 보냈습니다({kind}). Instagram에서 확인할 수 있습니다.', + instagramErrorUnavailable: 'Instagram에 연결할 수 없었습니다', + instagramErrorUndeliverable: 'Instagram에서 고객에게 연락할 수 없습니다', + instagramErrorMeta: 'Instagram가 거부했습니다(오류 {code})', + instagramErrorNotConnected: '이 웹사이트에서 Instagram이 꺼져 있거나 Facebook 페이지 연결이 끊어졌습니다', }; diff --git a/apps/dashboard/src/i18n/nl.ts b/apps/dashboard/src/i18n/nl.ts index ecb73e0..7cd9ea8 100644 --- a/apps/dashboard/src/i18n/nl.ts +++ b/apps/dashboard/src/i18n/nl.ts @@ -714,5 +714,12 @@ export const nl: Messages = { instagramEphemeral: 'Heeft een foto of video gestuurd die één keer te bekijken is. Die is alleen in Instagram te zien.', instagramUnsent: 'Heeft een bericht in Instagram ingetrokken', instagramUnsupported: 'Heeft iets gestuurd dat OpenChat niet kan tonen. Je kunt het in Instagram zien.', - instagramRepliesUnavailable: 'Antwoorden op Instagram kunnen nog niet vanuit OpenChat worden verstuurd. Antwoord in Instagram of voeg een interne notitie toe.', + sentFromInstagram: 'Verstuurd vanuit Instagram', + instagramWindowOpen: 'Antwoorden bereiken de klant via Instagram tot {time}.', + instagramWindowClosed: 'Er zijn meer dan 24 uur verstreken sinds het laatste bericht van de klant, dus Instagram staat geen antwoord toe tot de klant opnieuw schrijft. Je kunt een interne notitie toevoegen.', + instagramEchoUnsupported: 'Er is een bestand of andere inhoud verstuurd vanuit Instagram ({kind}). Je kunt het in Instagram zien.', + instagramErrorUnavailable: 'Instagram was niet bereikbaar', + instagramErrorUndeliverable: 'de klant is niet bereikbaar via Instagram', + instagramErrorMeta: 'Instagram heeft het geweigerd (fout {code})', + instagramErrorNotConnected: 'Instagram staat uit voor deze website, of de Facebook-pagina is losgekoppeld', }; diff --git a/apps/dashboard/src/i18n/pt.ts b/apps/dashboard/src/i18n/pt.ts index 12e39ad..b41912c 100644 --- a/apps/dashboard/src/i18n/pt.ts +++ b/apps/dashboard/src/i18n/pt.ts @@ -714,5 +714,12 @@ export const pt: Messages = { instagramEphemeral: 'Enviou uma foto ou um vídeo de visualização única. Só pode vê-lo no Instagram.', instagramUnsent: 'Anulou o envio de uma mensagem no Instagram', instagramUnsupported: 'Enviou algo que o OpenChat não consegue mostrar. Pode vê-lo no Instagram.', - instagramRepliesUnavailable: 'As respostas no Instagram ainda não podem ser enviadas a partir do OpenChat. Responda no Instagram ou adicione uma nota interna.', + sentFromInstagram: 'Enviado pelo Instagram', + instagramWindowOpen: 'As respostas chegam ao cliente pelo Instagram até {time}.', + instagramWindowClosed: 'Passaram-se mais de 24 horas desde a última mensagem do cliente, então o Instagram não permite resposta até que ele escreva de novo. Você pode adicionar uma nota interna.', + instagramEchoUnsupported: 'Foi enviado um arquivo ou outro conteúdo pelo Instagram ({kind}). Você pode ver no Instagram.', + instagramErrorUnavailable: 'não foi possível contatar o Instagram', + instagramErrorUndeliverable: 'não é possível contatar o cliente pelo Instagram', + instagramErrorMeta: 'O Instagram recusou (erro {code})', + instagramErrorNotConnected: 'O Instagram está desativado para este website ou a respetiva Página do Facebook está desligada', }; diff --git a/apps/dashboard/src/i18n/zh-hans.ts b/apps/dashboard/src/i18n/zh-hans.ts index 86d7b53..f19841b 100644 --- a/apps/dashboard/src/i18n/zh-hans.ts +++ b/apps/dashboard/src/i18n/zh-hans.ts @@ -714,5 +714,12 @@ export const zhHans: Messages = { instagramEphemeral: '发送了阅后即焚的照片或视频,只能在 Instagram 中查看。', instagramUnsent: '在 Instagram 中撤回了一条消息', instagramUnsupported: '发送了 OpenChat 无法显示的内容。你可以在 Instagram 中查看。', - instagramRepliesUnavailable: '暂时还不能从 OpenChat 回复 Instagram 消息。请在 Instagram 中回复,或添加内部备注。', + sentFromInstagram: '从 Instagram 发送', + instagramWindowOpen: '在 {time} 之前,回复会通过 Instagram 送达客户。', + instagramWindowClosed: '距客户上一条消息已超过 24 小时,在客户再次发消息之前,Instagram 不允许回复。你可以添加内部备注。', + instagramEchoUnsupported: '从 Instagram 发送了文件或其他内容({kind})。你可以在 Instagram 中查看。', + instagramErrorUnavailable: '无法连接 Instagram', + instagramErrorUndeliverable: '无法通过 Instagram 联系到客户', + instagramErrorMeta: 'Instagram 拒绝了它(错误 {code})', + instagramErrorNotConnected: '此网站的 Instagram 已关闭,或其 Facebook 主页已断开连接', }; diff --git a/apps/dashboard/src/i18n/zh-hant.ts b/apps/dashboard/src/i18n/zh-hant.ts index 6b98b22..2f10c63 100644 --- a/apps/dashboard/src/i18n/zh-hant.ts +++ b/apps/dashboard/src/i18n/zh-hant.ts @@ -714,5 +714,12 @@ export const zhHant: Messages = { instagramEphemeral: '傳送了只能觀看一次的相片或影片,只能在 Instagram 中查看。', instagramUnsent: '在 Instagram 中收回了一則訊息', instagramUnsupported: '傳送了 OpenChat 無法顯示的內容。你可以在 Instagram 中查看。', - instagramRepliesUnavailable: '暫時還不能從 OpenChat 回覆 Instagram 訊息。請在 Instagram 中回覆,或新增內部備註。', + sentFromInstagram: '從 Instagram 傳送', + instagramWindowOpen: '在 {time} 之前,回覆會透過 Instagram 送達客戶。', + instagramWindowClosed: '距客戶上一則訊息已超過 24 小時,在客戶再次傳訊之前,Instagram 不允許回覆。你可以新增內部備註。', + instagramEchoUnsupported: '從 Instagram 傳送了檔案或其他內容({kind})。你可以在 Instagram 中查看。', + instagramErrorUnavailable: '無法連線至 Instagram', + instagramErrorUndeliverable: '無法透過 Instagram 聯絡到客戶', + instagramErrorMeta: 'Instagram 拒絕了它(錯誤 {code})', + instagramErrorNotConnected: '此網站的 Instagram 已關閉,或其 Facebook 粉絲專頁已中斷連線', }; diff --git a/apps/dashboard/src/inbox/inbox-panel.tsx b/apps/dashboard/src/inbox/inbox-panel.tsx index 864ca06..37b7de3 100644 --- a/apps/dashboard/src/inbox/inbox-panel.tsx +++ b/apps/dashboard/src/inbox/inbox-panel.tsx @@ -502,7 +502,7 @@ function MessageBubble({ workspaceId, message, translation, instagram = false }: // A reply typed in Meta's own inbox (ADR-0027) is the team's too, though no member wrote it here. const echo = message.messenger?.echo === true; const fromTeam = message.sender.type === 'member' || ai || echo; - const sender = ai ? shown : echo ? t('sentFromMessenger') : message.sender.type === 'visitor' ? t('visitor') : message.sender.type === 'system' ? t('system') : message.sender.removed ? t('removedPerson', { name: shown }) : shown; + const sender = ai ? shown : echo ? t(instagram ? 'sentFromInstagram' : 'sentFromMessenger') : message.sender.type === 'visitor' ? t('visitor') : message.sender.type === 'system' ? t('system') : message.sender.removed ? t('removedPerson', { name: shown }) : shown; const look = note ? 'border border-amber-300 bg-amber-50 text-amber-950 dark:border-amber-700 dark:bg-amber-950 dark:text-amber-100' : ai @@ -528,7 +528,7 @@ function MessageBubble({ workspaceId, message, translation, instagram = false }: {message.whatsapp && } {message.messenger && (instagram ? : )} {message.whatsapp?.delivery && } - {message.messenger?.delivery && } + {message.messenger?.delivery && } ); @@ -582,11 +582,13 @@ function InstagramNote({ state }: { state: NonNullable }) ? t('instagramMediaPending') : state.media === 'failed' ? t('instagramMediaFailed') - : kind && kind in INSTAGRAM_KINDS - ? t(INSTAGRAM_KINDS[kind as keyof typeof INSTAGRAM_KINDS]) - : kind - ? t('instagramUnsupported') - : null; + : kind && state.echo + ? t('instagramEchoUnsupported', { kind }) + : kind && kind in INSTAGRAM_KINDS + ? t(INSTAGRAM_KINDS[kind as keyof typeof INSTAGRAM_KINDS]) + : kind + ? t('instagramUnsupported') + : null; return text ?

{text}

: null; } @@ -602,18 +604,18 @@ function whatsappFailure(error: NonNullable['error']): stri return t('whatsappErrorMeta', { code: String(error.code ?? '?') }); } -/** The same for Messenger. 551: the person cannot be reached; 190: the Page token is no longer valid. */ -function messengerFailure(error: NonNullable['error']): string { - if (!error || error.reason === 'unavailable') return t('messengerErrorUnavailable'); +/** The same for Messenger, and Instagram (ADR-0028). 551: the person cannot be reached; 190: the Page token is no longer valid. */ +function messengerFailure(error: NonNullable['error'], instagram: boolean): string { + if (!error || error.reason === 'unavailable') return t(instagram ? 'instagramErrorUnavailable' : 'messengerErrorUnavailable'); if (error.reason === 'window_closed') return t('whatsappErrorWindow'); - if (error.reason === 'not_connected') return t('messengerErrorNotConnected'); + if (error.reason === 'not_connected') return t(instagram ? 'instagramErrorNotConnected' : 'messengerErrorNotConnected'); if (error.code === 190) return t('messengerErrorToken'); - if (error.code === 551) return t('messengerErrorUndeliverable'); - return t('messengerErrorMeta', { code: String(error.code ?? '?') }); + if (error.code === 551) return t(instagram ? 'instagramErrorUndeliverable' : 'messengerErrorUndeliverable'); + return t(instagram ? 'instagramErrorMeta' : 'messengerErrorMeta', { code: String(error.code ?? '?') }); } /** A reply on WhatsApp (ADR-0026) or Messenger (ADR-0027): Meta's status for it, or why it failed, with Try again. */ -function ReplyDelivery({ workspaceId, message, channel }: { workspaceId: string; message: Message; channel: 'whatsapp' | 'messenger' }) { +function ReplyDelivery({ workspaceId, message, channel, instagram = false }: { workspaceId: string; message: Message; channel: 'whatsapp' | 'messenger'; instagram?: boolean }) { const client = useQueryClient(); const retry = useMutation({ mutationFn: () => (channel === 'whatsapp' ? api.retryWhatsAppMessage : api.retryMessengerMessage)(workspaceId, message.conversationId, message.id), @@ -624,7 +626,7 @@ function ReplyDelivery({ workspaceId, message, channel }: { workspaceId: string; const delivery = message[channel]?.delivery; if (!delivery) return null; if (delivery !== 'failed') return

{t(DELIVERY_TEXT[delivery])}

; - const reason = channel === 'whatsapp' ? whatsappFailure(message.whatsapp?.error) : messengerFailure(message.messenger?.error); + const reason = channel === 'whatsapp' ? whatsappFailure(message.whatsapp?.error) : messengerFailure(message.messenger?.error, instagram); return (

{t('whatsappNotDelivered', { reason })}

@@ -634,6 +636,13 @@ function ReplyDelivery({ workspaceId, message, channel }: { workspaceId: string; ); } +/** What the composer says about Meta's 24-hour window, by channel. */ +const WINDOW_TEXT = { + whatsapp: { open: 'whatsappWindowOpen', closed: 'whatsappWindowClosed' }, + messenger: { open: 'messengerWindowOpen', closed: 'messengerWindowClosed' }, + instagram: { open: 'instagramWindowOpen', closed: 'instagramWindowClosed' }, +} as const; + /** A reply that could not be translated is not sent (ADR-0024): the member chooses what happens. */ const TRANSLATION_REFUSALS = new Set(['translation_failed', 'translation_limit', 'translation_unavailable']); @@ -702,7 +711,7 @@ function Composer(props: { workspaceId: string; conversationId: string; drafts: }, // Meta's window closed while the member wrote: the conversation says so, and the composer follows. onError: (error) => { - if (error instanceof ApiError && (error.code === 'whatsapp_window_closed' || error.code === 'messenger_window_closed')) void client.invalidateQueries({ queryKey: detailKey(workspaceId, conversationId) }); + if (error instanceof ApiError && (error.code === 'whatsapp_window_closed' || error.code === 'messenger_window_closed' || error.code === 'instagram_window_closed')) void client.invalidateQueries({ queryKey: detailKey(workspaceId, conversationId) }); }, }); const submit = (untranslated = false) => { @@ -727,13 +736,11 @@ function Composer(props: { workspaceId: string; conversationId: string; drafts:
- {replyWindow && ( + {replyWindow && channel && (

- {channel === 'instagram' - ? t('instagramRepliesUnavailable') - : replyWindow.open && replyWindow.until - ? t(channel === 'messenger' ? 'messengerWindowOpen' : 'whatsappWindowOpen', { time: replyWindow.until.toLocaleString(intlLocale(), { weekday: 'short', hour: '2-digit', minute: '2-digit' }) }) - : t(channel === 'messenger' ? 'messengerWindowClosed' : 'whatsappWindowClosed')} + {replyWindow.open && replyWindow.until + ? t(WINDOW_TEXT[channel].open, { time: replyWindow.until.toLocaleString(intlLocale(), { weekday: 'short', hour: '2-digit', minute: '2-digit' }) }) + : t(WINDOW_TEXT[channel].closed)}

)} {saved !== null && ( @@ -1130,8 +1137,7 @@ function Thread(props: { workspaceId: string; conversationId: string; members: M : conversation.data?.channel === 'messenger' ? { channel: 'messenger', endsAt: conversation.data.messengerWindowEndsAt ?? null } : conversation.data?.channel === 'instagram' - ? // Replies on Instagram come in ADR-0028 step 3: until then, notes only. - { channel: 'instagram', endsAt: null } + ? { channel: 'instagram', endsAt: conversation.data.messengerWindowEndsAt ?? null } : undefined } /> diff --git a/docs/architecture/background-jobs.md b/docs/architecture/background-jobs.md index d3d5199..430480e 100644 --- a/docs/architecture/background-jobs.md +++ b/docs/architecture/background-jobs.md @@ -205,7 +205,7 @@ The job asks the Graph API for the file's link, which lasts five minutes, and do ## Messenger's files and names -A Messenger message ([ADR-0027](decisions/0027-messenger-channel.md), step 2) carries its file as a link on Meta's CDN, signed by Meta. The webhook stores the message at once, with the link under `messenger.media` in its metadata, status `pending`, one message per file, and queues **`messenger.media`** with the message ID only. The job downloads the link with no token, from Meta's hosts only (`fbcdn.net`, `fbsbx.com`, `facebook.com`, `cdninstagram.com`), and keeps the file or marks it `failed` as for WhatsApp; the link itself never leaves the server. A customer's first message also queues **`messenger.profile`** with the identity's ID, which asks the Graph API for their first and last name with the Page token and names the contact if it has no name yet. Meta refusing is not retried. Instagram direct messages ([ADR-0028](decisions/0028-instagram-channel.md)) use the same two jobs: files come from Instagram's CDN too (`cdninstagram.com`), and the profile asks for `name` and `username`, naming the contact with the name, else `@username`. +A Messenger message ([ADR-0027](decisions/0027-messenger-channel.md), step 2) carries its file as a link on Meta's CDN, signed by Meta. The webhook stores the message at once, with the link under `messenger.media` in its metadata, status `pending`, one message per file, and queues **`messenger.media`** with the message ID only. The job downloads the link with no token, from Meta's hosts only (`fbcdn.net`, `fbsbx.com`, `facebook.com`, `cdninstagram.com`), and keeps the file or marks it `failed` as for WhatsApp; the link itself never leaves the server. A customer's first message also queues **`messenger.profile`** with the identity's ID, which asks the Graph API for their first and last name with the Page token and names the contact if it has no name yet. Meta refusing is not retried. Instagram direct messages ([ADR-0028](decisions/0028-instagram-channel.md)) use the same two jobs: files come from Instagram's CDN too (`cdninstagram.com`), and the profile asks for `name` and `username`, naming the contact with the name, else `@username`. An Instagram reply goes by `messenger.send` too, to the customer's Instagram-scoped ID with the Page's token, in parts of at most 1,000 bytes of UTF-8. Instagram sends reads, each naming one message, which mark everything sent before the read's time as read, and no deliveries. ## WhatsApp replies diff --git a/docs/guide/admin.md b/docs/guide/admin.md index 34aa0b7..8db9bbd 100644 --- a/docs/guide/admin.md +++ b/docs/guide/admin.md @@ -99,7 +99,7 @@ A Page can be connected to one website at a time. **Receive messages from this P Direct messages to an Instagram account can reach the same website's inbox, through the Facebook Page the account is linked to ([ADR-0028](../architecture/decisions/0028-instagram-channel.md)). Connect Messenger first, as above: Instagram uses the Page's token and app. -**Replies from OpenChat come later.** Customers' direct messages reach the inbox, but the team replies in Instagram until a later version ([ADR-0028](../architecture/decisions/0028-instagram-channel.md) step 3). +Replies from OpenChat use the Page's token, so it needs no more permissions than receiving does. 1. The Instagram account must be a **professional** account (business or creator) linked to the Page. In the Instagram app, under **Settings and activity**, **Account type and tools**, **Messaging tools**, **Message controls**, turn on **Allow access to messages** (as of December 2026; Meta moves it from time to time). It is only in the phone app. 2. In [Business settings](https://business.facebook.com/settings), give the system user the Instagram account as well as the Page, and **Generate new token** again with `instagram_basic` and `instagram_manage_messages` added to the Messenger permissions (Meta adds `business_management` with them). Get the Page access token from it as before, and paste it on the website's **Messenger & Instagram** tab, replacing the old one. diff --git a/docs/guide/inbox.md b/docs/guide/inbox.md index e8ec344..da71c97 100644 --- a/docs/guide/inbox.md +++ b/docs/guide/inbox.md @@ -87,9 +87,9 @@ If an admin has [connected a Facebook Page](admin.md#connecting-messenger) to a ### Instagram -If an admin has [turned on Instagram](admin.md#connecting-instagram) for a website's Page, direct messages to its Instagram account appear in the inbox marked **Instagram**, under the customer's Instagram name, or their @username if they have none. Photos, videos and files arrive as on Messenger. +If an admin has [turned on Instagram](admin.md#connecting-instagram) for a website's Page, direct messages to its Instagram account appear in the inbox marked **Instagram**, under the customer's Instagram name, or their @username if they have none. Photos, videos and files arrive as on Messenger. Replying, Try again and the assistant work as on [Messenger](#messenger), with the same 24 hours, with two differences: a long reply goes as several messages of 1,000 bytes at most, which is fewer characters in scripts such as Chinese or Japanese, and Instagram says when a reply was **Read** but not when it was delivered. -- **You cannot reply from OpenChat yet**, and the assistant does not answer there. Reply in Instagram, or add an internal note. Replies come in a later version. +- **Replies from the Instagram app** or Meta Business Suite are shown as **Sent from Instagram**. - **What only Instagram sends** shows as a line saying what it was: a reply to your story or a mention in theirs, with Meta's link to the story, a shared post with its link, a view-once photo or video, which you can see only in Instagram, and a message the customer unsent. OpenChat keeps the unsent message's text. - **GIFs and stickers** a customer sends never reach OpenChat: Meta does not pass them on. diff --git a/docs/known-issues.md b/docs/known-issues.md index 4979c29..b04cb6e 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -49,7 +49,8 @@ To report a new problem, [open an issue](https://github.com/OpenChatRun/OpenChat ## Instagram -- **Steps 1 and 2 of [ADR-0028](architecture/decisions/0028-instagram-channel.md) are built:** an installation admin can turn on Instagram for the account linked to a website's Facebook Page, and customers' direct messages, files, story replies and mentions, shares and reactions reach the inbox. Members cannot reply from OpenChat yet (409 `instagram_replies_unavailable`, notes only), and the assistant does not answer there, until step 3. The apps show Instagram conversations without Instagram's mark until step 4. +- **Steps 1 to 3 of [ADR-0028](architecture/decisions/0028-instagram-channel.md) are built:** customers' direct messages reach the inbox and members and the assistant reply from OpenChat. The apps show Instagram conversations, and can reply, but without Instagram's mark, and show Instagram's window as Messenger's, until step 4 and a new store build. +- **Instagram shows no Delivered.** Meta sends only reads for Instagram, so a reply stays **Sent** until the customer reads it. - **An unsent message stays in OpenChat.** When a customer unsends a direct message, a line says so, but the original text is kept, since OpenChat cannot delete a single message yet. - **Customers get through only after Meta's App Review.** On 2 December 2026, with a published app and no review, a direct message from an account linked to the app's admin reached OpenChat, and three from an account with no role did not, even after its message request was accepted. Each business's Meta app needs Advanced Access to `instagram_manage_messages`, which needs App Review and business verification. A single Orango Labs app on Cloud, reviewed once, would spare businesses this; it is a separate decision. - **A business needs a Facebook Page** linked to its Instagram professional account. Connecting with Instagram Login, which needs no Page, is a later decision. diff --git a/packages/api-contracts/generated/openapi.json b/packages/api-contracts/generated/openapi.json index aefb2fe..1988c8f 100644 --- a/packages/api-contracts/generated/openapi.json +++ b/packages/api-contracts/generated/openapi.json @@ -3009,7 +3009,7 @@ "string", "null" ], - "description": "On Messenger, the same as `whatsappWindowEndsAt`: past it a reply is refused with 409 `messenger_window_closed`. Absent for other channels. From API minor 10." + "description": "On Messenger, the same as `whatsappWindowEndsAt`: past it a reply is refused with 409 `messenger_window_closed`. On Instagram, the same window, refused with 409 `instagram_window_closed` (from API minor 13). Absent for other channels. From API minor 10." } }, "required": [ @@ -9075,7 +9075,7 @@ ], "operationId": "sendMessage", "summary": "Send a reply or an internal note", - "description": "On WhatsApp (ADR-0026), a reply is committed, then sent by a job: follow `whatsapp.delivery` on the message. Past Meta's 24-hour window it is refused with 409 `whatsapp_window_closed`; see the conversation's `whatsappWindowEndsAt`. On Messenger (ADR-0027), the same: follow `messenger.delivery`; past the window a reply is refused with 409 `messenger_window_closed`; see `messengerWindowEndsAt`.", + "description": "On WhatsApp (ADR-0026), a reply is committed, then sent by a job: follow `whatsapp.delivery` on the message. Past Meta's 24-hour window it is refused with 409 `whatsapp_window_closed`; see the conversation's `whatsappWindowEndsAt`. On Messenger (ADR-0027), the same: follow `messenger.delivery`; past the window a reply is refused with 409 `messenger_window_closed`; see `messengerWindowEndsAt`. On Instagram (ADR-0028), the same as Messenger, with 409 `instagram_window_closed` and a text limit of 1,000 bytes per part.", "security": [ { "bearerAuth": [] diff --git a/packages/api-contracts/src/routes.ts b/packages/api-contracts/src/routes.ts index 278d5c6..c89d70e 100644 --- a/packages/api-contracts/src/routes.ts +++ b/packages/api-contracts/src/routes.ts @@ -101,8 +101,10 @@ export const getSecurityTxtRoute = createRoute({ * - 11: `instagram` on a Messenger connection, to turn on Instagram direct messages (ADR-0028). * - 12: `instagram` as a conversation's `channel`, `messenger` on its messages, and `instagram` in contact export * (ADR-0028 step 2). + * - 13: replies on Instagram: `messengerWindowEndsAt` and `messenger.delivery` on Instagram conversations, 409 + * `instagram_window_closed`, and retryMessengerMessage for them (ADR-0028 step 3). */ -export const API_MINOR_VERSION = 12; +export const API_MINOR_VERSION = 13; // ---------- Authentication ---------- @@ -868,7 +870,8 @@ export const ConversationSchema = z "On WhatsApp: when Meta's 24-hour window for replies ends, 24 hours after the customer last wrote. Past it a reply is refused with 409 `whatsapp_window_closed`; internal notes are not affected. Null when the customer has not written; absent for the website.", }), messengerWindowEndsAt: z.string().nullable().optional().openapi({ - description: "On Messenger, the same as `whatsappWindowEndsAt`: past it a reply is refused with 409 `messenger_window_closed`. Absent for other channels. From API minor 10.", + description: + "On Messenger, the same as `whatsappWindowEndsAt`: past it a reply is refused with 409 `messenger_window_closed`. On Instagram, the same window, refused with 409 `instagram_window_closed` (from API minor 13). Absent for other channels. From API minor 10.", }), }) .openapi('Conversation'); @@ -1073,7 +1076,7 @@ export const sendMessageRoute = createRoute({ operationId: 'sendMessage', summary: 'Send a reply or an internal note', description: - "On WhatsApp (ADR-0026), a reply is committed, then sent by a job: follow `whatsapp.delivery` on the message. Past Meta's 24-hour window it is refused with 409 `whatsapp_window_closed`; see the conversation's `whatsappWindowEndsAt`. On Messenger (ADR-0027), the same: follow `messenger.delivery`; past the window a reply is refused with 409 `messenger_window_closed`; see `messengerWindowEndsAt`.", + "On WhatsApp (ADR-0026), a reply is committed, then sent by a job: follow `whatsapp.delivery` on the message. Past Meta's 24-hour window it is refused with 409 `whatsapp_window_closed`; see the conversation's `whatsappWindowEndsAt`. On Messenger (ADR-0027), the same: follow `messenger.delivery`; past the window a reply is refused with 409 `messenger_window_closed`; see `messengerWindowEndsAt`. On Instagram (ADR-0028), the same as Messenger, with 409 `instagram_window_closed` and a text limit of 1,000 bytes per part.", security: bearer, request: { params: conversationParams, diff --git a/packages/core/src/instagram-inbound.ts b/packages/core/src/instagram-inbound.ts index d519b4e..7303968 100644 --- a/packages/core/src/instagram-inbound.ts +++ b/packages/core/src/instagram-inbound.ts @@ -6,7 +6,8 @@ * Instagram sends things Messenger does not: story mentions and replies, shared posts, view-once media, and unsent * messages. Each becomes a message saying what it was, with Meta's link where there is one, rather than being dropped. */ -import type { MessengerInbound } from './messenger-inbound'; +import type { MessengerInbound, MessengerPageEvent } from './messenger-inbound'; +import { MESSENGER_METADATA_PREFIX } from './messenger-outbound'; /** As for Messenger. Instagram's own limit is 1,000 bytes. */ const MAX_TEXT = 16_000; @@ -112,3 +113,42 @@ export function readInstagramWebhook(accountId: string, body: unknown): Messenge } return out; } + +/** + * The business's side (ADR-0028 step 3): replies sent from the Instagram app or Meta Business Suite, shown as sent from + * Instagram, and the customer's reads of OpenChat's replies. An echo of OpenChat's own reply carries its metadata, or + * is found by its message ID when stored. Instagram sends no deliveries, and a read names the message read, not a + * watermark: everything sent before the read's time counts as read. + */ +export function readInstagramPageEvents(accountId: string, body: unknown): MessengerPageEvent[] { + const out: MessengerPageEvent[] = []; + const root = obj(body); + if (root?.object !== 'instagram') return out; + for (const entry of list(root.entry)) { + if (obj(entry)?.id !== accountId) continue; + for (const raw of list(obj(entry)?.messaging)) { + const event = obj(raw); + if (!event) continue; + const sender = digits(obj(event.sender)?.id); + const recipient = digits(obj(event.recipient)?.id); + const message = obj(event.message); + if (message?.is_echo === true) { + const mid = id(message.mid); + if (sender !== accountId || !recipient || recipient === accountId || !mid || message.is_deleted === true) continue; + if (typeof message.metadata === 'string' && message.metadata.startsWith(MESSENGER_METADATA_PREFIX)) continue; + const attachments = list(message.attachments); + const text = words(message.text); + if (!text && attachments.length === 0) continue; + out.push({ kind: 'echo', psid: recipient, mid, content: text, ...(attachments.length > 0 ? { unsupported: id(obj(attachments[0])?.type, 64) ?? 'unknown' } : {}) }); + continue; + } + const read = obj(event.read); + if (!read || !sender || sender === accountId || recipient !== accountId) continue; + const at = event.timestamp; + const mid = id(read.mid); + if (typeof at !== 'number' || !Number.isFinite(at) || at <= 0) continue; + out.push({ kind: 'status', psid: sender, status: 'read', watermark: at, mids: mid ? [mid] : [] }); + } + } + return out; +} diff --git a/packages/core/src/messaging.ts b/packages/core/src/messaging.ts index 41f5fe8..02d35ec 100644 --- a/packages/core/src/messaging.ts +++ b/packages/core/src/messaging.ts @@ -10,14 +10,15 @@ import type { AuthDeps } from './auth-flows'; import { translateReply, type TranslationDeps } from './translation'; import { requireCapability } from './workspaces'; -/** Until OpenChat sends replies on Instagram (ADR-0028 step 3), one would be stored and never reach the customer. */ -export const instagramRepliesUnavailable = () => new AppError(409, 'instagram_replies_unavailable', 'Replies on Instagram cannot be sent from OpenChat yet. Reply in Instagram, or add a note.'); /** Meta's 24-hour window for replies on WhatsApp (ADR-0026), from the customer's last message. */ export const whatsappWindowOpen = (lastCustomerMessageAt: number | null, now = Date.now()) => lastCustomerMessageAt !== null && now < lastCustomerMessageAt + WHATSAPP_WINDOW_MS; /** Meta's 24-hour window for replies on Messenger (ADR-0027), from the customer's last message. */ export const messengerWindowOpen = (lastCustomerMessageAt: number | null, now = Date.now()) => lastCustomerMessageAt !== null && now < lastCustomerMessageAt + MESSENGER_WINDOW_MS; export const messengerWindowClosed = () => new AppError(409, 'messenger_window_closed', 'More than 24 hours have passed since the customer last wrote on Messenger, so Meta allows no reply until they write again. Add an internal note instead'); +/** Instagram's window is Messenger's (ADR-0028), but the customer is told where they wrote. */ +export const instagramWindowClosed = () => + new AppError(409, 'instagram_window_closed', 'More than 24 hours have passed since the customer last wrote on Instagram, so Meta allows no reply until they write again. Add an internal note instead'); export const whatsappWindowClosed = () => new AppError(409, 'whatsapp_window_closed', 'More than 24 hours have passed since the customer last wrote on WhatsApp, so Meta allows no reply until they write again. Add an internal note instead'); @@ -53,7 +54,7 @@ const toConversation = (row: ConversationRow) => ({ rating: toRating(row), channel: row.channel, ...(row.channel === 'whatsapp' ? { whatsappWindowEndsAt: row.whatsappLastCustomerMessageAt === null ? null : toIso(row.whatsappLastCustomerMessageAt + WHATSAPP_WINDOW_MS) } : {}), - ...(row.channel === 'messenger' ? { messengerWindowEndsAt: row.messengerLastCustomerMessageAt === null ? null : toIso(row.messengerLastCustomerMessageAt + MESSENGER_WINDOW_MS) } : {}), + ...(row.channel === 'messenger' || row.channel === 'instagram' ? { messengerWindowEndsAt: row.messengerLastCustomerMessageAt === null ? null : toIso(row.messengerLastCustomerMessageAt + MESSENGER_WINDOW_MS) } : {}), }); const invalidAttachments = () => new AppError(400, 'invalid_attachments', 'A file on this message was not uploaded by you to this conversation, or has already been sent'); @@ -256,7 +257,7 @@ export async function sendMessage( // Meta refuses a reply after its window. The send job checks again, since time passes before it runs. if (conversation.channel === 'whatsapp' && !whatsappWindowOpen(conversation.whatsappLastCustomerMessageAt)) throw whatsappWindowClosed(); if (conversation.channel === 'messenger' && !messengerWindowOpen(conversation.messengerLastCustomerMessageAt)) throw messengerWindowClosed(); - if (conversation.channel === 'instagram') throw instagramRepliesUnavailable(); + if (conversation.channel === 'instagram' && !messengerWindowOpen(conversation.messengerLastCustomerMessageAt)) throw instagramWindowClosed(); if (input.translate && translation) { reply = (await translateReply(translation.deps, ctx, { userId: translation.userId, visitorLanguage: conversation.visitorLanguage, content: input.content })) ?? reply; } diff --git a/packages/core/src/messenger-inbound.ts b/packages/core/src/messenger-inbound.ts index 9e2a269..9b03af8 100644 --- a/packages/core/src/messenger-inbound.ts +++ b/packages/core/src/messenger-inbound.ts @@ -34,7 +34,7 @@ import { ATTACHMENT_HEAD_BYTES, MAX_ATTACHMENT_BYTES, whatsappMediaFile } from ' import { type Fetcher } from './meta'; import { messengerGraph, openMessengerSecret } from './messenger'; import { MESSENGER_METADATA_PREFIX } from './messenger-outbound'; -import { readInstagramWebhook } from './instagram-inbound'; +import { readInstagramPageEvents, readInstagramWebhook } from './instagram-inbound'; import type { MediaStore } from './whatsapp-inbound'; /** As for a member's message. Messenger's own limit is 2,000 characters. */ @@ -261,8 +261,7 @@ export async function receiveMessengerWebhook(db: Database, connection: Messenge if (item.messenger?.media) result.media.push({ workspaceId: page.workspaceId, messageId: stored.messageId }); } const w = page.workspaceId; - // Instagram's echoes and reads come with replies, in step 3. - for (const event of instagram ? [] : readMessengerPageEvents(connection.pageId, body)) { + for (const event of instagram ? readInstagramPageEvents(page.pageId, body) : readMessengerPageEvents(connection.pageId, body)) { if (event.kind === 'echo') { if (await isMessengerSent(db, w, event.mid)) continue; const stored = await receiveMessengerEcho(db, page, event.psid, event); diff --git a/packages/core/src/messenger-outbound.ts b/packages/core/src/messenger-outbound.ts index 7210e99..d502bf1 100644 --- a/packages/core/src/messenger-outbound.ts +++ b/packages/core/src/messenger-outbound.ts @@ -23,13 +23,17 @@ import { } from '@openchat/database'; import { AppError, createLogger, notFound } from '@openchat/shared'; import { requireCapability } from './workspaces'; -import { messengerWindowClosed, messengerWindowOpen, toMessage } from './messaging'; +import { instagramWindowClosed, messengerWindowClosed, messengerWindowOpen, toMessage } from './messaging'; import { GRAPH_BASE_URL, GRAPH_TIMEOUT_MS, type Fetcher } from './meta'; import { openMessengerSecret } from './messenger'; import { replyParts, type ReplyFileStore, type ReplyPart } from './whatsapp-outbound'; /** Messenger's limit for a text message. A longer reply goes as several, in order. */ export const MESSENGER_TEXT_CHARS = 2000; +/** Instagram's is 1,000 bytes of UTF-8 (ADR-0028), not characters. */ +export const INSTAGRAM_TEXT_BYTES = 1000; +const utf8 = new TextEncoder(); +export const utf8Bytes = (text: string) => utf8.encode(text).length; const UPLOAD_TIMEOUT_MS = 60_000; /** What a part's metadata starts with. The message ID follows, which only OpenChat reads back. */ export const MESSENGER_METADATA_PREFIX = 'openchat:'; @@ -55,8 +59,8 @@ export function messengerAttachmentType(contentType: string): 'image' | 'video' * 1, 2: temporary; 4, 17, 32, 613: rate limits; 341: application limit; 1200: temporary send failure. */ const RETRYABLE_CODES = new Set([1, 2, 4, 17, 32, 341, 613, 1200]); -/** Code 10 with this subcode: the message was sent outside the 24-hour window. */ -const OUTSIDE_WINDOW_SUBCODE = 2018278; +/** Code 10 with these subcodes: the message was sent outside the 24-hour window, on Messenger or on Instagram. */ +const OUTSIDE_WINDOW_SUBCODES = new Set([2018278, 2534022]); class MetaRefused extends Error { constructor(readonly reason: 'window_closed' | `meta:${number}` | 'unavailable') { @@ -84,7 +88,7 @@ async function send(fetcher: Fetcher, token: string, pageId: string, body: BodyI } const code = typeof answer.error?.code === 'number' ? answer.error.code : 0; if (response.status === 429 || response.status >= 500 || RETRYABLE_CODES.has(code)) throw tryAgain(); - if (code === 10 && answer.error?.error_subcode === OUTSIDE_WINDOW_SUBCODE) throw new MetaRefused('window_closed'); + if (code === 10 && OUTSIDE_WINDOW_SUBCODES.has(answer.error?.error_subcode as number)) throw new MetaRefused('window_closed'); throw new MetaRefused(`meta:${code}`); } @@ -118,7 +122,10 @@ export async function sendMessengerReply(deps: MessengerSendDeps, workspaceId: s return delivery ? { outcome: delivery === 'failed' ? 'failed' : 'sent', conversationId: reply.conversationId } : { outcome: 'nothing' }; }; const connection = await messengerConnectionForWebsite(deps.db, workspaceId, reply.websiteId); - if (!connection || !connection.enabled || !deps.keys || !reply.recipient || reply.recipient.pageId !== connection.pageId) { + // On Instagram (ADR-0028) the customer belongs to the linked account, which must still be on; the Page's token sends. + const instagram = reply.channel === 'instagram'; + const from = instagram ? (connection?.instagram?.enabled ? connection.instagram.accountId : null) : connection?.pageId; + if (!connection || !connection.enabled || !deps.keys || !reply.recipient || !from || reply.recipient.pageId !== from) { await failMessengerPart(deps.db, workspaceId, messageId, 'not_connected'); return finish(); } @@ -127,7 +134,7 @@ export async function sendMessengerReply(deps: MessengerSendDeps, workspaceId: s return finish(); } const token = await openMessengerSecret(deps.keys, connection, 'accessToken'); - const parts = replyParts(reply.content, reply.files as MessengerReplyFile[], MESSENGER_TEXT_CHARS); + const parts = instagram ? replyParts(reply.content, reply.files as MessengerReplyFile[], INSTAGRAM_TEXT_BYTES, utf8Bytes) : replyParts(reply.content, reply.files as MessengerReplyFile[], MESSENGER_TEXT_CHARS); for (const [index, part] of parts.entries()) { if (reply.sent.includes(index)) continue; try { @@ -160,8 +167,8 @@ export async function retryMessengerMessage(db: Database, ctx: WorkspaceContext, const repos = repositories(db, ctx); const conversation = await repos.conversations.get(conversationId); if (!conversation) throw notFound(); - if (conversation.channel !== 'messenger') throw new AppError(409, 'not_failed', 'This message is not a failed Messenger reply'); - if (!messengerWindowOpen(conversation.messengerLastCustomerMessageAt)) throw messengerWindowClosed(); + if (conversation.channel !== 'messenger' && conversation.channel !== 'instagram') throw new AppError(409, 'not_failed', 'This message is not a failed Messenger reply'); + if (!messengerWindowOpen(conversation.messengerLastCustomerMessageAt)) throw conversation.channel === 'instagram' ? instagramWindowClosed() : messengerWindowClosed(); if (!(await retryMessengerSend(db, ctx.workspaceId, conversationId, messageId))) { if (!(await repos.messages.byId(conversationId, messageId))) throw notFound(); throw new AppError(409, 'not_failed', 'This message is not a failed Messenger reply'); diff --git a/packages/core/src/whatsapp-outbound.ts b/packages/core/src/whatsapp-outbound.ts index 9e85d56..f954c5f 100644 --- a/packages/core/src/whatsapp-outbound.ts +++ b/packages/core/src/whatsapp-outbound.ts @@ -47,16 +47,33 @@ export interface WhatsAppSendDeps { export type ReplyPart = { kind: 'text'; body: string } | { kind: 'file'; file: WhatsAppReplyFile }; type Part = ReplyPart; -/** The text in pieces the channel takes, split at a line or a space where one is near the end, then the files. */ -export function replyParts(content: string, files: WhatsAppReplyFile[], limit = WHATSAPP_TEXT_CHARS): Part[] { +/** The longest start of `text` whose size is within `limit`, never ending inside a surrogate pair. */ +function fitting(text: string, limit: number, size: (text: string) => number): number { + let low = 1; + let high = Math.min(text.length, limit); + while (low < high) { + const mid = Math.ceil((low + high) / 2); + if (size(text.slice(0, mid)) <= limit) low = mid; + else high = mid - 1; + } + const code = text.charCodeAt(low - 1); + return low > 1 && code >= 0xd800 && code <= 0xdbff ? low - 1 : low; +} + +/** + * The text in pieces the channel takes, split at a line or a space where one is near the end, then the files. `size` + * measures a piece in the channel's unit: characters, or bytes for Instagram (ADR-0028). + */ +export function replyParts(content: string, files: WhatsAppReplyFile[], limit = WHATSAPP_TEXT_CHARS, size: (text: string) => number = (text) => text.length): Part[] { const parts: Part[] = []; let rest = content.trim(); while (rest.length > 0) { let cut = rest.length; - if (rest.length > limit) { - const window = rest.slice(0, limit); + if (size(rest) > limit) { + const end = fitting(rest, limit, size); + const window = rest.slice(0, end); const at = Math.max(window.lastIndexOf('\n'), window.lastIndexOf(' ')); - cut = at > limit / 2 ? at : limit; + cut = at > end / 2 ? at : end; } parts.push({ kind: 'text', body: rest.slice(0, cut) }); rest = rest.slice(cut).trim(); diff --git a/packages/database/src/internal/message-statements.ts b/packages/database/src/internal/message-statements.ts index 205d5ed..656dfc3 100644 --- a/packages/database/src/internal/message-statements.ts +++ b/packages/database/src/internal/message-statements.ts @@ -73,10 +73,10 @@ export function messageStatements(d1: D1Database, input: MessageStatementsInput) WHEN NOT EXISTS (SELECT 1 FROM attachments a WHERE ${claimable} AND a.content_type NOT LIKE 'image/%') THEN 'image' ELSE 'file' END, ?2, ?7, ${DB_NOW_MS}, ?12, - -- A reply on WhatsApp or Messenger, by a member or the assistant, waits for the send job (ADR-0026, ADR-0027). + -- A reply on WhatsApp, Messenger or Instagram, by a member or the assistant, waits for the send job (ADR-0026 to 0028). CASE WHEN ?2 <> 'public' OR NOT (?4 = 'member' OR ?12 IS NOT NULL) THEN COALESCE(?13, '{}') WHEN c.channel = 'whatsapp' THEN json_set(COALESCE(?13, '{}'), '$.whatsapp.delivery', 'sending') - WHEN c.channel_kind = 'messenger' THEN json_set(COALESCE(?13, '{}'), '$.messenger.delivery', 'sending') + WHEN c.channel_kind IN ('messenger', 'instagram') THEN json_set(COALESCE(?13, '{}'), '$.messenger.delivery', 'sending') ELSE COALESCE(?13, '{}') END, ?15 FROM conversations c WHERE c.workspace_id = ?8 AND c.id = ?9 AND (?10 IS NULL OR c.contact_id = ?10) AND (SELECT COUNT(*) FROM attachments a WHERE ${claimable}) = json_array_length(?11) diff --git a/packages/database/src/messenger-outbound.ts b/packages/database/src/messenger-outbound.ts index fedd022..645fbed 100644 --- a/packages/database/src/messenger-outbound.ts +++ b/packages/database/src/messenger-outbound.ts @@ -23,11 +23,12 @@ export const MESSENGER_SEND_TOPIC = sendTopic('messenger'); export const MESSENGER_WINDOW_MS = 24 * 60 * 60 * 1000; /** - * When the customer last wrote on this website's Messenger, for a query with conversations as c: across their - * conversations, since a reply may go in an older one. The contact is theirs alone, made from their page-scoped ID. + * When the customer last wrote on this website's Messenger, or its Instagram (ADR-0028), for a query with conversations + * as c: across their conversations on that channel, since a reply may go in an older one. The contact is theirs alone, + * made from their page-scoped or Instagram-scoped ID. */ export const MESSENGER_LAST_CUSTOMER_MESSAGE = `(SELECT MAX(o.last_visitor_message_at) FROM conversations o - WHERE o.workspace_id = c.workspace_id AND o.contact_id = c.contact_id AND o.website_id = c.website_id AND o.channel_kind = 'messenger')`; + WHERE o.workspace_id = c.workspace_id AND o.contact_id = c.contact_id AND o.website_id = c.website_id AND o.channel_kind = c.channel_kind)`; export interface MessengerReplyFile { id: string; @@ -39,12 +40,14 @@ export interface MessengerReplyFile { export interface MessengerReply { workspaceId: string; + /** Messenger, or the Instagram account linked to the Page (ADR-0028). */ + channel: 'messenger' | 'instagram'; conversationId: string; messageId: string; websiteId: string; content: string; files: MessengerReplyFile[]; - /** Who it goes to: the customer's page-scoped ID, with the Page it belongs to. Null if there is none, as after erasure. */ + /** Who it goes to: the customer's page-scoped ID with the Page, or Instagram-scoped ID with the account. Null if there is none, as after erasure. */ recipient: { pageId: string; psid: string } | null; lastCustomerMessageAt: number | null; /** Parts Meta accepted already, by an earlier run of the job. */ @@ -57,12 +60,12 @@ export async function messengerReplyToSend(database: Database, workspaceId: stri const [main, files, sent] = await d1.batch([ d1 .prepare( - `SELECT m.workspace_id AS workspaceId, m.conversation_id AS conversationId, m.id AS messageId, c.website_id AS websiteId, m.content, + `SELECT m.workspace_id AS workspaceId, c.channel_kind AS channel, m.conversation_id AS conversationId, m.id AS messageId, c.website_id AS websiteId, m.content, ${MESSENGER_LAST_CUSTOMER_MESSAGE} AS lastCustomerMessageAt, (SELECT json_object('pageId', mi.page_id, 'psid', mi.psid) FROM messenger_identities mi - WHERE mi.workspace_id = c.workspace_id AND mi.contact_id = c.contact_id ORDER BY mi.updated_at DESC LIMIT 1) AS recipient + WHERE mi.workspace_id = c.workspace_id AND mi.contact_id = c.contact_id AND mi.channel = c.channel_kind ORDER BY mi.updated_at DESC LIMIT 1) AS recipient FROM messages m JOIN conversations c ON c.workspace_id = m.workspace_id AND c.id = m.conversation_id - WHERE m.workspace_id = ?1 AND m.id = ?2 AND c.channel_kind = 'messenger' AND m.visibility = 'public' + WHERE m.workspace_id = ?1 AND m.id = ?2 AND c.channel_kind IN ('messenger', 'instagram') AND m.visibility = 'public' AND json_extract(m.metadata_json, '$.messenger.delivery') = 'sending'`, ) .bind(workspaceId, messageId), @@ -94,7 +97,7 @@ const STATUS_BATCH = 50; /** * Meta's delivery or read for one customer: every part sent to them at or before `watermark`, Meta's time in - * milliseconds, is delivered or read. A status only moves forward. Returns the replies that changed. + * milliseconds, is delivered or read. On Instagram, which has no watermark, it is when they read. A status only moves forward. Returns the replies that changed. */ export async function applyMessengerWatermark( database: Database, @@ -108,7 +111,7 @@ export async function applyMessengerWatermark( .prepare( `SELECT DISTINCT s.message_id AS messageId, m.conversation_id AS conversationId FROM messenger_identities i - JOIN conversations c ON c.workspace_id = i.workspace_id AND c.contact_id = i.contact_id AND c.channel_kind = 'messenger' + JOIN conversations c ON c.workspace_id = i.workspace_id AND c.contact_id = i.contact_id AND c.channel_kind = i.channel JOIN messages m ON m.workspace_id = c.workspace_id AND m.conversation_id = c.id JOIN messenger_sent s ON s.workspace_id = m.workspace_id AND s.message_id = m.id WHERE i.workspace_id = ?1 AND i.page_id = ?2 AND i.psid = ?3 AND s.created_at <= ?5 AND s.status <> 'failed' diff --git a/packages/database/src/repositories.ts b/packages/database/src/repositories.ts index 2b46f45..b2ba628 100644 --- a/packages/database/src/repositories.ts +++ b/packages/database/src/repositories.ts @@ -358,7 +358,7 @@ const conversationSelect = (extra = '') => `SELECT ${extra} c.id, c.website_id A c.assistant_state AS assistantState, c.help_article_id AS helpArticleId, c.visitor_language AS visitorLanguage, c.visitor_page_url AS visitorPageUrl, c.visitor_page_at AS visitorPageAt, c.visitor_rating AS visitorRating, c.visitor_rating_comment AS visitorRatingComment, c.visitor_rated_at AS visitorRatedAt, ${CHANNEL} AS channel, CASE WHEN c.channel = 'whatsapp' THEN ${WHATSAPP_LAST_CUSTOMER_MESSAGE} END AS whatsappLastCustomerMessageAt, - CASE WHEN c.channel_kind = 'messenger' THEN ${MESSENGER_LAST_CUSTOMER_MESSAGE} END AS messengerLastCustomerMessageAt, + CASE WHEN c.channel_kind IN ('messenger', 'instagram') THEN ${MESSENGER_LAST_CUSTOMER_MESSAGE} END AS messengerLastCustomerMessageAt, (SELECT json_object('text', substr(lm.content, 1, ${PREVIEW_CHARS}), 'senderType', CASE WHEN lm.assistant_id IS NOT NULL THEN 'assistant' ELSE lm.sender_type END, 'senderId', CASE WHEN lm.sender_type = 'member' AND lm.assistant_id IS NULL THEN lm.sender_id END, 'type', lm.message_type) diff --git a/services/api/src/dispatch.ts b/services/api/src/dispatch.ts index 2776a33..dbd71e2 100644 --- a/services/api/src/dispatch.ts +++ b/services/api/src/dispatch.ts @@ -92,12 +92,11 @@ async function dispatchRow(env: Env, db: Database, row: OutboxRow): Promise { expect(await client.getDiscovery()).toEqual({ installationId: 'inst_test', name: 'Test installation', - api: { versions: ['v1'], minor: 12 }, + api: { versions: ['v1'], minor: 13 }, realtime: { protocolVersions: [1] }, relay: null, // emailCode follows the local email setting; sign-in codes (auth.test.ts) test both. diff --git a/services/api/test/messenger.test.ts b/services/api/test/messenger.test.ts index c07daac..3a77f93 100644 --- a/services/api/test/messenger.test.ts +++ b/services/api/test/messenger.test.ts @@ -647,15 +647,6 @@ describe('receiving Instagram direct messages (ADR-0028 step 2)', () => { expect((await thread(conversation.id))[0]).toMatchObject({ type: 'image', attachments: [{ contentType: 'image/png' }] }); }); - it('takes no reply and no assistant answer there yet, but takes a note', async () => { - const { id } = await connectInstagram(); - await deliver(id, igInbound([igText('ig_1', 'Hello')])); - const conversationId = (await inbox())[0]!.id; - const send = (type: string) => call('POST', `/api/v1/workspaces/work_1/conversations/${conversationId}/messages`, { token: tokens.lead, body: { clientMessageId: crypto.randomUUID(), type, content: 'Hi' } }); - expect(await code(await send('text'))).toBe('instagram_replies_unavailable'); - expect((await send('internal_note')).status).toBe(201); - }); - it('drops what is for another account, from the account itself, or while Instagram is off', async () => { const { id } = await connectInstagram(); await deliver(id, igInbound([igText('ig_1', 'Hello')], '17841400000000099')); @@ -681,6 +672,119 @@ describe('receiving Instagram direct messages (ADR-0028 step 2)', () => { }); }); +describe('replying on Instagram (ADR-0028 step 3)', () => { + beforeEach(() => { + queued.length = 0; + }); + + function fakeSend(options: { refuse?: number; subcode?: number } = {}) { + const sent: { path: string; body: Record }[] = []; + let n = 0; + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url); + expect(new Headers(init?.headers).get('authorization')).toBe(`Bearer ${KEYS.accessToken}`); + sent.push({ path: url.pathname, body: JSON.parse(String(init?.body)) as Record }); + if (options.refuse) return Response.json({ error: { code: options.refuse, error_subcode: options.subcode, message: 'Refused' } }, { status: 400 }); + return Response.json({ recipient_id: IGSID, message_id: `ig_out${++n}` }); + }); + return sent; + } + async function customerWrote(): Promise<{ connectionId: string; conversationId: string }> { + const { id } = await connectInstagram(); + await deliver(id, igInbound([igText('ig_in1', 'Do you ship to Spain?')])); + return { connectionId: id, conversationId: (await inbox())[0]!.id }; + } + const reply = (conversationId: string, body: object) => + call('POST', `/api/v1/workspaces/work_1/conversations/${conversationId}/messages`, { token: tokens.lead, body: { clientMessageId: crypto.randomUUID(), ...body }, testEnv: catching }); + const latest = async (conversationId: string) => (await thread(conversationId)).at(-1)!; + const sendJobs = () => queued.filter((j) => j.type === 'messenger.send'); + const igEcho = (mid: string, words: string, extra: Record = {}): Event => ({ + sender: { id: IG_ACCOUNT }, + recipient: { id: IGSID }, + timestamp: Date.now(), + message: { mid, is_echo: true, text: words, ...extra }, + }); + + it("sends a reply to the customer's Instagram-scoped ID with the Page's token, and marks it read when they read it", async () => { + const { connectionId, conversationId } = await customerWrote(); + const conversation = (await (await call('GET', `/api/v1/workspaces/work_1/conversations/${conversationId}`, { token: tokens.lead })).json()) as { messengerWindowEndsAt: string }; + expect(Date.parse(conversation.messengerWindowEndsAt)).toBeGreaterThan(Date.now() + 23 * 3600_000); + const created = (await (await reply(conversationId, { type: 'text', content: 'Yes, in 3 days.' })).json()) as Msg; + expect(created.messenger).toEqual({ delivery: 'sending' }); + const sent = fakeSend(); + await runMessengerSendJob(sendJobs()[0]!, withKey); + expect(sent).toEqual([ + { path: `/v26.0/${KEYS.pageId}/messages`, body: { recipient: { id: IGSID }, messaging_type: 'RESPONSE', message: { text: 'Yes, in 3 days.', metadata: `openchat:${created.id}` } } }, + ]); + vi.restoreAllMocks(); + const mine = async () => (await thread(conversationId)).find((m) => m.id === created.id)!.messenger; + expect(await mine()).toEqual({ delivery: 'sent' }); + // A read from before it was sent changes nothing; Instagram's read names a message and has no watermark. + await deliver(connectionId, igInbound([igFrom({ timestamp: 1000, read: { mid: 'ig_in1' } })])); + expect(await mine()).toEqual({ delivery: 'sent' }); + await deliver(connectionId, igInbound([igFrom({ timestamp: Date.now() + 60_000, read: { mid: 'ig_out1' } })])); + expect(await mine()).toEqual({ delivery: 'read' }); + }); + + it("shows a reply sent from the Instagram app as sent from Instagram, but not the echo of OpenChat's own", async () => { + const { connectionId, conversationId } = await customerWrote(); + const created = (await (await reply(conversationId, { type: 'text', content: 'From OpenChat' })).json()) as Msg; + fakeSend(); + await runMessengerSendJob(sendJobs()[0]!, withKey); + vi.restoreAllMocks(); + queued.length = 0; + await deliver( + connectionId, + igInbound([ + igEcho('ig_out1', 'From OpenChat', { metadata: `openchat:${created.id}` }), + igEcho('ig_out1', 'From OpenChat'), + igEcho('ig_app1', 'Typed in Instagram'), + igEcho('ig_app2', '', { attachments: [{ type: 'image', payload: { url: 'https://scontent.cdninstagram.com/x.jpg' } }] }), + igEcho('ig_app1', '', { is_deleted: true }), + ]), + ); + expect((await thread(conversationId)).map((m) => [m.content, m.sender.type, m.messenger])).toEqual([ + ['Do you ship to Spain?', 'visitor', undefined], + ['From OpenChat', 'member', { delivery: 'sent' }], + ['Typed in Instagram', 'system', { echo: true }], + ['', 'system', { echo: true, unsupported: 'image' }], + ]); + expect(sendJobs()).toHaveLength(0); + }); + + it("sends a long reply in parts of at most 1,000 bytes, whatever the script", async () => { + const { conversationId } = await customerWrote(); + const words = '你好世界 '.repeat(150).trim(); + await reply(conversationId, { type: 'text', content: words }); + const sent = fakeSend(); + await runMessengerSendJob(sendJobs()[0]!, withKey); + const texts = sent.map((s) => (s.body as { message: { text: string } }).message.text); + expect(texts.length).toBeGreaterThan(1); + for (const text of texts) expect(new TextEncoder().encode(text).length).toBeLessThanOrEqual(1000); + expect(texts.join(' ')).toBe(words); + // Never inside an emoji, which is two UTF-16 units. + expect(replyParts('😀'.repeat(300), [], 1000, (t) => new TextEncoder().encode(t).length).map((p) => (p.kind === 'text' ? p.body.length : 0))).toEqual([500, 100]); + }); + + it('refuses a reply after the window with its own code, fails on Meta saying so, and on Instagram being turned off', async () => { + const { conversationId } = await customerWrote(); + await env.DB.prepare(`UPDATE conversations SET last_visitor_message_at = ?1`).bind(Date.now() - 25 * 3600_000).run(); + expect(await code(await reply(conversationId, { type: 'text', content: 'Late' }))).toBe('instagram_window_closed'); + await env.DB.prepare(`UPDATE conversations SET last_visitor_message_at = ?1`).bind(Date.now()).run(); + await reply(conversationId, { type: 'text', content: 'Hello' }); + fakeSend({ refuse: 10, subcode: 2534022 }); + await runMessengerSendJob(sendJobs()[0]!, withKey); + expect((await latest(conversationId)).messenger).toEqual({ delivery: 'failed', error: { reason: 'window_closed' } }); + vi.restoreAllMocks(); + await reply(conversationId, { type: 'text', content: 'Hello again' }); + await env.DB.prepare(`UPDATE messenger_connections SET instagram_enabled = 0`).run(); + await runMessengerSendJob(sendJobs()[1]!, withKey); + expect((await latest(conversationId)).messenger).toEqual({ delivery: 'failed', error: { reason: 'not_connected' } }); + const retry = await call('POST', `/api/v1/workspaces/work_1/conversations/${conversationId}/messages/${(await latest(conversationId)).id}/messenger-retry`, { token: tokens.lead, testEnv: catching }); + expect(retry.status).toBe(200); + }); +}); + describe('replying on Messenger (ADR-0027 step 3)', () => { beforeEach(() => { queued.length = 0;