Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): make writes atomic and harden post-commit delivery (#781)

Gustavo Ye82051dd2c081
diff --git a/scripts/ci/d1-dynamic-bind-contract.test.ts b/scripts/ci/d1-dynamic-bind-contract.test.ts
index cdd469f74..e36ea6908 100644
--- a/scripts/ci/d1-dynamic-bind-contract.test.ts
+++ b/scripts/ci/d1-dynamic-bind-contract.test.ts
@@ -34,6 +34,7 @@ describe("D1 dynamic bind strategy contract", () => {
it("requires strategy-specific bind budgets", () => {
const exportedLimits = [
"src/shared/src/constants.ts",
+ "src/shared/src/constants/community.ts",
"src/shared/src/schemas.ts",
"src/shared/src/index.ts",
].map((file) => readFileSync(resolve(root, file), "utf8")).join("\n")
diff --git a/scripts/ci/d1-dynamic-bind-contract.ts b/scripts/ci/d1-dynamic-bind-contract.ts
index 976b243f5..64af52188 100644
--- a/scripts/ci/d1-dynamic-bind-contract.ts
+++ b/scripts/ci/d1-dynamic-bind-contract.ts
@@ -9,7 +9,7 @@ export interface DynamicBindSite {
file: string
functionName: string
operator: DynamicBindOperator
- strategyHint: "fixed-literal" | "exact-chunk" | "json-set" | "subquery"
+ strategyHint: "fixed-literal" | "exact-chunk" | "json-set" | "subquery" | "bounded-public-input"
fixedParamsHint?: number
}
@@ -132,17 +132,26 @@ export function scanDynamicBindSites(root: string, sourceOverride?: { file: stri
const key = `${relativeFile}:${functionName}:${operator}:${ordinal}`
const hint = bindStrategyHint(node, operator)
const fixedParamsByKey: Record<string, number> = {
+ "src/shared/src/db/queries/community/channel.ts:createChannel:values:1": 0,
+ "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:1": 0,
+ "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:2": 0,
"src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:1": 0,
"src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:2": 2,
"src/shared/src/db/queries/community/member.ts:getMembersByUserIds:inArray:1": 1,
"src/shared/src/db/queries/community/reaction.ts:listReactionsByMessageIds:inArray:1": 0,
}
+ const boundedAttachmentSites = new Set([
+ "src/shared/src/db/queries/community/message.ts:eligibleAttachments:inArray:1",
+ "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:1",
+ "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:2",
+ "src/shared/src/db/queries/community/message.ts:insertMessageRow:sql.join:1",
+ ])
sites.push({
key,
file: relativeFile,
functionName,
operator,
- ...hint,
+ ...(boundedAttachmentSites.has(key) ? { strategyHint: "bounded-public-input" as const } : hint),
...(hint.strategyHint === "exact-chunk" && key in fixedParamsByKey
? { fixedParamsHint: fixedParamsByKey[key] }
: {}),
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index e050b4a74..d0edf1cd1 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -496,6 +496,11 @@
"key": "src/shared/src/db/queries/community/category.ts:reorderCategories:inArray:1",
"strategy": "subquery"
},
+ {
+ "key": "src/shared/src/db/queries/community/channel.ts:createChannel:values:1",
+ "strategy": "exact-chunk",
+ "fixedParams": 0
+ },
{
"key": "src/shared/src/db/queries/community/channel.ts:deleteChannelMemberAndChildParticipants:inArray:1",
"strategy": "subquery"
@@ -708,6 +713,11 @@
"strategy": "exact-chunk",
"fixedParams": 10
},
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:eligibleAttachments:inArray:1",
+ "strategy": "bounded-public-input",
+ "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"
+ },
{
"key": "src/shared/src/db/queries/community/message.ts:getMessagesByIds:inArray:1",
"strategy": "exact-chunk",
@@ -718,6 +728,31 @@
"strategy": "exact-chunk",
"fixedParams": 10
},
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:1",
+ "strategy": "bounded-public-input",
+ "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"
+ },
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:inArray:2",
+ "strategy": "bounded-public-input",
+ "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"
+ },
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:sql.join:1",
+ "strategy": "bounded-public-input",
+ "maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"
+ },
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:1",
+ "strategy": "exact-chunk",
+ "fixedParams": 0
+ },
+ {
+ "key": "src/shared/src/db/queries/community/message.ts:insertMessageRow:values:2",
+ "strategy": "exact-chunk",
+ "fixedParams": 0
+ },
{
"key": "src/shared/src/db/queries/community/message.ts:listMessagesReferencingFriendship:inArray:1",
"strategy": "exact-chunk",
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index 1e897e13f..6f2902f89 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -9,10 +9,11 @@ import {
communityMessage,
} from "../../community-schema";
import type { Database } from "../../index";
-import { PARTICIPANT_SOURCE } from "../../../constants/community";
+import { nanoid } from "nanoid";
+import { PARTICIPANT_SOURCE, type ParticipantSource } from "../../../constants/community";
import { canSeePrivateChannel, visibilityIsDmParticipant } from "../../../utils/community-roles";
import { user } from "../../schema";
-import { chunk, D1_MAX_IN_PARAMS, maxInParams } from "../_chunk";
+import { chunk, D1_MAX_IN_PARAMS, maxInParams, maxRowsPerInsert } from "../_chunk";
// Column selection shared by every read query.
const CHANNEL_COLUMNS = {
@@ -147,11 +148,14 @@ export async function createChannel(
parentChannelId?: string | null;
creatorId?: string | null;
parentMessageId?: string | null;
+ initialParticipants?: { userId: string; source: ParticipantSource }[];
}
) {
- const rows = await db
+ const id = nanoid();
+ const insert = db
.insert(communityChannel)
.values({
+ id,
serverId: data.serverId,
categoryId: data.categoryId || null,
name: data.name,
@@ -162,6 +166,14 @@ export async function createChannel(
parentMessageId: data.parentMessageId ?? null,
})
.returning();
+ const participants = data.initialParticipants ?? [];
+ if (participants.length === 0) return (await insert)[0]!;
+ if (data.type !== "thread") throw new Error("initial participants require a thread");
+ const seeds = chunk(participants, maxRowsPerInsert(6)).map((batch) => db
+ .insert(communityChannelMember)
+ .values(batch.map((row) => ({ channelId: id, userId: row.userId, relation: "notify", source: row.source })))
+ .onConflictDoNothing({ target: [communityChannelMember.channelId, communityChannelMember.userId, communityChannelMember.relation] }));
+ const [rows] = await db.batch([insert, ...seeds]);
return rows[0]!;
}
diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.ts
index d2e61dbb4..77084569f 100644
--- a/src/shared/src/db/queries/community/dm.ts
+++ b/src/shared/src/db/queries/community/dm.ts
@@ -1,29 +1,20 @@
import { eq, and, asc, desc, exists, isNull, ne, notExists, or, sql } from "drizzle-orm";
+import { nanoid } from "nanoid";
import { alias } from "drizzle-orm/sqlite-core";
import { communityChannel, communityChannelMember, communityFriendship } from "../../community-schema";
import { user } from "../../schema";
import { PARTICIPANT_SOURCE } from "../../../constants/community";
import type { Database } from "../../index";
-// DMs are channels now (type='dm', server_id NULL). Their two participants are
-// relation='access' community_channel_member rows. One-DM-per-pair is enforced
-// at the application layer by a runtime member-set query — no stored uniqueness
-// key. See plans/community-schema-unification.md.
-
-/**
- * Find the existing type='dm' channel whose relation='access' member set is
- * EXACTLY {a,b} — both present AND no third access member. Returns the channel
- * id or null.
- */
-async function findDmChannelId(
+function dmChannelQuery(
db: Database,
userAId: string,
userBId: string
-): Promise<string | null> {
+) {
const selfMember = alias(communityChannelMember, "dm_self_member");
const peerMember = alias(communityChannelMember, "dm_peer_member");
const thirdMember = alias(communityChannelMember, "dm_third_member");
- const rows = await db
+ return db
.select({ id: communityChannel.id })
.from(communityChannel)
.where(
@@ -70,6 +61,10 @@ async function findDmChannelId(
)
.orderBy(asc(communityChannel.id))
.limit(1);
+}
+
+async function findDmChannelId(db: Database, userAId: string, userBId: string): Promise<string | null> {
+ const rows = await dmChannelQuery(db, userAId, userBId);
return rows[0]?.id ?? null;
}
@@ -86,30 +81,46 @@ export async function createOrGetDM(
return rows[0]!;
}
- const inserted = await db
- .insert(communityChannel)
- .values({ type: "dm", serverId: null, name: null, topic: "" })
- .returning();
- const channel = inserted[0]!;
-
+ const id = nanoid();
const now = new Date().toISOString();
- await db.insert(communityChannelMember).values([
- {
- channelId: channel.id,
- userId: data.userId1,
- relation: "access",
- source: PARTICIPANT_SOURCE.ADDED,
- addedAt: now,
- },
- {
- channelId: channel.id,
- userId: data.userId2,
- relation: "access",
- source: PARTICIPANT_SOURCE.ADDED,
- addedAt: now,
- },
- ]);
-
+ const insertChannel = db.insert(communityChannel).select(
+ db.select({
+ id: sql<string>`${id}`.as("id"),
+ serverId: sql`NULL`.as("server_id"),
+ categoryId: sql`NULL`.as("category_id"),
+ name: sql`NULL`.as("name"),
+ type: sql<string>`'dm'`.as("type"),
+ topic: sql<string>`''`.as("topic"),
+ position: sql<number>`0`.as("position"),
+ parentChannelId: sql`NULL`.as("parent_channel_id"),
+ creatorId: sql`NULL`.as("creator_id"),
+ messageCount: sql<number>`0`.as("message_count"),
+ archived: sql<number>`0`.as("archived"),
+ parentMessageId: sql`NULL`.as("parent_message_id"),
+ lastMessageAt: sql`NULL`.as("last_message_at"),
+ createdAt: sql<string>`${now}`.as("created_at"),
+ }).from(sql`(SELECT 1)`)
+ .where(notExists(dmChannelQuery(db, data.userId1, data.userId2)))
+ ).returning();
+ const members = [data.userId1, data.userId2].map((userId) =>
+ db.insert(communityChannelMember).select(
+ db.select({
+ id: sql<string>`${nanoid()}`.as("id"),
+ channelId: communityChannel.id,
+ userId: sql<string>`${userId}`.as("user_id"),
+ relation: sql<string>`'access'`.as("relation"),
+ source: sql<string>`${PARTICIPANT_SOURCE.ADDED}`.as("source"),
+ addedBy: sql`NULL`.as("added_by"),
+ addedAt: sql<string>`${now}`.as("added_at"),
+ }).from(communityChannel).where(eq(communityChannel.id, id))
+ )
+ );
+ const [inserted] = await db.batch([insertChannel, ...members] as any);
+ if (Array.isArray(inserted) && inserted[0]) return inserted[0];
+ const winnerId = await findDmChannelId(db, data.userId1, data.userId2);
+ if (!winnerId) throw new Error("DM missing after atomic creation");
+ const rows = await db.select().from(communityChannel).where(eq(communityChannel.id, winnerId));
+ const channel = rows[0]!;
return channel;
}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 35c74efe6..da7a26393 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1,4 +1,4 @@
-import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, type SQL } from "drizzle-orm";
+import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, isNull, count, type SQL } from "drizzle-orm";
import {
communityMessage,
communityChannel,
@@ -8,12 +8,14 @@ import {
communityChannelMember,
communityMention,
communityMessageTag,
+ communityAttachment,
} from "../../community-schema";
import { user } from "../../schema";
import { nanoid } from "nanoid";
import type { Database } from "../../index";
+import { MAX_ATTACHMENTS_PER_MESSAGE } from "../../../constants/community";
import { createLogger } from "../../../logger";
-import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
+import { chunk, D1_MAX_IN_PARAMS, maxRowsPerInsert } from "../_chunk";
// The canonical sender admits bursts of up to 30 requests per actor. Keep the
// ordinary-send retry budget above a full admitted collision wave so a hot
@@ -48,12 +50,17 @@ function errorChainMessages(error: unknown): string[] {
}
function isMessageSeqConflict(error: unknown): boolean {
- return errorChainMessages(error).some(
- (message) =>
- /unique constraint failed/i.test(message) &&
- ((message.includes("community_message.channel_id") &&
- message.includes("community_message.seq")) ||
- message.includes("uq_community_message_channel_seq"))
+ return errorChainMessages(error).some((message) =>
+ /not null constraint failed: community_message_seq.next_seq/i.test(message) ||
+ (/unique constraint failed/i.test(message) &&
+ ((message.includes("community_message.channel_id") && message.includes("community_message.seq")) ||
+ message.includes("uq_community_message_channel_seq")))
+ );
+}
+
+export function isMessageAttachmentConflict(error: unknown): boolean {
+ return errorChainMessages(error).some((message) =>
+ /not null constraint failed: community_message.content/i.test(message)
);
}
@@ -137,6 +144,15 @@ export type CreateMessageData = {
* identity-agnostic: the CALLER decides what to append, not `createMessage`.
*/
extraStatements?: unknown[];
+ attachmentIds?: string[];
+ mentions?: { userId: string; kind: string }[];
+ participants?: { userId: string; source: string }[];
+ forumThread?: {
+ id: string;
+ serverId: string;
+ name: string;
+ pendingAttachmentIds: string[];
+ };
};
/**
@@ -182,28 +198,48 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedS
const messageId = data.id ?? nanoid();
const authorIsHuman = data.authorKind === "human";
- // D1 batch() is one SQL transaction. The compare-and-swap counter claim and
- // the row that makes that seq visible must commit together: otherwise a
- // second agent send can observe the advanced counter while unread detection
- // cannot yet see the first message, then claim the following seq and bypass
- // channel alignment. The insert's unique (channel_id, seq) constraint turns
- // a lost CAS into a transaction failure, rolling back every statement below.
+ // A failed counter claim must abort the batch even when old message rows
+ // have been deleted. next_seq is NOT NULL; a stale claim violates it.
+ const currentCounter = db.select({ value: communityMessageSeq.nextSeq })
+ .from(communityMessageSeq)
+ .where(eq(communityMessageSeq.channelId, data.channelId));
const claimSeq = db
.insert(communityMessageSeq)
- .values({ channelId: data.channelId, nextSeq: seq })
+ .values({
+ channelId: data.channelId,
+ nextSeq: sql`CASE WHEN coalesce((${currentCounter}), 0) = ${expectedSeq} THEN ${seq} ELSE NULL END`,
+ })
.onConflictDoUpdate({
target: communityMessageSeq.channelId,
- set: { nextSeq: seq },
- setWhere: sql`${communityMessageSeq.nextSeq} = ${expectedSeq}`,
+ set: { nextSeq: sql`CASE WHEN ${communityMessageSeq.nextSeq} = ${expectedSeq} THEN ${seq} ELSE NULL END` },
})
.returning({ nextSeq: communityMessageSeq.nextSeq });
+ const attachmentIds = data.attachmentIds ?? [];
+ const pendingThreadIds = data.forumThread?.pendingAttachmentIds ?? [];
+ if (attachmentIds.length > MAX_ATTACHMENTS_PER_MESSAGE || pendingThreadIds.length > MAX_ATTACHMENTS_PER_MESSAGE) {
+ throw new Error("too many message attachments");
+ }
+ const eligibleAttachments = (ids: string[]) => db.select({ value: count() })
+ .from(communityAttachment)
+ .where(and(
+ inArray(communityAttachment.id, ids),
+ isNull(communityAttachment.messageId),
+ eq(communityAttachment.uploaderId, data.authorId),
+ eq(communityAttachment.targetId, data.channelId),
+ ));
+ const attachmentChecks = [attachmentIds, pendingThreadIds]
+ .filter((ids) => ids.length > 0)
+ .map((ids) => sql`(${eligibleAttachments(ids)}) = ${ids.length}`);
+ const checkedContent = attachmentChecks.length === 0 ? data.content
+ : sql<string>`CASE WHEN ${and(...attachmentChecks)} THEN ${data.content} ELSE NULL END`;
+
const insertMsg = db
.insert(communityMessage)
.values({
id: messageId,
authorId: data.authorId,
- content: data.content,
+ content: checkedContent,
channelId: data.channelId,
type: data.type ?? "default",
mentionType: data.mentionType ?? null,
@@ -239,16 +275,66 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedS
set: { lastReadAt: now, lastReadMessageId: messageId, lastReadSeq: seq },
setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,
});
+ const attachmentStatements = attachmentIds.length === 0 ? [] : [
+ db.update(communityAttachment).set({
+ messageId,
+ position: sql`CASE ${communityAttachment.id} ${sql.join(attachmentIds.map((id, index) => sql`WHEN ${id} THEN ${index}`), sql` `)} END`,
+ }).where(and(inArray(communityAttachment.id, attachmentIds), isNull(communityAttachment.messageId))),
+ ];
+ const threadStatements = data.forumThread ? [
+ db.insert(communityChannel).values({
+ id: data.forumThread.id,
+ serverId: data.forumThread.serverId,
+ parentChannelId: data.channelId,
+ parentMessageId: messageId,
+ name: data.forumThread.name,
+ type: "thread",
+ topic: "",
+ creatorId: data.authorId,
+ createdAt: now,
+ }),
+ db.insert(communityChannelMember).values({
+ channelId: data.forumThread.id,
+ userId: data.authorId,
+ relation: "notify",
+ source: "spoke",
+ }),
+ ...(pendingThreadIds.length === 0 ? [] : [
+ db.update(communityAttachment).set({ targetId: data.forumThread.id })
+ .where(and(inArray(communityAttachment.id, pendingThreadIds), isNull(communityAttachment.messageId))),
+ ]),
+ ] : [];
+ const mentionStatements = chunk(data.mentions ?? [], maxRowsPerInsert(5)).map((mentions) =>
+ db.insert(communityMention).values(mentions.map((mention) => ({ messageId, ...mention })))
+ );
+ const participantStatements = chunk(data.participants ?? [], maxRowsPerInsert(6)).map((participants) =>
+ db.insert(communityChannelMember).values(participants.map((participant) => ({
+ channelId: data.channelId,
+ relation: "notify",
+ ...participant,
+ }))).onConflictDoNothing({
+ target: [communityChannelMember.channelId, communityChannelMember.userId, communityChannelMember.relation],
+ }).returning({ userId: communityChannelMember.userId })
+ );
const baseStatements = [
claimSeq,
insertMsg,
scopeUpdate,
...(data.extraStatements ?? []),
authorWatermark,
+ ...attachmentStatements,
+ ...threadStatements,
+ ...mentionStatements,
+ ...participantStatements,
];
+ const participantStart = baseStatements.length - participantStatements.length;
+ const joinedParticipants = (results: any[]): string[] => results
+ .slice(participantStart, participantStart + participantStatements.length)
+ .flatMap((rows: Array<{ userId: string }>) => rows.map((row) => row.userId));
+ const createdThread = data.forumThread ? { id: data.forumThread.id, name: data.forumThread.name, createdAt: now } : undefined;
if (!authorIsHuman) {
const results = (await db.batch(baseStatements as any)) as any[];
- return (results[1] as InsertedMessage[])[0]!;
+ return { ...(results[1] as InsertedMessage[])[0]!, joinedParticipantUserIds: joinedParticipants(results), createdThread };
}
const humanRevision = db
@@ -267,7 +353,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedS
const revisionRows = results.at(-1) as Array<{ revision: number }> | undefined;
const revision = revisionRows?.[0]?.revision;
if (revision === undefined) throw new Error("human author read-state revision missing");
- return { ...msg, readStateRevision: revision };
+ return { ...msg, readStateRevision: revision, joinedParticipantUserIds: joinedParticipants(results), createdThread };
}
/**
diff --git a/src/shared/test/community-write-atomic.test.ts b/src/shared/test/community-write-atomic.test.ts
new file mode 100644
index 000000000..0a4db3b6f
--- /dev/null
+++ b/src/shared/test/community-write-atomic.test.ts
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { integer, sqliteTable } from "drizzle-orm/sqlite-core";
+import { sql } from "drizzle-orm";
+import { createMessage, isMessageAttachmentConflict } from "../src/db/queries/community/message";
+import { createChannel } from "../src/db/queries/community/channel";
+import { createOrGetDM } from "../src/db/queries/community/dm";
+import { communityWriteDb } from "./helpers/community-write-db";
+
+describe("Community durable writes — real SQLite transactions", () => {
+ let fixture: ReturnType<typeof communityWriteDb>;
+ beforeEach(() => { fixture = communityWriteDb(); });
+ afterEach(() => { fixture.sqlite.close(); });
+ const send = (overrides = {}) => createMessage(fixture.db, {
+ authorId: "author", authorKind: "human", content: "hello", channelId: "channel", ...overrides,
+ });
+ const rows = (table: string) => fixture.sqlite.prepare(`SELECT * FROM ${table}`).all();
+ const activity = sqliteTable("activity", { sent: integer("sent").notNull() });
+ const bump = () => fixture.db.update(activity).set({ sent: sql`${activity.sent} + 1` });
+
+ it("rolls back a new ordinary thread when an initial participant insert fails", async () => {
+ const root = await send();
+ const data = { serverId: "server", parentChannelId: "channel", parentMessageId: root!.id,
+ name: "thread", type: "thread", creatorId: "author",
+ initialParticipants: [{ userId: "author", source: "spoke" as const }, { userId: "peer", source: "added" as const }] };
+ fixture.sqlite.exec("CREATE TRIGGER fail_seed BEFORE INSERT ON community_channel_member WHEN NEW.user_id = 'peer' BEGIN SELECT RAISE(ABORT, 'seed failed'); END");
+ await expect(createChannel(fixture.db, data)).rejects.toThrow("seed failed");
+ expect(rows("community_channel")).toHaveLength(1);
+ expect(rows("community_channel_member")).toEqual([]);
+ fixture.sqlite.exec("DROP TRIGGER fail_seed");
+ const thread = await createChannel(fixture.db, data);
+ expect(rows("community_channel_member")).toHaveLength(2);
+ expect(rows("community_channel_member")).toEqual(expect.arrayContaining([
+ expect.objectContaining({ channel_id: thread.id, user_id: "author", source: "spoke", relation: "notify" }),
+ expect.objectContaining({ channel_id: thread.id, user_id: "peer", source: "added", relation: "notify" }),
+ ]));
+ await expect(createChannel(fixture.db, data)).rejects.toThrow();
+ expect(rows("community_channel")).toHaveLength(2);
+ expect(rows("community_channel_member")).toHaveLength(2);
+ });
+
+ it("bounds attachment input and keeps maximum-size statements below D1's bind limit", async () => {
+ const ids = Array.from({ length: 10 }, (_, i) => `attachment-${i}`);
+ const pending = Array.from({ length: 10 }, (_, i) => `pending-${i}`);
+ for (const id of [...ids, ...pending]) fixture.sqlite.prepare("INSERT INTO community_attachment (id, uploader_id, target_id) VALUES (?, 'author', 'channel')").run(id);
+ const forumThread = { id: "post", serverId: "server", name: "post", pendingAttachmentIds: pending };
+ await expect(send({ attachmentIds: [...ids, "extra"] })).rejects.toThrow("too many message attachments");
+ await expect(send({ forumThread: { ...forumThread, pendingAttachmentIds: [...pending, "extra"] } })).rejects.toThrow("too many message attachments");
+ expect(rows("community_message")).toEqual([]);
+ await send({ attachmentIds: ids, forumThread });
+ expect(Math.max(...fixture.batchSizes.flat())).toBeLessThanOrEqual(100);
+ expect(rows("community_attachment").filter((row: any) => row.message_id)).toHaveLength(10);
+ });
+
+ it("rejects stale seq in a deletion hole without any writes", async () => {
+ await send();
+ await send();
+ fixture.sqlite.exec("DELETE FROM community_message WHERE seq = 1");
+ const tables = ["community_message", "community_message_seq", "community_channel", "community_read_state", "community_read_state_revision", "activity"];
+ const before = tables.map(rows);
+ await expect(send({ expectedSeq: 0, extraStatements: [bump()] })).resolves.toBeNull();
+ expect(tables.map(rows)).toEqual(before);
+ await expect(send({ expectedSeq: 7 })).resolves.toBeNull();
+ expect(tables.map(rows)).toEqual(before);
+ expect((await send())!.seq).toBe(3);
+ });
+
+ it("rejects an ahead-of-counter claim even before the counter exists", async () => {
+ await expect(send({ expectedSeq: 1 })).resolves.toBeNull();
+ expect(rows("community_message_seq")).toEqual([]);
+ expect(rows("community_message")).toEqual([]);
+ });
+
+ it("concurrent ordinary sends use distinct increasing seqs", async () => {
+ const messages = await Promise.all(Array.from({ length: 12 }, () => send()));
+ expect(messages.map((message) => message!.seq).sort((a, b) => a - b)).toEqual(Array.from({ length: 12 }, (_, i) => i + 1));
+ expect(rows("community_channel")[0]).toMatchObject({ message_count: 12 });
+ });
+
+ it("concurrent reversed user-pair DM opens create one channel and two members", async () => {
+ const channels = await Promise.all(Array.from({ length: 12 }, (_, i) => createOrGetDM(fixture.db, {
+ userId1: i % 2 ? "author" : "peer", userId2: i % 2 ? "peer" : "author",
+ })));
+ expect(new Set(channels.map((channel) => channel.id)).size).toBe(1);
+ expect(rows("community_channel")).toHaveLength(2);
+ expect(rows("community_channel_member")).toHaveLength(2);
+ const existing = await createOrGetDM(fixture.db, { userId1: "peer", userId2: "author" });
+ expect(existing.id).toBe(channels[0]!.id);
+ });
+
+ it("a failed second DM membership leaves no orphan channel or first member", async () => {
+ await expect(createOrGetDM(fixture.db, { userId1: "author", userId2: "missing" })).rejects.toThrow();
+ expect(rows("community_channel")).toHaveLength(1);
+ expect(rows("community_channel_member")).toEqual([]);
+ });
+
+ it("commits attachments, mentions, participants and activity together; nonce collision rolls back", async () => {
+ fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");
+ const message = await send({
+ clientNonce: "nonce", attachmentIds: ["a"], mentions: [{ userId: "peer", kind: "mention" }],
+ participants: [{ userId: "author", source: "spoke" }, { userId: "peer", source: "mention" }], extraStatements: [bump()],
+ });
+ expect(rows("community_attachment")[0]).toMatchObject({ message_id: message!.id });
+ expect(rows("community_mention")).toHaveLength(1);
+ expect(rows("community_channel_member")).toHaveLength(2);
+ await expect(send({ clientNonce: "nonce", extraStatements: [bump()] })).rejects.toThrow();
+ expect(rows("activity")).toEqual([{ sent: 1 }]);
+ expect(rows("community_message_seq")).toEqual([{ channel_id: "channel", next_seq: 1 }]);
+ });
+
+ it("rejects missing, foreign and already reserved attachments without partial writes", async () => {
+ fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0), ('foreign', 'peer', 'channel', NULL, 0)");
+ for (const ids of [["a", "missing"], ["a", "foreign"], ["a", "a"]]) {
+ const error = await send({ attachmentIds: ids }).catch((error) => error);
+ expect(isMessageAttachmentConflict(error)).toBe(true);
+ expect(rows("community_message")).toEqual([]);
+ expect(rows("community_message_seq")).toEqual([]);
+ }
+ await send({ attachmentIds: ["a"] });
+ await expect(send({ attachmentIds: ["a"] })).rejects.toThrow();
+ expect(rows("community_message")).toHaveLength(1);
+ });
+
+ it("a later mention chunk failure rolls back all chunks and same nonce can retry", async () => {
+ fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user VALUES ('u${i}');`).join("\n"));
+ const mentions = Array.from({ length: 100 }, (_, i) => ({ userId: `u${i}`, kind: "mention" }));
+ fixture.sqlite.exec("CREATE TRIGGER fail_late_mention BEFORE INSERT ON community_mention WHEN NEW.user_id = 'u85' BEGIN SELECT RAISE(ABORT, 'injected mention failure'); END");
+ const data = { clientNonce: "retry", mentions, extraStatements: [bump()] };
+ await expect(send(data)).rejects.toThrow("injected mention failure");
+ for (const table of ["community_message", "community_message_seq", "community_mention", "community_read_state", "community_read_state_revision"]) expect(rows(table)).toEqual([]);
+ expect(rows("activity")).toEqual([{ sent: 0 }]);
+ fixture.sqlite.exec("DROP TRIGGER fail_late_mention");
+ await send(data);
+ expect(rows("community_mention")).toHaveLength(100);
+ expect(fixture.batchSizes.flat().every((size) => size <= 100)).toBe(true);
+ });
+
+ it("forum structure and pending rebind failure rolls back opener, activity and nonce", async () => {
+ fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");
+ fixture.sqlite.exec("CREATE TRIGGER fail_rebind BEFORE UPDATE OF target_id ON community_attachment BEGIN SELECT RAISE(ABORT, 'injected rebind failure'); END");
+ const data = { clientNonce: "forum", forumThread: { id: "thread", name: "title", serverId: "server", pendingAttachmentIds: ["a"] }, extraStatements: [bump()] };
+ await expect(send(data)).rejects.toThrow("injected rebind failure");
+ expect(rows("community_message")).toEqual([]);
+ expect(rows("community_channel")).toHaveLength(1);
+ expect(rows("community_channel_member")).toEqual([]);
+ expect(rows("activity")).toEqual([{ sent: 0 }]);
+ fixture.sqlite.exec("DROP TRIGGER fail_rebind");
+ const message = await send(data);
+ expect(rows("community_channel")[1]).toMatchObject({ parent_message_id: message!.id, type: "thread" });
+ expect(rows("community_attachment")[0]).toMatchObject({ target_id: "thread", message_id: null });
+ expect(rows("activity")).toEqual([{ sent: 1 }]);
+ });
+ it("later participant chunk failure rolls back the send and all earlier memberships", async () => {
+ fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user VALUES ('u${i}');`).join("\n"));
+ fixture.sqlite.exec("CREATE TRIGGER fail_late_participant BEFORE INSERT ON community_channel_member WHEN NEW.user_id = 'u85' BEGIN SELECT RAISE(ABORT, 'injected participant failure'); END");
+ const participants = Array.from({ length: 100 }, (_, i) => ({ userId: `u${i}`, source: "mention" }));
+ await expect(send({ participants })).rejects.toThrow("injected participant failure");
+ expect(rows("community_channel_member")).toEqual([]);
+ expect(rows("community_message")).toEqual([]);
+ expect(rows("community_read_state")).toEqual([]);
+ fixture.sqlite.exec("DROP TRIGGER fail_late_participant");
+ await send({ participants });
+ expect(rows("community_channel_member")).toHaveLength(100);
+ expect(fixture.batchSizes.flat().every((size) => size <= 100)).toBe(true);
+ });
+
+ it("an attachment write failure rolls back the message, author cursor, counter and sent count", async () => {
+ fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");
+ fixture.sqlite.exec("CREATE TRIGGER fail_attachment BEFORE UPDATE OF message_id ON community_attachment BEGIN SELECT RAISE(ABORT, 'injected attachment failure'); END");
+ await expect(send({ attachmentIds: ["a"], extraStatements: [bump()] })).rejects.toThrow("injected attachment failure");
+ for (const table of ["community_message", "community_message_seq", "community_read_state", "community_read_state_revision"]) expect(rows(table)).toEqual([]);
+ expect(rows("activity")).toEqual([{ sent: 0 }]);
+ expect(rows("community_attachment")[0]).toMatchObject({ message_id: null });
+ });
+
+});
diff --git a/src/shared/test/helpers/community-write-db.ts b/src/shared/test/helpers/community-write-db.ts
new file mode 100644
index 000000000..34e67ecae
--- /dev/null
+++ b/src/shared/test/helpers/community-write-db.ts
@@ -0,0 +1,62 @@
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import type { Database } from "../../src/db";
+
+export function communityWriteDb() {
+ const sqlite = new Sqlite(":memory:");
+ sqlite.pragma("foreign_keys = ON");
+ sqlite.exec(`
+ CREATE TABLE user (id TEXT PRIMARY KEY);
+ INSERT INTO user VALUES ('author'), ('peer');
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY, server_id TEXT, category_id TEXT, name TEXT,
+ type TEXT NOT NULL DEFAULT 'text', topic TEXT DEFAULT '', position INTEGER DEFAULT 0,
+ parent_channel_id TEXT REFERENCES community_channel(id), creator_id TEXT,
+ message_count INTEGER DEFAULT 0, archived INTEGER DEFAULT 0,
+ parent_message_id TEXT REFERENCES community_message(id), last_message_at TEXT, created_at TEXT NOT NULL
+ );
+ CREATE UNIQUE INDEX thread_anchor ON community_channel(parent_channel_id, parent_message_id) WHERE parent_message_id IS NOT NULL;
+ CREATE TABLE community_channel_member (
+ id TEXT PRIMARY KEY, channel_id TEXT NOT NULL REFERENCES community_channel(id),
+ user_id TEXT NOT NULL REFERENCES user(id), relation TEXT NOT NULL DEFAULT 'access',
+ source TEXT NOT NULL DEFAULT 'added', added_by TEXT, added_at TEXT NOT NULL,
+ UNIQUE(channel_id, user_id, relation)
+ );
+ CREATE TABLE community_message (
+ id TEXT PRIMARY KEY, author_id TEXT NOT NULL REFERENCES user(id), content TEXT NOT NULL DEFAULT '',
+ type TEXT NOT NULL DEFAULT 'default', mention_type TEXT, reply_to_id TEXT, embeds TEXT,
+ created_at TEXT NOT NULL, channel_id TEXT NOT NULL REFERENCES community_channel(id),
+ seq INTEGER NOT NULL, friendship_id TEXT, client_nonce TEXT
+ );
+ CREATE UNIQUE INDEX uq_community_message_channel_seq ON community_message(channel_id, seq) WHERE seq > 0;
+ CREATE UNIQUE INDEX uq_message_author_client_nonce ON community_message(author_id, client_nonce) WHERE client_nonce IS NOT NULL;
+ CREATE TABLE community_message_seq (channel_id TEXT PRIMARY KEY REFERENCES community_channel(id), next_seq INTEGER NOT NULL);
+ CREATE TABLE community_read_state (
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL, channel_id TEXT NOT NULL, last_read_at TEXT, last_read_message_id TEXT, last_read_seq INTEGER NOT NULL,
+ UNIQUE(user_id, channel_id)
+ );
+ CREATE TABLE community_read_state_revision (user_id TEXT PRIMARY KEY, revision INTEGER NOT NULL);
+ CREATE TABLE community_attachment (
+ id TEXT PRIMARY KEY, uploader_id TEXT NOT NULL, target_id TEXT NOT NULL REFERENCES community_channel(id),
+ message_id TEXT REFERENCES community_message(id), position INTEGER DEFAULT 0
+ );
+ CREATE TABLE community_mention (
+ id TEXT PRIMARY KEY, message_id TEXT NOT NULL REFERENCES community_message(id), user_id TEXT NOT NULL REFERENCES user(id),
+ kind TEXT NOT NULL DEFAULT 'mention', read INTEGER DEFAULT 0
+ );
+ CREATE TABLE activity (sent INTEGER NOT NULL);
+ INSERT INTO activity VALUES (0);
+ INSERT INTO community_channel (id, type, created_at) VALUES ('channel', 'text', 'now');
+ `);
+ const orm = drizzle(sqlite);
+ const batchSizes: number[][] = [];
+ const db = orm as unknown as Database;
+ (db as any).batch = async (statements: any[]) => {
+ batchSizes.push(statements.map((statement) => statement.toSQL().params.length));
+ return sqlite.transaction(() => statements.map((statement) => {
+ const query = statement.toSQL();
+ return sqlite.prepare(query.sql).reader ? statement.all() : statement.run();
+ }))();
+ };
+ return { sqlite, db, batchSizes };
+}
diff --git a/src/shared/test/queries/community-realtime-audiences.test.ts b/src/shared/test/queries/community-realtime-audiences.test.ts
index d2f18f907..8a56e34ab 100644
--- a/src/shared/test/queries/community-realtime-audiences.test.ts
+++ b/src/shared/test/queries/community-realtime-audiences.test.ts
@@ -8,6 +8,7 @@ import { filterChannelReadableUserIds, listReadableChannelsForUser, getReadableM
describe("realtime channel audiences with canonical SQLite permissions", () => {
let sqlite: Sqlite.Database;
let db: Database;
+ let queryCount: number;
beforeEach(() => {
sqlite = new Sqlite(":memory:");
sqlite.exec(`
@@ -39,7 +40,8 @@ describe("realtime channel audiences with canonical SQLite permissions", () => {
('da','dm','author','access'),('dr','dm','reader','access');
INSERT INTO community_message VALUES ('message','private-thread');
`);
- db = drizzle(sqlite) as unknown as Database;
+ queryCount = 0;
+ db = drizzle(sqlite, { logger: { logQuery: () => { queryCount++; } } }) as unknown as Database;
});
afterEach(() => sqlite.close());
@@ -78,6 +80,33 @@ describe("realtime channel audiences with canonical SQLite permissions", () => {
expect(await filterChannelReadableUserIds(db, "thread", [])).toEqual([]);
});
+ it("preserves audience semantics while avoiding duplicate membership reads for 100 members", async () => {
+ for (let i = 0; i < 96; i++) {
+ const id = `extra-${i}`;
+ sqlite.prepare("INSERT INTO user VALUES (?)").run(id);
+ sqlite.prepare("INSERT INTO community_server_member VALUES (?, 'server', ?, 'member')").run(id, id);
+ }
+ const counts = [];
+ for (const id of ["text", "forum", "private-text", "private-forum", "dm", "thread", "private-thread"]) {
+ queryCount = 0;
+ const oldContent = await resolveChannelContentRecipientUserIds(db, id);
+ const oldNotifications = await resolveChannelNotificationRecipientUserIds(db, id);
+ const before = queryCount;
+ queryCount = 0;
+ const content = await resolveChannelContentRecipientUserIds(db, id);
+ const notifications = id.includes("thread")
+ ? await resolveChannelNotificationRecipientUserIds(db, id)
+ : content;
+ expect(content).toEqual(oldContent);
+ expect(notifications.filter((userId) => content.includes(userId)).sort())
+ .toEqual(oldNotifications.filter((userId) => oldContent.includes(userId)).sort());
+ if (id.includes("thread")) expect(queryCount).toBe(before);
+ else expect(queryCount).toBeLessThan(before);
+ counts.push({ scope: id, members: content.length, before, after: queryCount });
+ }
+ process.stdout.write("audience-query-counts " + JSON.stringify(counts) + "\n");
+ });
+
it("chunks a large readable audience without dropping or duplicating users", async () => {
const ids = Array.from({ length: 200 }, (_, i) => `reader-${i}`);
for (const id of ids) {
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
new file mode 100644
index 000000000..f85f3d5d9
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { communityWriteDb } from "../../../../../../../../shared/test/helpers/community-write-db"
+
+const background: Promise<unknown>[] = []
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: () => ({ ctx: { waitUntil: (work: Promise<unknown>) => background.push(work) } }) }))
+
+let fixture: ReturnType<typeof communityWriteDb>
+let actorKind: "human" | "bot" = "bot"
+let targetKind: "channel" | "forum" = "channel"
+let nonceReads = 0
+let releaseReads: (() => void) | undefined
+let bothPrechecks: Promise<void>
+let beforeUnread: (() => Promise<boolean>) | undefined
+
+vi.mock("@/lib/db", () => ({ getDb: () => fixture.db, getPrimaryDb: () => fixture.db }))
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: (handler: any) => (request: any) => handler(request, {
+ env: { DB: {} }, actor: { kind: actorKind, userId: "author" }, params: { id: "channel" },
+ }),
+}))
+vi.mock("@/lib/community/message-door", () => ({
+ resolveMessageTarget: async () => ({ ok: true, value: { target: { kind: targetKind, channelId: "channel", serverId: "server" } } }),
+}))
+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: async () => ({ allowed: true }) }))
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: vi.fn(), fanOutToChannel: vi.fn(), fanOutToServerMembers: vi.fn(),
+}))
+vi.mock("@/lib/community/message-dispatcher", () => ({ dispatchCommittedMessage: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries,
+ communityChannel: { ...actual.queries.communityChannel, isChannelPrivate: async () => false },
+ communityMessage: { ...actual.queries.communityMessage,
+ getMessageByAuthorAndNonce: async (...args: Parameters<typeof actual.queries.communityMessage.getMessageByAuthorAndNonce>) => {
+ const row = await actual.queries.communityMessage.getMessageByAuthorAndNonce(...args)
+ const read = ++nonceReads
+ if (read <= 2) {
+ expect(row).toBeNull()
+ if (read === 2) releaseReads?.()
+ await bothPrechecks
+ }
+ return row
+ },
+ },
+ communityAgentInbox: { ...actual.queries.communityAgentInbox,
+ getLatestSeqForScope: async () => (fixture.sqlite.prepare("SELECT next_seq FROM community_message_seq").get() as any)?.next_seq ?? 0,
+ hasDeliverableUnreadForAgentScope: async () => beforeUnread ? beforeUnread() : false,
+ toAgentMessage: async (_db: unknown, row: unknown, _userId: unknown, attachments: unknown) => ({ ...row as object, attachments }),
+ },
+ } }
+})
+
+import { POST } from "./route"
+import { queries } from "@alook/shared"
+import { dispatchCommittedMessage } from "@/lib/community/message-dispatcher"
+
+describe("message HTTP route — concurrent nonce with real SQL writes", () => {
+ beforeEach(() => {
+ fixture = communityWriteDb()
+ actorKind = "bot"
+ targetKind = "channel"
+ nonceReads = 0
+ background.length = 0
+ beforeUnread = undefined
+ bothPrechecks = new Promise<void>((resolve) => { releaseReads = resolve })
+ vi.clearAllMocks()
+ fixture.sqlite.exec(`
+ ALTER TABLE user ADD COLUMN name TEXT;
+ ALTER TABLE user ADD COLUMN email TEXT;
+ ALTER TABLE user ADD COLUMN image TEXT;
+ ALTER TABLE user ADD COLUMN avatarVersion INTEGER DEFAULT 0;
+ ALTER TABLE community_attachment ADD COLUMN filename TEXT DEFAULT 'a.png';
+ ALTER TABLE community_attachment ADD COLUMN r2_key TEXT;
+ ALTER TABLE community_attachment ADD COLUMN thumbnail_r2_key TEXT;
+ ALTER TABLE community_attachment ADD COLUMN content_type TEXT;
+ ALTER TABLE community_attachment ADD COLUMN size INTEGER;
+ ALTER TABLE community_attachment ADD COLUMN width INTEGER;
+ ALTER TABLE community_attachment ADD COLUMN height INTEGER;
+ ALTER TABLE community_attachment ADD COLUMN created_at TEXT;
+ CREATE TABLE community_bot_daily_activity (bot_id TEXT NOT NULL, day TEXT NOT NULL, handled_count INTEGER NOT NULL DEFAULT 0, sent_count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(bot_id, day));
+ INSERT INTO community_attachment(id, uploader_id, target_id) VALUES ('a', 'author', 'channel');
+ `)
+ })
+ afterEach(() => fixture.sqlite.close())
+ function request() {
+ const body = actorKind === "bot"
+ ? { channel: "/test#1234/general", content: { text: "hello" }, nonce: "same-nonce", attachments: ["a"] }
+ : { content: "hello", nonce: "same-nonce", attachments: ["a"] }
+ return new NextRequest("http://localhost/api/community/channels/channel/messages", {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+ })
+ }
+
+ it.each(["human", "bot"] as const)("%s concurrent first sends both acknowledge the same complete attached message", async (kind) => {
+ actorKind = kind
+ const responses = await Promise.all([POST(request()), POST(request())])
+ const bodies = await Promise.all(responses.map((response) => response.json()))
+ expect(responses.map((response) => response.status)).toEqual(kind === "human" ? [201, 201] : [200, 200])
+ expect(bodies[0].message.id).toBe(bodies[1].message.id)
+ expect(bodies.filter((body) => body.deduped)).toHaveLength(1)
+ expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_message").get()).toEqual({ count: 1 })
+ expect(fixture.sqlite.prepare("SELECT message_id FROM community_attachment").get()).toEqual({ message_id: bodies[0].message.id })
+ expect(dispatchCommittedMessage).toHaveBeenCalledOnce()
+ if (kind === "bot") expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })
+ })
+
+ it("concurrent bot forum titles return the same complete thread and count sent once", async () => {
+ targetKind = "forum"
+ const responses = await Promise.all([POST(request()), POST(request())])
+ const bodies = await Promise.all(responses.map((response) => response.json()))
+ expect(responses.map((response) => response.status)).toEqual([200, 200])
+ expect(bodies[0].message.id).toBe(bodies[1].message.id)
+ expect(bodies[0].threadId).toBe(bodies[1].threadId)
+ expect(bodies[0].threadId).toBeTruthy()
+ expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_channel WHERE type='thread'").get()).toEqual({ count: 1 })
+ expect(fixture.sqlite.prepare("SELECT target_id, message_id FROM community_attachment").get()).toEqual({ target_id: bodies[0].threadId, message_id: null })
+ expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })
+ })
+
+ it("a nonce committed during the unread gate is returned instead of blocked", async () => {
+ nonceReads = 2
+ beforeUnread = async () => {
+ await queries.communityMessage.createMessage(fixture.db, {
+ authorId: "author", content: "hello", channelId: "channel", clientNonce: "same-nonce", attachmentIds: ["a"],
+ })
+ return true
+ }
+ const response = await POST(request())
+ const body = await response.json()
+ expect(response.status).toBe(200)
+ expect(body).toMatchObject({ state: "sent", deduped: true })
+ expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_message").get()).toEqual({ count: 1 })
+ })
+ it("notification failure after a forum commit preserves storage and replay counts once", async () => {
+ targetKind = "forum"
+ nonceReads = 2
+ vi.mocked(dispatchCommittedMessage).mockRejectedValueOnce(new Error("notification offline"))
+ expect((await POST(request())).status).toBe(200)
+ await Promise.all(background)
+ const committed = fixture.sqlite.prepare("SELECT id FROM community_message").get() as { id: string }
+ expect(committed.id).toBeTruthy()
+ expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_channel WHERE type='thread'").get()).toEqual({ count: 1 })
+ const response = await POST(request())
+ expect(await response.json()).toMatchObject({ state: "sent", message: { id: committed.id }, deduped: true })
+ expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })
+ expect(dispatchCommittedMessage).toHaveBeenCalledOnce()
+ })
+
+})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
index 101ec6926..da613f75e 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts
@@ -7,6 +7,7 @@ vi.mock("@/lib/db", () => ({
getPrimaryDb: vi.fn(() => ({})),
}))
+const mockSentStatement = vi.fn(() => ({ activity: "sent" }))
const mockCreateMessageWithThread = vi.fn()
const mockResolveTargetForMember = vi.fn()
const mockRequireMessageSurfaceAccess = vi.fn()
@@ -22,6 +23,7 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
...actual.queries,
+ communityBot: { ...actual.queries.communityBot, bumpBotDailyActivityStatement: (...args: unknown[]) => mockSentStatement(...args) },
communityAgentInbox: {
...actual.queries.communityAgentInbox,
getLatestSeqForScope: (...args: unknown[]) => mockGetLatestSeqForScope(...args),
@@ -106,6 +108,8 @@ describe("forum sends open a thread through the canonical message route", () =>
expectedSeq: 4,
}))
expect(await response.json()).toEqual(expect.objectContaining({ state: "sent", threadId: "thread_1" }))
+ expect(mockSentStatement).toHaveBeenCalledWith({}, "bot_1", expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/), "sent")
+ expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({ extraStatements: [{ activity: "sent" }] }))
})
it("passes pending attachment ids to the structural primitive for scope-safe rebind", async () => {
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 24bdd936c..a8ee56902 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
@@ -85,6 +85,7 @@ vi.mock("@alook/shared", async () => {
deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),
},
communityMessage: {
+ isMessageAttachmentConflict: actual.queries.communityMessage.isMessageAttachmentConflict,
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),
@@ -266,6 +267,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockToAgentMessage.mockImplementation(async (_db, row, _user, attachments) => ({ ...row, attachments }))
mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })
mockCreateChannel.mockResolvedValue({ id: "thread_1", creatorId: "u1", createdAt: "t0", name: "thread" })
+ mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "thread_1", creatorId: "u1", createdAt: "t0", name: "thread" })
mockRebindPendingAttachmentsToChild.mockResolvedValue(true)
mockAddThreadParticipant.mockResolvedValue(null)
mockListThreadParticipantUserIds.mockResolvedValue([])
@@ -427,24 +429,16 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockListByMessageIds.mockResolvedValue([])
const res = await POST(postReq({ content: "pics", attachments: ["att_1", "att_2"] }), ctx)
expect(res.status).toBe(201)
- // The validation query is scoped to THIS user + THIS channel (self-scope /
- // confused-deputy-safe — the human dual of the download authorize-from-row).
- expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledWith(
- {},
- expect.objectContaining({ ids: ["att_1", "att_2"], uploaderId: "u1" }),
- )
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({
+ attachmentIds: ["att_1", "att_2"], authorId: "u1", channelId: "c1",
+ }))
})
it("reserve-by-id confused-deputy guard: a foreign/stolen pending id (count mismatch) → 400, no message", async () => {
- // The composer sends 2 ids but only 1 is owned by this user in this target
- // (the other belongs to someone else / a different channel). The
- // uploader+target-scoped query returns fewer rows than requested → reject
- // with a generic 400 that never says which id failed, and NO message row is
- // created. This is the send-side confused-deputy guard.
- mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "att_mine" }])
+ mockCreateMessage.mockRejectedValueOnce(new Error("NOT NULL constraint failed: community_message.content"))
const res = await POST(postReq({ content: "steal", attachments: ["att_mine", "att_theirs"] }), ctx)
expect(res.status).toBe(400)
- expect(mockCreateMessage).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
it("fans out @everyone mention to every non-author member", async () => {
@@ -457,10 +451,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(res.status).toBe(201)
expect(mockListMemberUserIds).toHaveBeenCalledTimes(1)
expect(mockListMembers).not.toHaveBeenCalled()
- expect(mockCreateMentions).toHaveBeenCalledTimes(1)
- const [, payload] = mockCreateMentions.mock.calls[0]
- expect(payload.kind).toBe("mention")
- expect(payload.userIds.sort()).toEqual(["u2", "u3"])
+ expect(mockCreateMessage.mock.calls[0][1].mentions).toEqual([{ userId: "u2", kind: "mention" }, { userId: "u3", kind: "mention" }])
// Delivery receives only the committed identity. The dispatcher reads the
// mention rows back from D1 and derives policy/audience itself.
@@ -495,10 +486,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(res.status).toBe(201)
expect(mockListMembers).toHaveBeenCalledTimes(1)
expect(mockListMemberUserIds).not.toHaveBeenCalled()
- expect(mockCreateMentions).toHaveBeenCalledTimes(1)
- const [, payload] = mockCreateMentions.mock.calls[0]
- expect(payload.kind).toBe("mention")
- expect(payload.userIds).toEqual(["u2"])
+ expect(mockCreateMessage.mock.calls[0][1].mentions).toEqual([{ userId: "u2", kind: "mention" }])
})
it("does not query members for a plain channel post with no '@' and no everyone/here", async () => {
@@ -579,9 +567,9 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(first.status).toBe(201)
expect(replay.status).toBe(200)
expect(await replay.json()).toEqual(expect.objectContaining({ deduped: true }))
- expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledTimes(1)
+ expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()
expect(mockCreateMessage).toHaveBeenCalledTimes(1)
- expect(mockReserveAttachmentsForMessage).toHaveBeenCalledTimes(1)
+ expect(mockCreateMessage.mock.calls[0][1].attachmentIds).toEqual(["a1"])
})
it("auto-joins a first-touch thread before alignment, broadcasts once per resulting participant, and blocks on backlog", async () => {
@@ -790,7 +778,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(first.status).toBe(200)
expect(replay.status).toBe(200)
expect(await replay.json()).toEqual(expect.objectContaining({ state: "sent", deduped: true }))
- expect(mockFindPendingAttachmentsForSender).toHaveBeenCalledTimes(1)
+ expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()
expect(mockCreateMessage).toHaveBeenCalledTimes(1)
expect(mockHasDeliverableUnreadForAgentScope).toHaveBeenCalledTimes(1)
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index b8e463a83..bc4686ba2 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -246,15 +246,6 @@ async function handleHumanSend(
const clientNonce = typeof body?.nonce === "string" ? body.nonce : undefined
const target = resolved.value.target
- // Reserve-by-id (route/disc step 2b): the composer uploads first (creating a
- // pending row) and sends the attachment IDS, mirroring the bot flow. Validate
- // each id against (uploader = this user, target = this channel) BEFORE the
- // message insert — the SAME `findPendingAttachmentsForSender` scope the bot arm
- // uses (the query is keyed on the `uploaderId` param, so it is actor-agnostic:
- // a stolen id owned by another user, or one pending against a different
- // target, fails the count check and rejects with a generic 400 that never
- // leaks which id). This is the human-side dual of the download door's
- // authorize-from-row confused-deputy guard.
const attachmentIds = Array.isArray(body.attachments)
? (body.attachments as unknown[]).filter((x): x is string => typeof x === "string")
: []
@@ -294,17 +285,6 @@ async function handleHumanSend(
return NextResponse.json({ message: replay.row, deduped: true }, { status: 200 })
}
- if (attachmentIds.length > 0) {
- const channelId = target.channelId
- const rows = await withD1Retry(
- () => queries.communityAttachment.findPendingAttachmentsForSender(db, { ids: attachmentIds, uploaderId: userId, targetId: channelId }),
- { route: "community/messages:human-attachments" },
- )
- if (rows.length !== attachmentIds.length) {
- return NextResponse.json({ error: "attachment not found or not attachable to this target" }, { status: 400 })
- }
- }
-
const result = await createCommunityMessage({
db,
authorId: userId,
@@ -362,15 +342,19 @@ async function handleBotSend(
clientNonce: body.nonce,
...(expectedSeq !== undefined ? { expectedSeq } : {}),
source: "cli",
+ extraStatements: [
+ queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),
+ ],
})
- const replay = await getCommunityMessageReplay({
- db,
- authorId: botUserId,
- channelId,
- clientNonce: body.nonce,
- })
- if (replay) {
+ const replayResponse = async () => {
+ const replay = await getCommunityMessageReplay({
+ db,
+ authorId: botUserId,
+ channelId,
+ clientNonce: body.nonce,
+ })
+ if (!replay) return null
if (target.kind === "forum") {
const created = await createForumOpener(target.serverId)
if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })
@@ -386,6 +370,8 @@ async function handleBotSend(
const message = await queries.communityAgentInbox.toAgentMessage(db, replay.row, botUserId, orderedAttachments)
return NextResponse.json({ state: "sent", message, deduped: true })
}
+ const replay = await replayResponse()
+ if (replay) return replay
if (target.kind === "thread") {
const created = await withD1Retry(
@@ -421,19 +407,11 @@ async function handleBotSend(
{ route: "community/messages:has-unread" },
)
if (hasUnread) {
+ const replay = await replayResponse()
+ if (replay) return replay
return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, latestSeq - seen), latestSeq })
}
- if (body.attachments.length > 0) {
- const rows = await withD1Retry(
- () => queries.communityAttachment.findPendingAttachmentsForSender(db, { ids: body.attachments, uploaderId: botUserId, targetId: channelId }),
- { route: "community/messages:attachments" },
- )
- if (rows.length !== body.attachments.length) {
- return NextResponse.json({ error: "attachment not found or not attachable to this target" }, { status: 400 })
- }
- }
-
if (target.kind === "forum") {
const created = await createForumOpener(target.serverId, latestSeq)
if (!created.ok) {
diff --git a/src/web/src/app/api/community/friends/presence/route.test.ts b/src/web/src/app/api/community/friends/presence/route.test.ts
index 7a268a970..d1659e997 100644
--- a/src/web/src/app/api/community/friends/presence/route.test.ts
+++ b/src/web/src/app/api/community/friends/presence/route.test.ts
@@ -40,6 +40,7 @@ vi.mock("@/lib/middleware/helpers", () => {
const originalFetch = globalThis.fetch
beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development")
vi.clearAllMocks()
globalThis.fetch = mockFetch as unknown as typeof fetch
})
@@ -132,5 +133,6 @@ describe("GET /api/community/friends/presence", () => {
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
diff --git a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
index 464e83e18..4a39d196f 100644
--- a/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/presence/route.test.ts
@@ -47,6 +47,7 @@ vi.mock("@/lib/middleware/helpers", () => {
// the WS_DO_WORKER binding throws.
const originalFetch = globalThis.fetch
beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development")
vi.clearAllMocks()
globalThis.fetch = mockFetch as unknown as typeof fetch
})
@@ -177,5 +178,6 @@ describe("GET /api/community/servers/[id]/presence", () => {
// Restore global fetch after tests in this file finish so we don't leak the stub.
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
diff --git a/src/web/src/lib/broadcast.test.ts b/src/web/src/lib/broadcast.test.ts
index c2e5b3627..de7631945 100644
--- a/src/web/src/lib/broadcast.test.ts
+++ b/src/web/src/lib/broadcast.test.ts
@@ -36,11 +36,13 @@ const originalFetch = globalThis.fetch
const mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development")
vi.clearAllMocks()
globalThis.fetch = mockFetch as unknown as typeof fetch
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index 949d1a1e9..8e8fb0d70 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -105,11 +105,12 @@ describe("createThreadForUser", () => {
parentMessageId: "m1",
creatorId: "cli_author",
}))
- expect(mockAddThreadParticipants).toHaveBeenCalledWith(expect.anything(), "thread_1", [
+ expect(mockCreateChannel).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ initialParticipants: [
{ userId: "cli_author", source: "spoke" },
{ userId: "source_author", source: "added" },
- ])
- expect(order).toEqual(["create", "participants", "fanout"])
+ ] }))
+ expect(mockAddThreadParticipants).not.toHaveBeenCalled()
+ expect(order).toEqual(["create", "fanout"])
})
it("treats a same-actor race re-select as non-fresh and skips duplicate side effects", async () => {
@@ -146,290 +147,93 @@ describe("createThreadForUser", () => {
})
})
-describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensation primitive)", () => {
+describe("createMessageWithThread — atomic message composition", () => {
+ const input = {
+ db: {} as never, authorId: "u1", authorKind: "bot" as const,
+ parentChannelId: "forum_1", serverId: "s1", body: { content: "Title" },
+ }
+ const thread = { id: "th_1", name: "Title", creatorId: "u1", createdAt: "t0" }
beforeEach(() => {
vi.clearAllMocks()
- // vi.clearAllMocks() only clears call history, NOT a prior test's
- // mockRejectedValue/mockResolvedValue implementation — reset the two
- // compensating-delete mocks to a resolved default every test so a
- // rejection set by one failure-path test can never silently leak into
- // the next; any test exercising a rollback failure overrides explicitly.
- mockDeleteChannel.mockResolvedValue(undefined)
- mockHardDeleteMessage.mockResolvedValue(undefined)
- mockRebindPendingAttachmentsToChild.mockResolvedValue(true)
- })
-
- it("inserts the opener message into the PARENT channel, then opens a fresh thread rooted on it", async () => {
- mockCreateCommunityMessage.mockResolvedValue({
- ok: true,
- row: { id: "msg_1", content: "hello world", channelId: "forum_1" },
- attachments: [],
- })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hello world" })
-
- const res = await createMessageWithThread({
- db: {} as any,
- authorId: "u1",
- parentChannelId: "forum_1",
- serverId: "s1",
- body: { content: "hello world" },
- })
-
- expect(res.ok).toBe(true)
- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- authorId: "u1",
- target: { kind: "forum", channelId: "forum_1", serverId: "s1" },
- }),
- )
- expect(mockCreateChannel).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- serverId: "s1",
- parentChannelId: "forum_1",
- parentMessageId: "msg_1",
- type: "thread",
- creatorId: "u1",
- }),
- )
- if (res.ok) {
- expect(res.message.id).toBe("msg_1")
- expect(res.thread.id).toBe("th_1")
- }
- })
-
- it("threadName is ALWAYS truncated to MAX_CHANNEL_NAME_LENGTH (100), even when explicitly passed a longer string — the thread's `name` column is a channel-naming field, bounded like any other channel name, regardless of how long a post's title (up to MAX_MESSAGE_CONTENT_LENGTH=4000) happens to be", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "short", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "x" })
- const longTitle = "x".repeat(4000)
-
- await createMessageWithThread({
- db: {} as any,
- authorId: "u1",
- parentChannelId: "forum_1",
- serverId: "s1",
- body: { content: "short" },
- threadName: longTitle,
+ mockCreateCommunityMessage.mockReset().mockResolvedValue({
+ ok: true, row: { id: "msg_1", content: "Title" }, attachments: [],
})
-
- const [, createChannelArgs] = mockCreateChannel.mock.calls[0]
- expect(createChannelArgs.name.length).toBe(100)
- })
-
- it("fresh-create seeds the author as a SPOKE participant and fires CHILD_CHANNEL_CREATE by default", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hi" })
-
- await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },
- })
-
- expect(mockAddThreadParticipants).toHaveBeenCalledWith(
- expect.anything(), "th_1", [{ userId: "u1", source: "spoke" }],
- )
- expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)
+ mockGetThreadChannelByParentMessage.mockReset().mockResolvedValue(thread)
})
- it("suppressBroadcast passes through to createCommunityMessage; suppressThreadFanout independently silences ONLY the thread's own CHILD_CHANNEL_CREATE — enroll still runs unconditionally", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "hi" })
-
- await createMessageWithThread({
- db: {} as any,
- authorId: "u1",
- parentChannelId: "forum_1",
- serverId: "s1",
- body: { content: "hi" },
- suppressBroadcast: true,
- suppressThreadFanout: true,
- })
-
- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
- expect.objectContaining({ suppressBroadcast: true }),
- )
- // Enroll (structural core) is NOT gated by either suppress switch.
- expect(mockAddThreadParticipants).toHaveBeenCalledTimes(1)
- // But the thread's own broadcast IS silenced.
+ it("passes structure, pending attachments and activity to the same message write before broadcasting", async () => {
+ const broadcast = vi.fn()
+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1" }, attachments: [], broadcast })
+ const sent = { statement: "sent" }
+ const result = await createMessageWithThread({ ...input, expectedSeq: 8, pendingAttachmentIdsToRebind: ["a"], extraStatements: [sent] })
+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(expect.objectContaining({
+ expectedSeq: 8, extraStatements: [sent],
+ forumThread: { id: expect.any(String), name: "Title", serverId: "s1", pendingAttachmentIds: ["a"] },
+ }))
+ expect(result).toEqual({ ok: true, message: { id: "msg_1" }, attachments: [], thread })
+ expect(broadcast).not.toHaveBeenCalled()
expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ expect(mockCreateChannel).not.toHaveBeenCalled()
+ expect(mockRebindPendingAttachmentsToChild).not.toHaveBeenCalled()
})
- it("a concurrent-race re-select (not a fresh create) skips seed + fan-out entirely", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })
- // creatorId !== authorId ("u2") → this actor lost the race, re-selected someone else's row.
- mockCreateChannel.mockRejectedValue(Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT" }))
- mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "th_1", creatorId: "u2", createdAt: "t0", name: "hi" })
-
- const res = await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },
+ it("rejects oversized pending attachments before creating a forum opener", async () => {
+ const result = await createMessageWithThread({
+ ...input,
+ pendingAttachmentIdsToRebind: Array.from({ length: 11 }, (_, i) => `attachment-${i}`),
})
-
- expect(res.ok).toBe(true)
- expect(mockAddThreadParticipants).not.toHaveBeenCalled()
+ expect(result).toEqual({ ok: false, status: 400, error: "too many attachments (max 10)" })
+ expect(mockCreateCommunityMessage).not.toHaveBeenCalled()
+ expect(mockGetThreadChannelByParentMessage).not.toHaveBeenCalled()
expect(mockFanOutToChannel).not.toHaveBeenCalled()
- expect(mockHardDeleteMessage).not.toHaveBeenCalled()
})
- it("same-nonce replay returns the existing thread without rebinding or broadcasting", async () => {
- mockCreateCommunityMessage.mockResolvedValue({
- ok: true,
- row: { id: "msg_1", content: "Title", channelId: "forum_1" },
- attachments: [],
- deduped: true,
- })
- mockGetThreadChannelByParentMessage.mockResolvedValue({
- id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title",
- })
- mockListMessageAttachments.mockResolvedValue([{
- id: "att_1", targetId: "forum_1", filename: "photo.png",
- contentType: "image/png", size: 10, width: 640, height: 480,
- thumbnailR2Key: "original.thumbnail.jpg",
- }])
-
- const res = await createMessageWithThread({
- db: {} as any,
- authorId: "u1",
- parentChannelId: "forum_1",
- serverId: "s1",
- body: { content: "Title" },
- pendingAttachmentIdsToRebind: ["att_1"],
- clientNonce: "nonce_1",
- })
+ it("bounds explicit and content-derived thread names", async () => {
+ await createMessageWithThread({ ...input, threadName: "x".repeat(4000) })
+ expect(mockCreateCommunityMessage.mock.calls[0][0].forumThread.name).toBe("x".repeat(100))
+ await createMessageWithThread({ ...input, body: { content: "y".repeat(4000) } })
+ expect(mockCreateCommunityMessage.mock.calls[1][0].forumThread.name).toBe("y".repeat(100))
+ })
- expect(res).toEqual(expect.objectContaining({
- ok: true,
- deduped: true,
- thread: expect.objectContaining({ id: "th_1" }),
- attachments: [expect.objectContaining({
- thumbnailUrl: "/api/community/channels/forum_1/attachments/att_1/thumbnail",
- })],
- }))
- expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)
- expect(mockCreateChannel).not.toHaveBeenCalled()
- expect(mockAddThreadParticipants).not.toHaveBeenCalled()
+ it("returns complete nonce replay without mutating pending attachments or broadcasting", async () => {
+ const attachments = [{ id: "a", thumbnailUrl: "/thumbnail" }]
+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1" }, attachments, deduped: true })
+ const result = await createMessageWithThread({ ...input, clientNonce: "nonce", pendingAttachmentIdsToRebind: ["a"] })
+ expect(result).toEqual({ ok: true, message: { id: "msg_1" }, attachments, thread, deduped: true })
expect(mockFanOutToChannel).not.toHaveBeenCalled()
expect(mockRebindPendingAttachmentsToChild).not.toHaveBeenCalled()
- })
-
- it("returns the message-handler's error verbatim without touching the thread path at all", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 400, error: "content or attachments required" })
-
- const res = await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "" },
- })
-
- expect(res).toEqual({ ok: false, status: 400, error: "content or attachments required" })
- expect(mockCreateChannel).not.toHaveBeenCalled()
- })
-
- it("forwards the parent expectedSeq and leaves no thread side effects when the opener loses the CAS", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: false, status: 409, error: "seq_conflict" })
-
- const res = await createMessageWithThread({
- db: {} as any,
- authorId: "bot_1",
- authorKind: "bot",
- parentChannelId: "forum_1",
- serverId: "s1",
- body: { content: "lost race" },
- expectedSeq: 9,
- })
-
- expect(res).toEqual({ ok: false, status: 409, error: "seq_conflict" })
- expect(mockCreateCommunityMessage).toHaveBeenCalledWith(expect.objectContaining({ expectedSeq: 9 }))
- expect(mockCreateChannel).not.toHaveBeenCalled()
expect(mockAddThreadParticipants).not.toHaveBeenCalled()
- expect(mockFanOutToChannel).not.toHaveBeenCalled()
- })
-
- it("compensates with hardDeleteMessage when the thread-open throws unrecoverably (no orphan message left behind)", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockRejectedValue(new Error("D1 outage"))
-
- await expect(
- createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },
- }),
- ).rejects.toThrow("D1 outage")
-
- expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")
})
- it("when the compensating hardDelete ALSO fails, logs both errors but re-throws the ORIGINAL thread-open error (never masks the real cause, never fails silently)", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "hi", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockRejectedValue(new Error("D1 outage"))
- mockHardDeleteMessage.mockRejectedValue(new Error("rollback also down"))
-
- await expect(
- createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "hi" },
- }),
- ).rejects.toThrow("D1 outage")
-
- expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")
+ it("passes CAS and attachment rejection through without dispatch", async () => {
+ for (const error of [{ ok: false, status: 409, error: "seq_conflict" }, { ok: false, status: 400, error: "attachment not found" }]) {
+ mockCreateCommunityMessage.mockResolvedValue(error)
+ expect(await createMessageWithThread(input)).toEqual(error)
+ }
+ expect(mockGetThreadChannelByParentMessage).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
- it("rebinds pending attachments from the forum to the fresh child thread", async () => {
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [] })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })
-
- const res = await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",
- body: { content: "Title" }, pendingAttachmentIdsToRebind: ["att_1"],
- })
-
- expect(res.ok).toBe(true)
- expect(mockRebindPendingAttachmentsToChild).toHaveBeenCalledWith(expect.anything(), {
- ids: ["att_1"], uploaderId: "u1", parentTargetId: "forum_1", childTargetId: "th_1",
- })
+ it("failed atomic write never runs compensating deletes or fanout", async () => {
+ mockCreateCommunityMessage.mockRejectedValue(new Error("injected thread write failure"))
+ await expect(createMessageWithThread(input)).rejects.toThrow("injected thread write failure")
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
+ expect(mockDeleteChannel).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
- it("compensates the fresh opener and thread when attachment rebind is rejected", async () => {
- const broadcast = vi.fn()
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })
- mockRebindPendingAttachmentsToChild.mockResolvedValue(false)
-
- const res = await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",
- body: { content: "Title" }, pendingAttachmentIdsToRebind: ["stolen"],
- })
-
- expect(res).toEqual({ ok: false, status: 400, error: "attachment not found or not attachable to this thread" })
- expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "th_1")
- expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")
- expect(broadcast).not.toHaveBeenCalled()
+ it("rejects a legacy incomplete forum replay instead of acknowledging success", async () => {
+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1" }, attachments: [], deduped: true })
+ mockGetThreadChannelByParentMessage.mockResolvedValue(null)
+ await expect(createMessageWithThread(input)).rejects.toThrow("committed forum opener is missing its thread")
expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
- it("attempts both compensations and never publishes when rebind throws", async () => {
- const broadcast = vi.fn()
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })
- mockRebindPendingAttachmentsToChild.mockRejectedValue(new Error("rebind failed"))
- mockDeleteChannel.mockRejectedValue(new Error("delete thread failed"))
-
- await expect(createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1",
- body: { content: "Title" }, pendingAttachmentIdsToRebind: ["att_1"],
- })).rejects.toThrow("rebind failed")
-
- expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "th_1")
- expect(mockHardDeleteMessage).toHaveBeenCalledWith(expect.anything(), "msg_1")
- expect(broadcast).not.toHaveBeenCalled()
+ it("keeps broadcast suppression separate from structure", async () => {
+ await createMessageWithThread({ ...input, suppressBroadcast: true, suppressThreadFanout: true })
+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(expect.objectContaining({ suppressBroadcast: true, forumThread: expect.any(Object) }))
expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
- it("publishes the opener only after structure and participants commit", async () => {
- const broadcast = vi.fn(async () => undefined)
- mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1", content: "Title", channelId: "forum_1" }, attachments: [], broadcast })
- mockCreateChannel.mockResolvedValue({ id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title" })
- await createMessageWithThread({
- db: {} as any, authorId: "u1", parentChannelId: "forum_1", serverId: "s1", body: { content: "Title" },
- })
-
- expect(mockAddThreadParticipants.mock.invocationCallOrder[0]).toBeLessThan(mockRebindPendingAttachmentsToChild.mock.invocationCallOrder[0])
- expect(mockRebindPendingAttachmentsToChild.mock.invocationCallOrder[0]).toBeLessThan(broadcast.mock.invocationCallOrder[0])
- expect(broadcast.mock.invocationCallOrder[0]).toBeLessThan(mockFanOutToChannel.mock.invocationCallOrder[0])
- })
})
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index cf06f41a8..7b705ba96 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -4,37 +4,22 @@ import {
isChannelType,
channelCreation,
MAX_CHANNEL_NAME_LENGTH,
+ MAX_ATTACHMENTS_PER_MESSAGE,
MAX_CHANNEL_TOPIC_LENGTH,
WS_EVENTS,
slugify,
PARTICIPANT_SOURCE,
- createLogger,
type ChannelType,
type StoredChannelType,
type Database,
} from "@alook/shared"
-import { broadcastToUserSafe, fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"
+import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"
import { createWithCollisionPolicy } from "@/lib/community/create-collision"
import { requireServerMember, requireChannelMember } from "@/lib/community/permissions"
import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
import { guardDmOpen } from "@/lib/community/dm-guard"
import { createCommunityMessage, type IncomingMessageBody } from "@/lib/community/message-handler"
-import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
-
-const log = createLogger({ service: "community-create-channels" })
-
-/* istanbul ignore next -- real workerd compensation oracle covers revision fanout */
-async function hardDeleteMessageAndBroadcastReadState(db: Database, messageId: string) {
- const result = await queries.communityMessage.hardDeleteMessage(db, messageId)
- await Promise.all((result?.readStateRevisions ?? []).map((revision) =>
- broadcastToUserSafe(revision.userId, {
- type: WS_EVENTS.READ_STATE_ADVANCED,
- revision: revision.revision,
- inboxChanged: true,
- })
- ))
- return result
-}
+import { nanoid } from "nanoid"
/**
* Single-source creation cores for the `POST /channels` create door (route/disc
@@ -252,6 +237,14 @@ export async function createThreadForUser(
const existingThread = await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)
if (existingThread) return { ok: true, value: existingThread }
+ const seedRows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.ADDED }[] = [
+ { userId: actorUserId, source: PARTICIPANT_SOURCE.SPOKE },
+ ]
+ if (message.authorId !== actorUserId) {
+ const authorStillMember = await requireChannelMember(db, message.channelId, message.authorId)
+ if (authorStillMember.ok) seedRows.push({ userId: message.authorId, source: PARTICIPANT_SOURCE.ADDED })
+ }
+
let createdByThisAttempt = false
const threadResult = await createWithCollisionPolicy(channelCreation("thread"), {
attempt: async () => {
@@ -262,6 +255,7 @@ export async function createThreadForUser(
name,
type: "thread",
creatorId: actorUserId,
+ initialParticipants: seedRows,
})
createdByThisAttempt = true
return created
@@ -272,20 +266,8 @@ export async function createThreadForUser(
// this policy (it creates or re-selects, else throws); map to 404 defensively.
if (!threadResult.ok) return { ok: false, status: 404, error: "thread not found" }
const childChannel = threadResult.value
- // Seed the NOTIFY set on a fresh create only: creator (spoke) + original author
- // (added, if still a member — else a private channel's thread could leak to
- // someone who lost access). Idempotent per (channel,user) via onConflictDoNothing.
if (createdByThisAttempt) {
- const seedRows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.ADDED }[] = [
- { userId: actorUserId, source: PARTICIPANT_SOURCE.SPOKE },
- ]
- if (message.authorId !== actorUserId) {
- const authorStillMember = await requireChannelMember(db, message.channelId, message.authorId)
- if (authorStillMember.ok) seedRows.push({ userId: message.authorId, source: PARTICIPANT_SOURCE.ADDED })
- }
- await queries.communityThread.addThreadParticipants(db, childChannel.id, seedRows)
-
- await fanOutToChannel(message.channelId, {
+ void fanOutToChannel(message.channelId, {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: message.channelId,
channel: {
@@ -329,9 +311,14 @@ export async function createMessageWithThread(params: {
clientNonce?: string
expectedSeq?: number
source?: "cli" | "daemon-http" | "web"
+ extraStatements?: unknown[]
}): Promise<CreateMessageWithThreadResult> {
const { db, authorId, parentChannelId, serverId } = params
-
+ if ((params.pendingAttachmentIdsToRebind?.length ?? 0) > MAX_ATTACHMENTS_PER_MESSAGE) {
+ return { ok: false, status: 400, error: `too many attachments (max ${MAX_ATTACHMENTS_PER_MESSAGE})` }
+ }
+ const content = typeof params.body.content === "string" ? params.body.content : ""
+ const threadName = (params.threadName?.trim() || content.trim() || "thread").slice(0, MAX_CHANNEL_NAME_LENGTH)
const created = await createCommunityMessage({
db,
authorId,
@@ -343,167 +330,24 @@ export async function createMessageWithThread(params: {
clientNonce: params.clientNonce,
expectedSeq: params.expectedSeq,
suppressBroadcast: params.suppressBroadcast,
- deferBroadcast: true,
+ suppressThreadFanout: params.suppressThreadFanout,
+ extraStatements: params.extraStatements,
+ forumThread: {
+ id: nanoid(),
+ serverId,
+ name: threadName,
+ pendingAttachmentIds: params.pendingAttachmentIdsToRebind ?? [],
+ },
})
if (!created.ok) return { ok: false, status: created.status, error: created.error }
- const messageId = created.row.id
-
- if (created.deduped) {
- const thread = await queries.communityChannel.getThreadChannelByParentMessage(
- db,
- parentChannelId,
- messageId,
- )
- if (!thread) throw new Error("deduped forum opener is missing its thread")
- // Structure replay is already complete. Do not touch attachment rows here:
- // they may be pending on this thread (reply previously failed) or already
- // bound to the deduped reply (whole command previously succeeded).
- const storedAttachments = await queries.communityAttachment.listMessageAttachments(db, messageId)
- const toCreatedAttachment = (row: (typeof storedAttachments)[number]) => ({
- id: row.id,
- filename: row.filename,
- url: attachmentUrl(row.targetId, row.id),
- ...(row.thumbnailR2Key ? { thumbnailUrl: attachmentThumbnailUrl(row.targetId, row.id) } : {}),
- contentType: row.contentType,
- size: row.size,
- width: row.width,
- height: row.height,
- })
- return {
- ok: true,
- message: created.row,
- attachments: storedAttachments.map(toCreatedAttachment),
- thread,
- deduped: true,
- }
- }
-
- // Always truncated to MAX_CHANNEL_NAME_LENGTH — the thread's `name` column
- // is a channel-naming field (display-only, but still bounded like every
- // other channel name), regardless of how long the caller-supplied
- // threadName or the opener's own content happens to be (e.g. a post's
- // title can be up to MAX_MESSAGE_CONTENT_LENGTH — do not let that length
- // leak into this field uncapped).
- const threadName = (params.threadName?.trim() || created.row.content?.trim() || "thread").slice(0, MAX_CHANNEL_NAME_LENGTH)
-
- let threadResult: Awaited<ReturnType<typeof createWithCollisionPolicy<Awaited<ReturnType<typeof queries.communityChannel.createChannel>>>>>
- try {
- threadResult = await createWithCollisionPolicy(channelCreation("thread"), {
- attempt: () => queries.communityChannel.createChannel(db, {
- serverId,
- parentChannelId,
- parentMessageId: messageId,
- name: threadName,
- type: "thread",
- creatorId: authorId,
- }),
- refetchWinner: () => queries.communityChannel.getThreadChannelByParentMessage(db, parentChannelId, messageId),
- })
- } catch (err) {
- // Compensate: the message was inserted but its thread never opened — no
- // caller may see a message that's supposed to have a thread but doesn't.
- // If the compensating hardDelete ALSO throws (same D1 outage the
- // thread-open was recovering from), log BOTH and re-throw the ORIGINAL
- // thread-open error — it's the one the caller cares about; matches
- // message-handler.ts's attachment-reserve rollback shape exactly (never
- // let a secondary rollback failure mask the real cause, and never fail
- // silently — Aigneis #670/#680).
- try {
- await hardDeleteMessageAndBroadcastReadState(db, messageId)
- } catch (rollbackErr) {
- log.error("thread_open_rollback_failed", {
- messageId,
- threadOpenErr: err instanceof Error ? err.message : String(err),
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- throw err
- }
- if (!threadResult.ok) {
- try {
- /* istanbul ignore next -- retained thread-open compensation journey */
- await hardDeleteMessageAndBroadcastReadState(db, messageId)
- } catch (rollbackErr) {
- log.error("thread_open_rollback_failed", {
- messageId,
- threadOpenErr: threadResult.error,
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- return { ok: false, status: 404, error: "thread not found" }
- }
- const childChannel = threadResult.value
- const isFreshCreate = childChannel.creatorId === authorId
-
- const compensateFreshStructure = async (cause: unknown) => {
- if (isFreshCreate) {
- try {
- await queries.communityChannel.deleteChannel(db, childChannel.id)
- } catch (rollbackErr) {
- log.error("thread_rollback_delete_channel_failed", {
- messageId,
- cause: cause instanceof Error ? cause.message : String(cause),
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- try {
- await hardDeleteMessageAndBroadcastReadState(db, messageId)
- } catch (rollbackErr) {
- log.error("thread_rollback_delete_opener_failed", {
- messageId,
- cause: cause instanceof Error ? cause.message : String(cause),
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- }
- }
-
- if (isFreshCreate) {
- try {
- await queries.communityThread.addThreadParticipants(db, childChannel.id, [
- { userId: authorId, source: PARTICIPANT_SOURCE.SPOKE },
- ])
- } catch (err) {
- await compensateFreshStructure(err)
- throw err
- }
+ const childChannel = await queries.communityChannel.getThreadChannelByParentMessage(db, parentChannelId, created.row.id)
+ if (!childChannel) throw new Error("committed forum opener is missing its thread")
+
+ return {
+ ok: true,
+ message: created.row,
+ attachments: created.attachments,
+ thread: childChannel,
+ ...(created.deduped ? { deduped: true } : {}),
}
-
- let rebound: boolean
- try {
- rebound = await queries.communityAttachment.rebindPendingAttachmentsToChild(db, {
- ids: params.pendingAttachmentIdsToRebind ?? [],
- uploaderId: authorId,
- parentTargetId: parentChannelId,
- childTargetId: childChannel.id,
- })
- } catch (err) {
- await compensateFreshStructure(err)
- throw err
- }
- if (!rebound) {
- await compensateFreshStructure("attachment rebind rejected")
- return { ok: false, status: 400, error: "attachment not found or not attachable to this thread" }
- }
-
- if (isFreshCreate) {
- await created.broadcast?.()
-
- if (!params.suppressThreadFanout) {
- await fanOutToChannel(parentChannelId, {
- type: WS_EVENTS.CHILD_CHANNEL_CREATE,
- parentChannelId,
- channel: {
- id: childChannel.id,
- name: childChannel.name,
- type: "thread" as const,
- creatorId: authorId,
- createdAt: childChannel.createdAt,
- },
- parentMessageId: messageId,
- })
- }
- }
-
- return { ok: true, message: created.row, attachments: created.attachments, thread: childChannel }
}
diff --git a/src/web/src/lib/community/machine-disconnect.test.ts b/src/web/src/lib/community/machine-disconnect.test.ts
index acad10361..62856d60a 100644
--- a/src/web/src/lib/community/machine-disconnect.test.ts
+++ b/src/web/src/lib/community/machine-disconnect.test.ts
@@ -7,11 +7,13 @@ const originalFetch = globalThis.fetch
const mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development")
vi.clearAllMocks()
globalThis.fetch = mockFetch as unknown as typeof fetch
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
diff --git a/src/web/src/lib/community/message-delivery-transport.test.ts b/src/web/src/lib/community/message-delivery-transport.test.ts
index 6a381a228..529032387 100644
--- a/src/web/src/lib/community/message-delivery-transport.test.ts
+++ b/src/web/src/lib/community/message-delivery-transport.test.ts
@@ -91,11 +91,13 @@ function requestOperationId(callIndex: number): string | null {
beforeEach(() => {
vi.clearAllMocks()
+ vi.stubEnv("NODE_ENV", "development")
globalThis.fetch = globalFetch as unknown as typeof fetch
bindingFetch.mockImplementation(async () => Response.json({ failedUserIds: [] }))
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
@@ -255,4 +257,34 @@ describe("sendMessageDeliveryBatch", () => {
await expect(sendMessageDeliveryBatch(batch())).rejects.toThrow(/failed for 1 chunk/)
})
+ it.each(["network", 503, 429])("retries transient production %s with the same operation and payload", async (failure) => {
+ vi.stubEnv("NODE_ENV", "production")
+ if (failure === "network") bindingFetch.mockRejectedValueOnce(new Error("network unavailable"))
+ else bindingFetch.mockResolvedValueOnce(new Response("unavailable", { status: Number(failure) }))
+ await sendMessageDeliveryBatch(batch())
+ expect(bindingFetch).toHaveBeenCalledTimes(2)
+ expect(requestOperationId(1)).toBe(requestOperationId(0))
+ expect(requestBatch(1)).toEqual(requestBatch(0))
+ expect(globalFetch).not.toHaveBeenCalled()
+ })
+
+ it("keeps only the failed subset across a subsequent network retry", async () => {
+ vi.stubEnv("NODE_ENV", "production")
+ bindingFetch.mockResolvedValueOnce(Response.json({ failedUserIds: ["u2"] }, { status: 207 }))
+ .mockRejectedValueOnce(new Error("network unavailable"))
+ await sendMessageDeliveryBatch(batch())
+ expect(bindingFetch).toHaveBeenCalledTimes(3)
+ expect(requestBatch(1).contentUserIds).toEqual(["u2"])
+ expect(requestBatch(2)).toEqual(requestBatch(1))
+ expect(requestOperationId(2)).toBe(requestOperationId(0))
+ })
+
+ it("bounds persistent transport failure at three production attempts", async () => {
+ vi.stubEnv("NODE_ENV", "production")
+ bindingFetch.mockRejectedValue(new Error("network unavailable"))
+ await expect(sendMessageDeliveryBatch(batch())).rejects.toThrow("failed for 1 chunk")
+ expect(bindingFetch).toHaveBeenCalledTimes(3)
+ expect(globalFetch).not.toHaveBeenCalled()
+ })
+
})
diff --git a/src/web/src/lib/community/message-delivery-transport.ts b/src/web/src/lib/community/message-delivery-transport.ts
index fe3e003ed..942ec911f 100644
--- a/src/web/src/lib/community/message-delivery-transport.ts
+++ b/src/web/src/lib/community/message-delivery-transport.ts
@@ -17,6 +17,8 @@ const log = createLogger({ service: "message-delivery-transport" })
const maxAttempts = 3
const maxActiveChunks = 3
+class RetryableMessageDeliveryError extends Error {}
+
function allTargetUserIds(batch: MessageDeliveryBatch): string[] {
return [...new Set([
...batch.contentUserIds,
@@ -71,20 +73,28 @@ async function sendAttempt(
operationId: CommunityDeliveryOperationId,
): 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",
- [COMMUNITY_DELIVERY_OPERATION_ID_HEADER]: operationId,
+ let response: Response
+ try {
+ 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",
+ [COMMUNITY_DELIVERY_OPERATION_ID_HEADER]: operationId,
+ },
+ body: serializeMessageDeliveryBatch(batch),
},
- body: serializeMessageDeliveryBatch(batch),
- },
- { logPrefix: "message_delivery", log, label: batch.messageId },
- )
+ { logPrefix: "message_delivery", log, label: batch.messageId },
+ )
+ } catch (error) {
+ throw new RetryableMessageDeliveryError("message delivery: transport failed", { cause: error })
+ }
+ if (response.status >= 500 || response.status === 408 || response.status === 429) {
+ throw new RetryableMessageDeliveryError(`message delivery: ws-do responded ${response.status}`)
+ }
let body: unknown
try {
body = await response.json()
@@ -118,7 +128,13 @@ async function sendChunk(
let pending = initial
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
const startedAt = Date.now()
- const failed = await sendAttempt(env, pending, operationId)
+ let failed: string[]
+ try {
+ failed = await sendAttempt(env, pending, operationId)
+ } catch (error) {
+ if (!(error instanceof RetryableMessageDeliveryError) || attempt === maxAttempts) throw error
+ continue
+ }
log.info("message_delivery_attempt_complete", {
messageId: initial.messageId,
attempt,
diff --git a/src/web/src/lib/community/message-dispatcher-architecture.test.ts b/src/web/src/lib/community/message-dispatcher-architecture.test.ts
index ef42649d9..91e10ce9c 100644
--- a/src/web/src/lib/community/message-dispatcher-architecture.test.ts
+++ b/src/web/src/lib/community/message-dispatcher-architecture.test.ts
@@ -8,7 +8,7 @@ function source(name: string): string {
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).toContain("dispatchCommittedMessage(db, created.id")
expect(handler).not.toMatch(
/dispatchMessageNotify|resolveChannelRecipients|wakeMessageRow|enqueueBotWakes/,
)
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
index a5b28ddcc..b82ad4f4a 100644
--- a/src/web/src/lib/community/message-dispatcher.test.ts
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -385,6 +385,7 @@ describe("planCommittedMessage", () => {
})
it("deduplicates notification and attention candidates without consulting passive readers", async () => {
+ mockGetChannel.mockResolvedValue({ ...channel, type: "thread", parentChannelId: "parent" })
mockResolveRecipients.mockResolvedValue(["author_1", "reader", "u_all", "u_mentions"])
mockResolveNotificationRecipients.mockResolvedValue(["author_1", "u_all", "u_all", "u_mentions", "outside"])
mockListAttention.mockResolvedValue(["author_1", "u_mentions", "u_mentions", "u_mention_only"])
@@ -398,6 +399,13 @@ describe("planCommittedMessage", () => {
expect(plan.wakeBotUserIds).toEqual([])
})
+ it.each(["text", "forum", "dm"])("reuses the content audience for %s notification planning", async (type) => {
+ mockGetChannel.mockResolvedValue({ ...channel, type })
+ await planCommittedMessage({} as never, "msg_1")
+ expect(mockResolveRecipients).toHaveBeenCalledOnce()
+ expect(mockResolveNotificationRecipients).not.toHaveBeenCalled()
+ })
+
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")
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
index ec83b722c..ae45e1bb6 100644
--- a/src/web/src/lib/community/message-dispatcher.ts
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -1,6 +1,7 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
import {
deriveCommunityDeliveryOperationId,
+ reachIsParticipantSet,
WS_EVENTS,
createLogger,
queries,
@@ -83,13 +84,16 @@ export async function planCommittedMessage(
throw new Error("committed message scope not found")
}
- const [contentCandidates, notificationCandidates] = await Promise.all([
+ const [contentCandidates, participantCandidates] = await Promise.all([
resolveRecipients(db, channel.id),
- queries.communityMembersResolver.resolveChannelNotificationRecipientUserIds(
- db, channel.id,
- (phase, query) => withD1Retry(query, { route: recipientRetryRoute[phase] }),
- ),
+ reachIsParticipantSet(channel.type)
+ ? queries.communityMembersResolver.resolveChannelNotificationRecipientUserIds(
+ db, channel.id,
+ (phase, query) => withD1Retry(query, { route: recipientRetryRoute[phase] }),
+ )
+ : Promise.resolve(null),
])
+ const notificationCandidates = participantCandidates ?? contentCandidates
const contentUserIds = unique(contentCandidates)
const candidateNotificationUserIds = unique(notificationCandidates).filter((id) => id !== message.authorId)
const attentionIds = unique(attentionUserIds).filter((id) => id !== message.authorId)
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 965dfe156..c97fd16f5 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -32,6 +32,7 @@ vi.mock("@alook/shared", async () => {
}),
queries: {
communityMessage: {
+ isMessageAttachmentConflict: actual.queries.communityMessage.isMessageAttachmentConflict,
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),
@@ -71,8 +72,10 @@ vi.mock("./message-dispatcher", () => ({
dispatchCommittedMessage: (...a: unknown[]) => mockDispatchCommittedMessage(...a),
}))
+const mockFanOutToChannel = vi.fn(async () => {})
const mockBroadcastToUserSafe = vi.fn(async () => {})
vi.mock("./fanout", () => ({
+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
@@ -457,11 +460,7 @@ describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
})
expect(mockListMembers).toHaveBeenCalledWith({}, "srv_1")
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["alex_2"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["alex_2"].map((userId) => ({ userId, kind: "mention" })))
})
it("passes each member's discriminator through as a mention candidate", async () => {
@@ -474,11 +473,7 @@ describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
body: { content: "hey @Alex#0001" },
})
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["alex_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["alex_1"].map((userId) => ({ userId, kind: "mention" })))
})
})
@@ -524,11 +519,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
expect(mockCreateChannelMember).not.toHaveBeenCalled()
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["cara_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["cara_1"].map((userId) => ({ userId, kind: "mention" })))
})
it("@everyone is clamped to the audience (author excluded → only Cara)", async () => {
@@ -543,16 +534,12 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
expect(mockCreateChannelMember).not.toHaveBeenCalled()
// Bob (non-member) not notified; only the in-audience Cara.
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["cara_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["cara_1"].map((userId) => ({ userId, kind: "mention" })))
})
it("thread: author joins as 'spoke'; a non-audience mention is dropped (no channel auto-add)", async () => {
mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob", channelId: "t1" }))
- mockAddThreadParticipants.mockResolvedValueOnce(["author_1"])
+ mockCreateMessage.mockResolvedValueOnce({ id: "msg_1", joinedParticipantUserIds: ["author_1"] })
await createCommunityMessage({
db: {} as never,
@@ -563,7 +550,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
// Author joins the thread's notify set by speaking (bulk insert; Bob is
// outside the parent audience so he's not in the rows).
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
])
// Bob is outside the (private) parent audience → dropped, no mention row,
@@ -588,15 +575,11 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Bulk insert: author (spoke) + Cara (mention).
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["cara_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["cara_1"].map((userId) => ({ userId, kind: "mention" })))
// Thread participation is NOT a channel roster row.
expect(mockCreateChannelMember).not.toHaveBeenCalled()
})
@@ -616,15 +599,11 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Only the author joins the notify set — the mass mention does NOT enroll Cara.
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
])
// Cara is still notified once by the @everyone (a mention row is written).
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["cara_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["cara_1"].map((userId) => ({ userId, kind: "mention" })))
})
it("thread: a direct REPLY under @everyone still enrolls the replied-to user", async () => {
@@ -647,7 +626,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Author (spoke) + Cara (enrolled via the reply, despite @everyone dedup).
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
@@ -666,7 +645,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
body: { content: "first reply" },
})
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
])
expect(mockCreateChannelMember).not.toHaveBeenCalled()
@@ -683,7 +662,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
body: { content: "hey @Cara#0002" },
})
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
@@ -697,7 +676,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"])
+ mockCreateMessage.mockResolvedValueOnce({ id: "msg_1", joinedParticipantUserIds: ["author_1", "cara_1"] })
await createCommunityMessage({
db: {} as never,
@@ -708,7 +687,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Enroll is unaffected by the flag — Cara joins as a participant.
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
@@ -730,11 +709,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
expect(mockCreateChannelMember).not.toHaveBeenCalled()
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["bob_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["bob_1"].map((userId) => ({ userId, kind: "mention" })))
})
it("does not await a pending dispatcher on the normal delivery path", async () => {
@@ -789,16 +764,12 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Structural core KEPT: participant enroll (reach-axis write) still runs...
- expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "p1", [
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([
{ userId: "author_1", source: "spoke" },
{ userId: "cara_1", source: "mention" },
])
// ...and mention ROW persistence still runs (rows are not a broadcast).
- expect(mockCreateMentions).toHaveBeenCalledWith({}, {
- messageId: "msg_1",
- userIds: ["cara_1"],
- kind: "mention",
- })
+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual(["cara_1"].map((userId) => ({ userId, kind: "mention" })))
// Real-time delivery shell FULLY dropped: no WS fan-out of any kind.
expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
// ...and no deferred thunk handed back either (unlike deferBroadcast).
@@ -879,25 +850,17 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
}))
})
- it("reservation-mismatch → unreserve partial, hard-delete the orphan message, generic 400", async () => {
- mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // only 1 of 2 reserved
-
+ it("atomic attachment eligibility failure returns 400 without compensation or dispatch", async () => {
+ mockCreateMessage.mockRejectedValue(new Error("NOT NULL constraint failed: community_message.content"))
const res = await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
+ db: {} as never, authorId: "author_1",
target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hi" },
- attachmentIds: ["att_1", "att_2"],
+ body: { content: "hi" }, attachmentIds: ["att_1", "att_2"],
})
-
- expect(res.ok).toBe(false)
- if (res.ok) return
- expect(res.status).toBe(400)
- expect(res.error).toBe("attachment not found or not attachable to this target")
- expect(mockCreateMessage).toHaveBeenCalledTimes(1)
- expect(mockUnreserveAttachments).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))
- expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
+ expect(res).toEqual({ ok: false, status: 400, error: "attachment not found or not attachable to this target" })
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ attachmentIds: ["att_1", "att_2"] }))
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
+ expect(mockUnreserveAttachments).not.toHaveBeenCalled()
expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
})
@@ -919,94 +882,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
expect(mockHardDeleteMessage).not.toHaveBeenCalled()
})
- it("thrown reserve error → hard-delete the just-inserted message, re-throw", async () => {
- mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
- mockReserveAttachmentsForMessage.mockRejectedValue(new Error("d1_transient_reserve"))
-
- await expect(
- createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hi" },
- attachmentIds: ["att_1"],
- }),
- ).rejects.toThrow("d1_transient_reserve")
-
- expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
- expect(mockUnreserveAttachments).not.toHaveBeenCalled()
- })
-
- it("thrown reserve error + hardDelete ALSO throws → caller sees the ORIGINAL reserve error (not the rollback error)", async () => {
- mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
- mockReserveAttachmentsForMessage.mockRejectedValue(new Error("d1_transient_reserve"))
- mockHardDeleteMessage.mockRejectedValue(new Error("d1_transient_rollback"))
- mockLogError.mockClear()
-
- await expect(
- createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hi" },
- attachmentIds: ["att_1"],
- }),
- ).rejects.toThrow("d1_transient_reserve")
- // hardDelete WAS attempted; both errors are logged in one line.
- expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
- expect(mockLogError).toHaveBeenCalledWith(
- "attachment_reserve_rollback_failed",
- expect.objectContaining({
- messageId: "msg_preminted",
- insertErr: "d1_transient_reserve",
- rollbackErr: "d1_transient_rollback",
- }),
- )
- })
-
- it("partial reserve + unreserve throws → hardDelete STILL fires (not skipped), caller gets 400", async () => {
- mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // 1 of 2
- mockUnreserveAttachments.mockRejectedValueOnce(new Error("d1_transient_unreserve"))
-
- const res = await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hi" },
- attachmentIds: ["att_1", "att_2"],
- })
-
- expect(res.ok).toBe(false)
- if (res.ok) return
- expect(res.status).toBe(400)
- expect(res.error).toBe("attachment not found or not attachable to this target")
- expect(mockUnreserveAttachments).toHaveBeenCalledTimes(1)
- // hardDelete must NOT be skipped just because unreserve threw first — the
- // orphan message row still needs cleanup.
- expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
- })
-
- it("partial reserve + unreserve AND hardDelete both throw → caller still gets 400 envelope (no rethrow)", async () => {
- mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // 1 of 2
- mockUnreserveAttachments.mockRejectedValueOnce(new Error("d1_transient_unreserve"))
- mockHardDeleteMessage.mockRejectedValue(new Error("d1_transient_rollback"))
-
- const res = await createCommunityMessage({
- db: {} as never,
- authorId: "author_1",
- target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
- body: { content: "hi" },
- attachmentIds: ["att_1", "att_2"],
- })
-
- expect(res.ok).toBe(false)
- if (res.ok) return
- expect(res.status).toBe(400)
- expect(res.error).toBe("attachment not found or not attachable to this target")
- })
-
it("expectedSeq CAS-null → no reserve, no unreserve, no hardDelete, returns seq_conflict", async () => {
mockCreateMessage.mockResolvedValue(null) // CAS-null (returned, not thrown)
@@ -1100,3 +975,60 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
expect(mockUnreserveAttachments).not.toHaveBeenCalled()
})
})
+
+describe("post-commit notification registration", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCreateMessage.mockResolvedValue({ id: "msg_1", createdThread: { id: "child", name: "post", createdAt: "2026-01-01" } })
+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false })
+ mockGetMessage.mockResolvedValue(messageRow())
+ mockListByMessageIds.mockResolvedValue([])
+ mockDispatchCommittedMessage.mockResolvedValue(undefined)
+ })
+
+ const params = {
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel" as const, channelId: "c1", serverId: "s1" },
+ body: { content: "hello" },
+ }
+
+ it.each(["attachments", "message"])("registers message and child notices before a failed %s response read", async (projection) => {
+ const fail = async () => {
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledOnce()
+ expect(mockFanOutToChannel).toHaveBeenCalledOnce()
+ throw new Error("projection unavailable")
+ }
+ if (projection === "attachments") mockListByMessageIds.mockImplementationOnce(fail)
+ else mockGetMessage.mockImplementationOnce(fail)
+ await expect(createCommunityMessage({ ...params, attachmentIds: ["att_1"] })).rejects.toThrow("projection unavailable")
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
+ })
+
+ it("surfaces a missing response projection after registering notifications without deleting committed data", async () => {
+ mockGetMessage.mockResolvedValueOnce(null)
+ await expect(createCommunityMessage(params)).rejects.toThrow("message not found after insert")
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledOnce()
+ expect(mockFanOutToChannel).toHaveBeenCalledOnce()
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
+ })
+
+ it("returns the committed response while delivery is pending", async () => {
+ let resolve!: () => void
+ const pending = new Promise<void>((done) => { resolve = done })
+ mockDispatchCommittedMessage.mockReturnValueOnce(pending)
+ try {
+ const result = await createCommunityMessage(params)
+ expect(result.ok).toBe(true)
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledOnce()
+ } finally {
+ resolve()
+ }
+ })
+
+ it("preserves explicit notification suppression", async () => {
+ expect((await createCommunityMessage({ ...params, suppressBroadcast: true })).ok).toBe(true)
+ expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 2c9e67a44..720ce3a35 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -16,23 +16,10 @@ import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
-import { broadcastToUserSafe } from "./fanout"
+import { broadcastToUserSafe, fanOutToChannel } from "./fanout"
const log = createLogger({ service: "community-message-handler" })
-/* istanbul ignore next -- real workerd compensation oracle covers revision fanout */
-async function hardDeleteMessageAndBroadcastReadState(db: Database, messageId: string) {
- const result = await queries.communityMessage.hardDeleteMessage(db, messageId)
- await Promise.all((result?.readStateRevisions ?? []).map((revision) =>
- broadcastToUserSafe(revision.userId, {
- type: WS_EVENTS.READ_STATE_ADVANCED,
- revision: revision.revision,
- inboxChanged: true,
- })
- ))
- return result
-}
-
export type MessageTarget =
| { kind: "channel"; channelId: string; serverId: string }
| {
@@ -255,6 +242,8 @@ export async function createCommunityMessage(params: {
* identity-agnostic — the bot-only caller supplies the statement.
*/
extraStatements?: unknown[]
+ suppressThreadFanout?: boolean
+ forumThread?: Parameters<typeof queries.communityMessage.createMessage>[1]["forumThread"]
}): Promise<CreateMessageResult> {
const {
db,
@@ -357,173 +346,6 @@ export async function createCommunityMessage(params: {
? body.mentionType
: undefined
- const baseMessageData: {
- authorId: string;
- authorKind: "human" | "bot";
- content: string;
- channelId: string;
- replyToId: string | undefined;
- mentionType: MentionType | undefined;
- type?: string;
- clientNonce?: string;
- extraStatements?: unknown[];
- } = {
- authorId,
- authorKind,
- content,
- channelId: target.channelId,
- replyToId,
- mentionType,
- ...(messageType !== undefined ? { type: messageType } : {}),
- ...(clientNonce !== undefined ? { clientNonce } : {}),
- ...(extraStatements !== undefined ? { extraStatements } : {}),
- }
-
- // Insert first so `reserveAttachmentsForMessage`'s UPDATE can key off
- // `created.id` (the FK enforces the message row exists); compensate with
- // the cascading `hardDeleteMessage` on reserve failure or partial reserve.
- // See plans/attachment-pipeline-empty-body-guardrails.md Layer 5-6 for the
- // rollback contract.
- //
- // Narrow once here so downstream branches don't need `attachmentIds!`.
- const reserveIds: string[] | null =
- attachmentIds !== undefined && attachmentIds.length > 0 ? attachmentIds : null
-
- // `createMessage`'s overloads key off whether the `expectedSeq` property
- // is present at all, not just its runtime value — a `number | undefined`
- // typed property doesn't cleanly resolve against either overload, so the
- // pass-through branches explicitly instead of spreading `expectedSeq` in.
- let created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>>
- try {
- created =
- expectedSeq !== undefined
- ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
- : await queries.communityMessage.createMessage(db, baseMessageData)
- } catch (err) {
- // Insert-time idempotency race: two concurrent first-sends with the same
- // nonce both cleared the pre-check above, then one lost to the partial
- // unique index `uq_message_author_client_nonce` on INSERT. Recover by
- // re-fetching the winner's row and returning it as a deduped replay — same
- // shape as the pre-check hit. The re-fetch is what narrows this to the
- // NONCE constraint specifically: any OTHER unique violation (or an insert
- // with no nonce) finds no matching row, so we rethrow the original error
- // untouched. Only enter this branch when a nonce was actually supplied.
- if (clientNonce !== undefined && isUniqueConstraintError(err)) {
- const existing = await withD1Retry(
- () => queries.communityMessage.getMessageByAuthorAndNonce(db, authorId, clientNonce),
- { route: "message-handler:nonce-insert-race" },
- )
- if (existing) {
- if (existing.channelId !== target.channelId) throw err
- return {
- ok: true,
- row: existing,
- attachments: await hydrateStoredAttachments(db, existing.id),
- deduped: true,
- }
- }
- }
- throw err
- }
-
- // Lost the CAS race (plans/fix-agent-send-race-condition.md) — zero rows
- // were written anywhere (no message, no channel/DM bump, no read-state
- // watermark). No attachments were reserved yet, so nothing to unreserve.
- if (created === null) {
- return { ok: false, status: 409, error: "seq_conflict" }
- }
-
- if (reserveIds) {
- let reserved: string[]
- try {
- reserved = await queries.communityAttachment.reserveAttachmentsForMessage(db, {
- ids: reserveIds,
- messageId: created.id,
- })
- } catch (err) {
- // Reserve threw (transient D1 / constraint / etc.). The message row
- // exists but has zero attachments reserved to it — hard-delete it so
- // the caller can retry with the same attachment ids. If the
- // compensating hardDelete ALSO throws (same D1 outage the reserve was
- // recovering from), log both and re-throw the ORIGINAL reserve error —
- // it's the one the caller cares about; matches bots/route.ts:139's shape.
- try {
- await hardDeleteMessageAndBroadcastReadState(db, created.id)
- } catch (rollbackErr) {
- log.error("attachment_reserve_rollback_failed", {
- messageId: created.id,
- insertErr: err instanceof Error ? err.message : String(err),
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- throw err
- }
- if (reserved.length !== reserveIds.length) {
- // Partial-overlap race (S1={A,B}, S2={B,C}) or an id that no longer
- // matches (uploader/kind/target/messageId-null). Compensate:
- // unreserve whatever THIS caller uniquely grabbed AND hard-delete the
- // orphan message row. Both compensating writes are individually guarded:
- // if unreserve throws we still try the hardDelete (else we'd leave a
- // live message row alongside the stale partial-reserve); if either
- // throws we log but still return the 400 envelope — the caller-facing
- // shape doesn't depend on whether compensation succeeded.
- try {
- await queries.communityAttachment.unreserveAttachments(db, {
- ids: reserved,
- messageId: created.id,
- })
- } catch (unreserveErr) {
- log.error("attachment_partial_reserve_unreserve_failed", {
- messageId: created.id,
- unreserveErr: unreserveErr instanceof Error ? unreserveErr.message : String(unreserveErr),
- })
- }
- try {
- await hardDeleteMessageAndBroadcastReadState(db, created.id)
- } catch (rollbackErr) {
- log.error("attachment_partial_reserve_rollback_failed", {
- messageId: created.id,
- rollbackErr: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- })
- }
- return {
- ok: false,
- status: 400,
- error: "attachment not found or not attachable to this target",
- }
- }
- }
-
- // Reserve-by-id path (human web AND bot): the pending rows were reserved and
- // pointed at `created.id` above via `reserveAttachmentsForMessage`, so no
- // INSERT is needed here — just project the linked rows for the response. The
- // row already carries its dimensions (written at upload time, the single
- // source), so the display URL is derived id-addressed via `attachmentUrl`.
- let attachments: CreatedAttachment[] = []
- if (reserveIds) {
- const rows = await queries.communityAttachment.listByMessageIds(db, [created.id])
- attachments = rows.map((r) => ({
- id: r.id,
- filename: r.filename,
- url: attachmentUrl(r.targetId, r.id),
- ...(r.thumbnailR2Key ? { thumbnailUrl: attachmentThumbnailUrl(r.targetId, r.id) } : {}),
- contentType: r.contentType,
- size: r.size,
- width: r.width,
- height: r.height,
- }))
- }
-
- const row = await withD1Retry(
- () => queries.communityMessage.getMessage(db, created.id),
- { route: "message-handler:read-back" },
- )
- if (!row) {
- // createMessage just inserted this row; getMessage returning null means
- // the DB is gone — surface that to the caller instead of inventing data.
- throw new Error("message not found after insert")
- }
-
// 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
@@ -531,10 +353,10 @@ export async function createCommunityMessage(params: {
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`
- // scope, so re-querying here would be redundant. `row.replyToId` is already
+ // scope, so re-querying here would be redundant. `replyToId` is already
// null when the id was out-of-scope (dropped above), so this block only runs
// for a genuinely in-scope reply.
- if (!skipMentions && row.replyToId && resolvedReplyMsg) {
+ if (!skipMentions && replyToId && resolvedReplyMsg) {
// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path
if (resolvedReplyMsg.authorId && resolvedReplyMsg.authorId !== authorId) {
replyTargets.add(resolvedReplyMsg.authorId)
@@ -577,7 +399,7 @@ export async function createCommunityMessage(params: {
)
: null
- const hasAtMention = typeof row.content === "string" && row.content.includes("@")
+ const hasAtMention = typeof content === "string" && content.includes("@")
if (hasAtMention) {
const allMembers = await withD1Retry(
() => queries.communityMember.listMembers(db, target.serverId),
@@ -592,11 +414,11 @@ export async function createCommunityMessage(params: {
if (m.userId !== authorId) mentionTargets.add(m.userId)
}
}
- if (row.content) {
+ if (content) {
const candidates = members
.filter((m) => m.userId !== authorId && m.userName)
.map((m) => ({ userId: m.userId, name: m.userName as string, discriminator: m.discriminator }))
- for (const id of extractMentionedUserIds(row.content, candidates)) {
+ for (const id of extractMentionedUserIds(content, candidates)) {
mentionTargets.add(id)
explicitMentionTargets.add(id)
}
@@ -650,7 +472,7 @@ export async function createCommunityMessage(params: {
// 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
// participant reach without a parent, so the two rules stay separate.
- let joinedParticipantUserIds: string[] = []
+ let participants: { userId: string; source: string }[] = []
if (reachIsParticipantSet(target.kind) && !skipMentions) {
const rows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.MENTION }[] = [
{ userId: authorId, source: PARTICIPANT_SOURCE.SPOKE },
@@ -664,37 +486,61 @@ export async function createCommunityMessage(params: {
if (id !== authorId) rows.push({ userId: id, source: PARTICIPANT_SOURCE.MENTION })
}
// One bulk insert (author + mentioned) instead of N+1 sequential inserts.
- joinedParticipantUserIds =
- await queries.communityThread.addThreadParticipants(db, target.channelId, rows) ?? []
+ participants = rows
}
- // Mention/reply ROW writes are persistence, not broadcast — they run inline
- // even under `deferBroadcast` (only the WS emissions defer). When
- // `skipMentions` both sets are empty, so these are no-ops.
- const liveMentions = [...mentionTargets]
- const liveReplies = [...replyTargets]
- if (liveMentions.length > 0) {
- await queries.communityMention.createMentions(db, {
- messageId: row.id,
- userIds: liveMentions,
- kind: MENTION_KIND.MENTION,
- })
+ const baseMessageData: Omit<Parameters<typeof queries.communityMessage.createMessage>[1], "expectedSeq"> = {
+ authorId,
+ authorKind,
+ content,
+ channelId: target.channelId,
+ replyToId,
+ mentionType,
+ type: messageType,
+ clientNonce,
+ extraStatements,
+ attachmentIds,
+ participants,
+ mentions: [
+ ...[...mentionTargets].map((userId) => ({ userId, kind: MENTION_KIND.MENTION })),
+ ...[...replyTargets].map((userId) => ({ userId, kind: MENTION_KIND.REPLY })),
+ ],
+ forumThread: params.forumThread,
}
- if (liveReplies.length > 0) {
- await queries.communityMention.createMentions(db, {
- messageId: row.id,
- userIds: liveReplies,
- kind: MENTION_KIND.REPLY,
- })
+
+ let created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>>
+ try {
+ created =
+ expectedSeq !== undefined
+ ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
+ : await queries.communityMessage.createMessage(db, baseMessageData)
+ } catch (err) {
+ const attachmentConflict = queries.communityMessage.isMessageAttachmentConflict(err)
+ if (clientNonce !== undefined && (attachmentConflict || isUniqueConstraintError(err))) {
+ const replay = await getCommunityMessageReplay({ db, authorId, channelId: target.channelId, clientNonce })
+ if (replay) return replay
+ }
+ if (attachmentConflict) {
+ return { ok: false, status: 400, error: "attachment not found or not attachable to this target" }
+ }
+ throw err
+ }
+
+ if (created === null) {
+ const replay = await getCommunityMessageReplay({ db, authorId, channelId: target.channelId, clientNonce })
+ if (replay) return replay
+ return { ok: false, status: 409, error: "seq_conflict" }
}
+ const joinedParticipantUserIds = created.joinedParticipantUserIds ?? []
+
// Delivery is planned from committed D1 facts. The handler contributes only
// structural outcomes that cannot be safely reconstructed later.
const readStateRevision = (created as typeof created & {
readStateRevision?: number
}).readStateRevision
const doBroadcast = async (): Promise<void> => {
- const deliveries: Promise<void>[] = [dispatchCommittedMessage(db, row.id, {
+ const deliveries: Promise<void>[] = [dispatchCommittedMessage(db, created.id, {
...(joinedParticipantUserIds.includes(authorId)
? { memberAddedUserId: authorId }
: {}),
@@ -707,18 +553,39 @@ export async function createCommunityMessage(params: {
inboxChanged: true,
}))
}
+ if (created.createdThread && !params.suppressThreadFanout) {
+ deliveries.push(fanOutToChannel(target.channelId, {
+ type: WS_EVENTS.CHILD_CHANNEL_CREATE,
+ parentChannelId: target.channelId,
+ parentMessageId: created.id,
+ channel: { ...created.createdThread, type: "thread", creatorId: authorId },
+ }))
+ }
await Promise.all(deliveries)
}
- // 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.
- if (suppressBroadcast) {
- return { ok: true, row, attachments }
+ if (!suppressBroadcast && !deferBroadcast) {
+ void doBroadcast().catch((error) => {
+ log.warn("post_commit_notification_failed", { messageId: created.id, error: String(error) })
+ })
}
- if (deferBroadcast) {
+
+ const attachments = attachmentIds?.length
+ ? await hydrateStoredAttachments(db, created.id)
+ : []
+
+ const row = await withD1Retry(
+ () => queries.communityMessage.getMessage(db, created.id),
+ { route: "message-handler:read-back" },
+ )
+ if (!row) {
+ // createMessage just inserted this row; getMessage returning null means
+ // the DB is gone — surface that to the caller instead of inventing data.
+ throw new Error("message not found after insert")
+ }
+
+ if (!suppressBroadcast && deferBroadcast) {
return { ok: true, row, attachments, broadcast: doBroadcast }
}
- void doBroadcast()
return { ok: true, row, attachments }
}
diff --git a/src/web/src/lib/community/queue-transport.test.ts b/src/web/src/lib/community/queue-transport.test.ts
index ae01af587..f7ba27288 100644
--- a/src/web/src/lib/community/queue-transport.test.ts
+++ b/src/web/src/lib/community/queue-transport.test.ts
@@ -52,11 +52,13 @@ describe("createDevHttpQueueTransport", () => {
const mockGlobalFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development")
vi.clearAllMocks()
globalThis.fetch = mockGlobalFetch as unknown as typeof fetch
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
diff --git a/src/web/src/lib/dev-binding-fetch.test.ts b/src/web/src/lib/dev-binding-fetch.test.ts
index 4ccfd7fa1..d32166776 100644
--- a/src/web/src/lib/dev-binding-fetch.test.ts
+++ b/src/web/src/lib/dev-binding-fetch.test.ts
@@ -8,10 +8,12 @@ const log = new Logger({ service: "test", level: "silent" })
beforeEach(() => {
vi.clearAllMocks()
+ vi.stubEnv("NODE_ENV", "development")
globalThis.fetch = mockFetch as unknown as typeof fetch
})
afterAll(() => {
+ vi.unstubAllEnvs()
globalThis.fetch = originalFetch
})
@@ -96,4 +98,14 @@ describe("fetchViaBindingOrDevFallback", () => {
fetchViaBindingOrDevFallback({ fetch: bindingFetch }, "http://dev:1234", "/x", { method: "POST" }, { logPrefix: "test", log }),
).rejects.toThrow("network down")
})
+ it("production never falls back on a binding failure or missing binding", async () => {
+ vi.stubEnv("NODE_ENV", "production")
+ const bindingFetch = vi.fn().mockRejectedValue(new Error("network"))
+ await expect(fetchViaBindingOrDevFallback({ fetch: bindingFetch }, "http://dev", "/x", {}, { logPrefix: "test", log })).rejects.toThrow("network")
+ bindingFetch.mockResolvedValue(new Response("unavailable", { status: 503 }))
+ expect((await fetchViaBindingOrDevFallback({ fetch: bindingFetch }, "http://dev", "/x", {}, { logPrefix: "test", log })).status).toBe(503)
+ await expect(fetchViaBindingOrDevFallback(undefined, "http://dev", "/x", {}, { logPrefix: "test", log })).rejects.toThrow("service binding is required")
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+
})
diff --git a/src/web/src/lib/dev-binding-fetch.ts b/src/web/src/lib/dev-binding-fetch.ts
index 7e75ac0a1..7b108643e 100644
--- a/src/web/src/lib/dev-binding-fetch.ts
+++ b/src/web/src/lib/dev-binding-fetch.ts
@@ -15,7 +15,7 @@ interface FetcherLike {
* the worker's `[dev] port`" — never duplicate this decision tree per
* binding.
*
- * Falls back to `fallbackBaseUrl` when the binding is absent, throws, or
+ * In local development only, falls back when the binding is absent, throws, or
* returns a 5xx. Never falls back on a 4xx (client error — the caller's
* request was bad, retrying via HTTP won't help, and would just hide the
* real error behind a second, unrelated one).
@@ -27,6 +27,10 @@ export async function fetchViaBindingOrDevFallback(
init: RequestInit,
opts: { logPrefix: string; log: Logger; label?: string; type?: string },
): Promise<Response> {
+ if (process.env.NODE_ENV !== "development") {
+ if (!binding) throw new Error(`${opts.logPrefix}: service binding is required outside development`)
+ return binding.fetch(`http://internal${path}`, init)
+ }
const { logPrefix, log, label, type } = opts
let bindingAttempted = false
diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
index f6c20187a..e810d7d19 100644
--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
@@ -55,7 +55,7 @@ describe("human account read-state writer contract", () => {
expect(message).toContain('authorKind?: "human" | "bot"')
expect(message).toContain("communityReadStateRevision")
expect(message).toContain("authorWatermark")
- expect(message).toContain("return { ...msg, readStateRevision: revision }")
+ expect(message).toMatch(/return\s*\{\s*\.\.\.msg,[^}]*readStateRevision:\s*revision/s)
expect(message).toContain("impactedMentions")
expect(message).not.toContain("humanSnapshot")
diff --git a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
index fc67b8e6e..f0b334d06 100644
--- a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
+++ b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
@@ -289,6 +289,9 @@ test.describe.serial("actionable Inbox friend requests", () => {
const reject = bob.page.getByTestId(tid.inboxFriendRequestReject(friendshipId))
await expect(accept).toHaveAccessibleName(/Accept .+ friend request/)
await expect(reject).toHaveAccessibleName(/Reject .+ friend request/)
+ await inboxSurface.evaluate(async (element) => {
+ await Promise.all(element.getAnimations().map((animation) => animation.finished))
+ })
for (const action of [accept, reject]) {
const box = await action.boundingBox()
expect(box).not.toBeNull()
diff --git a/src/web/src/test/e2e/message-delivery-retry.test.ts b/src/web/src/test/e2e/message-delivery-retry.test.ts
index 0d004c965..cacd59d9c 100644
--- a/src/web/src/test/e2e/message-delivery-retry.test.ts
+++ b/src/web/src/test/e2e/message-delivery-retry.test.ts
@@ -42,6 +42,7 @@ function batch(): MessageDeliveryBatch {
}
beforeAll(async () => {
+ vi.stubEnv("NODE_ENV", "development")
server = createServer((request, response) => {
let body = ""
request.setEncoding("utf8")
@@ -60,6 +61,7 @@ beforeAll(async () => {
})
afterAll(async () => {
+ vi.unstubAllEnvs()
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
})