Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion apps/api/src/channel-spine/application/event-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<TenantDatabase>,
event: Extract<NormalizedChannelEvent, { kind: "participant.remove" }>,
): 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<TenantDatabase>,
event: Extract<NormalizedChannelEvent, { kind: "message.upsert" }>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ const payloadSchemas: Readonly<Record<string, z.ZodType<unknown>>> = {
conversation,
endpoint: endpoint.optional(),
leftAt: timestamp.optional(),
isSelf: z.boolean().optional(),
}),
"message.upsert": z.object({
conversation,
Expand Down
90 changes: 90 additions & 0 deletions apps/api/src/routes/channel-gateway.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
8 changes: 7 additions & 1 deletion apps/api/src/routes/conversations/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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),
});
});

Expand Down
14 changes: 13 additions & 1 deletion apps/api/src/routes/conversations/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/services/channel-outbound.service.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -394,6 +397,7 @@ async function isClaimStillAuthorized(claim: ClaimedIntent): Promise<boolean> {
// 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(
Expand Down
21 changes: 21 additions & 0 deletions apps/api/src/services/conversation-acceptance.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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);
}
5 changes: 5 additions & 0 deletions apps/web/src/lib/api/channel-conversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@
"connectionBadgeTitle": "{{identity}} · {{status}}",
"accountDisconnected": "غير متصل",
"whatsappAccountAria": "حساب WhatsApp: {{title}}",
"leftConversation": "هذا الحساب لم يعد ضمن هذه المحادثة، لذلك لا يمكن إرسال الرسائل هنا.",
"awaitingAcceptance": "لم يقبل {{name}} بعد. يمكنك الكتابة إليه بعد أن يقبل.",
"waitingForOlder": "جارٍ تحميل الرسائل الأقدم…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/ms.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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…"
},
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@
"connectionBadgeTitle": "{{identity}} · {{status}}",
"accountDisconnected": "已断开",
"whatsappAccountAria": "WhatsApp 账号:{{title}}",
"leftConversation": "此账号已不在该会话中,无法在此发送消息。",
"awaitingAcceptance": "{{name}} 尚未接受。对方接受后您即可发送消息。",
"waitingForOlder": "正在加载更早的消息…"
},
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/pages/ChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,14 @@ export function ChatPage() {
isSending={isSending}
contactName={threadContact.name}
>
{channelConversation?.awaitingAcceptance ? (
{channelConversation?.leftConversation ? (
<p
role="status"
className="border-t border-line bg-subtle px-4 py-3 text-center text-sm text-fg-muted"
>
{t("chat.leftConversation")}
</p>
) : channelConversation?.awaitingAcceptance ? (
// No composer at all: a disabled box invites typing a message
// that cannot be sent, and says nothing about why.
<p
Expand Down
7 changes: 7 additions & 0 deletions docs/channel-gateway-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,13 @@ account itself opened, add a `participant.upsert` for the other party
before the message: that is how the application finds the conversation's
customer when there is no inbound sender yet.

When the account itself is no longer in a conversation (it left a group,
was removed, or the group is gone), send `participant.remove` with
`isSelf: true` and the account's own `endpoint`. The application stops
accepting sends there and says why. It ignores the event for a conversation
it does not hold. When the account is back, send `participant.upsert` for
the same endpoint with `participantKind: "account"` and `isSelf: true`.

Every `conversation` reference must carry the conversation's current
`subject`. The application replaces the stored subject with what each event
carries.
Expand Down
7 changes: 7 additions & 0 deletions packages/shared/src/channel-spine/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,13 @@ export interface ParticipantRemoveEventPayload {
endpoint?: ExternalEndpointReference;
workspaceUserId?: string;
leftAt?: string;
/**
* The account itself is no longer in the conversation: it left a group,
* was removed from it, or the group is gone. `endpoint` is the account's
* own identity on the channel. Nothing can be sent until a
* `participant.upsert` for the same endpoint says it is back.
*/
isSelf?: boolean;
}

export interface MessageUpsertEventPayload {
Expand Down