From 827b1df35bac17bf2eed0c42678977c94bc63648 Mon Sep 17 00:00:00 2001 From: setkyar Date: Thu, 3 Dec 2026 19:57:07 +0700 Subject: [PATCH] feat(channels): a conversation the account has left says so and refuses sends A channel can report that the account itself is no longer in a conversation (participant.remove with isSelf): it left a group, was removed or the group is gone. The conversation then shows a notice in place of the composer, and sends are refused before anything is stored or queued. A participant.upsert for the same endpoint opens it again. The event is ignored for a conversation the inbox does not hold. --- .../application/event-processor.ts | 53 ++++++++++- .../providers/external-gateway/normalize.ts | 1 + .../channel-gateway.integration.test.ts | 90 +++++++++++++++++++ apps/api/src/routes/conversations/index.ts | 8 +- apps/api/src/routes/conversations/messages.ts | 14 ++- .../src/services/channel-outbound.service.ts | 6 +- .../conversation-acceptance.service.ts | 21 +++++ apps/web/src/lib/api/channel-conversations.ts | 5 ++ apps/web/src/locales/ar.json | 1 + apps/web/src/locales/de.json | 1 + apps/web/src/locales/en.json | 1 + apps/web/src/locales/es.json | 1 + apps/web/src/locales/fr.json | 1 + apps/web/src/locales/id.json | 1 + apps/web/src/locales/ms.json | 1 + apps/web/src/locales/pt-BR.json | 1 + apps/web/src/locales/zh-CN.json | 1 + apps/web/src/pages/ChatPage.tsx | 9 +- docs/channel-gateway-protocol.md | 7 ++ .../shared/src/channel-spine/contracts.ts | 7 ++ 20 files changed, 225 insertions(+), 5 deletions(-) diff --git a/apps/api/src/channel-spine/application/event-processor.ts b/apps/api/src/channel-spine/application/event-processor.ts index 89a6209f..7634ae44 100644 --- a/apps/api/src/channel-spine/application/event-processor.ts +++ b/apps/api/src/channel-spine/application/event-processor.ts @@ -224,7 +224,10 @@ async function applyParticipantMutation( NormalizedChannelEvent, { kind: "participant.upsert" | "participant.remove" } >, -): Promise<{ conversationId: string }> { +): Promise<{ conversationId?: string }> { + if (event.kind === "participant.remove" && event.payload.isSelf === true) { + return applyAccountLeft(trx, event); + } const conversationId = await ensureConversation( trx, event, @@ -300,6 +303,54 @@ async function applyParticipantMutation( return { conversationId }; } +/** + * The account itself left a conversation. Recorded on the account's own + * participant row, which is created here if the channel never reported one. + * + * A conversation the inbox does not hold is left alone: leaving a group + * nobody ever saw here is not a reason to start showing it. + */ +async function applyAccountLeft( + trx: Transaction, + event: Extract, +): Promise<{ conversationId?: string }> { + if (!event.payload.endpoint) throw new Error("participant_identity_missing"); + const conversation = await trx + .selectFrom("conversations") + .select("id") + .where("channel_account_id", "=", event.channelAccountId) + .where("client_thread_key", "=", event.payload.conversation.clientThreadKey) + .executeTakeFirst(); + if (!conversation) return {}; + const endpointId = await ensureEndpoint(trx, event, event.payload.endpoint); + const leftAt = new Date( + event.payload.leftAt ?? event.providerOccurredAt ?? event.receivedAt, + ); + const updated = await trx + .updateTable("conversation_participants") + .set({ left_at: leftAt, is_self: true, updated_at: new Date() }) + .where("conversation_id", "=", conversation.id) + .where("contact_endpoint_id", "=", endpointId) + .executeTakeFirst(); + if (Number(updated.numUpdatedRows ?? 0) === 0) { + await trx + .insertInto("conversation_participants") + .values({ + conversation_id: conversation.id, + contact_endpoint_id: endpointId, + workspace_user_id: null, + participant_kind: "account", + role: "member", + is_self: true, + joined_at: null, + left_at: leftAt, + provider_metadata: {}, + }) + .execute(); + } + return { conversationId: conversation.id }; +} + async function applyMessageUpsert( trx: Transaction, event: Extract, diff --git a/apps/api/src/channel-spine/providers/external-gateway/normalize.ts b/apps/api/src/channel-spine/providers/external-gateway/normalize.ts index cbcab6f2..7cda53c5 100644 --- a/apps/api/src/channel-spine/providers/external-gateway/normalize.ts +++ b/apps/api/src/channel-spine/providers/external-gateway/normalize.ts @@ -110,6 +110,7 @@ const payloadSchemas: Readonly>> = { conversation, endpoint: endpoint.optional(), leftAt: timestamp.optional(), + isSelf: z.boolean().optional(), }), "message.upsert": z.object({ conversation, diff --git a/apps/api/src/routes/channel-gateway.integration.test.ts b/apps/api/src/routes/channel-gateway.integration.test.ts index 7a4fda2d..dfc8eb02 100644 --- a/apps/api/src/routes/channel-gateway.integration.test.ts +++ b/apps/api/src/routes/channel-gateway.integration.test.ts @@ -1672,6 +1672,96 @@ describe("channel gateway, end to end through the routes", () => { }, ); + integration( + "a conversation the account has left refuses sends until it is back", + async () => { + await withWorkspace({}, async (workspace) => { + const accountId = await link(workspace); + await gateway.deliver(accountId, inbound("980")); + const { id: conversationId } = await workspace.tenantDb + .selectFrom("conversations") + .select("id") + .executeTakeFirstOrThrow(); + const own = { + externalId: "Uself000000000000000000000000001", + identityScope: "line-user", + endpointKind: "person", + displayName: "The shop", + }; + const left = (conversation: typeof thread, round: number) => [ + { + eventId: `line:membership:${conversation.externalThreadId}:${round}`, + kind: "participant.remove", + payload: { conversation, endpoint: own, isSelf: true }, + }, + ]; + const state = async () => + ( + await json<{ data: { leftConversation: boolean } }>( + await app.request(`/api/conversations/${conversationId}`, { + headers: workspace.headers, + }), + ) + ).data.leftConversation; + const send = (key: string) => + app.request(`/api/conversations/${conversationId}/messages`, { + method: "POST", + headers: { ...workspace.headers, "Idempotency-Key": key }, + body: JSON.stringify({ content: "Hello" }), + }); + + expect(await state()).toBe(false); + expect((await gateway.deliver(accountId, left(thread, 1))).status).toBe( + 200, + ); + expect(await state()).toBe(true); + const refused = await send("after-leaving"); + expect(refused.status).toBe(409); + expect(await json(refused)).toMatchObject({ + code: "CONVERSATION_LEFT", + }); + expect( + await workspace.tenantDb + .selectFrom("outbound_message_intents") + .select("id") + .execute(), + ).toEqual([]); + + // Leaving a group the inbox never held does not make it appear. + const unseen = { + externalThreadId: "Cunseen0000000000000000000000001", + clientThreadKey: "line:Cunseen0000000000000000000000001", + kind: "group", + }; + expect((await gateway.deliver(accountId, left(unseen, 1))).status).toBe( + 200, + ); + expect( + await workspace.tenantDb + .selectFrom("conversations") + .select("id") + .execute(), + ).toHaveLength(1); + + // Back in: the same endpoint is reported as a participant again. + await gateway.deliver(accountId, [ + { + eventId: `line:membership:${thread.externalThreadId}:back`, + kind: "participant.upsert", + payload: { + conversation: thread, + endpoint: own, + participantKind: "account", + role: "member", + isSelf: true, + }, + }, + ]); + expect(await state()).toBe(false); + }); + }, + ); + integration( "a contact who has not accepted yet cannot be written to, by any road", async () => { diff --git a/apps/api/src/routes/conversations/index.ts b/apps/api/src/routes/conversations/index.ts index 8b0056ab..3bb2691e 100644 --- a/apps/api/src/routes/conversations/index.ts +++ b/apps/api/src/routes/conversations/index.ts @@ -1,4 +1,7 @@ -import { isAwaitingAcceptance } from "../../services/conversation-acceptance.service.js"; +import { + hasLeftConversation, + isAwaitingAcceptance, +} from "../../services/conversation-acceptance.service.js"; import { Hono } from "hono"; import { successData } from "../../lib/response.js"; import { listConversationsQuerySchema } from "../../lib/schemas/conversation.js"; @@ -329,6 +332,9 @@ conversationRoutes.get("/:id", requireConversationVisibility(), async (c) => { // True while the other person has yet to accept this account on their // network. The composer stays shut until then. awaitingAcceptance: await isAwaitingAcceptance(tenantDb, conversation.id), + // True once the account is no longer in the conversation (it left the + // group or was removed). The composer is replaced by a notice. + leftConversation: await hasLeftConversation(tenantDb, conversation.id), }); }); diff --git a/apps/api/src/routes/conversations/messages.ts b/apps/api/src/routes/conversations/messages.ts index 81760841..edf509f8 100644 --- a/apps/api/src/routes/conversations/messages.ts +++ b/apps/api/src/routes/conversations/messages.ts @@ -71,7 +71,10 @@ import { ChannelGatewayError, requestGatewayHistory, } from "../../services/channel-gateway.service.js"; -import { isAwaitingAcceptance } from "../../services/conversation-acceptance.service.js"; +import { + hasLeftConversation, + isAwaitingAcceptance, +} from "../../services/conversation-acceptance.service.js"; import { validateGroupMentionJids } from "../../services/group-mention.service.js"; import { reserveMediaReferences } from "../../services/media-reference-lock.js"; import { resolveThreadProvenance } from "../../services/message-provenance.service.js"; @@ -647,6 +650,15 @@ messageRoutes.post( 409, ); } + if (await hasLeftConversation(tenantDb, neutralConversation.id)) { + return c.json( + { + error: "This account is no longer in this conversation.", + code: "CONVERSATION_LEFT", + }, + 409, + ); + } // The legacy path refuses a send to an inactive connection outright. The // neutral path would instead accept it and retry the intent every // fifteen minutes indefinitely, so the message sat "pending" in the diff --git a/apps/api/src/services/channel-outbound.service.ts b/apps/api/src/services/channel-outbound.service.ts index b3d7df7f..654104f0 100644 --- a/apps/api/src/services/channel-outbound.service.ts +++ b/apps/api/src/services/channel-outbound.service.ts @@ -1,4 +1,7 @@ -import { isAwaitingAcceptance } from "./conversation-acceptance.service.js"; +import { + hasLeftConversation, + isAwaitingAcceptance, +} from "./conversation-acceptance.service.js"; import { createHash } from "node:crypto"; import { db } from "@wateaminbox/database"; import type { @@ -394,6 +397,7 @@ async function isClaimStillAuthorized(claim: ClaimedIntent): Promise { // message or an automation queues its intent by another road, and none of // them may reach someone who has not accepted the account yet. if (await isAwaitingAcceptance(tenantDb, claim.conversationId)) return false; + if (await hasLeftConversation(tenantDb, claim.conversationId)) return false; const conversation = await tenantDb .selectFrom("conversations as conversation") .innerJoin( diff --git a/apps/api/src/services/conversation-acceptance.service.ts b/apps/api/src/services/conversation-acceptance.service.ts index f386df90..6b6229c7 100644 --- a/apps/api/src/services/conversation-acceptance.service.ts +++ b/apps/api/src/services/conversation-acceptance.service.ts @@ -53,3 +53,24 @@ export async function isAwaitingAcceptance( .executeTakeFirst(); return Boolean(row); } + +/** + * Whether the account is no longer in a conversation: it left a group, was + * removed from it, or the group is gone. The channel reports that as the + * account's own participant leaving. Nothing can be sent there, and saying so + * up front beats a message that fails after it was written. + */ +export async function hasLeftConversation( + db: AcceptanceDb, + conversationId: string, +): Promise { + const row = await db + .selectFrom("conversation_participants") + .select("id") + .where("conversation_id", "=", conversationId) + .where("is_self", "=", true) + .where("left_at", "is not", null) + .limit(1) + .executeTakeFirst(); + return Boolean(row); +} diff --git a/apps/web/src/lib/api/channel-conversations.ts b/apps/web/src/lib/api/channel-conversations.ts index 23c6ad14..ac9291fa 100644 --- a/apps/web/src/lib/api/channel-conversations.ts +++ b/apps/web/src/lib/api/channel-conversations.ts @@ -35,6 +35,11 @@ export interface ChannelConversation { * network (a friend request, say). Nothing can be sent until they do. */ awaitingAcceptance?: boolean; + /** + * True once the account is no longer in the conversation: it left the + * group, was removed, or the group is gone. Nothing can be sent. + */ + leftConversation?: boolean; } export interface ChannelMessageAttachment { diff --git a/apps/web/src/locales/ar.json b/apps/web/src/locales/ar.json index 9bb0ee42..515985ef 100644 --- a/apps/web/src/locales/ar.json +++ b/apps/web/src/locales/ar.json @@ -585,6 +585,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "غير متصل", "whatsappAccountAria": "حساب WhatsApp: {{title}}", + "leftConversation": "هذا الحساب لم يعد ضمن هذه المحادثة، لذلك لا يمكن إرسال الرسائل هنا.", "awaitingAcceptance": "لم يقبل {{name}} بعد. يمكنك الكتابة إليه بعد أن يقبل.", "waitingForOlder": "جارٍ تحميل الرسائل الأقدم…" }, diff --git a/apps/web/src/locales/de.json b/apps/web/src/locales/de.json index 5d90a963..86fa29d5 100644 --- a/apps/web/src/locales/de.json +++ b/apps/web/src/locales/de.json @@ -537,6 +537,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Getrennt", "whatsappAccountAria": "WhatsApp-Konto: {{title}}", + "leftConversation": "Dieses Konto ist nicht mehr Teil dieser Unterhaltung. Hier können keine Nachrichten gesendet werden.", "awaitingAcceptance": "{{name}} hat noch nicht angenommen. Sie können schreiben, sobald das geschehen ist.", "waitingForOlder": "Ältere Nachrichten werden geladen…" }, diff --git a/apps/web/src/locales/en.json b/apps/web/src/locales/en.json index 9d623359..d55c8e1f 100644 --- a/apps/web/src/locales/en.json +++ b/apps/web/src/locales/en.json @@ -537,6 +537,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Disconnected", "whatsappAccountAria": "WhatsApp account: {{title}}", + "leftConversation": "This account is no longer in this conversation, so messages can't be sent here.", "awaitingAcceptance": "{{name}} has not accepted yet. You can write to them once they do.", "waitingForOlder": "Loading older messages…" }, diff --git a/apps/web/src/locales/es.json b/apps/web/src/locales/es.json index 98232dfe..7b74e462 100644 --- a/apps/web/src/locales/es.json +++ b/apps/web/src/locales/es.json @@ -549,6 +549,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Desconectada", "whatsappAccountAria": "Cuenta de WhatsApp: {{title}}", + "leftConversation": "Esta cuenta ya no forma parte de esta conversación, por lo que no se pueden enviar mensajes aquí.", "awaitingAcceptance": "{{name}} aún no ha aceptado. Podrás escribirle cuando lo haga.", "waitingForOlder": "Cargando mensajes anteriores…" }, diff --git a/apps/web/src/locales/fr.json b/apps/web/src/locales/fr.json index 4ad4fd4b..5fffe271 100644 --- a/apps/web/src/locales/fr.json +++ b/apps/web/src/locales/fr.json @@ -549,6 +549,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Déconnecté", "whatsappAccountAria": "Compte WhatsApp : {{title}}", + "leftConversation": "Ce compte ne fait plus partie de cette conversation. Aucun message ne peut y être envoyé.", "awaitingAcceptance": "{{name}} n’a pas encore accepté. Vous pourrez lui écrire une fois que ce sera fait.", "waitingForOlder": "Chargement des messages précédents…" }, diff --git a/apps/web/src/locales/id.json b/apps/web/src/locales/id.json index 9c59e2e5..2de1cb12 100644 --- a/apps/web/src/locales/id.json +++ b/apps/web/src/locales/id.json @@ -525,6 +525,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Terputus", "whatsappAccountAria": "Akun WhatsApp: {{title}}", + "leftConversation": "Akun ini tidak lagi berada dalam percakapan ini, jadi pesan tidak dapat dikirim di sini.", "awaitingAcceptance": "{{name}} belum menerima. Anda dapat menulis kepadanya setelah ia menerima.", "waitingForOlder": "Memuat pesan sebelumnya…" }, diff --git a/apps/web/src/locales/ms.json b/apps/web/src/locales/ms.json index 1cf627bf..53357331 100644 --- a/apps/web/src/locales/ms.json +++ b/apps/web/src/locales/ms.json @@ -525,6 +525,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Terputus", "whatsappAccountAria": "Akaun WhatsApp: {{title}}", + "leftConversation": "Akaun ini tidak lagi berada dalam perbualan ini, jadi mesej tidak boleh dihantar di sini.", "awaitingAcceptance": "{{name}} belum menerima. Anda boleh menulis kepadanya selepas dia menerima.", "waitingForOlder": "Memuatkan mesej terdahulu…" }, diff --git a/apps/web/src/locales/pt-BR.json b/apps/web/src/locales/pt-BR.json index 7a170345..c5a64878 100644 --- a/apps/web/src/locales/pt-BR.json +++ b/apps/web/src/locales/pt-BR.json @@ -549,6 +549,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "Desconectada", "whatsappAccountAria": "Conta de WhatsApp: {{title}}", + "leftConversation": "Esta conta não faz mais parte desta conversa, então não é possível enviar mensagens aqui.", "awaitingAcceptance": "{{name}} ainda não aceitou. Você poderá escrever assim que aceitar.", "waitingForOlder": "Carregando mensagens anteriores…" }, diff --git a/apps/web/src/locales/zh-CN.json b/apps/web/src/locales/zh-CN.json index 26d9e2ed..f0c178ef 100644 --- a/apps/web/src/locales/zh-CN.json +++ b/apps/web/src/locales/zh-CN.json @@ -525,6 +525,7 @@ "connectionBadgeTitle": "{{identity}} · {{status}}", "accountDisconnected": "已断开", "whatsappAccountAria": "WhatsApp 账号:{{title}}", + "leftConversation": "此账号已不在该会话中,无法在此发送消息。", "awaitingAcceptance": "{{name}} 尚未接受。对方接受后您即可发送消息。", "waitingForOlder": "正在加载更早的消息…" }, diff --git a/apps/web/src/pages/ChatPage.tsx b/apps/web/src/pages/ChatPage.tsx index 0e1ad54d..bdfd7985 100644 --- a/apps/web/src/pages/ChatPage.tsx +++ b/apps/web/src/pages/ChatPage.tsx @@ -464,7 +464,14 @@ export function ChatPage() { isSending={isSending} contactName={threadContact.name} > - {channelConversation?.awaitingAcceptance ? ( + {channelConversation?.leftConversation ? ( +

+ {t("chat.leftConversation")} +

+ ) : channelConversation?.awaitingAcceptance ? ( // No composer at all: a disabled box invites typing a message // that cannot be sent, and says nothing about why.