Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor: unify committed message dispatch (#492)

Gustavo Ye76f0de5a0d55
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index f333e2980..95a38d07e 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -28,6 +28,7 @@ export const SPEC_SECONDS = {
"19-marketing-seo.spec.ts": 5,
"20-community-attachment-thumbnails.spec.ts": 60,
"21-mobile-message-layout.spec.ts": 20,
+ "22-committed-message-delivery.spec.ts": 85,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 9c81ff0ce..43998952c 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -37,7 +37,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([136, 136, 140, 140, 141])
+ expect(totals.sort((left, right) => left - right)).toEqual([155, 155, 155, 156, 157])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/community-message-delivery.ts b/src/shared/src/community-message-delivery.ts
new file mode 100644
index 000000000..8c9ba1fc4
--- /dev/null
+++ b/src/shared/src/community-message-delivery.ts
@@ -0,0 +1,158 @@
+import { z } from "zod";
+import {
+ CommunityWsEventSchema,
+ isValidCommunityUserTarget,
+ utf8ByteLength,
+} from "./community-ws-events";
+import type {
+ CommunityChildChannelUpdate,
+ CommunityMessageCreate,
+} from "./community-ws-events";
+
+export const MESSAGE_DELIVERY_MAX_USERS = 1_000;
+export const MESSAGE_DELIVERY_BODY_MAX_BYTES = 837_347;
+export const MESSAGE_DELIVERY_MAX_EVENTS_PER_USER = 5;
+
+export type MessageDeliveryMemberAdded = {
+ userId: string;
+ serverId: string;
+ channelId: string;
+};
+
+export type MessageDeliveryBatch = {
+ messageId: string;
+ messageEvent: CommunityMessageCreate;
+ contentUserIds: string[];
+ unreadPlainUserIds: string[];
+ unreadMentionUserIds: string[];
+ mentionUserIds: string[];
+ memberAdded?: MessageDeliveryMemberAdded;
+ parentProjection?: CommunityChildChannelUpdate;
+ parentProjectionUserIds?: string[];
+};
+
+export type MessageDeliveryPartial = { failedUserIds: string[] };
+
+const target = z.string().refine(isValidCommunityUserTarget);
+const targetList = z.array(target).max(MESSAGE_DELIVERY_MAX_USERS);
+const memberAddedSchema = z.strictObject({
+ userId: target,
+ serverId: z.string().min(1),
+ channelId: z.string().min(1),
+});
+
+const batchShape = z.strictObject({
+ messageId: z.string().min(1),
+ messageEvent: z.unknown(),
+ contentUserIds: targetList,
+ unreadPlainUserIds: targetList,
+ unreadMentionUserIds: targetList,
+ mentionUserIds: targetList,
+ memberAdded: memberAddedSchema.optional(),
+ parentProjection: z.unknown().optional(),
+ parentProjectionUserIds: targetList.optional(),
+});
+
+function hasDuplicates(values: readonly string[]): boolean {
+ return new Set(values).size !== values.length;
+}
+
+function isSubset(values: readonly string[], allowed: ReadonlySet<string>): boolean {
+ return values.every((value) => allowed.has(value));
+}
+
+export type MessageDeliveryBatchParseResult =
+ | { ok: true; batch: MessageDeliveryBatch }
+ | { ok: false; reason: "invalid-payload" | "too-many-targets" | "oversized" };
+
+export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchParseResult {
+ const outer = batchShape.safeParse(value);
+ if (!outer.success) return { ok: false, reason: "invalid-payload" };
+ const data = outer.data;
+ const message = CommunityWsEventSchema.safeParse(data.messageEvent);
+ if (!message.success || message.data.type !== "community:message.create") {
+ return { ok: false, reason: "invalid-payload" };
+ }
+ if (message.data.message.id !== data.messageId) {
+ return { ok: false, reason: "invalid-payload" };
+ }
+
+ let parentProjection: CommunityChildChannelUpdate | undefined;
+ if (data.parentProjection !== undefined) {
+ const parsed = CommunityWsEventSchema.safeParse(data.parentProjection);
+ if (!parsed.success || parsed.data.type !== "community:channel.child_update") {
+ return { ok: false, reason: "invalid-payload" };
+ }
+ parentProjection = parsed.data;
+ }
+ if ((parentProjection === undefined) !== (data.parentProjectionUserIds === undefined)) {
+ return { ok: false, reason: "invalid-payload" };
+ }
+ if (
+ parentProjection
+ && (
+ parentProjection.channelId !== message.data.channelId
+ || message.data.parentChannelId !== parentProjection.parentChannelId
+ )
+ ) {
+ return { ok: false, reason: "invalid-payload" };
+ }
+
+ const lists = [
+ data.contentUserIds,
+ data.unreadPlainUserIds,
+ data.unreadMentionUserIds,
+ data.mentionUserIds,
+ data.parentProjectionUserIds ?? [],
+ ];
+ if (lists.some(hasDuplicates)) return { ok: false, reason: "invalid-payload" };
+ const content = new Set(data.contentUserIds);
+ if (!isSubset(data.unreadPlainUserIds, content)) return { ok: false, reason: "invalid-payload" };
+ if (!isSubset(data.unreadMentionUserIds, content)) return { ok: false, reason: "invalid-payload" };
+ const unreadMention = new Set(data.unreadMentionUserIds);
+ if (data.unreadPlainUserIds.some((id) => unreadMention.has(id))) {
+ return { ok: false, reason: "invalid-payload" };
+ }
+ if (data.memberAdded) {
+ if (
+ !content.has(data.memberAdded.userId)
+ || message.data.serverId === undefined
+ || data.memberAdded.channelId !== message.data.channelId
+ || data.memberAdded.serverId !== message.data.serverId
+ ) {
+ return { ok: false, reason: "invalid-payload" };
+ }
+ }
+
+ const allTargets = new Set(lists.flat());
+ if (allTargets.size > MESSAGE_DELIVERY_MAX_USERS) {
+ return { ok: false, reason: "too-many-targets" };
+ }
+ const encoded = JSON.stringify(value);
+ if (utf8ByteLength(encoded) > MESSAGE_DELIVERY_BODY_MAX_BYTES) {
+ return { ok: false, reason: "oversized" };
+ }
+
+ return {
+ ok: true,
+ batch: {
+ messageId: data.messageId,
+ messageEvent: message.data,
+ contentUserIds: data.contentUserIds,
+ unreadPlainUserIds: data.unreadPlainUserIds,
+ unreadMentionUserIds: data.unreadMentionUserIds,
+ mentionUserIds: data.mentionUserIds,
+ ...(data.memberAdded ? { memberAdded: data.memberAdded } : {}),
+ ...(parentProjection ? { parentProjection } : {}),
+ ...(data.parentProjectionUserIds
+ ? { parentProjectionUserIds: data.parentProjectionUserIds }
+ : {}),
+ },
+ };
+}
+
+export function serializeMessageDeliveryBatch(batch: MessageDeliveryBatch): string {
+ const parsed = parseMessageDeliveryBatch(batch);
+ if (!parsed.ok) throw new Error(`invalid message delivery batch: ${parsed.reason}`);
+ return JSON.stringify(parsed.batch);
+}
diff --git a/src/shared/src/db/queries/community/mention.ts b/src/shared/src/db/queries/community/mention.ts
index 172f1438d..55fedb761 100644
--- a/src/shared/src/db/queries/community/mention.ts
+++ b/src/shared/src/db/queries/community/mention.ts
@@ -37,6 +37,25 @@ export async function createMentions(
return rows;
}
+/**
+ * Return the persisted attention audience for one committed message.
+ *
+ * Both direct mentions and reply attention are included. Delivery planning
+ * deliberately reads this fact back from D1 instead of accepting an
+ * in-memory recipient hint from the route, so deferred dispatch and retries
+ * use the same committed source of truth.
+ */
+export async function listMessageMentionUserIds(
+ db: Database,
+ messageId: string,
+): Promise<string[]> {
+ const rows = await db
+ .select({ userId: communityMention.userId })
+ .from(communityMention)
+ .where(eq(communityMention.messageId, messageId));
+ return [...new Set(rows.map((row) => row.userId))];
+}
+
export async function listUnreadMentions(
db: Database,
userId: string,
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index b2a01d7c7..17952100d 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -220,8 +220,8 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
// folded into `markReadToMessageBuilder`, which is deliberately "humans
// only" — see its comment) because this path must write `lastReadSeq` per
// design §4 — every author (bot or human) must have its own `lastReadSeq`
- // stay in lockstep with its sends, or `enqueueBotWakes` sees a stale
- // watermark. Runs as a separate await because it needs `msg.id`.
+ // stay in lockstep with its sends, or the committed-message planner sees a
+ // stale wake cursor. Runs as a separate await because it needs `msg.id`.
await db
.insert(communityReadState)
.values({
@@ -832,9 +832,7 @@ export async function getMessage(db: Database, messageId: string) {
embeds: communityMessage.embeds,
createdAt: communityMessage.createdAt,
channelId: communityMessage.channelId,
- // Needed by the wake producer's `toAgentMessage(messageRow)` (plan §8) —
- // `enqueueBotWakes` is called from `message-handler.ts` with this exact
- // row, no separate re-fetch.
+ // Needed by committed-message delivery and agent projections.
seq: communityMessage.seq,
authorName: user.name,
authorEmail: user.email,
@@ -848,6 +846,23 @@ export async function getMessage(db: Database, messageId: string) {
return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };
}
+/**
+ * Delivery-only optimistic correlation field. Kept out of the general
+ * `getMessage` projection so unrelated readers cannot accidentally expose a
+ * sender nonce; the committed-message dispatcher is the sole consumer.
+ */
+export async function getMessageClientNonceForDelivery(
+ db: Database,
+ messageId: string,
+): Promise<string | null> {
+ const rows = await db
+ .select({ clientNonce: communityMessage.clientNonce })
+ .from(communityMessage)
+ .where(eq(communityMessage.id, messageId))
+ .limit(1);
+ return rows[0]?.clientNonce ?? null;
+}
+
/**
* Idempotency lookup for the message-send dedup path (mutation-idempotency
* plan). Returns the message this author already committed under `nonce`, or
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 70aa9816e..20fbd894a 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -500,6 +500,21 @@ export {
dispatchOneUnreadWake,
} from "./community/wake-dispatch";
export { parseAttemptedCountReceipt } from "./transport-receipt";
+export { parseStrictFailedSubset } from "./strict-failed-subset";
+export type { StrictFailedSubsetOptions } from "./strict-failed-subset";
+export {
+ MESSAGE_DELIVERY_BODY_MAX_BYTES,
+ MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,
+ MESSAGE_DELIVERY_MAX_USERS,
+ parseMessageDeliveryBatch,
+ serializeMessageDeliveryBatch,
+} from "./community-message-delivery";
+export type {
+ MessageDeliveryBatch,
+ MessageDeliveryBatchParseResult,
+ MessageDeliveryMemberAdded,
+ MessageDeliveryPartial,
+} from "./community-message-delivery";
export type { DispatchOneWakeResult } from "./community/wake-dispatch";
export type { WakePayload, BuildUnreadWakeResult } from "./community/wake-dispatch";
diff --git a/src/shared/src/strict-failed-subset.ts b/src/shared/src/strict-failed-subset.ts
new file mode 100644
index 000000000..b9583ba14
--- /dev/null
+++ b/src/shared/src/strict-failed-subset.ts
@@ -0,0 +1,30 @@
+export type StrictFailedSubsetOptions<T> = {
+ isTarget(value: unknown): value is T;
+ key(target: T): string;
+};
+
+/**
+ * Validate a failure list against the exact targets from the originating
+ * request. Wire-shape validation stays with each transport; this primitive
+ * owns the shared subset and duplicate invariants.
+ */
+export function parseStrictFailedSubset<T>(
+ value: unknown,
+ requested: readonly T[],
+ options: StrictFailedSubsetOptions<T>,
+): T[] | null {
+ if (!Array.isArray(value) || value.length === 0) return null;
+ const allowed = new Set(requested.map(options.key));
+ const seen = new Set<string>();
+ const failed: T[] = [];
+
+ for (const candidate of value) {
+ if (!options.isTarget(candidate)) return null;
+ const key = options.key(candidate);
+ if (!allowed.has(key) || seen.has(key)) return null;
+ seen.add(key);
+ failed.push(candidate);
+ }
+
+ return failed;
+}
diff --git a/src/shared/test/community-message-delivery.test.ts b/src/shared/test/community-message-delivery.test.ts
new file mode 100644
index 000000000..542b7cce9
--- /dev/null
+++ b/src/shared/test/community-message-delivery.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+import { parseMessageDeliveryBatch } from "../src/community-message-delivery";
+
+const messageEvent = {
+ type: "community:message.create" as const,
+ channelId: "thread-1",
+ serverId: "server-1",
+ parentChannelId: "forum-1",
+ message: {
+ id: "message-1",
+ seq: 4,
+ authorId: "u1",
+ authorName: "Alice",
+ content: "hello",
+ type: "chat" as const,
+ createdAt: "2026-08-18T00:00:00.000Z",
+ },
+};
+
+const valid = {
+ messageId: "message-1",
+ messageEvent,
+ contentUserIds: ["u1", "u2"],
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: ["u2"],
+ mentionUserIds: ["u2"],
+ memberAdded: { userId: "u1", serverId: "server-1", channelId: "thread-1" },
+ parentProjection: {
+ type: "community:channel.child_update" as const,
+ parentChannelId: "forum-1",
+ channelId: "thread-1",
+ changes: { messageCount: 4, lastMessageAt: "2026-08-18T00:00:00.000Z" },
+ },
+ parentProjectionUserIds: ["u1", "u2", "u3"],
+};
+
+describe("message delivery batch", () => {
+ it("accepts a strict message-specific batch with separate parent audience", () => {
+ expect(parseMessageDeliveryBatch(valid)).toEqual({ ok: true, batch: valid });
+ });
+
+ it("accepts a thread mention-only nonparticipant", () => {
+ const batch = {
+ ...valid,
+ contentUserIds: ["u1"],
+ unreadMentionUserIds: [],
+ mentionUserIds: ["parent-visible-nonparticipant"],
+ };
+ expect(parseMessageDeliveryBatch(batch).ok).toBe(true);
+ });
+
+ it.each([
+ { ...valid, extra: true },
+ { ...valid, messageId: "other" },
+ { ...valid, contentUserIds: ["u1", "u1"] },
+ { ...valid, unreadPlainUserIds: ["outside"] },
+ { ...valid, unreadPlainUserIds: ["u2"], unreadMentionUserIds: ["u2"] },
+ { ...valid, parentProjectionUserIds: undefined },
+ { ...valid, memberAdded: { ...valid.memberAdded, channelId: "other" } },
+ { ...valid, memberAdded: { ...valid.memberAdded, serverId: "other" } },
+ {
+ ...valid,
+ messageEvent: { ...messageEvent, serverId: undefined, parentChannelId: undefined },
+ memberAdded: { userId: "u1", serverId: "server-1", channelId: "thread-1" },
+ parentProjection: undefined,
+ parentProjectionUserIds: undefined,
+ },
+ ])("rejects an invalid batch", (batch) => {
+ expect(parseMessageDeliveryBatch(batch).ok).toBe(false);
+ });
+});
diff --git a/src/shared/test/queries/community-mention.test.ts b/src/shared/test/queries/community-mention.test.ts
index 59edcd879..ca4a577fd 100644
--- a/src/shared/test/queries/community-mention.test.ts
+++ b/src/shared/test/queries/community-mention.test.ts
@@ -61,6 +61,23 @@ describe("hasMentionForMessage", () => {
});
});
+describe("listMessageMentionUserIds", () => {
+ it("returns one persisted attention target per user across mention kinds", async () => {
+ const chain: any = {};
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([
+ { userId: "u_mention" },
+ { userId: "u_reply" },
+ { userId: "u_mention" },
+ ]));
+ const db = { select: vi.fn(() => chain) };
+ await expect(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ mentionQueries.listMessageMentionUserIds(db as any, "msg_1"),
+ ).resolves.toEqual(["u_mention", "u_reply"]);
+ });
+});
+
describe("markChannelMentionsReadBuilder", () => {
it("returns a builder synchronously and never awaits a select", () => {
const db = createUpdateBuilderMock();
diff --git a/src/shared/test/queries/community-message-embeds.test.ts b/src/shared/test/queries/community-message-embeds.test.ts
index fff7e7985..6a084701a 100644
--- a/src/shared/test/queries/community-message-embeds.test.ts
+++ b/src/shared/test/queries/community-message-embeds.test.ts
@@ -142,6 +142,25 @@ describe("safeParseEmbeds via getMessage", () => {
});
});
+describe("getMessageClientNonceForDelivery", () => {
+ it("keeps optimistic correlation behind a delivery-only projection", async () => {
+ const db = createSelectMock([{ clientNonce: "client-1" }]);
+ await expect(
+ messageQueries.getMessageClientNonceForDelivery(db, "m_1"),
+ ).resolves.toBe("client-1");
+ expect(db.select).toHaveBeenCalledWith({
+ clientNonce: communityMessage.clientNonce,
+ });
+ });
+
+ it("returns null for a missing message", async () => {
+ const db = createSelectMock([]);
+ await expect(
+ messageQueries.getMessageClientNonceForDelivery(db, "missing"),
+ ).resolves.toBeNull();
+ });
+});
+
describe("safeParseEmbeds via getMessagesByIds", () => {
beforeEach(() => warn.mockReset());
diff --git a/src/shared/test/strict-failed-subset.test.ts b/src/shared/test/strict-failed-subset.test.ts
new file mode 100644
index 000000000..cde449a00
--- /dev/null
+++ b/src/shared/test/strict-failed-subset.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { parseStrictFailedSubset } from "../src/strict-failed-subset";
+
+const options = {
+ isTarget: (value: unknown): value is string => typeof value === "string" && value.length > 0,
+ key: (value: string) => value,
+};
+
+describe("parseStrictFailedSubset", () => {
+ it("accepts a unique non-empty requested subset", () => {
+ expect(parseStrictFailedSubset(["u2"], ["u1", "u2"], options)).toEqual(["u2"]);
+ });
+
+ it.each([[], ["u2", "u2"], ["outside"], [1], null])("rejects %j", (value) => {
+ expect(parseStrictFailedSubset(value, ["u1", "u2"], options)).toBeNull();
+ });
+});
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index 2f6a48608..3f00199e1 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -48,8 +48,7 @@ const mockHardDeleteMessage = vi.fn()
const mockRebindPendingAttachmentsToChild = vi.fn()
const mockFanOutToChannel = vi.fn()
-const mockResolveChannelRecipients = vi.fn(async () => [] as string[])
-const mockDispatchMessageNotify = vi.fn(async () => {})
+const mockDispatchCommittedMessage = vi.fn(async () => {})
const mockBroadcastToUser = vi.fn()
const mockCheckMessageRateLimit = vi.fn()
@@ -145,11 +144,10 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
- resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),
}))
-vi.mock("@/lib/community/notify", () => ({
- dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),
+vi.mock("@/lib/community/message-dispatcher", () => ({
+ dispatchCommittedMessage: (...a: unknown[]) => mockDispatchCommittedMessage(...a),
}))
vi.mock("@/lib/broadcast", () => ({
@@ -438,13 +436,9 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(payload.kind).toBe("mention")
expect(payload.userIds.sort()).toEqual(["u2", "u3"])
- // MENTION_CREATE pushes now flow through the level-gated notify pipeline
- // (not raw broadcastToUser). The @everyone expansion is handed to it as the
- // mention set — @everyone counts as a mention (Gener #28), author excluded.
- expect(mockDispatchMessageNotify).toHaveBeenCalledTimes(1)
- const notifyArgs = mockDispatchMessageNotify.mock.calls[0]
- const mentionedUserIds = (notifyArgs[4] as { mentionedUserIds: string[] }).mentionedUserIds
- expect([...mentionedUserIds].sort()).toEqual(["u2", "u3"])
+ // Delivery receives only the committed identity. The dispatcher reads the
+ // mention rows back from D1 and derives policy/audience itself.
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "m1", {})
})
it("resolves @Bob candidate via listMembers (name-projected) when content includes '@'", async () => {
@@ -491,7 +485,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockListMemberUserIds).not.toHaveBeenCalled()
})
- it("fans CHILD_CHANNEL_UPDATE to the parent when POSTing to a thread channel", async () => {
+ it("hands a thread message to the D1-backed dispatcher without route-owned parent fanout", async () => {
// A channel row with a non-null parentChannelId is a thread. Server-side
// detection replaced the client-side branch: the client always POSTs to
// /channels/{id}, and this route must recognize the thread and fan out
@@ -515,14 +509,8 @@ describe("POST /api/community/channels/[id]/messages", () => {
const res = await POST(postReq({ content: "in-thread" }), ctx)
expect(res.status).toBe(201)
- const childUpdateCall = mockFanOutToChannel.mock.calls.find(
- (c) => c[1]?.type === WS_EVENTS.CHILD_CHANNEL_UPDATE,
- )
- expect(childUpdateCall).toBeTruthy()
- expect(childUpdateCall![0]).toBe("c-parent")
- expect(childUpdateCall![1].parentChannelId).toBe("c-parent")
- expect(childUpdateCall![1].channelId).toBe("c1")
- expect(childUpdateCall![1].changes.messageCount).toBe(7)
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "m1", {})
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
it("does NOT fan CHILD_CHANNEL_UPDATE for a top-level channel (regression)", async () => {
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
index d6e4dc258..cc9171ff4 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
@@ -135,4 +135,23 @@ describe("POST /servers/[id]/bots — approval-request rollback failure", () =>
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ status: "pending" })
})
+
+ it("invokes committed delivery only after the approval row exists", async () => {
+ const order: string[] = []
+ const broadcast = vi.fn(async () => { order.push("dispatch") })
+ mockCreateCommunityMessage.mockResolvedValueOnce({
+ ok: true,
+ row: { id: "msg1", content: "card", createdAt: "2026-01-01T00:00:00Z" },
+ broadcast,
+ })
+ mockCreateApprovalRequestStatement.mockImplementationOnce(async () => {
+ order.push("approval")
+ })
+
+ const res = await POST(req({ botId: "bot1" }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(order).toEqual(["approval", "dispatch"])
+ expect(broadcast).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.ts
index 4879e761a..5e479a3ed 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts
@@ -10,7 +10,7 @@ import type { CommunityMemberJoin } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
-import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"
+import { fanOutToServerMembers } from "@/lib/community/fanout"
import { createCommunityMessage } from "@/lib/community/message-handler"
const log = createLogger({ service: "community-bots-server-add" })
@@ -94,20 +94,17 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// "undefined".
const caller = await queries.user.getUserSelf(db, ctx.userId)
const requesterLabel = caller?.name?.trim() || "A friend"
- const botName = target.name || "the bot"
// Unified pipeline, broadcast-deferred: the card must not reach the owner
// until the approval-request row commits (a rollback below would otherwise
- // leave a phantom, unactionable card). `skipMentions`/`skipWake` — a bot DM
- // card mentions no one and wakes no one. The returned `broadcast` thunk is
- // never invoked; this route fires its own minimal `MESSAGE_CREATE` after the
- // approval row persists.
+ // leave a phantom, unactionable card). The bot DM card mentions no one, so
+ // mention persistence is skipped. Its dispatcher thunk is invoked only after the
+ // approval row persists, so no client can observe an unactionable card.
const created = await createCommunityMessage({
db,
authorId: botId,
target: { kind: "dm", channelId: dm.id, otherUserId: ownerId },
body: { content: `${requesterLabel} wants to add me to a server. Approve?` },
skipMentions: true,
- skipWake: true,
deferBroadcast: true,
})
if (!created.ok) return writeError(created.error, created.status)
@@ -147,23 +144,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// the caller-facing shape identical to the idempotent case above.
return writeJSON({ status: "pending" }, 200)
}
-
-
- // Fan-out the DM to the owner so their DM view updates. DMs are channels
- // now — key the MESSAGE_CREATE by the DM's channel id.
- broadcastToUserSafe(ownerId, {
- type: WS_EVENTS.MESSAGE_CREATE,
- channelId: dm.id,
- message: {
- id: msg.id,
- seq: msg.seq,
- authorId: botId,
- authorName: botName,
- content: msg.content,
- type: "chat",
- createdAt: msg.createdAt,
- },
- })
+ await created.broadcast?.()
return writeJSON({ status: "pending" }, 200)
})
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index c50ee2a7a..4b0eff522 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -19,7 +19,15 @@ import {
resetHookMemoization,
} from "./test-harness"
-beforeEach(resetCommunityWsHarness)
+const scheduleGapRepairMock = vi.hoisted(() => vi.fn(() => null))
+vi.mock("@/hooks/community/community-ws/reconnect-messages", () => ({
+ scheduleFocusedMessageGapRepair: (...args: unknown[]) => scheduleGapRepairMock(...args),
+}))
+
+beforeEach(() => {
+ resetCommunityWsHarness()
+ scheduleGapRepairMock.mockClear()
+})
afterEach(cleanupCommunityWsHarness)
function seedParent(serverId: string, parentId: string, type: "forum" | "text") {
@@ -30,6 +38,46 @@ function seedParent(serverId: string, parentId: string, type: "forum" | "text")
}
describe("useCommunityWs — message.create", () => {
+ it("checks a focused channel gap before projecting the incoming overlay row", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_gap" })
+ resetHookMemoization()
+ await mountHook()
+ scheduleGapRepairMock.mockImplementationOnce(() => {
+ expect(getMessageOverlay({ kind: "channel", id: "ch_gap", serverId: "s1" }).liveById.size).toBe(0)
+ return null
+ })
+ const event = messageCreate("ch_gap")
+ event.message.seq = 5
+
+ capturedOnMessage!(event)
+
+ expect(scheduleGapRepairMock).toHaveBeenCalledWith(
+ capturedQueryClient,
+ { kind: "channel", scopeId: "ch_gap", serverId: "s1" },
+ 5,
+ )
+ })
+
+ it("checks a focused DM gap and ignores an unrelated scope", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_gap" })
+ resetHookMemoization()
+ await mountHook()
+ const event = messageCreate("dm_gap")
+ event.message.seq = 8
+
+ capturedOnMessage!(event)
+ capturedOnMessage!(messageCreate("other"))
+
+ expect(scheduleGapRepairMock).toHaveBeenCalledTimes(1)
+ expect(scheduleGapRepairMock).toHaveBeenCalledWith(
+ capturedQueryClient,
+ { kind: "dm", scopeId: "dm_gap" },
+ 8,
+ )
+ })
+
it("patches a loaded forum-sidebar child activity without a refetch", async () => {
await mountHook()
seedParent("srv_1", "forum_1", "forum")
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index c142610c4..885251190 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -31,6 +31,7 @@ import {
} from "@/hooks/community/community-ws/cache"
import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"
import type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"
+import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"
type CommunityMessageEdited = Extract<
CommunityWsEvent,
@@ -52,6 +53,11 @@ export function handleMessageCreate(
if (event.channelId === sub.channelId) {
const serverId = useCommunityStore.getState().currentServerId
if (serverId) {
+ void scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: event.channelId, serverId },
+ event.message.seq,
+ )
useMessageStreamStore.getState().dispatch(
{ kind: "channel", id: event.channelId, serverId },
{ type: "wsMessage", message: projected },
@@ -59,6 +65,11 @@ export function handleMessageCreate(
}
}
if (event.channelId === sub.dmConversationId) {
+ void scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "dm", scopeId: event.channelId },
+ event.message.seq,
+ )
useMessageStreamStore.getState().dispatch(
{ kind: "dm", id: event.channelId },
{ type: "wsMessage", message: projected },
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
index 49c3abe97..e3515c71c 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -6,7 +6,10 @@ import {
} from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { ApiError } from "@/lib/errors"
-import { reconcileFocusedMessageQueries } from "./reconnect-messages"
+import {
+ reconcileFocusedMessageQueries,
+ scheduleFocusedMessageGapRepair,
+} from "./reconnect-messages"
const apiFetchMock = vi.hoisted(() => vi.fn())
@@ -82,6 +85,98 @@ beforeEach(() => {
})
describe("focused message reconnect catch-up", () => {
+ it("does not repair exact-next, duplicate, or out-of-order frames", () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_contiguous")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+
+ expect(scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: "ch_contiguous", serverId: "s1" },
+ 3,
+ )).toBeNull()
+ expect(scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: "ch_contiguous", serverId: "s1" },
+ 2,
+ )).toBeNull()
+ expect(scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: "ch_contiguous", serverId: "s1" },
+ 1,
+ )).toBeNull()
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ unsubscribe()
+ })
+
+ it("coalesces simultaneous gap frames onto one focused catch-up", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_gap")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ latestSeq: 6,
+ hasMore: false,
+ })
+ .mockResolvedValueOnce({
+ messages: [3, 4, 5, 6].map((seq) => ({
+ id: `m_${seq}`,
+ type: "chat",
+ seq,
+ createdAt: `2026-08-15T00:00:0${seq}.000Z`,
+ })),
+ latestSeq: 6,
+ hasMoreNewer: false,
+ })
+
+ const first = scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: "ch_gap", serverId: "s1" },
+ 5,
+ )
+ const second = scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "channel", scopeId: "ch_gap", serverId: "s1" },
+ 6,
+ )
+ expect(first).not.toBeNull()
+ expect(second).toBe(first)
+ await first
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ unsubscribe()
+ })
+
+ it("does not mistake a page latestSeq watermark for a locally cached row", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.dmMessages("dm_gap")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ queryClient.setQueryData<any>(queryKey, (current: any) => ({
+ ...current,
+ pages: current.pages.map((page: any) => ({ ...page, latestSeq: 99 })),
+ }))
+ apiFetchMock.mockResolvedValue({
+ messages: [],
+ latestSeq: 2,
+ hasMore: false,
+ })
+
+ const repair = scheduleFocusedMessageGapRepair(
+ queryClient,
+ { kind: "dm", scopeId: "dm_gap" },
+ 5,
+ )
+ expect(repair).not.toBeNull()
+ await repair
+ expect(apiFetchMock).toHaveBeenCalled()
+ unsubscribe()
+ })
+
it("keeps the painted message cache visible while reconnect reconciliation is in flight", async () => {
const queryClient = new QueryClient()
const queryKey = communityKeys.channelMessages("ch_visible")
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
index 0b168c437..b7caaed98 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -2,7 +2,7 @@ import type { InfiniteData, QueryClient, QueryKey } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
-import { useMessageStreamStore } from "@/stores/community/message-stream"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import type {
MessagesPage,
MessagesPageParam,
@@ -107,6 +107,82 @@ function cachedLatestSeq(cache: MessageCache): number {
), 0)
}
+function cachedMessageRowLatestSeq(cache: MessageCache): number {
+ return cache.pages.reduce((latest, page) => Math.max(
+ latest,
+ ...page.messages.map((message) => message.seq ?? 0),
+ ), 0)
+}
+
+type GapRepairScope = {
+ kind: "channel" | "dm"
+ scopeId: string
+ serverId?: string
+}
+
+const gapRepairs = new WeakMap<QueryClient, Map<string, Promise<void>>>()
+
+function knownFocusedMessageSeq(
+ queryClient: QueryClient,
+ scope: GapRepairScope,
+): number {
+ const queryKey = scope.kind === "channel"
+ ? communityKeys.channelMessages(scope.scopeId)
+ : communityKeys.dmMessages(scope.scopeId)
+ const queries = queryClient.getQueryCache().findAll({ queryKey, type: "active" })
+ let latest = 0
+ for (const query of queries) {
+ if (isMessageCache(query.state.data)) {
+ // `page.latestSeq` is a server watermark, not proof that the row is
+ // present locally. Only concrete cached messages close a sequence gap.
+ latest = Math.max(latest, cachedMessageRowLatestSeq(query.state.data))
+ }
+ }
+ const overlay = scope.kind === "channel"
+ ? getMessageOverlay({
+ kind: "channel",
+ id: scope.scopeId,
+ serverId: scope.serverId ?? "",
+ })
+ : getMessageOverlay({ kind: "dm", id: scope.scopeId })
+ for (const message of overlay.liveById.values()) {
+ latest = Math.max(latest, message.seq ?? 0)
+ }
+ return latest
+}
+
+/**
+ * Detect a missing focused message before the incoming frame is projected.
+ * One repair runs per scope; later gap frames share the in-flight D1 catch-up.
+ */
+export function scheduleFocusedMessageGapRepair(
+ queryClient: QueryClient,
+ scope: GapRepairScope,
+ incomingSeq: number,
+): Promise<void> | null {
+ if (incomingSeq <= knownFocusedMessageSeq(queryClient, scope) + 1) return null
+ let repairs = gapRepairs.get(queryClient)
+ if (!repairs) {
+ repairs = new Map()
+ gapRepairs.set(queryClient, repairs)
+ }
+ const key = `${scope.kind}:${scope.scopeId}`
+ const existing = repairs.get(key)
+ if (existing) return existing
+ const repair = reconcileFocusedMessageQueries(
+ queryClient,
+ scope.kind,
+ scope.scopeId,
+ ).catch(() => {
+ // Realtime delivery is fail-open. A reconnect still runs the same
+ // authoritative reconciliation path if this best-effort repair fails.
+ }).finally(() => {
+ repairs!.delete(key)
+ })
+ repairs.set(key, repair)
+ return repair
+}
+
/**
* Classify an active query as a paint-preserving warm window or a cold query.
*
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index 1dc3ba4b7..06884372f 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -62,11 +62,6 @@ vi.mock("../broadcast", () => ({
broadcastToUsers: (...a: unknown[]) => mockBroadcastToUsers(...a),
}))
-const mockEnqueueBotWakes = vi.fn()
-vi.mock("./wake-producer", () => ({
- enqueueBotWakes: (...a: unknown[]) => mockEnqueueBotWakes(...a),
-}))
-
const mockListMembers = vi.fn()
const mockListMemberUserIds = vi.fn()
const mockGetChannel = vi.fn()
@@ -87,7 +82,6 @@ import {
fanOutToDM,
fanOutStatusUpdate,
broadcastToUserSafe,
- resolveChannelRecipients,
} from "./fanout"
import { WS_EVENTS } from "@alook/shared"
@@ -230,58 +224,6 @@ describe("fanOutToServerMembers", () => {
expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
})
- it("keeps Web type and selected-branch retries as two independently labelled phases", async () => {
- const typeQuery = vi.fn(async () => "text")
- const scopeQuery = vi.fn(async () => ["u1"])
- mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
- await runQuery("channel-type", typeQuery)
- return runQuery("scope-members", scopeQuery)
- })
-
- await expect(resolveChannelRecipients({} as never, "c1")).resolves.toEqual(["u1"])
-
- expect(mockWithD1Retry).toHaveBeenCalledTimes(2)
- expect(mockWithD1Retry.mock.calls.map((call) => call[1])).toEqual([
- { route: "fanout:channel-type" },
- { route: "fanout:scope-members" },
- ])
- expect(typeQuery).toHaveBeenCalledTimes(1)
- expect(scopeQuery).toHaveBeenCalledTimes(1)
- })
-
- it("stops after a type-phase failure without starting the recipient phase", async () => {
- const failure = new Error("bad channel type")
- const scopeQuery = vi.fn(async () => ["u1"])
- mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
- await runQuery("channel-type", async () => { throw failure })
- return runQuery("scope-members", scopeQuery)
- })
-
- await expect(resolveChannelRecipients({} as never, "c1")).rejects.toBe(failure)
- expect(mockWithD1Retry).toHaveBeenCalledTimes(1)
- expect(mockWithD1Retry.mock.calls[0]?.[1]).toEqual({ route: "fanout:channel-type" })
- expect(scopeQuery).not.toHaveBeenCalled()
- })
-
- it("retries only the selected branch without re-reading channel type", async () => {
- const typeQuery = vi.fn(async () => "text")
- const scopeQuery = vi.fn()
- .mockRejectedValueOnce(new Error("SQLITE_BUSY"))
- .mockResolvedValueOnce(["u1"])
- mockWithD1Retry.mockImplementation(async (fn, opts) => {
- if ((opts as { route?: string }).route !== "fanout:scope-members") return fn()
- try { return await fn() } catch { return fn() }
- })
- mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
- await runQuery("channel-type", typeQuery)
- return runQuery("scope-members", scopeQuery)
- })
-
- await expect(resolveChannelRecipients({} as never, "c1")).resolves.toEqual(["u1"])
- expect(typeQuery).toHaveBeenCalledTimes(1)
- expect(scopeQuery).toHaveBeenCalledTimes(2)
- })
-
it("contains no local reach classifier after delegating to shared", () => {
const source = readFileSync(new URL("./fanout.ts", import.meta.url), "utf8")
expect(source).not.toMatch(/\bchannelReach\b|\bisStoredChannelType\b|switch\s*\(\s*reach\s*\)/)
@@ -341,178 +283,6 @@ describe("fanOutStatusUpdate", () => {
})
})
-describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for MESSAGE_CREATE with a wakeMessageRow", () => {
- const wakeMessageRow = {
- id: "msg_1",
- seq: 7,
- authorId: "u1",
- channelId: "c1",
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
- mockBroadcastToUser.mockResolvedValue(undefined)
- mockBroadcastToUsers.mockResolvedValue(undefined)
- mockEnqueueBotWakes.mockResolvedValue(undefined)
- })
-
- it("fanOutToChannel includes the actor in browser fan-out but excludes them from wakes", async () => {
- mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2", "u3"])
-
- await fanOutToChannel(
- "c1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- { excludeWakeUserId: "u1", wakeMessageRow },
- )
-
- expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
- expect(mockEnqueueBotWakes).toHaveBeenCalledWith({
- recipients: ["u2", "u3"],
- channelId: "c1",
- messageRow: wakeMessageRow,
- mentionedUserIds: undefined,
- })
- expect(mockBroadcastToUsers).toHaveBeenCalledWith(
- ["u1", "u2", "u3"],
- expect.objectContaining({ type: WS_EVENTS.MESSAGE_CREATE }),
- )
- })
-
- it("starts wake enqueue before a slow recipient broadcast settles", async () => {
- let releaseBroadcast!: () => void
- mockBroadcastToUsers.mockImplementation(
- () => new Promise<void>((resolve) => {
- releaseBroadcast = resolve
- }),
- )
-
- const pending = fanOutToChannel(
- "c1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- {
- excludeWakeUserId: "u1",
- recipients: ["u1", "u2"],
- wakeMessageRow,
- },
- )
-
- expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
- releaseBroadcast()
- await pending
- })
-
- it("starts wake enqueue even when the bulk hop rejects", async () => {
- mockBroadcastToUsers.mockRejectedValue(new Error("bulk down"))
-
- await expect(fanOutToChannel(
- "c1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- {
- excludeWakeUserId: "u1",
- recipients: ["u1", "u2"],
- wakeMessageRow,
- },
- )).resolves.toBeUndefined()
-
- expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
- expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
- })
-
- it("fire-and-forget fanOut registers its waitUntil before recipient resolution settles", async () => {
- const waitUntil = vi.fn()
- mockGetCloudflareContext.mockImplementation(() => ({
- env: { DB: {} },
- ctx: { waitUntil },
- }))
- let releaseRecipients!: (ids: string[]) => void
- mockResolveChannelRecipientUserIds.mockImplementationOnce(
- () => new Promise<string[]>((resolve) => {
- releaseRecipients = resolve
- }),
- )
-
- const floatingFanout = fanOutToChannel(
- "c1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- {
- excludeWakeUserId: "u1",
- wakeMessageRow,
- },
- )
-
- expect(waitUntil).toHaveBeenCalledTimes(1)
- expect(mockEnqueueBotWakes).not.toHaveBeenCalled()
-
- releaseRecipients(["u1", "u2"])
- await waitUntil.mock.calls[0]![0]
- expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
- await floatingFanout
- })
-
- it("fanOutToDM enqueues wakes with channelId scope via listChannelMemberUserIds", async () => {
- mockGetDM.mockResolvedValue({ id: "dm1" })
- mockListChannelMemberUserIds.mockResolvedValue(["u1", "u2"])
-
- await fanOutToDM(
- "dm1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "dm1", message: {} as never } as never,
- { excludeWakeUserId: "u1", wakeMessageRow: { ...wakeMessageRow, channelId: "dm1" } },
- )
-
- expect(mockListChannelMemberUserIds).toHaveBeenCalledWith(expect.anything(), "dm1")
- expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
- expect(mockEnqueueBotWakes).toHaveBeenCalledWith({
- recipients: ["u2"],
- channelId: "dm1",
- messageRow: { ...wakeMessageRow, channelId: "dm1" },
- mentionedUserIds: undefined,
- })
- })
-
- it("does not enqueue wakes when wakeMessageRow is omitted", async () => {
- mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
-
- await fanOutToChannel("c1", {
- type: WS_EVENTS.MESSAGE_CREATE,
- channelId: "c1",
- message: {} as never,
- } as never)
-
- expect(mockEnqueueBotWakes).not.toHaveBeenCalled()
- })
-
- it("does not enqueue wakes for non-MESSAGE_CREATE events even with a wakeMessageRow", async () => {
- mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
-
- await fanOutToChannel(
- "c1",
- {
- type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
- parentChannelId: "parent1",
- channelId: "c1",
- changes: { messageCount: 1, lastMessageAt: "2026-01-01T00:00:00.000Z" },
- } as never,
- { wakeMessageRow } as never,
- )
-
- expect(mockEnqueueBotWakes).not.toHaveBeenCalled()
- })
-
- it("a failing enqueueBotWakes does not reject fanOutToChannel", async () => {
- mockResolveChannelRecipientUserIds.mockResolvedValue(["u1"])
- mockEnqueueBotWakes.mockRejectedValue(new Error("queue down"))
-
- await expect(
- fanOutToChannel(
- "c1",
- { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
- { wakeMessageRow },
- ),
- ).resolves.toBeUndefined()
- })
-})
-
describe("fanout helpers absorb setup failures", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index a84122ddc..1887b9814 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -17,22 +17,11 @@ import { queries, createLogger, WS_EVENTS, withD1Retry } from "@alook/shared"
import type { CommunityWsEvent, Database } from "@alook/shared"
import { getDb } from "../db"
import { broadcastToUser, broadcastToUsers } from "../broadcast"
-import { enqueueBotWakes, type WakeMessageRow } from "./wake-producer"
const log = createLogger({ service: "community-fanout" })
type BroadcastableEvent = CommunityWsEvent & { type: string }
-/**
- * Passed by `message-handler.ts` alongside a `MESSAGE_CREATE` event so
- * `fanOutToChannel`/`fanOutToDM` can trigger the push-wake pipeline (plan
- * §8) using the SAME recipient list already resolved for the human-WS
- * broadcast, instead of re-querying membership a second time. Omitted (or
- * event.type !== MESSAGE_CREATE) → no wake dispatch, e.g.
- * `CHILD_CHANNEL_UPDATE` never wakes anyone.
- */
-type WakeOpts = { wakeMessageRow?: WakeMessageRow; mentionedUserIds?: string[] }
-
/**
* Resolves all member user IDs for a server.
*/
@@ -72,24 +61,13 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Prom
)
}
-/**
- * Public wrapper so `message-handler` can resolve a channel's recipient set
- * ONCE and share it between the unfiltered `MESSAGE_CREATE` fan-out and the
- * level-filtered notify pipeline (no second membership query). Same split as
- * `getChannelRecipientUserIds` (child thread → participants; dm → access
- * members; channel/forum → scope audience).
- */
-export async function resolveChannelRecipients(db: Database, channelId: string): Promise<string[]> {
- return getChannelRecipientUserIds(db, channelId)
-}
-
/**
* Fan out an event to all members of the server that owns a channel.
*/
export function fanOutToChannel(
channelId: string,
event: BroadcastableEvent,
- opts?: { excludeWakeUserId?: string; recipients?: string[] } & WakeOpts
+ opts?: { recipients?: string[] }
): Promise<void> {
try {
const { env, ctx } = getCloudflareContext()
@@ -100,9 +78,6 @@ export function fanOutToChannel(
// (message-handler shares one set between fan-out and the notify pipeline),
// else resolve here.
const userIds = opts?.recipients ?? await getChannelRecipientUserIds(db, channelId)
- // Register the wake's waitUntil before any human-WS broadcast can stall.
- // A slow best-effort UI fan-out must never delay or drop the bot wake.
- maybeEnqueueWakes(event, userIds, { channelId }, opts)
await broadcastToRecipients(userIds, event)
} catch (err) {
log.warn("fanout_to_channel_failed", {
@@ -135,7 +110,6 @@ export function fanOutToChannel(
export function fanOutToDM(
channelId: string,
event: BroadcastableEvent,
- opts?: { excludeWakeUserId?: string } & WakeOpts
): Promise<void> {
try {
const { env, ctx } = getCloudflareContext()
@@ -148,8 +122,6 @@ export function fanOutToDM(
return
}
const userIds = await queries.communityChannel.listChannelMemberUserIds(db, channelId)
- // Keep wake delivery independent from the best-effort UI broadcast.
- maybeEnqueueWakes(event, userIds, { channelId }, opts)
await broadcastToRecipients(userIds, event)
} catch (err) {
log.warn("fanout_to_dm_failed", {
@@ -171,35 +143,6 @@ export function fanOutToDM(
}
}
-/**
- * Wake dispatch only fires for real new-message events (plan §8) — reactions,
- * edits, pins, `CHILD_CHANNEL_UPDATE`, etc. never wake anyone. The sender is
- * excluded independently from browser fan-out (a bot never wakes itself off
- * its own send, while the author's other browser connections still sync).
- * Never throws — `enqueueBotWakes` owns its own error handling via
- * `ctx.waitUntil`; this is best-effort on top.
- */
-function maybeEnqueueWakes(
- event: BroadcastableEvent,
- recipients: string[],
- scope: { channelId: string },
- opts?: { excludeWakeUserId?: string } & WakeOpts
-): void {
- if (event.type !== WS_EVENTS.MESSAGE_CREATE || !opts?.wakeMessageRow) return
- const filtered = opts.excludeWakeUserId
- ? recipients.filter((id) => id !== opts.excludeWakeUserId)
- : recipients
- enqueueBotWakes({
- recipients: filtered,
- ...scope,
- messageRow: opts.wakeMessageRow,
- mentionedUserIds: opts.mentionedUserIds,
- }).catch((err) => {
- log.warn("enqueue_bot_wakes_from_fanout_failed", { err: String(err) })
- })
-}
-
-
/**
* Resolves the audience for a self-authored profile change: co-members
* (every server the user shares with someone) union friends. Mirrors
diff --git a/src/web/src/lib/community/message-delivery-transport.test.ts b/src/web/src/lib/community/message-delivery-transport.test.ts
new file mode 100644
index 000000000..02c1ebc4b
--- /dev/null
+++ b/src/web/src/lib/community/message-delivery-transport.test.ts
@@ -0,0 +1,268 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ MESSAGE_DELIVERY_BODY_MAX_BYTES,
+ type MessageDeliveryBatch,
+} from "@alook/shared"
+
+const {
+ bindingFetch,
+ broadcastToUsers,
+ logInfo,
+ logWarn,
+ logError,
+} = vi.hoisted(() => ({
+ bindingFetch: vi.fn<(...args: unknown[]) => Promise<Response>>(),
+ broadcastToUsers: vi.fn<(...args: unknown[]) => Promise<void>>(async () => {}),
+ logInfo: vi.fn(),
+ logWarn: vi.fn(),
+ logError: vi.fn(),
+}))
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => ({
+ env: {
+ WS_DO_WORKER: { fetch: bindingFetch },
+ DEV_WS_DO_URL: "http://dev-ws:8789",
+ },
+ ctx: { waitUntil: vi.fn() },
+ }),
+}))
+
+vi.mock("../broadcast", () => ({ broadcastToUsers }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ createLogger: () => ({
+ info: (...args: unknown[]) => logInfo(...args),
+ warn: (...args: unknown[]) => logWarn(...args),
+ error: (...args: unknown[]) => logError(...args),
+ debug: vi.fn(),
+ }),
+ }
+})
+
+import { sendMessageDeliveryBatch } from "./message-delivery-transport"
+
+const originalFetch = globalThis.fetch
+const globalFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
+
+function batch(overrides: Partial<MessageDeliveryBatch> = {}): MessageDeliveryBatch {
+ return {
+ messageId: "message-1",
+ messageEvent: {
+ type: "community:message.create",
+ channelId: "thread-1",
+ serverId: "server-1",
+ parentChannelId: "forum-1",
+ message: {
+ id: "message-1",
+ seq: 4,
+ authorId: "u1",
+ authorName: "Alice",
+ content: "hello",
+ type: "chat",
+ createdAt: "2026-08-18T00:00:00.000Z",
+ },
+ },
+ contentUserIds: ["u1", "u2", "u3"],
+ unreadPlainUserIds: ["u2"],
+ unreadMentionUserIds: ["u3"],
+ mentionUserIds: ["u3"],
+ memberAdded: { userId: "u1", serverId: "server-1", channelId: "thread-1" },
+ parentProjection: {
+ type: "community:channel.child_update",
+ parentChannelId: "forum-1",
+ channelId: "thread-1",
+ changes: { messageCount: 4, lastMessageAt: "2026-08-18T00:00:00.000Z" },
+ },
+ parentProjectionUserIds: ["u1", "parent-only"],
+ ...overrides,
+ }
+}
+
+function requestBatch(callIndex: number): MessageDeliveryBatch {
+ const init = bindingFetch.mock.calls[callIndex]?.[1] as RequestInit
+ return JSON.parse(init.body as string) as MessageDeliveryBatch
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ globalThis.fetch = globalFetch as unknown as typeof fetch
+ bindingFetch.mockImplementation(async () => Response.json({ failedUserIds: [] }))
+})
+
+afterAll(() => {
+ globalThis.fetch = originalFetch
+})
+
+describe("sendMessageDeliveryBatch", () => {
+ it("sends one valid batch when target and byte limits both fit", async () => {
+ await sendMessageDeliveryBatch(batch())
+
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe(
+ "http://internal/broadcast/community/message-delivery",
+ )
+ expect(requestBatch(0)).toEqual(batch())
+ })
+
+ it("chunks 1,000 targets without dropping or duplicating a target", async () => {
+ const ids = Array.from({ length: 1_000 }, (_, index) => `user-${index}`)
+ await sendMessageDeliveryBatch(batch({
+ contentUserIds: ids,
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ memberAdded: undefined,
+ parentProjection: undefined,
+ parentProjectionUserIds: undefined,
+ }))
+
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(requestBatch(0).contentUserIds).toEqual(ids)
+ })
+
+ it("splits fewer than 1,000 targets when repeated escaped ids exceed the byte cap", async () => {
+ const ids = Array.from(
+ { length: 500 },
+ (_, index) => `u${index}-${String.fromCharCode(1).repeat(120)}`,
+ )
+ const oversized = batch({
+ contentUserIds: ids,
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: ids,
+ mentionUserIds: ids,
+ memberAdded: undefined,
+ parentProjectionUserIds: ids,
+ })
+
+ await sendMessageDeliveryBatch(oversized)
+
+ expect(bindingFetch.mock.calls.length).toBeGreaterThan(1)
+ const delivered = bindingFetch.mock.calls.flatMap((_, index) => requestBatch(index).contentUserIds)
+ expect(delivered).toEqual(ids)
+ for (const call of bindingFetch.mock.calls) {
+ const init = call[1] as RequestInit
+ expect(new TextEncoder().encode(init.body as string).byteLength)
+ .toBeLessThanOrEqual(MESSAGE_DELIVERY_BODY_MAX_BYTES)
+ }
+ })
+
+ it("fails closed when even a single-target batch is oversized", async () => {
+ const oversized = batch({
+ messageEvent: {
+ ...batch().messageEvent,
+ message: {
+ ...batch().messageEvent.message,
+ content: "x".repeat(MESSAGE_DELIVERY_BODY_MAX_BYTES),
+ },
+ },
+ contentUserIds: ["u1"],
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ memberAdded: undefined,
+ parentProjection: undefined,
+ parentProjectionUserIds: undefined,
+ })
+
+ await expect(sendMessageDeliveryBatch(oversized)).rejects.toThrow(/oversized/)
+ expect(bindingFetch).not.toHaveBeenCalled()
+ })
+
+ it("accepts an exact 207 subset and retries only failed users", async () => {
+ bindingFetch
+ .mockResolvedValueOnce(Response.json({ failedUserIds: ["u2"] }, { status: 207 }))
+ .mockResolvedValueOnce(Response.json({ failedUserIds: [] }))
+
+ await sendMessageDeliveryBatch(batch())
+
+ expect(bindingFetch).toHaveBeenCalledTimes(2)
+ expect(requestBatch(1)).toMatchObject({
+ contentUserIds: ["u2"],
+ unreadPlainUserIds: ["u2"],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ })
+ expect(requestBatch(1).memberAdded).toBeUndefined()
+ expect(requestBatch(1).parentProjection).toBeUndefined()
+ expect(globalFetch).not.toHaveBeenCalled()
+ expect(broadcastToUsers).not.toHaveBeenCalled()
+ })
+
+ it("stops after the initial attempt plus two failed-only retries", async () => {
+ bindingFetch.mockImplementation(
+ async () => Response.json({ failedUserIds: ["u2"] }, { status: 207 }),
+ )
+
+ await expect(sendMessageDeliveryBatch(batch())).rejects.toThrow(/failed for 1 chunk/)
+ expect(bindingFetch).toHaveBeenCalledTimes(3)
+ expect(requestBatch(1).contentUserIds).toEqual(["u2"])
+ expect(requestBatch(2).contentUserIds).toEqual(["u2"])
+ })
+
+ it.each([
+ { name: "non-JSON", response: () => new Response("nope", { status: 207 }) },
+ { name: "empty subset", response: () => Response.json({ failedUserIds: [] }, { status: 207 }) },
+ { name: "duplicate", response: () => Response.json({ failedUserIds: ["u2", "u2"] }, { status: 207 }) },
+ { name: "outside request", response: () => Response.json({ failedUserIds: ["outside"] }, { status: 207 }) },
+ { name: "extra key", response: () => Response.json({ failedUserIds: ["u2"], extra: true }, { status: 207 }) },
+ ])("fails closed on a malformed 207: $name", async ({ response }) => {
+ bindingFetch.mockResolvedValue(response())
+
+ await expect(sendMessageDeliveryBatch(batch())).rejects.toThrow(/failed for 1 chunk/)
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(globalFetch).not.toHaveBeenCalled()
+ expect(broadcastToUsers).not.toHaveBeenCalled()
+ })
+
+ it.each([404, 405])("uses ordered plan-projected legacy delivery only for %i", async (status) => {
+ bindingFetch.mockResolvedValue(new Response("old worker", { status }))
+
+ await sendMessageDeliveryBatch(batch())
+
+ expect(broadcastToUsers.mock.calls.map((call) =>
+ (call[1] as { type: string }).type,
+ )).toEqual([
+ "community:message.create",
+ "community:unread.bump",
+ "community:unread.bump",
+ "community:mention.create",
+ "community:channel.member_add",
+ "community:channel.child_update",
+ ])
+ expect((broadcastToUsers.mock.calls[1]?.[1] as { userId: string }).userId).toBe("u2")
+ expect((broadcastToUsers.mock.calls[2]?.[1] as { userId: string }).userId).toBe("u3")
+ expect((broadcastToUsers.mock.calls[3]?.[1] as { userId: string }).userId).toBe("u3")
+ expect(logWarn).toHaveBeenCalledWith(
+ "message_delivery_legacy_compat",
+ expect.objectContaining({ messageId: "message-1", status, targetCount: 4 }),
+ )
+ expect(globalFetch).not.toHaveBeenCalled()
+ })
+
+ it("does not enter legacy mode after a binding 5xx or throw", async () => {
+ bindingFetch.mockResolvedValueOnce(new Response("unavailable", { status: 503 }))
+ globalFetch.mockResolvedValueOnce(Response.json({ failedUserIds: [] }))
+ await sendMessageDeliveryBatch(batch())
+
+ bindingFetch.mockRejectedValueOnce(new Error("binding unavailable"))
+ globalFetch.mockResolvedValueOnce(Response.json({ failedUserIds: [] }))
+ await sendMessageDeliveryBatch(batch())
+
+ expect(broadcastToUsers).not.toHaveBeenCalled()
+ expect(logWarn).not.toHaveBeenCalledWith(
+ "message_delivery_legacy_compat",
+ expect.anything(),
+ )
+ })
+
+ it("does not enter legacy mode for an invalid successful response", async () => {
+ bindingFetch.mockResolvedValue(new Response("not json", { status: 200 }))
+
+ await expect(sendMessageDeliveryBatch(batch())).rejects.toThrow(/failed for 1 chunk/)
+ expect(broadcastToUsers).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/message-delivery-transport.ts b/src/web/src/lib/community/message-delivery-transport.ts
new file mode 100644
index 000000000..fcef06df1
--- /dev/null
+++ b/src/web/src/lib/community/message-delivery-transport.ts
@@ -0,0 +1,251 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import {
+ DEV_WS_DO_URL,
+ MESSAGE_DELIVERY_MAX_USERS,
+ createLogger,
+ isValidCommunityUserTarget,
+ parseStrictFailedSubset,
+ serializeMessageDeliveryBatch,
+ type MessageDeliveryBatch,
+} from "@alook/shared"
+import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"
+import { broadcastToUsers } from "../broadcast"
+
+const log = createLogger({ service: "message-delivery-transport" })
+const maxAttempts = 3
+const maxActiveChunks = 3
+
+function allTargetUserIds(batch: MessageDeliveryBatch): string[] {
+ return [...new Set([
+ ...batch.contentUserIds,
+ ...batch.unreadPlainUserIds,
+ ...batch.unreadMentionUserIds,
+ ...batch.mentionUserIds,
+ ...(batch.memberAdded ? [batch.memberAdded.userId] : []),
+ ...(batch.parentProjectionUserIds ?? []),
+ ])]
+}
+
+function selectTargets(batch: MessageDeliveryBatch, selected: ReadonlySet<string>): MessageDeliveryBatch {
+ const keep = (ids: readonly string[]) => ids.filter((id) => selected.has(id))
+ const parentProjectionUserIds = keep(batch.parentProjectionUserIds ?? [])
+ return {
+ messageId: batch.messageId,
+ messageEvent: batch.messageEvent,
+ contentUserIds: keep(batch.contentUserIds),
+ unreadPlainUserIds: keep(batch.unreadPlainUserIds),
+ unreadMentionUserIds: keep(batch.unreadMentionUserIds),
+ mentionUserIds: keep(batch.mentionUserIds),
+ ...(batch.memberAdded && selected.has(batch.memberAdded.userId)
+ ? { memberAdded: batch.memberAdded }
+ : {}),
+ ...(batch.parentProjection && parentProjectionUserIds.length > 0
+ ? { parentProjection: batch.parentProjection, parentProjectionUserIds }
+ : {}),
+ }
+}
+
+function parseFailedUserIds(value: unknown, requested: readonly string[]): string[] | null {
+ if (
+ typeof value !== "object"
+ || value === null
+ || Array.isArray(value)
+ || Object.keys(value).length !== 1
+ || !Object.prototype.hasOwnProperty.call(value, "failedUserIds")
+ ) return null
+ return parseStrictFailedSubset(
+ (value as { failedUserIds?: unknown }).failedUserIds,
+ requested,
+ {
+ isTarget: isValidCommunityUserTarget,
+ key: (target) => target,
+ },
+ )
+}
+
+async function sendAttempt(env: Env, batch: MessageDeliveryBatch): Promise<string[]> {
+ const requested = allTargetUserIds(batch)
+ const response = await fetchViaBindingOrDevFallback(
+ env.WS_DO_WORKER,
+ env.DEV_WS_DO_URL || DEV_WS_DO_URL,
+ "/broadcast/community/message-delivery",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: serializeMessageDeliveryBatch(batch),
+ },
+ { logPrefix: "message_delivery", log, label: batch.messageId },
+ )
+ if (response.status === 404 || response.status === 405) {
+ log.warn("message_delivery_legacy_compat", {
+ messageId: batch.messageId,
+ status: response.status,
+ targetCount: requested.length,
+ contentCount: batch.contentUserIds.length,
+ unreadCount: batch.unreadPlainUserIds.length + batch.unreadMentionUserIds.length,
+ mentionCount: batch.mentionUserIds.length,
+ memberCount: batch.memberAdded ? 1 : 0,
+ parentCount: batch.parentProjectionUserIds?.length ?? 0,
+ })
+ await deliverWithLegacyCommunityBroadcast(batch)
+ return []
+ }
+ let body: unknown
+ try {
+ body = await response.json()
+ } catch {
+ throw new Error("message delivery: invalid response")
+ }
+ if (response.status === 200) {
+ if (
+ typeof body !== "object"
+ || body === null
+ || Array.isArray(body)
+ || Object.keys(body).length !== 1
+ || !Array.isArray((body as { failedUserIds?: unknown }).failedUserIds)
+ || (body as { failedUserIds: unknown[] }).failedUserIds.length !== 0
+ ) throw new Error("message delivery: invalid success response")
+ return []
+ }
+ if (response.status !== 207) {
+ throw new Error(`message delivery: ws-do responded ${response.status}`)
+ }
+ const failed = parseFailedUserIds(body, requested)
+ if (!failed) throw new Error("message delivery: invalid partial response")
+ return failed
+}
+
+async function deliverWithLegacyCommunityBroadcast(batch: MessageDeliveryBatch): Promise<void> {
+ const message = batch.messageEvent
+ if (batch.contentUserIds.length > 0) {
+ await broadcastToUsers(batch.contentUserIds, message)
+ }
+ await settleLegacyTargets(batch.unreadPlainUserIds, (userId) =>
+ broadcastToUsers([userId], {
+ type: "community:unread.bump",
+ userId,
+ channelId: message.channelId,
+ ...(message.serverId ? { serverId: message.serverId } : {}),
+ ...(message.serverId
+ ? { railChannelId: message.parentChannelId ?? message.channelId }
+ : {}),
+ isMention: false,
+ }),
+ )
+ await settleLegacyTargets(batch.unreadMentionUserIds, (userId) =>
+ broadcastToUsers([userId], {
+ type: "community:unread.bump",
+ userId,
+ channelId: message.channelId,
+ ...(message.serverId ? { serverId: message.serverId } : {}),
+ ...(message.serverId
+ ? { railChannelId: message.parentChannelId ?? message.channelId }
+ : {}),
+ isMention: true,
+ }),
+ )
+ await settleLegacyTargets(batch.mentionUserIds, (userId) =>
+ broadcastToUsers([userId], {
+ type: "community:mention.create",
+ userId,
+ messageId: batch.messageId,
+ channelId: message.channelId,
+ authorName: message.message.authorName,
+ }),
+ )
+ if (batch.memberAdded) {
+ await broadcastToUsers([batch.memberAdded.userId], {
+ type: "community:channel.member_add",
+ ...batch.memberAdded,
+ })
+ }
+ if (batch.parentProjection && batch.parentProjectionUserIds?.length) {
+ await broadcastToUsers(batch.parentProjectionUserIds, batch.parentProjection)
+ }
+}
+
+async function settleLegacyTargets(
+ userIds: readonly string[],
+ send: (userId: string) => Promise<void>,
+): Promise<void> {
+ let next = 0
+ const workers = Array.from({ length: Math.min(maxActiveChunks, userIds.length) }, async () => {
+ while (next < userIds.length) await send(userIds[next++]!)
+ })
+ await Promise.all(workers)
+}
+
+async function sendChunk(env: Env, initial: MessageDeliveryBatch): Promise<void> {
+ let pending = initial
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ const startedAt = Date.now()
+ const failed = await sendAttempt(env, pending)
+ log.info("message_delivery_attempt_complete", {
+ messageId: initial.messageId,
+ attempt,
+ targetCount: allTargetUserIds(pending).length,
+ failedCount: failed.length,
+ durationMs: Date.now() - startedAt,
+ })
+ if (failed.length === 0) return
+ if (attempt === maxAttempts) {
+ throw new Error(`message delivery exhausted for ${failed.length} user(s)`)
+ }
+ pending = selectTargets(initial, new Set(failed))
+ }
+}
+
+async function settleChunks(env: Env, chunks: MessageDeliveryBatch[]): Promise<void> {
+ let next = 0
+ const results: PromiseSettledResult<void>[] = new Array(chunks.length)
+ const workers = Array.from({ length: Math.min(maxActiveChunks, chunks.length) }, async () => {
+ while (next < chunks.length) {
+ const index = next++
+ try {
+ await sendChunk(env, chunks[index]!)
+ results[index] = { status: "fulfilled", value: undefined }
+ } catch (reason) {
+ results[index] = { status: "rejected", reason }
+ }
+ }
+ })
+ await Promise.all(workers)
+ const failures = results.filter((result) => result.status === "rejected")
+ if (failures.length > 0) {
+ throw new Error(`message delivery failed for ${failures.length} chunk(s)`)
+ }
+}
+
+export async function sendMessageDeliveryBatch(batch: MessageDeliveryBatch): Promise<void> {
+ const { env } = getCloudflareContext()
+ const targets = allTargetUserIds(batch)
+ const chunks: MessageDeliveryBatch[] = []
+ let index = 0
+ while (index < targets.length) {
+ const maxEnd = Math.min(index + MESSAGE_DELIVERY_MAX_USERS, targets.length)
+ let low = index + 1
+ let high = maxEnd
+ let accepted: MessageDeliveryBatch | null = null
+ let acceptedEnd = index
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2)
+ const candidate = selectTargets(batch, new Set(targets.slice(index, middle)))
+ try {
+ serializeMessageDeliveryBatch(candidate)
+ accepted = candidate
+ acceptedEnd = middle
+ low = middle + 1
+ } catch {
+ high = middle - 1
+ }
+ }
+ if (!accepted) {
+ const single = selectTargets(batch, new Set([targets[index]!]))
+ serializeMessageDeliveryBatch(single)
+ throw new Error("message delivery: unable to form chunk")
+ }
+ chunks.push(accepted)
+ index = acceptedEnd
+ }
+ await settleChunks(env as Env, chunks)
+}
diff --git a/src/web/src/lib/community/message-dispatcher-architecture.test.ts b/src/web/src/lib/community/message-dispatcher-architecture.test.ts
new file mode 100644
index 000000000..a7424a6a4
--- /dev/null
+++ b/src/web/src/lib/community/message-dispatcher-architecture.test.ts
@@ -0,0 +1,33 @@
+import { existsSync, readFileSync } from "node:fs"
+import { describe, expect, it } from "vitest"
+
+function source(name: string): string {
+ return readFileSync(new URL(name, import.meta.url), "utf8")
+}
+
+describe("committed-message delivery architecture", () => {
+ it("keeps the message handler as a persistence-to-dispatch seam", () => {
+ const handler = source("./message-handler.ts")
+ expect(handler).toContain("dispatchCommittedMessage(db, row.id")
+ expect(handler).not.toMatch(
+ /dispatchMessageNotify|resolveChannelRecipients|wakeMessageRow|enqueueBotWakes/,
+ )
+ expect(handler).not.toMatch(/type:\s*WS_EVENTS\.MESSAGE_CREATE/)
+ })
+
+ it("removes message wake policy from generic fanout", () => {
+ const fanout = source("./fanout.ts")
+ expect(fanout).not.toMatch(/wake-producer|wakeMessageRow|excludeWakeUserId|maybeEnqueueWakes/)
+ })
+
+ it("leaves wake-producer as payload transport rather than a second planner", () => {
+ const producer = source("./wake-producer.ts")
+ expect(producer).toContain("enqueueBotWakePayloads")
+ expect(producer).not.toMatch(/\bqueries\b|findWakeCandidates|resolveNotificationEligibility/)
+ })
+
+ it("deletes the old per-recipient notify implementation", () => {
+ expect(existsSync(new URL("./notify.ts", import.meta.url))).toBe(false)
+ expect(existsSync(new URL("./notify.test.ts", import.meta.url))).toBe(false)
+ })
+})
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
new file mode 100644
index 000000000..76ae7711d
--- /dev/null
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -0,0 +1,384 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mockWaitUntil = vi.fn()
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => ({ ctx: { waitUntil: mockWaitUntil } }),
+}))
+
+const mockGetMessage = vi.fn()
+const mockGetMessageInScope = vi.fn()
+const mockGetMessageClientNonceForDelivery = vi.fn()
+const mockGetChannel = vi.fn()
+const mockListAttention = vi.fn()
+const mockListAttachments = vi.fn()
+const mockResolveRecipients = vi.fn()
+const mockResolveEligibility = vi.fn()
+const mockFindWakeCandidates = vi.fn()
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ withD1Retry: (run: () => Promise<unknown>) => run(),
+ queries: {
+ communityMessage: {
+ getMessage: (...args: unknown[]) => mockGetMessage(...args),
+ getMessageInScope: (...args: unknown[]) => mockGetMessageInScope(...args),
+ getMessageClientNonceForDelivery: (...args: unknown[]) =>
+ mockGetMessageClientNonceForDelivery(...args),
+ },
+ communityChannel: {
+ getChannel: (...args: unknown[]) => mockGetChannel(...args),
+ },
+ communityMention: {
+ listMessageMentionUserIds: (...args: unknown[]) => mockListAttention(...args),
+ },
+ communityAttachment: {
+ listMessageAttachments: (...args: unknown[]) => mockListAttachments(...args),
+ },
+ communityMembersResolver: {
+ resolveChannelRecipientUserIds: (...args: unknown[]) => mockResolveRecipients(...args),
+ },
+ communityNotificationEligibility: {
+ resolveNotificationEligibilityForUsers: (...args: unknown[]) => mockResolveEligibility(...args),
+ },
+ communityNotificationSetting: {
+ policyAllows: actual.queries.communityNotificationSetting.policyAllows,
+ },
+ communityBot: {
+ findWakeCandidates: (...args: unknown[]) => mockFindWakeCandidates(...args),
+ },
+ },
+ }
+})
+
+const mockSendMessageDeliveryBatch = vi.fn()
+vi.mock("./message-delivery-transport", () => ({
+ sendMessageDeliveryBatch: (...args: unknown[]) => mockSendMessageDeliveryBatch(...args),
+}))
+const mockEnqueueBotWakePayloads = vi.fn()
+vi.mock("./wake-producer", () => ({
+ enqueueBotWakePayloads: (...args: unknown[]) => mockEnqueueBotWakePayloads(...args),
+}))
+
+import { dispatchCommittedMessage, planCommittedMessage } from "./message-dispatcher"
+
+const message = {
+ id: "msg_1",
+ authorId: "author_1",
+ authorName: "Author",
+ authorEmail: "[email protected]",
+ authorImage: null,
+ content: "hello",
+ type: "default",
+ mentionType: null,
+ replyToId: null,
+ embeds: null,
+ createdAt: "2026-08-18T00:00:00.000Z",
+ channelId: "c1",
+ clientNonce: "nonce_1",
+ seq: 7,
+}
+
+const channel = {
+ id: "c1",
+ serverId: "s1",
+ categoryId: null,
+ name: "general",
+ type: "text",
+ topic: "",
+ position: 0,
+ parentChannelId: null,
+ creatorId: "author_1",
+ messageCount: 7,
+ archived: false,
+ parentMessageId: null,
+ lastMessageAt: "2026-08-18T00:00:00.000Z",
+ createdAt: "2026-08-01T00:00:00.000Z",
+}
+
+function state(overrides: Partial<{
+ currentLevel: "all" | "mentions" | "nothing"
+ hasAttention: boolean
+ isUnread: boolean
+ isReadable: boolean
+}> = {}) {
+ return {
+ currentLevel: "all" as const,
+ hasAttention: false,
+ isUnread: true,
+ isReadable: true,
+ ...overrides,
+ }
+}
+
+describe("planCommittedMessage", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMessage.mockResolvedValue(message)
+ mockGetMessageInScope.mockResolvedValue(null)
+ mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")
+ mockGetChannel.mockResolvedValue(channel)
+ mockListAttachments.mockResolvedValue([])
+ mockListAttention.mockResolvedValue(["u_mentions", "u_mention_only", "bot_1"])
+ mockResolveRecipients.mockImplementation(async (_db, channelId: string) =>
+ channelId === "c1"
+ ? ["author_1", "u_all", "u_mentions", "bot_1"]
+ : [],
+ )
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["author_1", state()],
+ ["u_all", state()],
+ ["u_mentions", state({ currentLevel: "mentions", hasAttention: true })],
+ ["u_mention_only", state({ currentLevel: "mentions", hasAttention: true })],
+ ["bot_1", state({ hasAttention: true })],
+ ]))
+ mockFindWakeCandidates.mockResolvedValue([
+ { botUserId: "bot_1", name: "Bot", machineId: "m1", runtime: "codex" },
+ ])
+ mockSendMessageDeliveryBatch.mockResolvedValue(undefined)
+ mockEnqueueBotWakePayloads.mockResolvedValue(undefined)
+ })
+
+ it("derives content, notification, mention, and bot targets from one D1 plan", async () => {
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1", "u_all", "u_mentions", "bot_1"])
+ expect(plan.unreadPlainUserIds).toEqual(["u_all"])
+ expect(plan.unreadMentionUserIds).toEqual(["u_mentions", "bot_1"])
+ expect(plan.mentionUserIds).toEqual(["u_mentions", "u_mention_only", "bot_1"])
+ expect(plan.wakeBotUserIds).toEqual(["bot_1"])
+ expect(plan.messageEvent).toMatchObject({
+ type: "community:message.create",
+ channelId: "c1",
+ serverId: "s1",
+ message: { id: "msg_1", seq: 7, clientNonce: "nonce_1" },
+ })
+ expect(mockResolveEligibility).toHaveBeenCalledWith(
+ {},
+ ["author_1", "u_all", "u_mentions", "bot_1", "u_mention_only"],
+ "msg_1",
+ )
+ expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, {
+ recipients: ["u_all", "u_mentions", "bot_1"],
+ channelId: "c1",
+ newSeq: 7,
+ })
+ })
+
+ it("rehydrates attachment dimensions and reply preview from committed rows", async () => {
+ mockGetMessage.mockResolvedValue({ ...message, replyToId: "reply_1" })
+ mockGetMessageInScope.mockResolvedValue({
+ id: "reply_1",
+ authorName: "Earlier",
+ content: "previous message",
+ })
+ mockListAttachments.mockResolvedValue([{
+ id: "att_1",
+ targetId: "c1",
+ filename: "photo.png",
+ thumbnailR2Key: "thumb",
+ contentType: "image/png",
+ size: 1000,
+ width: 1920,
+ height: 1080,
+ }])
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.messageEvent.message.replyTo).toMatchObject({
+ id: "reply_1",
+ authorName: "Earlier",
+ text: "previous message",
+ })
+ expect(plan.messageEvent.message.attachments).toEqual([
+ expect.objectContaining({
+ id: "att_1",
+ width: 1920,
+ height: 1080,
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
+ }),
+ ])
+ })
+
+ it("keeps forum-thread participants, mention-only attention, and parent access distinct", async () => {
+ mockGetMessage.mockResolvedValue({ ...message, channelId: "t1" })
+ mockGetChannel.mockResolvedValue({
+ ...channel,
+ id: "t1",
+ type: "thread",
+ parentChannelId: "forum_1",
+ messageCount: 3,
+ })
+ mockListAttention.mockResolvedValue(["parent_viewer"])
+ mockResolveRecipients.mockImplementation(async (_db, channelId: string) => {
+ if (channelId === "t1") return ["author_1", "participant_1"]
+ if (channelId === "forum_1") return ["participant_1", "parent_viewer"]
+ return []
+ })
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["participant_1", state()],
+ ["author_1", state()],
+ ["parent_viewer", state({ hasAttention: true })],
+ ]))
+ mockFindWakeCandidates.mockResolvedValue([])
+
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1", "participant_1"])
+ expect(plan.mentionUserIds).toEqual(["parent_viewer"])
+ expect(plan.parentProjectionUserIds).toEqual(["participant_1", "parent_viewer"])
+ expect(plan.parentProjection).toMatchObject({
+ parentChannelId: "forum_1",
+ channelId: "t1",
+ changes: { messageCount: 3 },
+ })
+ })
+
+ it("uses the resolved access snapshot for a private server channel", async () => {
+ mockResolveRecipients.mockResolvedValue(["author_1", "private_member"])
+ mockListAttention.mockResolvedValue([])
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["author_1", state()],
+ ["private_member", state()],
+ ]))
+ mockFindWakeCandidates.mockResolvedValue([])
+
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1", "private_member"])
+ expect(plan.unreadPlainUserIds).toEqual(["private_member"])
+ })
+
+ it("plans a DM from its two resolved members without server projections", async () => {
+ mockGetChannel.mockResolvedValue({
+ ...channel,
+ serverId: null,
+ type: "dm",
+ parentChannelId: null,
+ })
+ mockResolveRecipients.mockResolvedValue(["author_1", "dm_peer"])
+ mockListAttention.mockResolvedValue([])
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["author_1", state()],
+ ["dm_peer", state()],
+ ]))
+ mockFindWakeCandidates.mockResolvedValue([])
+
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1", "dm_peer"])
+ expect(plan.messageEvent).not.toHaveProperty("serverId")
+ expect(plan).not.toHaveProperty("parentProjection")
+ })
+
+ it("keeps the author in content while excluding them from every side effect", async () => {
+ mockListAttention.mockResolvedValue(["author_1"])
+ mockResolveRecipients.mockResolvedValue(["author_1"])
+ mockResolveEligibility.mockResolvedValue(new Map([["author_1", state({ hasAttention: true })]]))
+ mockFindWakeCandidates.mockResolvedValue([
+ { botUserId: "author_1", name: "Author Bot", machineId: "m1", runtime: "codex" },
+ ])
+
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1"])
+ expect(plan.unreadPlainUserIds).toEqual([])
+ expect(plan.unreadMentionUserIds).toEqual([])
+ expect(plan.mentionUserIds).toEqual([])
+ expect(plan.wakeBotUserIds).toEqual([])
+ expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, {
+ recipients: [],
+ channelId: "c1",
+ newSeq: 7,
+ })
+ })
+
+ it("produces an empty plan when the committed scope currently has no readable audience", async () => {
+ mockResolveRecipients.mockResolvedValue([])
+ mockListAttention.mockResolvedValue([])
+ mockResolveEligibility.mockResolvedValue(new Map())
+ mockFindWakeCandidates.mockResolvedValue([])
+
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual([])
+ expect(plan.unreadPlainUserIds).toEqual([])
+ expect(plan.unreadMentionUserIds).toEqual([])
+ expect(plan.mentionUserIds).toEqual([])
+ expect(plan.wakeBotUserIds).toEqual([])
+ })
+
+ it("filters muted, caught-up, and unread-ineligible users consistently", async () => {
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["author_1", state()],
+ ["u_all", state({ currentLevel: "nothing" })],
+ ["u_mentions", state({ currentLevel: "mentions", hasAttention: false })],
+ ["u_mention_only", state({ hasAttention: true, isUnread: false })],
+ ["bot_1", state({ isReadable: false })],
+ ]))
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.unreadPlainUserIds).toEqual([])
+ expect(plan.unreadMentionUserIds).toEqual([])
+ expect(plan.mentionUserIds).toEqual([])
+ expect(plan.wakeBotUserIds).toEqual([])
+ })
+
+ it("accepts only an in-scope structural participant outcome", async () => {
+ const plan = await planCommittedMessage(
+ {} as never,
+ "msg_1",
+ { memberAddedUserId: "u_all" },
+ )
+ expect(plan.memberAdded).toEqual({ userId: "u_all", serverId: "s1", channelId: "c1" })
+ await expect(planCommittedMessage(
+ {} as never,
+ "msg_1",
+ { memberAddedUserId: "outside" },
+ )).rejects.toThrow("outside message scope")
+ })
+
+ it("removes a stale participant that no longer has readable access", async () => {
+ mockResolveEligibility.mockResolvedValue(new Map([
+ ["author_1", state()],
+ ["u_all", state({ isReadable: false })],
+ ["u_mentions", state({ hasAttention: true })],
+ ["u_mention_only", state({ hasAttention: true })],
+ ["bot_1", state({ isReadable: false })],
+ ]))
+ const plan = await planCommittedMessage({} as never, "msg_1")
+ expect(plan.contentUserIds).toEqual(["author_1", "u_mentions"])
+ expect(plan.wakeBotUserIds).toEqual([])
+ })
+
+ it("is stable when rerun from the same committed facts", async () => {
+ const first = await planCommittedMessage({} as never, "msg_1")
+ const second = await planCommittedMessage({} as never, "msg_1")
+ expect(second).toEqual(first)
+ })
+})
+
+describe("dispatchCommittedMessage", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMessage.mockResolvedValue(message)
+ mockGetChannel.mockResolvedValue(channel)
+ mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")
+ mockListAttachments.mockResolvedValue([])
+ mockListAttention.mockResolvedValue([])
+ mockResolveRecipients.mockResolvedValue(["author_1"])
+ mockResolveEligibility.mockResolvedValue(new Map())
+ mockFindWakeCandidates.mockResolvedValue([])
+ mockSendMessageDeliveryBatch.mockResolvedValue(undefined)
+ mockEnqueueBotWakePayloads.mockResolvedValue(undefined)
+ })
+
+ it("registers one fail-open dispatch and sends browser plus wake plans", async () => {
+ const work = dispatchCommittedMessage({} as never, "msg_1")
+ expect(mockWaitUntil).toHaveBeenCalledWith(work)
+ await expect(work).resolves.toBeUndefined()
+ expect(mockSendMessageDeliveryBatch).toHaveBeenCalledTimes(1)
+ expect(mockEnqueueBotWakePayloads).toHaveBeenCalledWith([])
+ })
+
+ it("does not reject the committed mutation when planning or transport fails", async () => {
+ mockGetMessage.mockRejectedValueOnce(new Error("D1 unavailable"))
+ await expect(dispatchCommittedMessage({} as never, "msg_1")).resolves.toBeUndefined()
+
+ mockGetMessage.mockResolvedValue(message)
+ mockSendMessageDeliveryBatch.mockRejectedValueOnce(new Error("ws unavailable"))
+ await expect(dispatchCommittedMessage({} as never, "msg_1")).resolves.toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
new file mode 100644
index 000000000..b444cadaf
--- /dev/null
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -0,0 +1,298 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import {
+ WS_EVENTS,
+ createLogger,
+ queries,
+ withD1Retry,
+ type CommunityMessageCreate,
+ type Database,
+ type MessageDeliveryBatch,
+ type WakePayload,
+} from "@alook/shared"
+import { mapMessageForWs } from "./message-payload"
+import { sendMessageDeliveryBatch } from "./message-delivery-transport"
+import { enqueueBotWakePayloads } from "./wake-producer"
+import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
+
+const log = createLogger({ service: "committed-message-dispatcher" })
+
+export type CommittedMessageStructuralOutcome = {
+ /** A participant row inserted by this exact message write. */
+ memberAddedUserId?: string
+ /** Existing thread-open collision suppression; no audience/policy input. */
+ suppressParentProjection?: boolean
+}
+
+export type MessageDeliveryPlan = MessageDeliveryBatch & {
+ wakeBotUserIds: string[]
+}
+
+const recipientRetryRoute = {
+ "channel-type": "message-dispatcher:channel-type",
+ "thread-participants": "message-dispatcher:thread-participants",
+ "dm-members": "message-dispatcher:dm-members",
+ "scope-members": "message-dispatcher:scope-members",
+} as const
+
+async function resolveRecipients(db: Database, channelId: string): Promise<string[]> {
+ return queries.communityMembersResolver.resolveChannelRecipientUserIds(
+ db,
+ channelId,
+ (phase, query) => withD1Retry(query, { route: recipientRetryRoute[phase] }),
+ )
+}
+
+function unique(values: readonly string[]): string[] {
+ return [...new Set(values)]
+}
+
+export async function planCommittedMessage(
+ db: Database,
+ messageId: string,
+ structural: CommittedMessageStructuralOutcome = {},
+): Promise<MessageDeliveryPlan> {
+ const message = await withD1Retry(
+ () => queries.communityMessage.getMessage(db, messageId),
+ { route: "message-dispatcher:message" },
+ )
+ if (!message) throw new Error("committed message not found")
+ const [channel, attentionUserIds, attachments, clientNonce] = await Promise.all([
+ withD1Retry(
+ () => queries.communityChannel.getChannel(db, message.channelId),
+ { route: "message-dispatcher:channel" },
+ ),
+ withD1Retry(
+ () => queries.communityMention.listMessageMentionUserIds(db, messageId),
+ { route: "message-dispatcher:attention" },
+ ),
+ withD1Retry(
+ () => queries.communityAttachment.listMessageAttachments(db, messageId),
+ { route: "message-dispatcher:attachments" },
+ ),
+ withD1Retry(
+ () => queries.communityMessage.getMessageClientNonceForDelivery(db, messageId),
+ { route: "message-dispatcher:client-nonce" },
+ ),
+ ])
+ if (!channel || channel.id !== message.channelId) {
+ throw new Error("committed message scope not found")
+ }
+
+ const candidateContentUserIds = unique(await resolveRecipients(db, channel.id))
+ const attentionIds = unique(attentionUserIds).filter((id) => id !== message.authorId)
+ const eligibilityUserIds = unique([...candidateContentUserIds, ...attentionIds])
+
+ const [eligibility, replyTarget] = await Promise.all([
+ withD1Retry(
+ () => queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers(
+ db,
+ eligibilityUserIds,
+ message.id,
+ ),
+ { route: "message-dispatcher:eligibility" },
+ ),
+ message.replyToId
+ ? withD1Retry(
+ () => queries.communityMessage.getMessageInScope(
+ db,
+ message.replyToId!,
+ { channelId: message.channelId },
+ ),
+ { route: "message-dispatcher:reply" },
+ )
+ : Promise.resolve(null),
+ ])
+
+ const contentUserIds = candidateContentUserIds.filter(
+ (id) => eligibility.get(id)?.isReadable,
+ )
+ const notifyContentUserIds = contentUserIds.filter((id) => id !== message.authorId)
+ const wakeCandidates = await withD1Retry(
+ () => queries.communityBot.findWakeCandidates(db, {
+ recipients: notifyContentUserIds,
+ channelId: message.channelId,
+ newSeq: message.seq,
+ }),
+ { route: "message-dispatcher:wake-candidates" },
+ )
+
+ const allowed = (userId: string) => {
+ const state = eligibility.get(userId)
+ return Boolean(
+ state?.isReadable
+ && state.isUnread
+ && queries.communityNotificationSetting.policyAllows(
+ state.currentLevel,
+ state.hasAttention,
+ )
+ )
+ }
+ const unreadMentionUserIds = notifyContentUserIds.filter((id) => {
+ const state = eligibility.get(id)
+ return allowed(id) && Boolean(state?.hasAttention)
+ })
+ const unreadMentionSet = new Set(unreadMentionUserIds)
+ const unreadPlainUserIds = notifyContentUserIds.filter(
+ (id) => allowed(id) && !unreadMentionSet.has(id),
+ )
+ const mentionUserIds = attentionIds.filter((id) => {
+ const state = eligibility.get(id)
+ return allowed(id) && Boolean(state?.hasAttention)
+ })
+ const notifyContentSet = new Set(notifyContentUserIds)
+ const wakeBotUserIds = unique(
+ wakeCandidates
+ .map((candidate) => candidate.botUserId)
+ .filter((id) => notifyContentSet.has(id) && allowed(id)),
+ )
+
+ const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()
+ if (replyTarget) {
+ replyMap.set(replyTarget.id, {
+ id: replyTarget.id,
+ authorName: replyTarget.authorName,
+ content: replyTarget.content,
+ })
+ }
+ const messageEvent: CommunityMessageCreate = {
+ type: WS_EVENTS.MESSAGE_CREATE,
+ channelId: message.channelId,
+ ...(channel.serverId ? { serverId: channel.serverId } : {}),
+ ...(channel.parentChannelId ? { parentChannelId: channel.parentChannelId } : {}),
+ message: mapMessageForWs(message, {
+ replyMap,
+ clientNonce: clientNonce ?? undefined,
+ attachments: attachments.map((attachment) => ({
+ id: attachment.id,
+ filename: attachment.filename,
+ url: attachmentUrl(attachment.targetId, attachment.id),
+ ...(attachment.thumbnailR2Key
+ ? { thumbnailUrl: attachmentThumbnailUrl(attachment.targetId, attachment.id) }
+ : {}),
+ contentType: attachment.contentType ?? undefined,
+ size: attachment.size ?? undefined,
+ width: attachment.width ?? undefined,
+ height: attachment.height ?? undefined,
+ })),
+ }),
+ }
+
+ const includeParent = Boolean(channel.parentChannelId && !structural.suppressParentProjection)
+ const parentProjectionUserIds = includeParent
+ ? unique(await resolveRecipients(db, channel.parentChannelId!))
+ : []
+ const parentProjection = includeParent
+ ? {
+ type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
+ parentChannelId: channel.parentChannelId!,
+ channelId: channel.id,
+ changes: {
+ messageCount: channel.messageCount,
+ lastMessageAt: channel.lastMessageAt ?? message.createdAt,
+ },
+ } as const
+ : undefined
+
+ if (
+ structural.memberAddedUserId
+ && (!channel.serverId || !contentUserIds.includes(structural.memberAddedUserId))
+ ) {
+ throw new Error("committed participant outcome is outside message scope")
+ }
+
+ return {
+ messageId: message.id,
+ messageEvent,
+ contentUserIds,
+ unreadPlainUserIds,
+ unreadMentionUserIds,
+ mentionUserIds,
+ wakeBotUserIds,
+ ...(structural.memberAddedUserId && channel.serverId
+ ? {
+ memberAdded: {
+ userId: structural.memberAddedUserId,
+ serverId: channel.serverId,
+ channelId: channel.id,
+ },
+ }
+ : {}),
+ ...(parentProjection
+ ? { parentProjection, parentProjectionUserIds }
+ : {}),
+ }
+}
+
+async function runCommittedMessageDispatch(
+ db: Database,
+ messageId: string,
+ structural: CommittedMessageStructuralOutcome,
+): Promise<void> {
+ const startedAt = Date.now()
+ const plan = await planCommittedMessage(db, messageId, structural)
+ const browserBatch: MessageDeliveryBatch = {
+ messageId: plan.messageId,
+ messageEvent: plan.messageEvent,
+ contentUserIds: plan.contentUserIds,
+ unreadPlainUserIds: plan.unreadPlainUserIds,
+ unreadMentionUserIds: plan.unreadMentionUserIds,
+ mentionUserIds: plan.mentionUserIds,
+ ...(plan.memberAdded ? { memberAdded: plan.memberAdded } : {}),
+ ...(plan.parentProjection
+ ? {
+ parentProjection: plan.parentProjection,
+ parentProjectionUserIds: plan.parentProjectionUserIds,
+ }
+ : {}),
+ }
+ const wakePayloads: WakePayload[] = plan.wakeBotUserIds.map((botUserId) => ({
+ messageId: plan.messageId,
+ botUserId,
+ }))
+ const [browser, wake] = await Promise.allSettled([
+ sendMessageDeliveryBatch(browserBatch),
+ enqueueBotWakePayloads(wakePayloads),
+ ])
+ if (browser.status === "rejected") {
+ log.warn("committed_message_browser_delivery_failed", {
+ messageId,
+ err: String(browser.reason),
+ })
+ }
+ if (wake.status === "rejected") {
+ log.warn("committed_message_wake_delivery_failed", {
+ messageId,
+ err: String(wake.reason),
+ })
+ }
+ log.info("committed_message_dispatch_complete", {
+ messageId,
+ contentCount: plan.contentUserIds.length,
+ unreadCount: plan.unreadPlainUserIds.length + plan.unreadMentionUserIds.length,
+ mentionCount: plan.mentionUserIds.length,
+ wakeCount: plan.wakeBotUserIds.length,
+ parentCount: plan.parentProjectionUserIds?.length ?? 0,
+ durationMs: Date.now() - startedAt,
+ })
+}
+
+/**
+ * Register one committed delivery with the request lifetime. Delivery is a
+ * fail-open realtime hint: a transport or planning failure never rejects the
+ * already successful message mutation.
+ */
+export function dispatchCommittedMessage(
+ db: Database,
+ messageId: string,
+ structural: CommittedMessageStructuralOutcome = {},
+): Promise<void> {
+ const work = runCommittedMessageDispatch(db, messageId, structural).catch((err) => {
+ log.warn("committed_message_dispatch_failed", { messageId, err: String(err) })
+ })
+ try {
+ getCloudflareContext().ctx.waitUntil(work)
+ } catch {
+ // Unit tests and non-Cloudflare callers may not expose a request context.
+ }
+ return work
+}
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index e56768f34..6dd786988 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -66,25 +66,9 @@ vi.mock("@alook/shared", async () => {
}
})
-const mockFanOutToChannel = vi.fn()
-const mockFanOutToDM = vi.fn()
-const mockBroadcastToUserSafe = vi.fn()
-const mockResolveChannelRecipients = vi.fn(async () => [] as string[])
-vi.mock("./fanout", () => ({
- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
- fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),
- broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
- resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),
-}))
-
-const mockDispatchMessageNotify = vi.fn(async () => {})
-vi.mock("./notify", () => ({
- dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),
-}))
-
-const mockBroadcastToUser = vi.fn()
-vi.mock("../broadcast", () => ({
- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+const mockDispatchCommittedMessage = vi.fn(async () => {})
+vi.mock("./message-dispatcher", () => ({
+ dispatchCommittedMessage: (...a: unknown[]) => mockDispatchCommittedMessage(...a),
}))
@@ -145,9 +129,6 @@ describe("createCommunityMessage — replyToId write-path scope validation (dang
vi.clearAllMocks()
mockCreateMessage.mockResolvedValue({ id: "msg_1" })
mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
})
// The reply target the client asked to answer, living in the SAME channel.
@@ -275,9 +256,6 @@ describe("createCommunityMessage — replyToId write-path scope validation (dang
describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-condition.md)", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
})
it("expectedSeq mismatch (createMessage returns null) → { ok: false, status: 409, error: 'seq_conflict' }, no side effects", async () => {
@@ -296,8 +274,7 @@ describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-conditi
// Lost the race — none of the downstream pipeline steps should fire.
expect(mockGetMessage).not.toHaveBeenCalled()
expect(mockCreateMentions).not.toHaveBeenCalled()
- expect(mockFanOutToChannel).not.toHaveBeenCalled()
- expect(mockFanOutToDM).not.toHaveBeenCalled()
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
})
it("passes expectedSeq through to createMessage when provided", async () => {
@@ -337,16 +314,13 @@ describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-conditi
})
})
-describe("createCommunityMessage — attachment width/height reach the live WS broadcast", () => {
+describe("createCommunityMessage — committed delivery handoff", () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
})
- it("includes width/height on an image attachment in the MESSAGE_CREATE broadcast payload (reserve-by-id)", async () => {
+ it("returns reserved attachment dimensions but hands only committed identity to the dispatcher", async () => {
// Reserve-by-id (route/disc step 2b): dimensions are written onto the
// pending row at UPLOAD (single source) and reach the broadcast when the
// reserved rows are re-read via listByMessageIds after the reserve. There is
@@ -370,7 +344,7 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
])
mockGetMessage.mockResolvedValue(messageRow())
- await createCommunityMessage({
+ const result = await createCommunityMessage({
db: {} as never,
authorId: "author_1",
target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
@@ -378,19 +352,19 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
attachmentIds: ["att_1"],
})
- expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)
- const [, event] = mockFanOutToChannel.mock.calls[0]!
- expect(event).toMatchObject({ serverId: "srv_1" })
- expect(event.message.attachments).toEqual([
+ expect(result.ok).toBe(true)
+ if (!result.ok) return
+ expect(result.attachments).toEqual([
expect.objectContaining({
width: 1920,
height: 1080,
thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
}),
])
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {})
})
- it("includes server + parent metadata for a child message so server-scoped sidebars can patch", async () => {
+ it("does not pass server, parent, audience, or policy through the handler", async () => {
mockCreateMessage.mockResolvedValue({ id: "msg_1" })
mockGetMessage.mockResolvedValue(messageRow())
@@ -406,12 +380,7 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
body: { content: "reply" },
})
- expect(mockFanOutToChannel.mock.calls[0]?.[1]).toMatchObject({
- type: "community:message.create",
- channelId: "post_1",
- serverId: "srv_1",
- parentChannelId: "forum_1",
- })
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {})
})
})
@@ -419,9 +388,6 @@ describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
beforeEach(() => {
vi.clearAllMocks()
mockCreateMessage.mockResolvedValue({ id: "msg_1" })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
mockListMembers.mockResolvedValue([
{ userId: "author_1", userName: "Author", discriminator: "1111" },
@@ -470,10 +436,6 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
beforeEach(() => {
vi.clearAllMocks()
mockCreateMessage.mockResolvedValue({ id: "msg_1" })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockFanOutToDM.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
- mockBroadcastToUserSafe.mockResolvedValue(undefined)
mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
mockListMembers.mockResolvedValue([
{ userId: "author_1", userName: "Author", discriminator: "1111" },
@@ -497,7 +459,6 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
// Channel roster is NOT expanded by a mention.
expect(mockCreateChannelMember).not.toHaveBeenCalled()
- expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
// Bob was outside the audience → dropped → no mention row.
expect(mockCreateMentions).not.toHaveBeenCalled()
})
@@ -559,11 +520,8 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
// and NEVER auto-added to the channel roster.
expect(mockCreateChannelMember).not.toHaveBeenCalled()
expect(mockCreateMentions).not.toHaveBeenCalled()
- expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("author_1", {
- type: "community:channel.member_add",
- serverId: "srv_1",
- channelId: "t1",
- userId: "author_1",
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {
+ memberAddedUserId: "author_1",
})
})
@@ -689,6 +647,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
// tick are decoupled: enroll runs, the tick does not.
mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])
mockGetMessage.mockResolvedValue(messageRow({ content: "welcome @Cara#0002", channelId: "p1" }))
+ mockAddThreadParticipants.mockResolvedValueOnce(["author_1", "cara_1"])
await createCommunityMessage({
db: {} as never,
@@ -703,11 +662,10 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
- // No CHILD_CHANNEL_UPDATE fanned to the parent forum.
- const childUpdateCalls = mockFanOutToChannel.mock.calls.filter(
- (c) => (c[1] as { type?: string })?.type === "community:channel.child_update",
- )
- expect(childUpdateCalls).toHaveLength(0)
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {
+ memberAddedUserId: "author_1",
+ suppressParentProjection: true,
+ })
})
it("public channel: mention of any server member is kept, no roster row", async () => {
@@ -729,10 +687,9 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
})
- it("does not await a pending notify work on the normal delivery path", async () => {
+ it("does not await a pending dispatcher on the normal delivery path", async () => {
mockGetMessage.mockResolvedValue(messageRow({ content: "hello" }))
- mockResolveChannelRecipients.mockResolvedValueOnce(["author_1", "cara_1"])
- mockDispatchMessageNotify.mockReturnValueOnce(new Promise<void>(() => {}))
+ mockDispatchCommittedMessage.mockReturnValueOnce(new Promise<void>(() => {}))
const result = await createCommunityMessage({
db: {} as never,
@@ -742,19 +699,11 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
expect(result.ok).toBe(true)
- expect(mockDispatchMessageNotify).toHaveBeenCalledWith(
- {},
- { authorName: "Author" },
- { id: "msg_1", channelId: "c1" },
- ["cara_1"],
- expect.objectContaining({ mentionedUserIds: [] }),
- )
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {})
})
- it("starts notify only when a deferred broadcast thunk is invoked", async () => {
+ it("starts dispatch only when a deferred broadcast thunk is invoked", async () => {
mockGetMessage.mockResolvedValue(messageRow({ content: "hello" }))
- mockResolveChannelRecipients.mockResolvedValueOnce(["author_1", "cara_1"])
- mockDispatchMessageNotify.mockReturnValueOnce(new Promise<void>(() => {}))
const result = await createCommunityMessage({
db: {} as never,
@@ -766,9 +715,9 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
expect(result.ok).toBe(true)
if (!result.ok) return
- expect(mockDispatchMessageNotify).not.toHaveBeenCalled()
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
await expect(result.broadcast?.()).resolves.toBeUndefined()
- expect(mockDispatchMessageNotify).toHaveBeenCalledTimes(1)
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {})
})
it("suppressBroadcast (migration-backfill mode): STRUCTURAL core runs (enroll + mention rows), real-time delivery shell is fully dropped", async () => {
@@ -801,8 +750,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
kind: "mention",
})
// Real-time delivery shell FULLY dropped: no WS fan-out of any kind.
- expect(mockFanOutToChannel).not.toHaveBeenCalled()
- expect(mockDispatchMessageNotify).not.toHaveBeenCalled()
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
// ...and no deferred thunk handed back either (unlike deferBroadcast).
expect(result.ok).toBe(true)
if (result.ok) expect(result.broadcast).toBeUndefined()
@@ -813,8 +761,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
beforeEach(() => {
vi.clearAllMocks()
mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: true, deletedAt: null })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockBroadcastToUser.mockResolvedValue(undefined)
mockGetMessage.mockResolvedValue(messageRow())
mockListByMessageIds.mockResolvedValue([])
})
@@ -902,7 +848,7 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
expect(mockCreateMessage).toHaveBeenCalledTimes(1)
expect(mockUnreserveAttachments).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))
expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
- expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
})
it("thrown insertMessageRow error → nothing reserved yet, no unreserve, re-throw", async () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index f3e5ed4c4..2a7eec5b8 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -4,7 +4,6 @@ import {
isMentionType,
MAX_MESSAGE_CONTENT_LENGTH,
MAX_ATTACHMENTS_PER_MESSAGE,
- WS_EVENTS,
PARTICIPANT_SOURCE,
MENTION_KIND,
createLogger,
@@ -14,9 +13,7 @@ import {
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
-import { broadcastToUserSafe, fanOutToChannel, resolveChannelRecipients } from "./fanout"
-import { dispatchMessageNotify } from "./notify"
-import { mapMessageForWs } from "./message-payload"
+import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
const log = createLogger({ service: "community-message-handler" })
@@ -59,15 +56,6 @@ export function isChannelTarget(target: { kind: string } | string): boolean {
return (typeof target === "string" ? target : target.kind) === "channel"
}
-// A thread enrolls participants (spoke/mention) and fires the parent
-// CHILD_CHANNEL_UPDATE via its `parentChannelId`. This narrows to the one
-// variant that carries one.
-function hasParentChannel(
- target: MessageTarget,
-): target is Extract<MessageTarget, { kind: "thread" }> {
- return target.kind === "thread"
-}
-
export type IncomingMessageBody = {
content?: unknown
replyToId?: unknown
@@ -135,11 +123,9 @@ type CreateMessageOk = {
attachments: CreatedAttachment[]
/**
* Present ONLY when the caller passed `deferBroadcast: true`. Invoking it
- * fires the WS side effects (MENTION_CREATE, MESSAGE_CREATE fan-out, DM peer
- * ping / CHILD_CHANNEL_UPDATE, bot-wake enqueue) that `createCommunityMessage`
- * would otherwise have run inline. The DM-card producers deliberately never
- * invoke this — they persist their approval-request row first and fire their
- * own minimal `MESSAGE_CREATE` after it commits (see plan §producer).
+ * dispatches the committed message through the same D1-rehydrated delivery
+ * plan that `createCommunityMessage` would otherwise schedule immediately.
+ * Deferred producers invoke it only after their dependent row has committed.
*/
broadcast?: () => Promise<void>
/**
@@ -157,8 +143,8 @@ export type CreateMessageResult = CreateMessageOk | CreateMessageError
*
* Handles request-body validation, message + attachment inserts, reply
* resolution, mention extraction (channel/thread only — DMs only flag the
- * reply target), mention/reply broadcast, channel-or-DM fan-out, and the
- * parent-channel CHILD_CHANNEL_UPDATE that follows a thread reply.
+ * reply target), participant writes, and one committed dispatcher call that
+ * derives message, notification, wake, and parent projections from D1.
*
* Each route resolves permission/target first, then delegates here.
*/
@@ -188,11 +174,6 @@ export async function createCommunityMessage(params: {
* cards) opt in — they never mention anyone.
*/
skipMentions?: boolean
- /**
- * Skip the bot-wake enqueue that rides the `MESSAGE_CREATE` fan-out. System
- * / card messages set this — they must not wake bots.
- */
- skipWake?: boolean
/**
* Reserve-by-id attachment path (the ONLY attachment path — human web and bot
* both use it, route/disc step 2b). Pending attachment ids the caller has
@@ -267,7 +248,6 @@ export async function createCommunityMessage(params: {
expectedSeq,
messageType,
skipMentions,
- skipWake,
deferBroadcast,
suppressBroadcast,
attachmentIds,
@@ -527,9 +507,7 @@ export async function createCommunityMessage(params: {
// Reply target for mention broadcasts. Scoped at the query level (not a
// post-hoc `.filter()`) so a caller can't attach a preview of a message
// from a different DM/channel by passing its id. The payload-side reply
- // preview is built from the same scope-checked map by `mapMessageForWs`
- // below.
- const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()
+ // preview is rebuilt from this same persisted relation by the dispatcher.
const replyTargets = new Set<string>()
// Reuse the in-scope reply target resolved at the write-validation step above
// (`resolvedReplyMsg`) — it was fetched with the identical `getMessageInScope`
@@ -538,11 +516,6 @@ export async function createCommunityMessage(params: {
// for a genuinely in-scope reply.
if (!skipMentions && row.replyToId && resolvedReplyMsg) {
// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path
- replyMap.set(resolvedReplyMsg.id, {
- id: resolvedReplyMsg.id,
- authorName: resolvedReplyMsg.authorName,
- content: resolvedReplyMsg.content,
- })
if (resolvedReplyMsg.authorId && resolvedReplyMsg.authorId !== authorId) {
replyTargets.add(resolvedReplyMsg.authorId)
}
@@ -652,7 +625,7 @@ export async function createCommunityMessage(params: {
// agent-inbox deliverable narrowing (the READ side, who's-participant) key on,
// so who-enrolls and who's-read can never drift (the class of bug the agent
// thread-inbox deadlock was). `target.kind` is the channel's stored type here
- // (channel/thread/forum/dm). NOT folded with `hasParentChannel` below: that
+ // (channel/thread/forum/dm). NOT folded with parent-channel delivery: that
// is a distinct STRUCTURAL fact ("has a parent channel" → railChannelId /
// parent CHILD_CHANNEL_UPDATE tick), which merely coincides with participant-set
// for today's types — a future type could have a parent but server reach, or
@@ -695,137 +668,15 @@ export async function createCommunityMessage(params: {
})
}
- const messagePayload = mapMessageForWs(row, {
- replyMap,
- // Raw client nonce (NOT `effectiveNonce`): echoed so the sender's optimistic
- // row reconciles in place. `undefined` when the client sent none — in which
- // case `effectiveNonce` is the `srv:` fallback, which must not reach the wire
- // (content fingerprint; no client optimistic row to match). `mapMessageForWs`
- // also prefix-guards `srv:` defensively.
- clientNonce,
- attachments: attachments.map((a) => ({
- id: a.id,
- filename: a.filename,
- url: a.url,
- thumbnailUrl: a.thumbnailUrl,
- contentType: a.contentType ?? undefined,
- size: a.size ?? undefined,
- width: a.width ?? undefined,
- height: a.height ?? undefined,
- })),
+ // Delivery is planned from committed D1 facts. The handler contributes only
+ // structural outcomes that cannot be safely reconstructed later.
+ const doBroadcast = (): Promise<void> => dispatchCommittedMessage(db, row.id, {
+ ...(joinedParticipantUserIds.includes(authorId)
+ ? { memberAddedUserId: authorId }
+ : {}),
+ ...(skipChildChannelUpdate ? { suppressParentProjection: true } : {}),
})
- // Wake-dispatch row (minimal-wake-queue-unread-notice plan §1/§5) — the
- // same `row` already fetched above via `getMessage` (which now selects
- // `seq`). Passed alongside the MESSAGE_CREATE event so
- // `fanOutToChannel`/`fanOutToDM` can enqueue bot wakes using the SAME
- // recipient list already resolved for the human-WS broadcast, no second
- // membership query. Deliberately no `content`/`createdAt` — the queue
- // payload only ever carries `{ messageId, botUserId }`. Suppressed when
- // `skipWake` (system/card messages never wake bots).
- const wakeMessageRow = skipWake
- ? undefined
- : {
- id: row.id,
- seq: row.seq,
- authorId: row.authorId,
- channelId: row.channelId,
- }
-
- // All WS side effects live here so `deferBroadcast` can hand them back as a
- // thunk instead of firing them inline.
- const doBroadcast = async (): Promise<void> => {
- // Resolve the recipient set ONCE and share it between the unfiltered
- // MESSAGE_CREATE fan-out (mute ≠ blindness: content always syncs) and the
- // level-filtered notify pipeline (per-recipient MENTION_CREATE push +
- // UNREAD_BUMP badge) — no second membership query. DMs are channels now, so
- // both DM and channel targets flow through the same path; the notify
- // pipeline resolves each recipient's effective level (a DM's level is
- // self-contained, defaulting to `all`).
- const recipients = await resolveChannelRecipients(db, target.channelId)
-
- // If this send newly enrolled the author in a thread's notify set, send a
- // membership event directly so their open Members drawer and sidebar
- // participation state also refresh.
- if (joinedParticipantUserIds.includes(authorId) && !isDmTarget(target)) {
- void broadcastToUserSafe(authorId, {
- type: WS_EVENTS.CHANNEL_MEMBER_ADD,
- serverId: target.serverId,
- channelId: target.channelId,
- userId: authorId,
- })
- }
-
- fanOutToChannel(
- target.channelId,
- {
- type: WS_EVENTS.MESSAGE_CREATE,
- channelId: target.channelId,
- ...(isDmTarget(target)
- ? {}
- : {
- serverId: target.serverId,
- ...(hasParentChannel(target) ? { parentChannelId: target.parentChannelId } : {}),
- }),
- message: messagePayload,
- },
- {
- excludeWakeUserId: authorId,
- recipients,
- wakeMessageRow,
- mentionedUserIds: [...liveMentions, ...liveReplies],
- },
- ).catch(() => { })
-
- // Level-filtered human notify legs. Author is excluded (never notifies
- // self); mention sets are already author-excluded upstream. `nothing`
- // recipients are dropped from push + badge — but their mention ROWS were
- // already written above (createMentions is never level-gated).
- dispatchMessageNotify(
- db,
- { authorName: row.authorName },
- { id: row.id, channelId: row.channelId },
- recipients.filter((id) => id !== authorId),
- {
- mentionedUserIds: [...liveMentions, ...liveReplies],
- // serverId + railChannelId ride the UNREAD_BUMP so the client patches
- // the right server tree + a parent fallback for unlisted child threads
- // without a query — straight off the resolved `target` (DM has neither). See
- // inbox-dot-ws-driven plan.
- ...(isDmTarget(target)
- ? {}
- : {
- serverId: target.serverId,
- railChannelId: hasParentChannel(target)
- ? target.parentChannelId
- : target.channelId,
- }),
- },
- ).catch(() => { })
-
- if (!isDmTarget(target)) {
- if (hasParentChannel(target) && !skipChildChannelUpdate) {
- const updated = await withD1Retry(
- () => queries.communityChannel.getChannel(db, target.channelId),
- { route: "message-handler:child-channel-read" },
- )
- fanOutToChannel(
- target.parentChannelId,
- {
- type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
- parentChannelId: target.parentChannelId,
- channelId: target.channelId,
- changes: {
- messageCount: updated?.messageCount ?? 1,
- lastMessageAt:
- updated?.lastMessageAt ?? new Date().toISOString(),
- },
- },
- ).catch(() => { })
- }
- }
- }
-
// Migration-backfill mode drops the real-time delivery shell entirely — the
// structural core (row + thread + enroll + mention rows) already committed
// inline above; `doBroadcast` is never run and no thunk is handed back.
@@ -835,6 +686,6 @@ export async function createCommunityMessage(params: {
if (deferBroadcast) {
return { ok: true, row, attachments, broadcast: doBroadcast }
}
- await doBroadcast()
+ void doBroadcast()
return { ok: true, row, attachments }
}
diff --git a/src/web/src/lib/community/notify.test.ts b/src/web/src/lib/community/notify.test.ts
deleted file mode 100644
index 12c8d47d2..000000000
--- a/src/web/src/lib/community/notify.test.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest"
-
-const mockInfo = vi.fn()
-const mockWarn = vi.fn()
-const mockWaitUntil = vi.fn()
-const mockGetCloudflareContext = vi.fn()
-const mockResolveNotificationEligibilityForUsers = vi.fn()
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: () => mockGetCloudflareContext(),
-}))
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- createLogger: () => ({
- info: (...args: unknown[]) => mockInfo(...args),
- warn: (...args: unknown[]) => mockWarn(...args),
- error: vi.fn(),
- debug: vi.fn(),
- }),
- queries: {
- communityNotificationSetting: {
- policyAllows: actual.queries.communityNotificationSetting.policyAllows,
- },
- communityNotificationEligibility: {
- resolveNotificationEligibilityForUsers: (...args: unknown[]) =>
- mockResolveNotificationEligibilityForUsers(...args),
- },
- },
- }
-})
-
-const mockBroadcastToUser = vi.fn()
-vi.mock("../broadcast", () => ({
- broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),
-}))
-
-import {
- dispatchMessageNotify,
- settleNotifyTasks,
-} from "./notify"
-
-const db = {} as never
-const message = { id: "m1", channelId: "c1" }
-const notifyContext = { authorName: "Alice" }
-
-function deferred<T>() {
- let resolve!: (value: T | PromiseLike<T>) => void
- let reject!: (reason?: unknown) => void
- const promise = new Promise<T>((resolvePromise, rejectPromise) => {
- resolve = resolvePromise
- reject = rejectPromise
- })
- return { promise, resolve, reject }
-}
-
-function eventsOfType(type: string): Record<string, unknown>[] {
- return mockBroadcastToUser.mock.calls
- .map((call) => call[1] as Record<string, unknown>)
- .filter((event) => event.type === type)
-}
-
-function deliveryStates(
- ids: string[],
- overrides: Partial<{
- currentLevel: "all" | "mentions" | "nothing"
- hasAttention: boolean
- isUnread: boolean
- isReadable: boolean
- }> = {},
-) {
- return new Map(ids.map((id) => [id, {
- currentLevel: "all" as const,
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- ...overrides,
- }]))
-}
-
-describe("settleNotifyTasks", () => {
- it.each([0, 1, 3, 4, 1001])(
- "settles %i tasks with at most three active",
- async (taskCount) => {
- let active = 0
- let observedMaxActive = 0
- const tasks = Array.from({ length: taskCount }, (_, index) => index)
-
- const settled = await settleNotifyTasks(tasks, async () => {
- active += 1
- observedMaxActive = Math.max(observedMaxActive, active)
- await Promise.resolve()
- active -= 1
- })
-
- expect(settled.results).toHaveLength(taskCount)
- expect(settled.results.every((result) => result.status === "fulfilled")).toBe(true)
- expect(settled.maxActive).toBe(Math.min(taskCount, 3))
- expect(observedMaxActive).toBe(Math.min(taskCount, 3))
- },
- )
-
- it("starts the fourth task only after one of the first three settles", async () => {
- const gates = Array.from({ length: 4 }, () => deferred<void>())
- const started: number[] = []
- const work = settleNotifyTasks([0, 1, 2, 3], async (index) => {
- started.push(index)
- await gates[index].promise
- })
-
- expect(started).toEqual([0, 1, 2])
- gates[1].resolve(undefined)
- await Promise.resolve()
- await Promise.resolve()
- expect(started).toEqual([0, 1, 2, 3])
-
- gates[0].resolve(undefined)
- gates[2].resolve(undefined)
- gates[3].resolve(undefined)
- await expect(work).resolves.toMatchObject({ maxActive: 3 })
- })
-
- it("keeps results aligned by input index when tasks settle out of order", async () => {
- const gates = Array.from({ length: 3 }, () => deferred<void>())
- const failure = new Error("task one failed")
- const work = settleNotifyTasks([0, 1, 2], (index) => gates[index].promise)
-
- gates[2].resolve(undefined)
- gates[1].reject(failure)
- gates[0].resolve(undefined)
-
- const { results } = await work
- expect(results[0]).toEqual({ status: "fulfilled", value: undefined })
- expect(results[1]).toEqual({ status: "rejected", reason: failure })
- expect(results[2]).toEqual({ status: "fulfilled", value: undefined })
- })
-
- it("continues with later tasks after a synchronous rejection", async () => {
- const started: number[] = []
- const failure = new Error("rejected")
- const { results } = await settleNotifyTasks([0, 1, 2, 3], async (index) => {
- started.push(index)
- if (index === 1) throw failure
- })
-
- expect(started).toEqual([0, 1, 2, 3])
- expect(results[1]).toEqual({ status: "rejected", reason: failure })
- expect(results[3]).toEqual({ status: "fulfilled", value: undefined })
- })
-})
-
-describe("dispatchMessageNotify", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockBroadcastToUser.mockReset()
- mockBroadcastToUser.mockResolvedValue(undefined)
- mockGetCloudflareContext.mockReturnValue({ ctx: { waitUntil: mockWaitUntil } })
- })
-
- it("registers the returned work before the level resolver settles", async () => {
- const states = deferred<ReturnType<typeof deliveryStates>>()
- mockResolveNotificationEligibilityForUsers.mockReturnValue(states.promise)
-
- const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {
- mentionedUserIds: [],
- })
-
- expect(mockWaitUntil).toHaveBeenCalledWith(work)
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
- states.resolve(deliveryStates(["u1"]))
- await work
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
- })
-
- it("keeps aggregate work pending until every lazily started leaf settles", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(
- deliveryStates(["u0", "u1", "u2", "u3"]),
- )
- const gates = Array.from({ length: 4 }, () => deferred<void>())
- mockBroadcastToUser.mockImplementation(() => {
- const index = mockBroadcastToUser.mock.calls.length - 1
- return gates[index].promise
- })
-
- const work = dispatchMessageNotify(
- db,
- notifyContext,
- message,
- ["u0", "u1", "u2", "u3"],
- { mentionedUserIds: [] },
- )
- let settled = false
- void work.then(() => {
- settled = true
- })
-
- await Promise.resolve()
- await Promise.resolve()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)
- expect(settled).toBe(false)
-
- gates[0].resolve(undefined)
- await Promise.resolve()
- await Promise.resolve()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(4)
- expect(settled).toBe(false)
-
- gates[1].resolve(undefined)
- gates[2].resolve(undefined)
- gates[3].resolve(undefined)
- await work
- expect(settled).toBe(true)
- expect(mockWaitUntil).toHaveBeenCalledWith(work)
- })
-
- it("builds mention tasks before deduplicated unread tasks", async () => {
- const states = deliveryStates(["u_plain", "u_mentioned", "u_extra"])
- states.set("u_mentioned", { ...states.get("u_mentioned")!, hasAttention: true })
- states.set("u_extra", { ...states.get("u_extra")!, hasAttention: true })
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(states)
-
- await dispatchMessageNotify(
- db,
- notifyContext,
- message,
- ["u_plain", "u_mentioned", "u_plain"],
- { mentionedUserIds: ["u_mentioned", "u_extra", "u_mentioned"] },
- )
-
- expect(mockBroadcastToUser.mock.calls.map((call) => [
- call[0],
- (call[1] as { type: string }).type,
- ])).toEqual([
- ["u_mentioned", "community:mention.create"],
- ["u_extra", "community:mention.create"],
- ["u_plain", "community:unread.bump"],
- ["u_mentioned", "community:unread.bump"],
- ])
- expect(mockInfo).toHaveBeenCalledWith(
- "dispatch_message_notify_complete",
- expect.objectContaining({
- recipientCount: 2,
- mentionedCount: 2,
- leafTaskCount: 4,
- mentionSuccess: 2,
- mentionFailure: 0,
- unreadSuccess: 2,
- unreadFailure: 0,
- maxActive: 3,
- durationMs: expect.any(Number),
- }),
- )
- })
-
- it("isolates one rejected leaf and continues remaining deliveries", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(
- deliveryStates(["u0", "u1", "u2", "u3"]),
- )
- mockBroadcastToUser.mockImplementation((userId: string) => (
- userId === "u1" ? Promise.reject(new Error("binding failed")) : Promise.resolve()
- ))
-
- await expect(dispatchMessageNotify(
- db,
- notifyContext,
- message,
- ["u0", "u1", "u2", "u3"],
- { mentionedUserIds: [] },
- )).resolves.toBeUndefined()
-
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(4)
- expect(mockInfo).toHaveBeenCalledWith(
- "dispatch_message_notify_complete",
- expect.objectContaining({
- unreadSuccess: 3,
- unreadFailure: 1,
- }),
- )
- })
-
- it("preserves all and mentions notification-level behavior", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([
- ["u_all", { currentLevel: "all", hasAttention: false, isUnread: true, isReadable: true }],
- ["u_mentions_plain", { currentLevel: "mentions", hasAttention: false, isUnread: true, isReadable: true }],
- ["u_mentions_hit", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],
- ]))
-
- await dispatchMessageNotify(
- db,
- notifyContext,
- message,
- ["u_all", "u_mentions_plain", "u_mentions_hit"],
- { mentionedUserIds: ["u_mentions_hit"] },
- )
-
- expect(eventsOfType("community:mention.create").map((event) => event.userId)).toEqual([
- "u_mentions_hit",
- ])
- expect(eventsOfType("community:unread.bump").map((event) => event.userId)).toEqual([
- "u_all",
- "u_mentions_hit",
- ])
- })
-
- it("suppresses nothing-level deliveries without emitting message-create", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([
- ["u_muted", { currentLevel: "nothing", hasAttention: true, isUnread: true, isReadable: true }],
- ]))
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_muted"], {
- mentionedUserIds: ["u_muted"],
- })
-
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
- expect(mockInfo).toHaveBeenCalledWith(
- "dispatch_message_notify_complete",
- expect.objectContaining({ leafTaskCount: 0, maxActive: 0 }),
- )
- })
-
- it("fails closed when a recipient is missing from the delivery snapshot", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map())
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {
- mentionedUserIds: [],
- })
-
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
- })
-
- it("does not relight a message cleared before deferred notify, but delivers a newer unread", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([
- ["u_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: false, isReadable: true }],
- ]))
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_mentioned"], {
- mentionedUserIds: ["u_mentioned"],
- })
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
-
- mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([
- ["u_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],
- ]))
- await dispatchMessageNotify(
- db,
- notifyContext,
- { id: "m2", channelId: "c1" },
- ["u_mentioned"],
- { mentionedUserIds: ["u_mentioned"] },
- )
- expect(mockBroadcastToUser.mock.calls.map((call) => (call[1] as { type: string }).type)).toEqual([
- "community:mention.create",
- "community:unread.bump",
- ])
- })
-
- it("does not notify a captured recipient after current access is revoked", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([
- ["u_removed", { currentLevel: "all", hasAttention: true, isUnread: true, isReadable: false }],
- ]))
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_removed"], {
- mentionedUserIds: ["u_removed"],
- })
-
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
-
- await dispatchMessageNotify(
- db,
- notifyContext,
- { id: "m_after_revoke", channelId: "c1" },
- ["u_removed"],
- { mentionedUserIds: ["u_removed"] },
- )
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
- })
-
- it("preserves optional unread routing fields", async () => {
- const states = deliveryStates(["u_plain", "u_mentioned"])
- states.set("u_mentioned", { ...states.get("u_mentioned")!, hasAttention: true })
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(states)
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_plain", "u_mentioned"], {
- mentionedUserIds: ["u_mentioned"],
- serverId: "srv_1",
- railChannelId: "parent_c1",
- })
-
- const unreadEvents = eventsOfType("community:unread.bump")
- for (const event of unreadEvents) {
- expect(event.serverId).toBe("srv_1")
- expect(event.railChannelId).toBe("parent_c1")
- expect(event.channelId).toBe("c1")
- }
- expect(unreadEvents.find((event) => event.userId === "u_mentioned")?.isMention).toBe(true)
- expect(unreadEvents.find((event) => event.userId === "u_plain")?.isMention).toBe(false)
- })
-
- it("omits optional unread routing fields for a direct message", async () => {
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(deliveryStates(["u_dm"]))
-
- await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {
- mentionedUserIds: [],
- })
-
- const [event] = eventsOfType("community:unread.bump")
- expect(event.serverId).toBeUndefined()
- expect(event.railChannelId).toBeUndefined()
- expect(event.isMention).toBe(false)
- })
-
- it("absorbs a resolver failure and records its duration", async () => {
- mockResolveNotificationEligibilityForUsers.mockRejectedValue(new Error("d1 blip"))
-
- const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {
- mentionedUserIds: [],
- })
-
- expect(mockWaitUntil).toHaveBeenCalledWith(work)
- await expect(work).resolves.toBeUndefined()
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
- expect(mockWarn).toHaveBeenCalledWith(
- "dispatch_message_notify_failed",
- expect.objectContaining({
- messageId: "m1",
- err: "Error: d1 blip",
- durationMs: expect.any(Number),
- }),
- )
- })
-
- it("continues when Cloudflare context lookup is unavailable", async () => {
- mockGetCloudflareContext.mockImplementation(() => {
- throw new Error("not in a request context")
- })
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(deliveryStates(["u1"]))
-
- await expect(dispatchMessageNotify(
- db,
- notifyContext,
- message,
- ["u1"],
- { mentionedUserIds: [] },
- )).resolves.toBeUndefined()
-
- expect(mockWaitUntil).not.toHaveBeenCalled()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/src/web/src/lib/community/notify.ts b/src/web/src/lib/community/notify.ts
deleted file mode 100644
index f5788e310..000000000
--- a/src/web/src/lib/community/notify.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-/**
- * Unified per-recipient message-notify pipeline (adapted from PR-408 batch 3,
- * commit 2b61535d, to main's post-#412 DM-as-channel model).
- *
- * ONE trunk for the HUMAN notify legs of a new message: resolve each
- * recipient's current delivery state, apply the 3-tier matrix, then
- * dispatch the mute-gated per-user signals — a `MENTION_CREATE` live push (when
- * that recipient was mentioned) and a per-user `UNREAD_BUMP` badge. Writes NO
- * persistent state — offline replay rides the existing `community_read_state`
- * cursors.
- *
- * Scope boundaries (Melly #23 ruling):
- * - This pipeline does NOT own bot WAKE. Wake gating lives in
- * `wake-producer` (the produce/enqueue seam), gated by the SAME
- * shared delivery-state resolver. Keeping wake out of here keeps notify.ts to the
- * human legs and avoids a double gate.
- * - This pipeline NEVER emits `MESSAGE_CREATE`. That broadcast is the ONLY
- * content-sync path, stays in `fanOutToChannel`, and is unfiltered by level —
- * so a user viewing their own muted channel still sees messages live, and a
- * bot's `inbox pull` / `channel history` are never affected (mute ≠
- * blindness).
- * - Mention ROWS (`createMentions`) are written by the caller, independent of
- * this pipeline and NEVER level-gated — a `nothing` recipient's mention still
- * persists and surfaces via inbox.
- *
- * The 3-tier matrix (bots and users, same predicate — Gener #28):
- * level plain msg (not mentioned) mentioned
- * all badge badge + MENTION_CREATE push
- * mentions silent badge + MENTION_CREATE push
- * nothing silent silent (mention row still written)
- *
- * where "mentioned" = personal @ ∪ @everyone ∪ reply-to-me (the caller's full
- * mention set — @everyone counts, no split; Gener #28).
- */
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, WS_EVENTS, createLogger } from "@alook/shared"
-import type { Database, WsMessage } from "@alook/shared"
-import { broadcastToUser } from "../broadcast"
-
-const log = createLogger({ service: "community-notify" })
-const notifyMaxActive = 3
-
-type NotifyLeafTask = {
- kind: "mention" | "unread"
- userId: string
- event: WsMessage
-}
-
-type BoundedSettleResult = {
- results: PromiseSettledResult<void>[]
- maxActive: number
-}
-
-export async function settleNotifyTasks<T>(
- tasks: readonly T[],
- run: (task: T, index: number) => Promise<void>,
-): Promise<BoundedSettleResult> {
- const results = new Array<PromiseSettledResult<void>>(tasks.length)
- let nextIndex = 0
- let active = 0
- let maxActive = 0
-
- const workers = Array.from(
- { length: Math.min(notifyMaxActive, tasks.length) },
- async () => {
- while (nextIndex < tasks.length) {
- const index = nextIndex
- nextIndex += 1
- active += 1
- maxActive = Math.max(maxActive, active)
- try {
- await run(tasks[index], index)
- results[index] = { status: "fulfilled", value: undefined }
- } catch (reason) {
- results[index] = { status: "rejected", reason }
- } finally {
- active -= 1
- }
- }
- },
- )
-
- await Promise.all(workers)
- return { results, maxActive }
-}
-
-function safeLog(write: () => void): void {
- try {
- write()
- } catch {}
-}
-
-export interface MessageNotifyContext {
- /**
- * Snapshot author name for the `MENTION_CREATE` payload. The author is
- * already excluded from `recipients`/`mentionedUserIds` upstream — this is
- * only the label mentioned users see.
- */
- authorName: string
-}
-
-/**
- * `true` when a recipient at `level` should receive the human notify legs for a
- * message where `wasMentioned` reflects whether THIS recipient was mentioned
- * (personal @ ∪ @everyone ∪ reply). Governs both badge and the mention push
- * uniformly.
- */
-/**
- * Dispatch level-filtered HUMAN notify signals for one just-created message.
- * Fire-and-forget: absorbs all failures (the message already synced via
- * `MESSAGE_CREATE`; a level-resolution blip must never fail the send).
- *
- * @param channelId the message's channel scope. Every scope (channel, child
- * thread, AND dm) resolves its per-recipient level here — there is NO
- * channelId-nullness bypass (main's DMs are channels with a channelId; a DM's
- * level is self-contained and defaults to `all`, so routing it through the
- * resolver both honors an explicit per-DM mute and never inherits a
- * server/parent `nothing`).
- * @param recipients the fan-out recipient set (human + bot), already
- * author-excluded — the SAME list resolved for the `MESSAGE_CREATE` broadcast.
- * @param mentionedUserIds the full mention set (explicit @ ∪ @everyone
- * expansion ∪ reply targets), already author-excluded — @everyone counts as a
- * mention (Gener #28), no carve-out.
- */
-async function runMessageNotify(
- db: Database,
- ctx: MessageNotifyContext,
- message: { id: string; channelId: string },
- recipients: string[],
- opts: {
- mentionedUserIds: string[]
- /** Server the message belongs to — rides the UNREAD_BUMP so the client
- * patches the right server tree/rail (inbox-dot-ws-driven). Undefined for
- * a DM (no server). From the caller's `target.serverId`, no extra query. */
- serverId?: string
- /** Sidebar-locatable row = `parentChannelId ?? channelId` (child-thread
- * light the parent row). From the caller's target, no extra query. */
- railChannelId?: string
- },
-): Promise<void> {
- const startedAt = Date.now()
- try {
- const { channelId } = message
- const recipientIds = [...new Set(recipients)]
- const mentionedIds = [...new Set(opts.mentionedUserIds)]
- const everyone = [...new Set([...recipientIds, ...mentionedIds])]
- const delivery = await queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers(
- db,
- everyone,
- message.id,
- )
- const tasks: NotifyLeafTask[] = []
-
- for (const userId of mentionedIds) {
- const state = delivery.get(userId)
- if (
- !state?.isReadable ||
- !state.hasAttention ||
- !state.isUnread ||
- !queries.communityNotificationSetting.policyAllows(state.currentLevel, state.hasAttention)
- ) continue
- tasks.push({
- kind: "mention",
- userId,
- event: {
- type: WS_EVENTS.MENTION_CREATE,
- userId,
- messageId: message.id,
- channelId,
- authorName: ctx.authorName,
- },
- })
- }
-
- for (const userId of recipientIds) {
- const state = delivery.get(userId)
- if (
- !state?.isReadable ||
- !state.isUnread ||
- !queries.communityNotificationSetting.policyAllows(state.currentLevel, state.hasAttention)
- ) continue
- tasks.push({
- kind: "unread",
- userId,
- event: {
- type: WS_EVENTS.UNREAD_BUMP,
- userId,
- channelId,
- ...(opts.serverId !== undefined ? { serverId: opts.serverId } : {}),
- ...(opts.railChannelId !== undefined ? { railChannelId: opts.railChannelId } : {}),
- isMention: state.hasAttention,
- },
- })
- }
-
- const { results, maxActive } = await settleNotifyTasks(
- tasks,
- (task) => broadcastToUser(task.userId, task.event),
- )
- let mentionSuccess = 0
- let mentionFailure = 0
- let unreadSuccess = 0
- let unreadFailure = 0
-
- for (const [index, result] of results.entries()) {
- const succeeded = result.status === "fulfilled"
- if (tasks[index].kind === "mention") {
- if (succeeded) mentionSuccess += 1
- else mentionFailure += 1
- } else if (succeeded) {
- unreadSuccess += 1
- } else {
- unreadFailure += 1
- }
- }
-
- safeLog(() => log.info("dispatch_message_notify_complete", {
- messageId: message.id,
- recipientCount: recipientIds.length,
- mentionedCount: mentionedIds.length,
- leafTaskCount: tasks.length,
- mentionSuccess,
- mentionFailure,
- unreadSuccess,
- unreadFailure,
- maxActive,
- durationMs: Date.now() - startedAt,
- }))
- } catch (err) {
- safeLog(() => log.warn("dispatch_message_notify_failed", {
- messageId: message.id,
- err: String(err),
- durationMs: Date.now() - startedAt,
- }))
- }
-}
-
-export function dispatchMessageNotify(
- db: Database,
- ctx: MessageNotifyContext,
- message: { id: string; channelId: string },
- recipients: string[],
- opts: {
- mentionedUserIds: string[]
- serverId?: string
- railChannelId?: string
- },
-): Promise<void> {
- const work = runMessageNotify(db, ctx, message, recipients, opts)
- try {
- const cloudflareContext = getCloudflareContext()
- cloudflareContext.ctx.waitUntil(work)
- } catch {}
- return work
-}
diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.ts
index 90d78905a..8412c3d94 100644
--- a/src/web/src/lib/community/wake-producer.test.ts
+++ b/src/web/src/lib/community/wake-producer.test.ts
@@ -1,443 +1,76 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-const mockCtxWaitUntil = vi.fn((p: Promise<unknown>) => p)
const mockGetCloudflareContext = vi.fn(() => ({
- env: { DB: {}, WAKE_QUEUE: { __queue: true } },
- ctx: { waitUntil: mockCtxWaitUntil },
+ env: { WAKE_QUEUE: { queue: true } },
}))
vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: (...a: unknown[]) => mockGetCloudflareContext(...(a as [])),
-}))
-
-const mockFindWakeCandidates = vi.fn()
-const mockCanBotReadWakeScope = vi.fn()
-// Default: every bot passes the current-policy gate. Policy tests below
-// override individual states.
-const mockResolveNotificationEligibilityForUsers = vi.fn(
- async (_db: unknown, userIds: string[]) => new Map(userIds.map((id) => [id, {
- currentLevel: "all",
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- }])),
-)
-const mockWarn = vi.fn()
-const mockInfo = vi.fn()
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return {
- ...actual,
- createLogger: () => ({
- info: (...a: unknown[]) => mockInfo(...a),
- warn: (...a: unknown[]) => mockWarn(...a),
- error: vi.fn(),
- debug: vi.fn(),
- }),
- queries: {
- communityBot: {
- findWakeCandidates: (...a: unknown[]) => mockFindWakeCandidates(...a),
- },
- communityMember: {
- canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),
- },
- communityNotificationSetting: {
- policyAllows: actual.queries.communityNotificationSetting.policyAllows,
- },
- communityNotificationEligibility: {
- resolveNotificationEligibilityForUsers: (...a: unknown[]) =>
- mockResolveNotificationEligibilityForUsers(...(a as [unknown, string[]])),
- },
- },
- }
-})
-
-vi.mock("../db", () => ({
- getDb: vi.fn(() => ({})),
+ getCloudflareContext: () => mockGetCloudflareContext(),
}))
const mockQueueSend = vi.fn()
-const mockDevHttpSend = vi.fn()
+const mockDevSend = vi.fn()
const mockCreateQueueWakeTransport = vi.fn(() => ({ send: mockQueueSend }))
-const mockCreateDevHttpWakeTransport = vi.fn(() => ({ send: mockDevHttpSend }))
+const mockCreateDevHttpWakeTransport = vi.fn(() => ({ send: mockDevSend }))
vi.mock("./wake-transport", () => ({
- createQueueWakeTransport: (...a: unknown[]) => mockCreateQueueWakeTransport(...a),
- createDevHttpWakeTransport: (...a: unknown[]) => mockCreateDevHttpWakeTransport(...a),
+ createQueueWakeTransport: (...args: unknown[]) => mockCreateQueueWakeTransport(...args),
+ createDevHttpWakeTransport: (...args: unknown[]) => mockCreateDevHttpWakeTransport(...args),
}))
-import { enqueueBotWakes } from "./wake-producer"
-
-const messageRow = {
- id: "msg_1",
- seq: 7,
- authorId: "human_1",
- channelId: "c1",
- dmConversationId: null,
-}
+import { enqueueBotWakePayloads } from "./wake-producer"
-function defaultEligibility(_db: unknown, userIds: string[]) {
- return Promise.resolve(new Map(userIds.map((id) => [id, {
- currentLevel: "all",
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- }])))
-}
-
-describe("enqueueBotWakes", () => {
+describe("enqueueBotWakePayloads", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockResolveNotificationEligibilityForUsers.mockImplementation(defaultEligibility)
+ vi.stubEnv("NODE_ENV", "test")
mockQueueSend.mockResolvedValue(undefined)
- mockDevHttpSend.mockResolvedValue(undefined)
- // Default: every candidate passes the wake gate. Tests that need to
- // exercise gate-filtering override this per case.
- mockCanBotReadWakeScope.mockResolvedValue(true)
+ mockDevSend.mockResolvedValue(undefined)
})
- it("no-ops when recipients is empty — never queries or picks a transport", async () => {
- await enqueueBotWakes({ recipients: [], channelId: "c1", messageRow })
+ afterEach(() => vi.unstubAllEnvs())
- expect(mockFindWakeCandidates).not.toHaveBeenCalled()
+ it("does not construct a transport for an empty plan", async () => {
+ await expect(enqueueBotWakePayloads([])).resolves.toBeUndefined()
expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()
expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()
})
- it("no-ops when no candidates are behind — zero transport.send calls, not an empty one", async () => {
- mockFindWakeCandidates.mockResolvedValue([])
-
- await enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow })
-
- expect(mockQueueSend).not.toHaveBeenCalled()
+ it("sends only stable minimal payloads through the queue", async () => {
+ const payloads = [
+ { messageId: "msg_1", botUserId: "bot_1" },
+ { messageId: "msg_1", botUserId: "bot_2" },
+ ]
+ await enqueueBotWakePayloads(payloads)
+ expect(mockQueueSend).toHaveBeenCalledWith(payloads)
+ expect(mockDevSend).not.toHaveBeenCalled()
})
- it("builds a minimal { messageId, botUserId } payload per candidate and sends a single batch via the queue transport", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },
- { botUserId: "bot2", name: "kai", machineId: "m2", runtime: "codex" },
- ])
-
- await enqueueBotWakes({ recipients: ["bot1", "bot2"], channelId: "c1", messageRow })
-
- expect(mockFindWakeCandidates).toHaveBeenCalledWith(
- {},
- { recipients: ["bot1", "bot2"], channelId: "c1", dmConversationId: undefined, newSeq: 7 },
- )
- expect(mockCreateQueueWakeTransport).toHaveBeenCalledTimes(1)
- expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- const [payloads] = mockQueueSend.mock.calls[0]!
- expect(payloads).toEqual([
- { messageId: "msg_1", botUserId: "bot1" },
- { messageId: "msg_1", botUserId: "bot2" },
- ])
- })
-
- it("drops candidates that fail the wake gate (visibility / participation) before sending", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_visible", name: "zoe", machineId: "m1", runtime: "claude" },
- { botUserId: "bot_hidden", name: "kai", machineId: "m2", runtime: "codex" },
- ])
- mockCanBotReadWakeScope.mockImplementation(async (_db: unknown, botId: string) =>
- botId === "bot_visible",
- )
-
- await enqueueBotWakes({ recipients: ["bot_visible", "bot_hidden"], channelId: "c1", messageRow })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- const [payloads] = mockQueueSend.mock.calls[0]!
- expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_visible" }])
- })
-
- // ── Mute gate (net-new #4) ──────────────────────────────────────────────
- it("MUTE GATE — a bot at 'nothing' never wakes, even when mentioned", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_muted", name: "z", machineId: "m1", runtime: "claude" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_muted", {
- currentLevel: "nothing",
- hasAttention: true,
- isUnread: true,
- isReadable: true,
- }]]))
-
- await enqueueBotWakes({
- recipients: ["bot_muted"],
- channelId: "c1",
- messageRow,
- mentionedUserIds: ["bot_muted"], // even mentioned
- })
-
- expect(mockQueueSend).not.toHaveBeenCalled()
- })
-
- it("MUTE GATE — a bot at 'mentions' wakes only when in the mention set (incl. @everyone)", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_mentioned", name: "a", machineId: "m1", runtime: "claude" },
- { botUserId: "bot_plain", name: "b", machineId: "m2", runtime: "codex" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(
- new Map([
- ["bot_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],
- ["bot_plain", { currentLevel: "mentions", hasAttention: false, isUnread: true, isReadable: true }],
- ]),
- )
-
- await enqueueBotWakes({
- recipients: ["bot_mentioned", "bot_plain"],
- channelId: "c1",
- messageRow,
- mentionedUserIds: ["bot_mentioned"], // only this one is in the mention set
- })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- const [payloads] = mockQueueSend.mock.calls[0]!
- expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_mentioned" }])
- })
-
- it("MUTE GATE — a bot at 'all' wakes on any unread, mentioned or not", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_all", name: "a", machineId: "m1", runtime: "claude" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_all", {
- currentLevel: "all",
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- }]]))
-
- await enqueueBotWakes({
- recipients: ["bot_all"],
- channelId: "c1",
- messageRow,
- mentionedUserIds: [], // not mentioned — still wakes at 'all'
- })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- const [payloads] = mockQueueSend.mock.calls[0]!
- expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_all" }])
- })
-
- it("MUTE GATE — a bot with no setting defaults to 'all' (wakes) — covers DM independence (no server/parent to inherit a mute from)", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_dm", name: "a", machineId: "m1", runtime: "claude" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_dm", {
- currentLevel: "all",
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- }]]))
-
- await enqueueBotWakes({
- recipients: ["bot_dm"],
- channelId: "dm_channel",
- messageRow,
- mentionedUserIds: [],
- })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- })
-
- it("CURSOR GATE — a message cleared before deferred enqueue never wakes, while a newer unread does", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_1", name: "a", machineId: "m1", runtime: "claude" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([["bot_1", {
- currentLevel: "all",
- hasAttention: false,
- isUnread: false,
- isReadable: true,
- }]]))
-
- await enqueueBotWakes({ recipients: ["bot_1"], channelId: "c1", messageRow })
- expect(mockQueueSend).not.toHaveBeenCalled()
-
- mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([["bot_1", {
- currentLevel: "all",
- hasAttention: false,
- isUnread: true,
- isReadable: true,
- }]]))
- await enqueueBotWakes({
- recipients: ["bot_1"],
- channelId: "c1",
- messageRow: { ...messageRow, id: "msg_2", seq: 8 },
- })
- expect(mockQueueSend).toHaveBeenCalledWith([{ messageId: "msg_2", botUserId: "bot_1" }])
- })
-
- it("READABILITY GATE — a captured bot removed from the scope is dropped before enqueue", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_removed", name: "a", machineId: "m1", runtime: "claude" },
- ])
- mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_removed", {
- currentLevel: "all",
- hasAttention: true,
- isUnread: true,
- isReadable: false,
- }]]))
-
- await enqueueBotWakes({ recipients: ["bot_removed"], channelId: "c1", messageRow })
-
- expect(mockQueueSend).not.toHaveBeenCalled()
- })
-
- it("retains a candidate when its producer prefilter rejects without collapsing the batch", async () => {
- // Regression guard: a transient D1 blip on ONE candidate's gate check
- // must not permanently lose that candidate. The consumer performs the
- // authoritative access check and will retry transient failures there.
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_ok_1", name: "a", machineId: "m1", runtime: "claude" },
- { botUserId: "bot_flaky", name: "b", machineId: "m2", runtime: "codex" },
- { botUserId: "bot_ok_2", name: "c", machineId: "m3", runtime: "claude" },
- ])
- mockCanBotReadWakeScope.mockImplementation(async (_db: unknown, botId: string) => {
- if (botId === "bot_flaky") throw new Error("d1 blip")
- return true
- })
-
- await enqueueBotWakes({
- recipients: ["bot_ok_1", "bot_flaky", "bot_ok_2"],
- channelId: "c1",
- messageRow,
- })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(1)
- const [payloads] = mockQueueSend.mock.calls[0]!
- expect(payloads).toEqual([
- { messageId: "msg_1", botUserId: "bot_ok_1" },
- { messageId: "msg_1", botUserId: "bot_flaky" },
- { messageId: "msg_1", botUserId: "bot_ok_2" },
- ])
+ it("chunks the transport at 100 payloads", async () => {
+ const payloads = Array.from({ length: 201 }, (_, index) => ({
+ messageId: "msg_1",
+ botUserId: `bot_${index}`,
+ }))
+ await enqueueBotWakePayloads(payloads)
+ expect(mockQueueSend).toHaveBeenCalledTimes(3)
+ expect(mockQueueSend.mock.calls.map(([chunk]) => chunk.length)).toEqual([100, 100, 1])
})
- it("no-ops when every candidate fails the gate — never picks a transport", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot_a", name: "a", machineId: "m1", runtime: "claude" },
- { botUserId: "bot_b", name: "b", machineId: "m2", runtime: "codex" },
- ])
- mockCanBotReadWakeScope.mockResolvedValue(false)
-
- await enqueueBotWakes({ recipients: ["bot_a", "bot_b"], channelId: "c1", messageRow })
-
+ it("uses the dev HTTP transport only in development", async () => {
+ vi.stubEnv("NODE_ENV", "development")
+ const payloads = [{ messageId: "msg_1", botUserId: "bot_1" }]
+ await enqueueBotWakePayloads(payloads)
+ expect(mockDevSend).toHaveBeenCalledWith(payloads)
expect(mockQueueSend).not.toHaveBeenCalled()
- expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()
- })
-
- it("chunks into 100-candidate slices for large fanouts", async () => {
- const candidates = Array.from({ length: 250 }, (_, i) => ({
- botUserId: `bot${i}`,
- name: `bot${i}`,
- machineId: `m${i}`,
- runtime: "claude",
- }))
- mockFindWakeCandidates.mockResolvedValue(candidates)
-
- await enqueueBotWakes({
- recipients: candidates.map((c) => c.botUserId),
- channelId: "c1",
- messageRow,
- })
-
- expect(mockQueueSend).toHaveBeenCalledTimes(3)
- expect(mockQueueSend.mock.calls[0]![0]).toHaveLength(100)
- expect(mockQueueSend.mock.calls[1]![0]).toHaveLength(100)
- expect(mockQueueSend.mock.calls[2]![0]).toHaveLength(50)
})
- it("partial chunk failure: sibling chunks still send, failure is logged, call does not throw", async () => {
- const candidates = Array.from({ length: 250 }, (_, i) => ({
- botUserId: `bot${i}`,
- name: `bot${i}`,
- machineId: `m${i}`,
- runtime: "claude",
- }))
- mockFindWakeCandidates.mockResolvedValue(candidates)
+ it("settles every chunk and rejects when any chunk fails", async () => {
mockQueueSend
+ .mockRejectedValueOnce(new Error("queue down"))
.mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error("queue unavailable"))
- .mockResolvedValueOnce(undefined)
-
- await expect(
- enqueueBotWakes({ recipients: candidates.map((c) => c.botUserId), channelId: "c1", messageRow }),
- ).resolves.toBeUndefined()
-
- expect(mockQueueSend).toHaveBeenCalledTimes(3)
- expect(mockWarn).toHaveBeenCalledWith(
- "wake_batch_chunk_failed",
- expect.objectContaining({
- botIds: candidates.slice(100, 200).map((c) => c.botUserId),
- err: expect.stringContaining("queue unavailable"),
- }),
- )
- })
-
- it("registers ctx.waitUntil synchronously and does not require the caller to await", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },
- ])
-
- const promise = enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow })
- expect(mockCtxWaitUntil).toHaveBeenCalledTimes(1)
- await promise
- })
-
- it("falls back to running standalone (no throw) when not in a CF request context", async () => {
- mockGetCloudflareContext.mockImplementationOnce(() => ({
- env: { DB: {}, WAKE_QUEUE: { __queue: true } },
- ctx: { waitUntil: () => { throw new Error("no request context") } },
+ const payloads = Array.from({ length: 101 }, (_, index) => ({
+ messageId: "msg_1",
+ botUserId: `bot_${index}`,
}))
- mockFindWakeCandidates.mockResolvedValue([])
-
- await expect(enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow })).resolves.toBeUndefined()
- })
-})
-
-describe("enqueueBotWakes — dev HTTP transport selection (NODE_ENV=development)", () => {
- const originalNodeEnv = process.env.NODE_ENV
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockResolveNotificationEligibilityForUsers.mockImplementation(defaultEligibility)
- mockQueueSend.mockResolvedValue(undefined)
- mockDevHttpSend.mockResolvedValue(undefined)
- process.env.NODE_ENV = "development"
- })
-
- afterEach(() => {
- process.env.NODE_ENV = originalNodeEnv
- })
-
- it("picks the dev HTTP transport instead of the queue transport", async () => {
- mockFindWakeCandidates.mockResolvedValue([
- { botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" },
- { botUserId: "bot2", name: "kai", machineId: "m2", runtime: "codex" },
- ])
-
- await enqueueBotWakes({ recipients: ["bot1", "bot2"], channelId: "c1", messageRow })
-
- expect(mockCreateDevHttpWakeTransport).toHaveBeenCalledTimes(1)
- expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()
- expect(mockDevHttpSend).toHaveBeenCalledTimes(1)
- expect(mockQueueSend).not.toHaveBeenCalled()
- expect(mockDevHttpSend).toHaveBeenCalledWith([
- { messageId: "msg_1", botUserId: "bot1" },
- { messageId: "msg_1", botUserId: "bot2" },
- ])
- })
-
- it("logs and does not throw when the dev HTTP transport rejects", async () => {
- mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot1", name: "zoe", machineId: "m1", runtime: "claude" }])
- mockDevHttpSend.mockRejectedValue(new Error("alook-wake-worker unreachable"))
-
- await expect(
- enqueueBotWakes({ recipients: ["bot1"], channelId: "c1", messageRow }),
- ).resolves.toBeUndefined()
-
- expect(mockWarn).toHaveBeenCalledWith(
- "wake_batch_chunk_failed",
- expect.objectContaining({ err: expect.stringContaining("alook-wake-worker unreachable") }),
- )
+ await expect(enqueueBotWakePayloads(payloads)).rejects.toThrow("1 chunk")
+ expect(mockQueueSend).toHaveBeenCalledTimes(2)
})
})
diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.ts
index 95a91ac66..8935551bf 100644
--- a/src/web/src/lib/community/wake-producer.ts
+++ b/src/web/src/lib/community/wake-producer.ts
@@ -1,173 +1,43 @@
/**
- * Push-wake producer — after a message lands and the human-WS fanout has
- * broadcast it, this filters the fanout's recipient set down to "bots that
- * are actually behind on this scope" and hands one minimal `{ messageId,
- * botUserId }` payload per candidate off to a `WakeTransport`
- * (minimal-wake-queue-unread-notice plan §1/§5). Deliberately carries NO
- * `HostCommand`, `machineId`, runtime, or message content — the consumer
- * (real `alook-wake-worker`, in both transports — see `wake-transport.ts`)
- * rebuilds the `agent:wake` command from CURRENT D1 state at consume time
- * (`dispatchOneUnreadWake`/`buildUnreadWakeCommand`), so a stale item never
- * wakes an old machine or carries stale content.
- *
- * This module owns ONLY "who are the candidates" — it never talks to
- * `WAKE_QUEUE`/`WAKE_WORKER` directly and never re-implements what happens
- * to a candidate. See `wake-transport.ts` for which transport runs in which
- * environment and why (local Cloudflare Queues can't bridge separate
- * `wrangler dev`/`next dev` processes today).
+ * Transport-only producer for already planned committed-message wake targets.
+ * Audience, policy, readability, cursor, and bot selection live in the
+ * committed-message dispatcher; this seam only chunks stable minimal payloads
+ * onto the environment-appropriate transport.
*/
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, createLogger, withD1Retry } from "@alook/shared"
-import type { WakePayload } from "@alook/shared"
-import { getDb } from "../db"
-import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"
+import { createLogger, type WakePayload } from "@alook/shared"
+import { createDevHttpWakeTransport, createQueueWakeTransport } from "./wake-transport"
import type { WakeTransport } from "./wake-transport"
const log = createLogger({ service: "community-wake-producer" })
-
-// Cloudflare Queues caps a single `sendBatch` call at 100 messages; kept the
-// same batch size for the dev HTTP transport for a uniform code path.
const WAKE_BATCH_SIZE = 100
-/**
- * The just-inserted message row — lean, no body/preview (plan §1/§5): only
- * what `findWakeCandidates`' unread filter needs. Must include `seq` (see
- * `getMessage`'s select).
- */
-export interface WakeMessageRow {
- id: string
- seq: number
- authorId: string
- channelId: string
-}
-
-export interface EnqueueBotWakesOpts {
- /** Every fanout recipient (human + bot) — this function does its own bot/unread filtering. */
- recipients: string[]
- channelId: string
- messageRow: WakeMessageRow
- /**
- * Compatibility hint carried by the fan-out call. The authoritative gate
- * deliberately rehydrates persisted mention/reply facts with current policy,
- * so a stale or incomplete in-memory set cannot change delivery.
- */
- mentionedUserIds?: string[]
-}
-
-/**
- * Fire-and-forget from the caller's perspective, but NOT actually
- * fire-and-forget under the hood: this function acquires the Cloudflare
- * context and registers `ctx.waitUntil(...)` synchronously in its own first
- * tick (before any `await`), so the enclosing request's response can be
- * written and the isolate can still be kept alive long enough for the
- * transport call to land. Callers MUST invoke this before the response is
- * sent (same requirement as `broadcastToUser`/`fanOutToChannel`) — calling it
- * after the response has already been returned risks the `waitUntil`
- * registration being dropped.
- */
-export function enqueueBotWakes(opts: EnqueueBotWakesOpts): Promise<void> {
- const { env, ctx } = getCloudflareContext()
- const promise = doEnqueueBotWakes(env as Env, opts)
- try {
- ctx.waitUntil(promise.catch((err) => {
- log.warn("enqueue_bot_wakes_failed", { err: String(err) })
- }))
- } catch {
- // Not in a CF request context (e.g. some test harnesses) — the promise
- // still runs to completion on its own.
- }
- return promise
-}
-
-/**
- * `NODE_ENV === "development"` (never `test`, `production`, or an
- * opennextjs-cloudflare preview/deploy build — all of which set `NODE_ENV`
- * to something else) is the only case that gets the dev HTTP transport;
- * every other environment keeps the real Cloudflare Queue.
- */
function selectWakeTransport(env: Env): WakeTransport {
return process.env.NODE_ENV === "development"
? createDevHttpWakeTransport(env)
: createQueueWakeTransport(env.WAKE_QUEUE)
}
-async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<void> {
- const { recipients, channelId, messageRow } = opts
- if (recipients.length === 0) return
-
- const db = getDb(env.DB)
- const candidates = await withD1Retry(
- () => queries.communityBot.findWakeCandidates(db, { recipients, channelId, newSeq: messageRow.seq }),
- { route: "wake-producer:find-candidates" },
- )
- if (candidates.length === 0) return
-
- // Defense-in-depth visibility + participation gate. `findWakeCandidates`
- // starts from the fanout recipient set, which for well-behaved audience
- // helpers already excludes non-visible / non-participating bots — but a
- // future regression in a helper (or a new caller) could leak a bot in.
- // Re-check per candidate against the same wake gate the consumer uses
- // (`canBotReadWakeScope`), so this producer path is belt-and-suspenders.
- //
- // `allSettled` (not `all`): a transient D1 blip on ONE candidate's gate
- // check must not collapse the whole batch's enqueue. Rejected legs are
- // treated as "gate indeterminate" and retained because this check is only
- // a producer-side prefilter. The consumer re-runs the same gate
- // authoritatively and fails closed/retries if that check is unavailable.
- const scope: { channelId: string } = { channelId }
- const gateResults = await Promise.allSettled(
- candidates.map((c) => queries.communityMember.canBotReadWakeScope(db, c.botUserId, scope))
- )
- const gated = candidates.filter((c, i) => {
- const r = gateResults[i]!
- if (r.status === "rejected") {
- log.warn("wake_gate_check_failed", { botUserId: c.botUserId, err: String(r.reason) })
- return true
- }
- return r.value
- })
- if (gated.length === 0) return
-
- // Resolve current readability, read cursor, persisted attention, and policy
- // together so a deferred enqueue cannot relight cleared or revoked work.
- const eligibility = await withD1Retry(
- () =>
- queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers(
- db,
- gated.map((c) => c.botUserId),
- messageRow.id,
- ),
- { route: "wake-producer:notification-eligibility" },
- )
- const woken = gated.filter((c) => {
- const state = eligibility.get(c.botUserId)
- if (!state?.isReadable || !state.isUnread) return false
- return queries.communityNotificationSetting.policyAllows(
- state.currentLevel,
- state.hasAttention,
- )
- })
- if (woken.length === 0) return
-
- const payloads: WakePayload[] = woken.map((c) => ({
- messageId: messageRow.id,
- botUserId: c.botUserId,
- }))
-
+async function sendWakePayloads(env: Env, payloads: WakePayload[]): Promise<void> {
+ if (payloads.length === 0) return
+ const transport = selectWakeTransport(env)
const chunks: WakePayload[][] = []
- for (let i = 0; i < payloads.length; i += WAKE_BATCH_SIZE) {
- chunks.push(payloads.slice(i, i + WAKE_BATCH_SIZE))
+ for (let index = 0; index < payloads.length; index += WAKE_BATCH_SIZE) {
+ chunks.push(payloads.slice(index, index + WAKE_BATCH_SIZE))
}
-
- const transport = selectWakeTransport(env)
const results = await Promise.allSettled(chunks.map((chunk) => transport.send(chunk)))
- for (let i = 0; i < results.length; i++) {
- const r = results[i]!
- if (r.status === "rejected") {
- log.warn("wake_batch_chunk_failed", {
- botIds: chunks[i]!.map((p) => p.botUserId),
- err: String(r.reason),
- })
- }
+ const failures = results.filter((result) => result.status === "rejected")
+ if (failures.length > 0) {
+ log.warn("wake_batch_delivery_failed", {
+ chunkCount: chunks.length,
+ failedChunkCount: failures.length,
+ payloadCount: payloads.length,
+ })
+ throw new Error(`wake delivery failed for ${failures.length} chunk(s)`)
}
}
+
+export function enqueueBotWakePayloads(payloads: WakePayload[]): Promise<void> {
+ const { env } = getCloudflareContext()
+ return sendWakePayloads(env as Env, payloads)
+}
diff --git a/src/web/src/lib/community/wake-transport.ts b/src/web/src/lib/community/wake-transport.ts
index 85cac9938..1d12d86b1 100644
--- a/src/web/src/lib/community/wake-transport.ts
+++ b/src/web/src/lib/community/wake-transport.ts
@@ -1,4 +1,4 @@
-import { createLogger, DEV_WAKE_WORKER_URL } from "@alook/shared"
+import { createLogger, DEV_WAKE_WORKER_URL, parseStrictFailedSubset } from "@alook/shared"
import type { WakePayload } from "@alook/shared"
import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"
@@ -20,36 +20,18 @@ function parsePartialFailure(value: unknown, payloads: WakePayload[]): WakePaylo
const keys = Object.keys(value)
if (keys.length !== 1 || keys[0] !== "failed") return null
- const failed = (value as Record<string, unknown>).failed
- if (!Array.isArray(failed) || failed.length === 0 || !failed.every(isExactFailedCandidate)) return null
-
- const allowed = new Map<string, Set<string>>()
- for (const item of payloads) {
- let botIds = allowed.get(item.messageId)
- if (!botIds) {
- botIds = new Set<string>()
- allowed.set(item.messageId, botIds)
- }
- botIds.add(item.botUserId)
- }
-
- const seen = new Map<string, Set<string>>()
- for (const item of failed) {
- if (!allowed.get(item.messageId)?.has(item.botUserId)) return null
- let botIds = seen.get(item.messageId)
- if (!botIds) {
- botIds = new Set<string>()
- seen.set(item.messageId, botIds)
- }
- if (botIds.has(item.botUserId)) return null
- botIds.add(item.botUserId)
- }
-
- return failed
+ return parseStrictFailedSubset(
+ (value as Record<string, unknown>).failed,
+ payloads,
+ {
+ isTarget: isExactFailedCandidate,
+ key: (item) => `${item.messageId}\u0000${item.botUserId}`,
+ },
+ )
}
/**
- * How `enqueueBotWakes` hands a batch of wake candidates off to whatever
+ * How the committed-message dispatcher hands a batch of wake candidates to
* will actually resolve them. Exactly two implementations below — neither
* caller (`wake-producer.ts`) ever talks to `WAKE_QUEUE`/`WAKE_WORKER`
* directly, and neither ever re-implements "rebuild from D1, skip or
diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
new file mode 100644
index 000000000..53f320298
--- /dev/null
+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
@@ -0,0 +1,179 @@
+import { test, expect, userId } from "./_fixtures/community-fixture"
+import { composerEditable, expectMessageVisible, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
+import {
+ memberInfo,
+ seedChannel,
+ seedDm,
+ seedDmMessage,
+ seedForumThread,
+ seedJoinServer,
+ seedMessage,
+ seedServer,
+} from "./_fixtures/seed"
+import {
+ frozenF1090ebeDecoderAccepts,
+ proxyCommunityWebSockets,
+ type CapturedCommunityFrame,
+} from "./_fixtures/community-ws-proxy"
+
+function messageFrame(frame: CapturedCommunityFrame, channelId: string, content: string): boolean {
+ return frame.type === "community:message.create"
+ && frame.channelId === channelId
+ && frame.message?.content === content
+}
+
+test.describe.serial("committed message delivery QA", () => {
+ test("Q4: a parent-only forum viewer gets the parent projection and no child message", async ({ asUser }) => {
+ const serverId = await seedServer("alice", `Parent projection ${Date.now()}`)
+ const forumId = await seedChannel("alice", serverId, "parent-projection", "forum")
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
+ const threadId = await seedForumThread("alice", forumId, `Projection ${Date.now()}`, "opener")
+
+ const carol = await asUser("carol")
+ let armed = false
+ const carolFrames = await proxyCommunityWebSockets(carol.context)
+ await gotoAfterUserWsAuth(carol.page, `/c/channels/${serverId}/${forumId}`)
+ await expect(carol.page.getByTestId(`community-forum-post-${threadId}`)).toBeVisible({ timeout: 20_000 })
+ armed = true
+
+ const bob = await asUser("bob")
+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${threadId}`)
+ await expect(composerEditable(bob.page)).toBeVisible()
+ const body = `participant reply ${Date.now()}`
+ await sendMessage(bob.page, body)
+
+ await expect.poll(() => carolFrames.some((frame) => armed
+ && frame.type === "community:channel.child_update"
+ && frame.parentChannelId === forumId
+ && frame.channelId === threadId), { timeout: 20_000 }).toBe(true)
+ expect(carolFrames.some((frame) => messageFrame(frame, threadId, body))).toBe(false)
+ await expect(carol.page.getByText(body, { exact: false })).toHaveCount(0)
+ })
+
+ test("Q7 channel: a dropped message frame is repaired when a later seq arrives", async ({ asUser }) => {
+ const serverId = await seedServer("alice", `Gap channel ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "gap-channel")
+ await seedJoinServer("alice", "bob", serverId)
+ await seedMessage("alice", channelId, "gap baseline")
+
+ const bob = await asUser("bob")
+ let armed = false
+ let dropped = false
+ const frames = await proxyCommunityWebSockets(bob.context, (frame) => {
+ if (armed && !dropped && frame.type === "community:message.create" && frame.channelId === channelId) {
+ dropped = true
+ return "drop"
+ }
+ return "forward"
+ })
+ const gapRequests: string[] = []
+ bob.page.on("request", (request) => {
+ const url = new URL(request.url())
+ if (url.pathname === `/api/community/channels/${channelId}/messages` && url.searchParams.has("since")) {
+ gapRequests.push(url.toString())
+ }
+ })
+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)
+ await expect(composerEditable(bob.page)).toBeVisible()
+
+ const alice = await asUser("alice")
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
+ const missing = `missing channel ${Date.now()}`
+ const later = `later channel ${Date.now()}`
+ armed = true
+ await sendMessage(alice.page, missing)
+ await expect.poll(() => dropped, { timeout: 20_000 }).toBe(true)
+ await sendMessage(alice.page, later)
+
+ await expectMessageVisible(bob.page, missing)
+ await expectMessageVisible(bob.page, later)
+ expect(gapRequests.length).toBeGreaterThan(0)
+ expect(frames.filter((frame) => messageFrame(frame, channelId, missing))).toHaveLength(1)
+ })
+
+ test("Q7 DM: a dropped message frame is repaired when a later seq arrives", async ({ asUser }) => {
+ const dmId = await seedDm("alice", userId("bob"))
+ await seedDmMessage("alice", dmId, "dm gap baseline")
+ const bob = await asUser("bob")
+ let armed = false
+ let dropped = false
+ await proxyCommunityWebSockets(bob.context, (frame) => {
+ if (armed && !dropped && frame.type === "community:message.create" && frame.channelId === dmId) {
+ dropped = true
+ return "drop"
+ }
+ return "forward"
+ })
+ const gapRequests: string[] = []
+ bob.page.on("request", (request) => {
+ const url = new URL(request.url())
+ if (url.pathname === `/api/community/channels/${dmId}/messages` && url.searchParams.has("since")) {
+ gapRequests.push(url.toString())
+ }
+ })
+ await gotoAfterUserWsAuth(bob.page, `/c/me/${dmId}`)
+ await expect(composerEditable(bob.page)).toBeVisible()
+
+ const alice = await asUser("alice")
+ await gotoAfterUserWsAuth(alice.page, `/c/me/${dmId}`)
+ const missing = `missing dm ${Date.now()}`
+ const later = `later dm ${Date.now()}`
+ armed = true
+ await sendMessage(alice.page, missing)
+ await expect.poll(() => dropped, { timeout: 20_000 }).toBe(true)
+ await sendMessage(alice.page, later)
+
+ await expectMessageVisible(bob.page, missing)
+ await expectMessageVisible(bob.page, later)
+ expect(gapRequests.length).toBeGreaterThan(0)
+ })
+
+ test("Q8: the frozen f1090ebe browser decoder accepts live channel, mention, and DM frames", async ({ asUser }) => {
+ const serverId = await seedServer("alice", `Old decoder ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "old-decoder")
+ await seedJoinServer("alice", "bob", serverId)
+ const dmId = await seedDm("alice", userId("bob"))
+ const bobInfo = await memberInfo("alice", serverId, userId("bob"))
+
+ const bob = await asUser("bob")
+ const droppedDiagnostics: string[] = []
+ bob.page.on("console", (message) => {
+ if (message.text().includes("community_ws_frame_dropped")) droppedDiagnostics.push(message.text())
+ })
+ const frames = await proxyCommunityWebSockets(bob.context)
+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)
+ await expect(composerEditable(bob.page)).toBeVisible()
+
+ const alice = await asUser("alice")
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
+ const editable = composerEditable(alice.page)
+ await editable.click()
+ await editable.pressSequentially(`@${bobInfo.name.slice(0, 3)}`)
+ await alice.page.getByTestId(`community-mention-option-${bobInfo.id}`).click()
+ await editable.pressSequentially(" compatibility channel")
+ await alice.page.keyboard.press("Enter")
+ await expect.poll(() => frames.some((frame) => frame.type === "community:mention.create"), {
+ timeout: 20_000,
+ }).toBe(true)
+
+ await gotoAfterUserWsAuth(bob.page, `/c/me/${dmId}`)
+ await gotoAfterUserWsAuth(alice.page, `/c/me/${dmId}`)
+ const dmBody = `compatibility dm ${Date.now()}`
+ await sendMessage(alice.page, dmBody)
+ await expectMessageVisible(bob.page, dmBody)
+
+ const relevant = frames.filter((frame) => [
+ "community:message.create",
+ "community:unread.bump",
+ "community:mention.create",
+ "community:channel.member_add",
+ "community:channel.child_update",
+ ].includes(frame.type))
+ expect(relevant.some((frame) => frame.type === "community:message.create" && frame.channelId === channelId)).toBe(true)
+ expect(relevant.some((frame) => frame.type === "community:mention.create" && frame.channelId === channelId)).toBe(true)
+ expect(relevant.some((frame) => frame.type === "community:message.create" && frame.channelId === dmId)).toBe(true)
+ expect(relevant.every(frozenF1090ebeDecoderAccepts)).toBe(true)
+ expect(droppedDiagnostics).toEqual([])
+ })
+})
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
new file mode 100644
index 000000000..3abddee53
--- /dev/null
+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
@@ -0,0 +1,92 @@
+import type { BrowserContext, WebSocketRoute } from "@playwright/test"
+
+export type CapturedCommunityFrame = {
+ type: string
+ contractVersion?: number
+ channelId?: string
+ parentChannelId?: string
+ messageId?: string
+ message?: { id?: string; seq?: number; content?: string }
+ [key: string]: unknown
+}
+
+type FrameDecision = (frame: CapturedCommunityFrame) => "drop" | "forward"
+
+function parseCommunityFrame(message: string | Buffer): CapturedCommunityFrame | null {
+ try {
+ const value = JSON.parse(message.toString()) as unknown
+ if (
+ typeof value !== "object"
+ || value === null
+ || !("type" in value)
+ || typeof value.type !== "string"
+ || !value.type.startsWith("community:")
+ ) return null
+ return value as CapturedCommunityFrame
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Test-only transparent WS proxy. It records community browser-v1 frames and
+ * can drop selected server frames without adding a production fault hook.
+ */
+export async function proxyCommunityWebSockets(
+ context: BrowserContext,
+ decide: FrameDecision = () => "forward",
+): Promise<CapturedCommunityFrame[]> {
+ const frames: CapturedCommunityFrame[] = []
+ await context.routeWebSocket(/.*/, (client: WebSocketRoute) => {
+ const server = client.connectToServer()
+ server.onMessage((message) => {
+ const frame = parseCommunityFrame(message)
+ if (frame) {
+ frames.push(frame)
+ if (decide(frame) === "drop") return
+ }
+ client.send(message)
+ })
+ })
+ return frames
+}
+
+// Frozen compatibility surface from the pre-change browser at f1090ebe. The
+// dispatcher may change internal batching, but these exact browser-v1 shapes
+// must remain consumable without a new wire event.
+const F1090EBE_TYPES = new Set([
+ "community:message.create",
+ "community:unread.bump",
+ "community:mention.create",
+ "community:channel.member_add",
+ "community:channel.child_update",
+])
+
+export function frozenF1090ebeDecoderAccepts(frame: CapturedCommunityFrame): boolean {
+ if (frame.contractVersion !== 1 || !F1090EBE_TYPES.has(frame.type)) return false
+ if (frame.type === "community:message.create") {
+ return typeof frame.channelId === "string"
+ && typeof frame.message?.id === "string"
+ && typeof frame.message.seq === "number"
+ && typeof frame.message.content === "string"
+ }
+ if (frame.type === "community:unread.bump") {
+ return typeof frame.channelId === "string"
+ && typeof frame.userId === "string"
+ && typeof frame.isMention === "boolean"
+ }
+ if (frame.type === "community:mention.create") {
+ return typeof frame.channelId === "string"
+ && typeof frame.messageId === "string"
+ && typeof frame.userId === "string"
+ }
+ if (frame.type === "community:channel.member_add") {
+ return typeof frame.channelId === "string"
+ && typeof frame.serverId === "string"
+ && typeof frame.userId === "string"
+ }
+ return typeof frame.channelId === "string"
+ && typeof frame.parentChannelId === "string"
+ && typeof frame.changes === "object"
+ && frame.changes !== null
+}
diff --git a/src/web/src/test/e2e/message-delivery-retry.test.ts b/src/web/src/test/e2e/message-delivery-retry.test.ts
new file mode 100644
index 000000000..a6e5457dd
--- /dev/null
+++ b/src/web/src/test/e2e/message-delivery-retry.test.ts
@@ -0,0 +1,80 @@
+import { createServer, type Server } from "node:http"
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"
+import type { MessageDeliveryBatch } from "@alook/shared"
+
+const fake = vi.hoisted(() => ({ url: "" }))
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => ({
+ env: { DEV_WS_DO_URL: fake.url },
+ ctx: { waitUntil: vi.fn() },
+ }),
+}))
+
+import { sendMessageDeliveryBatch } from "../../lib/community/message-delivery-transport"
+
+const requests: MessageDeliveryBatch[] = []
+let server: Server
+
+function batch(): MessageDeliveryBatch {
+ return {
+ messageId: "message-qa-1",
+ messageEvent: {
+ type: "community:message.create",
+ channelId: "channel-qa-1",
+ serverId: "server-qa-1",
+ message: {
+ id: "message-qa-1",
+ seq: 3,
+ authorId: "author",
+ authorName: "Author",
+ content: "failed-only retry",
+ type: "chat",
+ createdAt: "2026-08-18T00:00:00.000Z",
+ },
+ },
+ contentUserIds: ["author", "healthy", "retry"],
+ unreadPlainUserIds: ["healthy", "retry"],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ }
+}
+
+beforeAll(async () => {
+ server = createServer((request, response) => {
+ let body = ""
+ request.setEncoding("utf8")
+ request.on("data", (chunk) => { body += chunk })
+ request.on("end", () => {
+ requests.push(JSON.parse(body) as MessageDeliveryBatch)
+ response.statusCode = requests.length === 1 ? 207 : 200
+ response.setHeader("content-type", "application/json")
+ response.end(JSON.stringify({ failedUserIds: requests.length === 1 ? ["retry"] : [] }))
+ })
+ })
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
+ const address = server.address()
+ if (!address || typeof address === "string") throw new Error("fake ws-do did not bind")
+ fake.url = `http://127.0.0.1:${address.port}`
+})
+
+afterAll(async () => {
+ await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
+})
+
+describe("message delivery failed-only retry QA", () => {
+ it("retries only the failed target after a real HTTP 207", async () => {
+ await sendMessageDeliveryBatch(batch())
+
+ expect(requests).toHaveLength(2)
+ expect(requests[0]?.contentUserIds).toEqual(["author", "healthy", "retry"])
+ expect(requests[1]).toMatchObject({
+ contentUserIds: ["retry"],
+ unreadPlainUserIds: ["retry"],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ })
+ expect(requests[1]?.contentUserIds).not.toContain("healthy")
+ expect(requests[1]?.contentUserIds).not.toContain("author")
+ })
+})
diff --git a/src/ws-do/src/community-browser-event-ingress.ts b/src/ws-do/src/community-browser-event-ingress.ts
index 8d2d05c91..e863c08d3 100644
--- a/src/ws-do/src/community-browser-event-ingress.ts
+++ b/src/ws-do/src/community-browser-event-ingress.ts
@@ -1,5 +1,7 @@
import {
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
+ MESSAGE_DELIVERY_BODY_MAX_BYTES,
+ MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,
COMMUNITY_USER_TARGET_PATH_PREFIX,
decodeCommunityBrowserEvent,
encodeCommunityBrowserEvent,
@@ -119,6 +121,41 @@ export async function readCommunityBrowserEventRequest(
return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount)
}
+export async function readCommunityBrowserEventBundleRequest(
+ request: Request,
+): Promise<
+ | { ok: true; bodies: string[]; eventCount: number }
+ | CommunityBrowserEventIngressFailure
+> {
+ const parsed = await readBoundedJsonRequest(request, MESSAGE_DELIVERY_BODY_MAX_BYTES)
+ if (!parsed.ok) return parsed
+ if (
+ typeof parsed.value !== "object"
+ || parsed.value === null
+ || Array.isArray(parsed.value)
+ || Object.keys(parsed.value).length !== 1
+ || !Object.prototype.hasOwnProperty.call(parsed.value, "events")
+ ) {
+ return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
+ }
+ const events = (parsed.value as { events?: unknown }).events
+ if (
+ !Array.isArray(events)
+ || events.length === 0
+ || events.length > MESSAGE_DELIVERY_MAX_EVENTS_PER_USER
+ ) {
+ return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
+ }
+ const normalized = events.map((event) => normalizeCommunityBrowserEvent(event))
+ const failure = normalized.find((event) => !event.ok)
+ if (failure && !failure.ok) return failure
+ return {
+ ok: true,
+ bodies: normalized.map((event) => (event as CommunityBrowserEventIngressSuccess).body),
+ eventCount: normalized.length,
+ }
+}
+
export function decodeCommunityTargetPathSegment(encodedTarget: string):
| { ok: true; target: string }
| CommunityBrowserEventIngressFailure {
@@ -151,7 +188,7 @@ export function invalidCommunityBrowserEventResponse(
export function logCommunityBrowserEventRejected(
log: { warn: (message: string, metadata: Record<string, unknown>) => void },
- route: "strict-single" | "strict-bulk" | "target-do" | "ws-do-producer",
+ route: "strict-single" | "strict-bulk" | "target-do" | "target-do-bundle" | "ws-do-producer",
failure: CommunityBrowserEventIngressFailure,
targetCount?: number,
) {
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index ca48d4d49..4e428c5b0 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -78,6 +78,7 @@ describe("ws-do router", () => {
"handleDaemonBroadcast",
"handleCommunityUserBroadcast",
"handleCommunityUsersBroadcast",
+ "handleMessageDelivery",
"handleUserBroadcast",
"handleUsersBroadcast",
"handleAuditBroadcast",
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 1ff2b67bd..0dbae8668 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -8,6 +8,7 @@ import {
} from "./routes/broadcast"
import { handleMachinePush, handleMachineWake } from "./routes/community-machine-delivery"
import { handleMachineDiagnostics } from "./routes/community-machine-diagnostics"
+import { handleMessageDelivery } from "./routes/message-delivery"
import {
handleMachineBatchReset,
handleMachineForceClose,
@@ -49,6 +50,8 @@ export default {
if (response) return response
response = await handleCommunityUsersBroadcast(context)
if (response) return response
+ response = await handleMessageDelivery(context)
+ if (response) return response
response = await handleUserBroadcast(context)
if (response) return response
response = await handleUsersBroadcast(context)
diff --git a/src/ws-do/src/internal-user-broadcast.ts b/src/ws-do/src/internal-user-broadcast.ts
index f34c8acd8..371dfe418 100644
--- a/src/ws-do/src/internal-user-broadcast.ts
+++ b/src/ws-do/src/internal-user-broadcast.ts
@@ -41,6 +41,21 @@ export function createInternalCommunityUserBroadcastRequest(
})
}
+export function createInternalCommunityUserBundleRequest(
+ targetUserId: string,
+ events: readonly unknown[],
+): Request {
+ const headers = new Headers({
+ "content-type": "application/json",
+ [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent(targetUserId),
+ })
+ return new Request("http://internal/community-broadcast-bundle", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ events }),
+ })
+}
+
export function createInternalBrowserBroadcastRequest(
targetUserId: string,
payload: unknown,
diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.ts
new file mode 100644
index 000000000..a48169c05
--- /dev/null
+++ b/src/ws-do/src/routes/message-delivery.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"
+import {
+ createRouterTestContext,
+ loadRouter,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const messageEvent = {
+ type: "community:message.create" as const,
+ channelId: "thread-1",
+ serverId: "server-1",
+ parentChannelId: "forum-1",
+ message: {
+ id: "message-1",
+ seq: 4,
+ authorId: "author",
+ authorName: "Alice",
+ content: "hello",
+ type: "chat" as const,
+ createdAt: "2026-08-18T00:00:00.000Z",
+ },
+}
+
+const batch = {
+ messageId: "message-1",
+ messageEvent,
+ contentUserIds: ["author", "overlap"],
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: ["overlap"],
+ mentionUserIds: ["overlap", "mention-only"],
+ memberAdded: { userId: "author", serverId: "server-1", channelId: "thread-1" },
+ parentProjection: {
+ type: "community:channel.child_update" as const,
+ parentChannelId: "forum-1",
+ channelId: "thread-1",
+ changes: { messageCount: 4, lastMessageAt: "2026-08-18T00:00:00.000Z" },
+ },
+ parentProjectionUserIds: ["overlap", "parent-only"],
+}
+
+describe("message delivery route", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.resetModules()
+ })
+
+ it("inverts buckets into one ordered bundle per user", async () => {
+ doMock.stubFetch.mockImplementation(async (request: Request) => {
+ const body = await request.clone().json() as { events: unknown[] }
+ return Response.json({ accepted: body.events.length })
+ })
+
+ const response = await handler.fetch(new Request(
+ "http://localhost/broadcast/community/message-delivery",
+ { method: "POST", body: JSON.stringify(batch) },
+ ), env as never)
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({ failedUserIds: [] })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(4)
+ const calls = await Promise.all(doMock.stubFetch.mock.calls.map(async ([request]) => {
+ const req = request as Request
+ return {
+ userId: decodeURIComponent(req.headers.get(INTERNAL_USER_TARGET_HEADER)!),
+ types: ((await req.clone().json()) as { events: Array<{ type: string }> }).events.map((event) => event.type),
+ }
+ }))
+ expect(calls).toContainEqual({
+ userId: "overlap",
+ types: [
+ "community:message.create",
+ "community:unread.bump",
+ "community:mention.create",
+ "community:channel.child_update",
+ ],
+ })
+ expect(calls).toContainEqual({ userId: "mention-only", types: ["community:mention.create"] })
+ expect(calls).toContainEqual({ userId: "parent-only", types: ["community:channel.child_update"] })
+ })
+
+ it("returns an exact failed subset while healthy siblings complete", async () => {
+ doMock.stubFetch.mockImplementation(async (request: Request) => {
+ const userId = decodeURIComponent(request.headers.get(INTERNAL_USER_TARGET_HEADER)!)
+ if (userId === "overlap") return new Response("bad", { status: 502 })
+ const body = await request.clone().json() as { events: unknown[] }
+ return Response.json({ accepted: body.events.length })
+ })
+
+ const response = await handler.fetch(new Request(
+ "http://localhost/broadcast/community/message-delivery",
+ { method: "POST", body: JSON.stringify(batch) },
+ ), env as never)
+
+ expect(response.status).toBe(207)
+ await expect(response.json()).resolves.toEqual({ failedUserIds: ["overlap"] })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(4)
+ })
+
+ it.each([
+ ["throws", () => Promise.reject(new Error("DO unavailable"))],
+ ["returns invalid JSON", () => Promise.resolve(new Response("not-json"))],
+ ["returns an invalid receipt", () => Promise.resolve(Response.json({ accepted: -1 }))],
+ ])("returns only the failed target when one user DO %s", async (_label, failedResponse) => {
+ doMock.stubFetch.mockImplementation(async (request: Request) => {
+ const userId = decodeURIComponent(request.headers.get(INTERNAL_USER_TARGET_HEADER)!)
+ if (userId === "overlap") return failedResponse()
+ const body = await request.clone().json() as { events: unknown[] }
+ return Response.json({ accepted: body.events.length })
+ })
+
+ const response = await handler.fetch(new Request(
+ "http://localhost/broadcast/community/message-delivery",
+ { method: "POST", body: JSON.stringify(batch) },
+ ), env as never)
+
+ expect(response.status).toBe(207)
+ await expect(response.json()).resolves.toEqual({ failedUserIds: ["overlap"] })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(4)
+ })
+
+ it("delivers the maximum 1,000 distinct targets exactly once", async () => {
+ const userIds = Array.from({ length: 1_000 }, (_, index) => `user-${index}`)
+ doMock.stubFetch.mockImplementation(async () => Response.json({ accepted: 1 }))
+ const response = await handler.fetch(new Request(
+ "http://localhost/broadcast/community/message-delivery",
+ {
+ method: "POST",
+ body: JSON.stringify({
+ ...batch,
+ contentUserIds: userIds,
+ unreadPlainUserIds: [],
+ unreadMentionUserIds: [],
+ mentionUserIds: [],
+ memberAdded: undefined,
+ parentProjection: undefined,
+ parentProjectionUserIds: undefined,
+ }),
+ },
+ ), env as never)
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({ failedUserIds: [] })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(1_000)
+ })
+
+ it.each([
+ ["invalid JSON", "{"],
+ ["extra key", JSON.stringify({ ...batch, extra: true })],
+ ["cross-scope member", JSON.stringify({ ...batch, memberAdded: { ...batch.memberAdded, channelId: "other" } })],
+ ])("rejects %s before DO access", async (_label, body) => {
+ const response = await handler.fetch(new Request(
+ "http://localhost/broadcast/community/message-delivery",
+ { method: "POST", body },
+ ), env as never)
+ expect(response.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.ts
new file mode 100644
index 000000000..b2d088979
--- /dev/null
+++ b/src/ws-do/src/routes/message-delivery.ts
@@ -0,0 +1,163 @@
+import {
+ MESSAGE_DELIVERY_BODY_MAX_BYTES,
+ WS_EVENTS,
+ encodeCommunityBrowserEvent,
+ parseMessageDeliveryBatch,
+ type CommunityWsEvent,
+} from "@alook/shared"
+import { readBoundedJsonRequest } from "../community-browser-event-ingress"
+import { createInternalCommunityUserBundleRequest } from "../internal-user-broadcast"
+import type { RouterContext } from "../router-context"
+import { settleInBatches } from "../settle-in-batches"
+
+const targetBatchSize = 40
+
+type TargetResult =
+ | { ok: true }
+ | { ok: false; kind: "throw" | "non-ok" | "invalid-json" | "invalid-receipt" }
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+function addEvent(
+ bundles: Map<string, CommunityWsEvent[]>,
+ userId: string,
+ event: CommunityWsEvent,
+): void {
+ const events = bundles.get(userId) ?? []
+ events.push(event)
+ bundles.set(userId, events)
+}
+
+async function deliverTarget(
+ env: Env,
+ userId: string,
+ events: CommunityWsEvent[],
+): Promise<TargetResult> {
+ const envelopes: unknown[] = []
+ for (const event of events) {
+ const encoded = encodeCommunityBrowserEvent(event)
+ if (!encoded.ok) return { ok: false, kind: "invalid-receipt" }
+ envelopes.push(encoded.event)
+ }
+ try {
+ const id = env.WS_DO.idFromName(`user:${userId}`)
+ const response = await env.WS_DO.get(id).fetch(
+ createInternalCommunityUserBundleRequest(userId, envelopes),
+ )
+ if (!response.ok) return { ok: false, kind: "non-ok" }
+ let receipt: unknown
+ try {
+ receipt = await response.json()
+ } catch {
+ return { ok: false, kind: "invalid-json" }
+ }
+ if (
+ !isRecord(receipt)
+ || Object.keys(receipt).length !== 1
+ || receipt.accepted !== events.length
+ ) {
+ return { ok: false, kind: "invalid-receipt" }
+ }
+ return { ok: true }
+ } catch {
+ return { ok: false, kind: "throw" }
+ }
+}
+
+export async function handleMessageDelivery(
+ { request, env, url, traceId, log }: RouterContext,
+): Promise<Response | null> {
+ if (url.pathname !== "/broadcast/community/message-delivery" || request.method !== "POST") {
+ return null
+ }
+ const parsedBody = await readBoundedJsonRequest(request, MESSAGE_DELIVERY_BODY_MAX_BYTES)
+ if (!parsedBody.ok) {
+ return Response.json({ error: "invalid message delivery", reason: parsedBody.reason }, { status: 400 })
+ }
+ const parsed = parseMessageDeliveryBatch(parsedBody.value)
+ if (!parsed.ok) {
+ return Response.json({ error: "invalid message delivery", reason: parsed.reason }, { status: 400 })
+ }
+ const batch = parsed.batch
+ const bundles = new Map<string, CommunityWsEvent[]>()
+
+ for (const userId of batch.contentUserIds) addEvent(bundles, userId, batch.messageEvent)
+ for (const userId of batch.unreadPlainUserIds) {
+ addEvent(bundles, userId, {
+ type: WS_EVENTS.UNREAD_BUMP,
+ userId,
+ channelId: batch.messageEvent.channelId,
+ ...(batch.messageEvent.serverId ? { serverId: batch.messageEvent.serverId } : {}),
+ ...(batch.messageEvent.serverId
+ ? { railChannelId: batch.messageEvent.parentChannelId ?? batch.messageEvent.channelId }
+ : {}),
+ isMention: false,
+ })
+ }
+ for (const userId of batch.unreadMentionUserIds) {
+ addEvent(bundles, userId, {
+ type: WS_EVENTS.UNREAD_BUMP,
+ userId,
+ channelId: batch.messageEvent.channelId,
+ ...(batch.messageEvent.serverId ? { serverId: batch.messageEvent.serverId } : {}),
+ ...(batch.messageEvent.serverId
+ ? { railChannelId: batch.messageEvent.parentChannelId ?? batch.messageEvent.channelId }
+ : {}),
+ isMention: true,
+ })
+ }
+ for (const userId of batch.mentionUserIds) {
+ addEvent(bundles, userId, {
+ type: WS_EVENTS.MENTION_CREATE,
+ userId,
+ messageId: batch.messageId,
+ channelId: batch.messageEvent.channelId,
+ authorName: batch.messageEvent.message.authorName,
+ })
+ }
+ if (batch.memberAdded) {
+ addEvent(bundles, batch.memberAdded.userId, {
+ type: WS_EVENTS.CHANNEL_MEMBER_ADD,
+ ...batch.memberAdded,
+ })
+ }
+ if (batch.parentProjection && batch.parentProjectionUserIds) {
+ for (const userId of batch.parentProjectionUserIds) {
+ addEvent(bundles, userId, batch.parentProjection)
+ }
+ }
+
+ const entries = [...bundles.entries()]
+ const startedAt = Date.now()
+ const results = await settleInBatches(
+ entries,
+ ([userId, events]) => deliverTarget(env, userId, events),
+ targetBatchSize,
+ )
+ const failedUserIds: string[] = []
+ const failureCounts = { throw: 0, "non-ok": 0, "invalid-json": 0, "invalid-receipt": 0 }
+ for (const [index, result] of results.entries()) {
+ const target = entries[index]!
+ if (result.status === "rejected") {
+ failedUserIds.push(target[0])
+ failureCounts.throw += 1
+ } else if (!result.value.ok) {
+ failedUserIds.push(target[0])
+ failureCounts[result.value.kind] += 1
+ }
+ }
+ log.info("message_delivery_complete", {
+ traceId,
+ messageId: batch.messageId,
+ targetCount: entries.length,
+ failedCount: failedUserIds.length,
+ failureCounts,
+ durationMs: Date.now() - startedAt,
+ })
+ return Response.json(
+ { failedUserIds },
+ { status: failedUserIds.length > 0 ? 207 : 200 },
+ )
+}
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
index 5fc719881..e28771fef 100644
--- a/src/ws-do/src/ws-durable/user-auth.test.ts
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -110,6 +110,81 @@ describe("WebSocketDurableObject", () => {
})
})
+ describe("fetch — strict community ordered bundle", () => {
+ const events = [
+ {
+ type: "community:message.create",
+ channelId: "ch-1",
+ message: {
+ id: "m-1",
+ seq: 1,
+ authorId: "author",
+ authorName: "Alice",
+ content: "hello",
+ type: "chat",
+ createdAt: "2026-08-18T00:00:00.000Z",
+ },
+ contractVersion: 1,
+ },
+ {
+ type: "community:unread.bump",
+ userId: "user-42",
+ channelId: "ch-1",
+ isMention: false,
+ contractVersion: 1,
+ },
+ {
+ type: "community:mention.create",
+ userId: "user-42",
+ messageId: "m-1",
+ channelId: "ch-1",
+ authorName: "Alice",
+ contractVersion: 1,
+ },
+ ]
+
+ it("validates all events before sending them in order to every target tab", async () => {
+ const { durable, ctx } = createDO()
+ const first = createMockWebSocket()
+ const second = createMockWebSocket()
+ first.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+ second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])
+
+ const response = await durable.fetch(new Request("http://internal/community-broadcast-bundle", {
+ method: "POST",
+ headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
+ body: JSON.stringify({ events }),
+ }))
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({ accepted: 3 })
+ expect(first.send.mock.calls.map(([body]) => JSON.parse(body as string).type)).toEqual([
+ "community:message.create",
+ "community:unread.bump",
+ "community:mention.create",
+ ])
+ expect(second.send).toHaveBeenCalledTimes(3)
+ })
+
+ it("sends zero frames when any event is invalid", async () => {
+ const { durable, ctx } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
+ const invalid = [...events, { type: "community:unknown", contractVersion: 1 }]
+
+ const response = await durable.fetch(new Request("http://internal/community-broadcast-bundle", {
+ method: "POST",
+ headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
+ body: JSON.stringify({ events: invalid }),
+ }))
+
+ expect(response.status).toBe(400)
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+ })
+
describe("fetch — WebSocket upgrade", () => {
it("returns 101 for valid WebSocket upgrade", async () => {
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
index fb16a7755..59b3a2860 100644
--- a/src/ws-do/src/ws-durable/user-auth.ts
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -23,6 +23,7 @@ import {
import {
invalidCommunityBrowserEventResponse,
logCommunityBrowserEventRejected,
+ readCommunityBrowserEventBundleRequest,
readCommunityBrowserEventRequest,
} from "../community-browser-event-ingress"
@@ -31,6 +32,24 @@ export async function handleUserFetch(
request: Request,
url: URL,
): Promise<Response | null> {
+ if (url.pathname === "/community-broadcast-bundle" && request.method === "POST") {
+ const targetUserId = getInternalCommunityUserTarget(request)
+ if (!isValidCommunityUserTarget(targetUserId)) {
+ const failure = { ok: false, reason: "invalid-target", type: "unknown" } as const
+ logCommunityBrowserEventRejected(context.log, "target-do-bundle", failure)
+ return invalidCommunityBrowserEventResponse(failure)
+ }
+ const bundle = await readCommunityBrowserEventBundleRequest(request)
+ if (!bundle.ok) {
+ logCommunityBrowserEventRejected(context.log, "target-do-bundle", bundle)
+ return invalidCommunityBrowserEventResponse(bundle)
+ }
+ broadcastBundle(context, bundle.bodies, targetUserId)
+ return new Response(JSON.stringify({ accepted: bundle.eventCount }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
if (url.pathname === "/community-broadcast" && request.method === "POST") {
const targetUserId = getInternalCommunityUserTarget(request)
if (!isValidCommunityUserTarget(targetUserId)) {
@@ -309,6 +328,26 @@ function broadcast(
return sent
}
+function broadcastBundle(
+ context: WsDurableContext,
+ messages: readonly string[],
+ targetUserId: string,
+): void {
+ for (const ws of context.ctx.getWebSockets()) {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (!state?.authenticated) continue
+ if (state.type !== "user" || state.userId !== targetUserId) {
+ if (state.type === "user") {
+ invalidateMismatchedUserSocket(context, ws, state, targetUserId, "broadcast")
+ }
+ continue
+ }
+ for (const message of messages) {
+ try { ws.send(message) } catch { }
+ }
+ }
+}
+
function invalidateMismatchedUserSocket(
context: WsDurableContext,
ws: WebSocket,
diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.ts
index 1cb76d910..4af945129 100644
--- a/tests/integration/daemon/control-plane.test.ts
+++ b/tests/integration/daemon/control-plane.test.ts
@@ -4,7 +4,7 @@
* suite instead drives the ACTUAL production path end to end:
*
* POST /api/community/channels/:id/messages (human, real HTTP)
- * → fanOutToChannel → enqueueBotWakes (dev HTTP transport)
+ * → committed message dispatcher → wake producer (dev HTTP transport)
* → alook-wake-worker (real process) → dispatchOneUnreadWake
* → sendWakeToMachine → alook-ws-do (real DO) → the daemon's real
* `WsControlChannel`, over a real WebSocket, receives `agent:wake`
@@ -142,7 +142,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
await opened
// Human owner posts a real message — exercises the real wake-producer
- // path (fanOutToChannel → enqueueBotWakes → dev HTTP transport →
+ // path (committed dispatcher → wake producer → dev HTTP transport →
// wake-worker → forward-agent-wake → the DO → our open socket).
const postRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie, {
method: "POST",