Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): delete canonical forum posts (#530)

Gener550fb11f8df2
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index f7d84f730..9b94a8a68 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -34,6 +34,7 @@ export const SPEC_SECONDS = {
"24-composer-overflow.spec.ts": 35,
"25-composer-accessory-rail-occupancy.spec.ts": 60,
"26-mobile-forum-post-actions.spec.ts": 45,
+ "27-canonical-forum-post-delete.spec.ts": 30,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 26c994fe1..971a7f76c 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([183, 184, 186, 187, 188])
+ expect(totals.sort((left, right) => left - right)).toEqual([188, 192, 192, 193, 193])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 1e4464232..90e2d7304 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -198,7 +198,13 @@ const communityChannelDeleteSchema = z.strictObject({
serverId: string,
channelId: string,
parentChannelId: nullableString.optional(),
-})
+ parentMessageId: string.optional(),
+}).refine(
+ (event) => event.parentMessageId === undefined || (
+ typeof event.parentChannelId === "string" && event.parentChannelId.length > 0
+ ),
+ { message: "parentMessageId requires parentChannelId" },
+)
const positionedIdSchema = z.strictObject({ id: string, position: z.number() })
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index ec86767e6..8cdeded91 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -85,7 +85,9 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(
creatorId: text("creator_id").references(() => user.id, { onDelete: "set null" }),
messageCount: integer("message_count").default(0),
archived: integer("archived").default(0),
- parentMessageId: text("parent_message_id"),
+ parentMessageId: text("parent_message_id").references(() => communityMessage.id, {
+ onDelete: "cascade",
+ }),
lastMessageAt: text("last_message_at"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
},
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 83ef2d1ef..09693c9bd 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -37,6 +37,7 @@ export * as communityMember from "./queries/community/member";
export * as communityMembersResolver from "./queries/community/members-resolver";
export * as communityThread from "./queries/community/thread";
export * as communityMessage from "./queries/community/message";
+export * as communityForumPostDelete from "./queries/community/forum-post-delete";
export * as communityFriendship from "./queries/community/friendship";
export * as communityDm from "./queries/community/dm";
export * as communityInvite from "./queries/community/invite";
diff --git a/src/shared/src/db/queries/community/forum-post-delete.ts b/src/shared/src/db/queries/community/forum-post-delete.ts
new file mode 100644
index 000000000..74d5ba57d
--- /dev/null
+++ b/src/shared/src/db/queries/community/forum-post-delete.ts
@@ -0,0 +1,176 @@
+import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
+import {
+ communityAttachment,
+ communityChannel,
+ communityMessage,
+ communityReadState,
+} from "../../community-schema";
+import type { Database } from "../../index";
+
+export type DeleteForumPostInput = {
+ openerId: string;
+ openerSeq: number;
+ forumChannelId: string;
+ childChannelId: string;
+};
+
+export type DeleteForumPostResult = {
+ /** False only when a concurrently-resolved delete committed first. */
+ deleted: boolean;
+ /** Captured in the same D1 batch before message/channel cascades ran. */
+ mediaKeys: string[];
+};
+
+/**
+ * Delete one already-authorized canonical forum post as a single D1 unit.
+ *
+ * The route resolves and authorizes the exact opener→forum→unique-child tuple;
+ * this primitive owns only mutation atomicity. It intentionally does not reuse
+ * `hardDeleteMessage`, whose bookkeeping and contract are limited to immediate
+ * send rollback.
+ *
+ * Batch order matters:
+ * 1. snapshot every linked/pending Community-media key;
+ * 2. repair or remove parent-forum read cursors that point at the opener;
+ * 3. remove child-scoped pending attachment rows (linked rows cascade);
+ * 4. update parent forum count/activity once;
+ * 5. delete the opener, whose FK cascades the child channel and its rows.
+ *
+ * Every mutating statement is guarded by the opener still existing in the
+ * resolved forum. D1 serializes each batch transaction, so when two requests
+ * resolve before either commits, the loser becomes a no-op rather than
+ * decrementing the parent twice.
+ */
+export async function deleteForumPost(
+ db: Database,
+ input: DeleteForumPostInput,
+): Promise<DeleteForumPostResult> {
+ const openerStillExists = sql<boolean>`EXISTS (
+ SELECT 1 FROM community_message AS guarded_opener
+ WHERE guarded_opener.id = ${input.openerId}
+ AND guarded_opener.channel_id = ${input.forumChannelId}
+ )`;
+ const priorMessageExists = sql<boolean>`EXISTS (
+ SELECT 1 FROM community_message AS prior_message
+ WHERE prior_message.channel_id = ${input.forumChannelId}
+ AND prior_message.seq < ${input.openerSeq}
+ )`;
+ // Drizzle has no scalar-subquery setter that can project three columns from
+ // the same ordered prior row. Keep the three SQL expressions adjacent and
+ // identical in scope/order so the read-state invariant is explicit.
+ const priorId = sql<string>`(
+ SELECT prior_message.id FROM community_message AS prior_message
+ WHERE prior_message.channel_id = ${input.forumChannelId}
+ AND prior_message.seq < ${input.openerSeq}
+ ORDER BY prior_message.seq DESC LIMIT 1
+ )`;
+ const priorSeq = sql<number>`(
+ SELECT prior_message.seq FROM community_message AS prior_message
+ WHERE prior_message.channel_id = ${input.forumChannelId}
+ AND prior_message.seq < ${input.openerSeq}
+ ORDER BY prior_message.seq DESC LIMIT 1
+ )`;
+ const priorCreatedAt = sql<string>`(
+ SELECT prior_message.created_at FROM community_message AS prior_message
+ WHERE prior_message.channel_id = ${input.forumChannelId}
+ AND prior_message.seq < ${input.openerSeq}
+ ORDER BY prior_message.seq DESC LIMIT 1
+ )`;
+
+ const childMessageIds = db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(eq(communityMessage.channelId, input.childChannelId));
+
+ const mediaSnapshot = db
+ .select({
+ r2Key: communityAttachment.r2Key,
+ thumbnailR2Key: communityAttachment.thumbnailR2Key,
+ })
+ .from(communityAttachment)
+ .where(or(
+ eq(communityAttachment.messageId, input.openerId),
+ inArray(communityAttachment.messageId, childMessageIds),
+ and(
+ isNull(communityAttachment.messageId),
+ eq(communityAttachment.targetId, input.childChannelId),
+ ),
+ ));
+
+ const repairReadStates = db
+ .update(communityReadState)
+ .set({
+ lastReadMessageId: priorId,
+ lastReadSeq: priorSeq,
+ lastReadAt: priorCreatedAt,
+ })
+ .where(and(
+ eq(communityReadState.channelId, input.forumChannelId),
+ eq(communityReadState.lastReadMessageId, input.openerId),
+ openerStillExists,
+ priorMessageExists,
+ ));
+
+ const removeEmptyReadStates = db
+ .delete(communityReadState)
+ .where(and(
+ eq(communityReadState.channelId, input.forumChannelId),
+ eq(communityReadState.lastReadMessageId, input.openerId),
+ openerStillExists,
+ sql<boolean>`NOT (${priorMessageExists})`,
+ ));
+
+ const removePendingAttachments = db
+ .delete(communityAttachment)
+ .where(and(
+ isNull(communityAttachment.messageId),
+ eq(communityAttachment.targetId, input.childChannelId),
+ openerStillExists,
+ ));
+
+ const updateForum = db
+ .update(communityChannel)
+ .set({
+ messageCount: sql<number>`CASE
+ WHEN COALESCE(${communityChannel.messageCount}, 0) > 0
+ THEN ${communityChannel.messageCount} - 1
+ ELSE 0
+ END`,
+ lastMessageAt: sql<string | null>`(
+ SELECT MAX(surviving_message.created_at)
+ FROM community_message AS surviving_message
+ WHERE surviving_message.channel_id = ${input.forumChannelId}
+ AND surviving_message.id != ${input.openerId}
+ )`,
+ })
+ .where(and(
+ eq(communityChannel.id, input.forumChannelId),
+ openerStillExists,
+ ));
+
+ const deleteOpener = db
+ .delete(communityMessage)
+ .where(and(
+ eq(communityMessage.id, input.openerId),
+ eq(communityMessage.channelId, input.forumChannelId),
+ ))
+ .returning({ id: communityMessage.id });
+
+ const results = (await db.batch([
+ mediaSnapshot,
+ repairReadStates,
+ removeEmptyReadStates,
+ removePendingAttachments,
+ updateForum,
+ deleteOpener,
+ ] as any)) as unknown[];
+ const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>;
+ const deletedRows = results[5] as Array<{ id: string }>;
+
+ return {
+ deleted: deletedRows.length > 0,
+ mediaKeys: deletedRows.length > 0
+ ? mediaRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key].filter((key): key is string => !!key))
+ : [],
+ };
+}
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index f2cca5e8e..0fb32a3ef 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -1,12 +1,56 @@
import { describe, it, expect } from "vitest";
-import { isCommunityEvent, WS_EVENTS } from "../src/community-ws-events";
+import { CommunityWsEventSchema, isCommunityEvent, WS_EVENTS } from "../src/community-ws-events";
import type {
+ CommunityChannelDelete,
CommunityMessageEdited,
CommunityMachineCreated,
CommunityMachineUpdated,
CommunityMachineSummary,
} from "../src/community-ws-events";
+describe("CommunityChannelDelete post-unit address contract", () => {
+ it("accepts canonical post identity while preserving legacy/top-level compatibility", () => {
+ const canonical: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "child_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ };
+ expect(CommunityWsEventSchema.parse(canonical)).toEqual(canonical);
+ expect(CommunityWsEventSchema.safeParse({
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "channel_1",
+ }).success).toBe(true);
+ });
+
+ it("keeps the frame strict", () => {
+ expect(CommunityWsEventSchema.safeParse({
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "child_1",
+ parentChannelId: "forum_1",
+ parentMessageId: 42,
+ }).success).toBe(false);
+ for (const parentChannelId of [undefined, null, ""]) {
+ expect(CommunityWsEventSchema.safeParse({
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "child_1",
+ ...(parentChannelId !== undefined ? { parentChannelId } : {}),
+ parentMessageId: "opener_1",
+ }).success).toBe(false);
+ }
+ expect(CommunityWsEventSchema.safeParse({
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "child_1",
+ parentChannelId: "forum_1",
+ }).success).toBe(true);
+ });
+});
+
describe("CommunityMessageEdited address contract", () => {
it("supports forum opener, ordinary server, and DM edits", () => {
const events: CommunityMessageEdited[] = [
diff --git a/src/shared/test/migrations/community-channel-parent-message-fk.test.ts b/src/shared/test/migrations/community-channel-parent-message-fk.test.ts
new file mode 100644
index 000000000..05c38c801
--- /dev/null
+++ b/src/shared/test/migrations/community-channel-parent-message-fk.test.ts
@@ -0,0 +1,329 @@
+import Sqlite from "better-sqlite3";
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { getTableConfig } from "drizzle-orm/sqlite-core";
+import { afterEach, describe, expect, it } from "vitest";
+import { communityChannel } from "../../src/db/community-schema";
+
+const testDirectory = dirname(fileURLToPath(import.meta.url));
+const migrationPath = resolve(
+ testDirectory,
+ "../../../web/migrations/0089_community_channel_parent_message_fk.sql",
+);
+
+type ChannelRow = {
+ id: string;
+ server_id: string | null;
+ type: string;
+ parent_channel_id: string | null;
+ parent_message_id: string | null;
+ message_count: number;
+ last_message_at: string | null;
+};
+
+function createCurrentSchema(sqlite: Sqlite.Database): void {
+ sqlite.pragma("foreign_keys = ON");
+ sqlite.exec(`
+ CREATE TABLE community_server (id TEXT PRIMARY KEY);
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ server_id TEXT REFERENCES community_server(id) ON DELETE CASCADE,
+ 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) ON DELETE CASCADE,
+ creator_id TEXT,
+ message_count INTEGER DEFAULT 0,
+ archived INTEGER DEFAULT 0,
+ parent_message_id TEXT,
+ last_message_at TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_message (
+ id TEXT PRIMARY KEY,
+ author_id TEXT NOT NULL,
+ 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) ON DELETE CASCADE,
+ seq INTEGER NOT NULL DEFAULT 0,
+ friendship_id TEXT,
+ client_nonce TEXT
+ );
+ CREATE UNIQUE INDEX idx_channel_parent_message
+ ON community_channel(parent_message_id) WHERE parent_message_id IS NOT NULL;
+ CREATE UNIQUE INDEX uq_community_channel_parent_message
+ ON community_channel(parent_channel_id, parent_message_id)
+ WHERE parent_channel_id IS NOT NULL AND parent_message_id IS NOT NULL;
+ CREATE INDEX idx_channel_forum_created
+ ON community_channel(parent_channel_id, created_at DESC, id DESC)
+ WHERE type = 'thread' AND archived = 0 AND parent_message_id IS NOT NULL;
+ `);
+}
+
+function insertChannel(
+ sqlite: Sqlite.Database,
+ row: {
+ id: string;
+ type: string;
+ parentChannelId?: string | null;
+ parentMessageId?: string | null;
+ serverId?: string | null;
+ messageCount?: number;
+ lastMessageAt?: string | null;
+ },
+): void {
+ sqlite.prepare(`
+ INSERT INTO community_channel (
+ id, server_id, name, type, parent_channel_id, message_count,
+ archived, parent_message_id, last_message_at, created_at
+ ) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
+ `).run(
+ row.id,
+ row.serverId === undefined ? "server_1" : row.serverId,
+ row.id,
+ row.type,
+ row.parentChannelId ?? null,
+ row.messageCount ?? 0,
+ row.parentMessageId ?? null,
+ row.lastMessageAt ?? null,
+ `2026-08-23T00:00:0${row.id.length % 10}.000Z`,
+ );
+}
+
+function insertMessage(
+ sqlite: Sqlite.Database,
+ id: string,
+ channelId: string,
+ seq: number,
+): void {
+ sqlite.prepare(`
+ INSERT INTO community_message (
+ id, author_id, content, created_at, channel_id, seq
+ ) VALUES (?, 'user_1', ?, ?, ?, ?)
+ `).run(id, id, `2026-08-23T00:01:${String(seq).padStart(2, "0")}.000Z`, channelId, seq);
+}
+
+function applyMigration(sqlite: Sqlite.Database): void {
+ const migration = readFileSync(migrationPath, "utf8");
+ sqlite.transaction(() => sqlite.exec(migration))();
+}
+
+function listChannels(sqlite: Sqlite.Database): ChannelRow[] {
+ return sqlite.prepare(`
+ SELECT id, server_id, type, parent_channel_id, parent_message_id,
+ message_count, last_message_at
+ FROM community_channel ORDER BY id
+ `).all() as ChannelRow[];
+}
+
+function listAllChannels(sqlite: Sqlite.Database): unknown[] {
+ return sqlite.prepare("SELECT * FROM community_channel ORDER BY id").all();
+}
+
+function targetIndexDefinitions(sqlite: Sqlite.Database): Array<{ name: string; sql: string }> {
+ return (sqlite.prepare(`
+ SELECT name, sql FROM sqlite_master
+ WHERE type = 'index' AND name IN (
+ 'idx_channel_parent_message',
+ 'uq_community_channel_parent_message',
+ 'idx_channel_forum_created'
+ )
+ ORDER BY name
+ `).all() as Array<{ name: string; sql: string }>).map((row) => ({
+ name: row.name,
+ sql: row.sql.replace(/\s+/g, " ").trim().toLowerCase(),
+ }));
+}
+
+describe("0089 community_channel.parent_message_id cascade FK", () => {
+ let sqlite: Sqlite.Database | undefined;
+
+ afterEach(() => sqlite?.close());
+
+ it("mirrors the parent-message cascade in the Drizzle schema", () => {
+ const parentMessageFk = getTableConfig(communityChannel).foreignKeys.find((foreignKey) =>
+ foreignKey.reference().columns.some((column) => column.name === "parent_message_id")
+ );
+
+ expect(parentMessageFk?.reference()).toMatchObject({
+ foreignColumns: [{ name: "id" }],
+ });
+ expect(parentMessageFk?.onDelete).toBe("cascade");
+ });
+
+ it("preserves valid forum and ordinary text threads, then cascades only the selected opener unit", () => {
+ sqlite = new Sqlite(":memory:");
+ createCurrentSchema(sqlite);
+ sqlite.prepare("INSERT INTO community_server (id) VALUES (?)").run("server_1");
+
+ insertChannel(sqlite, { id: "forum", type: "forum", messageCount: 2 });
+ insertChannel(sqlite, { id: "text", type: "text", messageCount: 1 });
+ insertMessage(sqlite, "forum_opener", "forum", 1);
+ insertMessage(sqlite, "forum_sibling_opener", "forum", 2);
+ insertMessage(sqlite, "text_opener", "text", 1);
+ insertChannel(sqlite, {
+ id: "forum_child",
+ type: "thread",
+ parentChannelId: "forum",
+ parentMessageId: "forum_opener",
+ messageCount: 1,
+ });
+ insertChannel(sqlite, {
+ id: "forum_sibling",
+ type: "thread",
+ parentChannelId: "forum",
+ parentMessageId: "forum_sibling_opener",
+ });
+ insertChannel(sqlite, {
+ id: "text_thread",
+ type: "thread",
+ parentChannelId: "text",
+ parentMessageId: "text_opener",
+ messageCount: 1,
+ });
+ insertMessage(sqlite, "forum_reply", "forum_child", 1);
+ insertMessage(sqlite, "text_reply", "text_thread", 1);
+
+ const before = listChannels(sqlite);
+ const allColumnsBefore = listAllChannels(sqlite);
+ const indexesBefore = targetIndexDefinitions(sqlite);
+ applyMigration(sqlite);
+
+ expect(listChannels(sqlite)).toEqual(before);
+ expect(listAllChannels(sqlite)).toEqual(allColumnsBefore);
+ expect(targetIndexDefinitions(sqlite)).toEqual(indexesBefore);
+ const parentMessageFk = (sqlite.pragma("foreign_key_list('community_channel')") as Array<{
+ table: string;
+ from: string;
+ to: string;
+ on_delete: string;
+ }>).find((fk) => fk.from === "parent_message_id");
+ expect(parentMessageFk).toMatchObject({
+ table: "community_message",
+ to: "id",
+ on_delete: "CASCADE",
+ });
+ expect(sqlite.pragma("foreign_key_check")).toEqual([]);
+
+ sqlite.prepare("DELETE FROM community_message WHERE id = ?").run("forum_opener");
+
+ expect(listChannels(sqlite).map((row) => row.id)).toEqual([
+ "forum",
+ "forum_sibling",
+ "text",
+ "text_thread",
+ ]);
+ expect(sqlite.prepare("SELECT id FROM community_message ORDER BY id").all()).toEqual([
+ { id: "forum_sibling_opener" },
+ { id: "text_opener" },
+ { id: "text_reply" },
+ ]);
+ expect(sqlite.pragma("foreign_key_check")).toEqual([]);
+ });
+
+ it.each([
+ {
+ label: "orphan opener",
+ arrange(db: Sqlite.Database) {
+ insertChannel(db, { id: "forum", type: "forum" });
+ insertChannel(db, {
+ id: "child",
+ type: "thread",
+ parentChannelId: "forum",
+ parentMessageId: "missing",
+ });
+ },
+ },
+ {
+ label: "opener in the wrong parent scope",
+ arrange(db: Sqlite.Database) {
+ insertChannel(db, { id: "forum", type: "forum" });
+ insertChannel(db, { id: "other", type: "forum" });
+ insertMessage(db, "opener", "other", 1);
+ insertChannel(db, {
+ id: "child",
+ type: "thread",
+ parentChannelId: "forum",
+ parentMessageId: "opener",
+ });
+ },
+ },
+ {
+ label: "child thread without an opener",
+ arrange(db: Sqlite.Database) {
+ insertChannel(db, { id: "forum", type: "forum" });
+ insertChannel(db, {
+ id: "child",
+ type: "thread",
+ parentChannelId: "forum",
+ parentMessageId: null,
+ });
+ },
+ },
+ {
+ label: "missing parent channel",
+ arrange(db: Sqlite.Database) {
+ insertChannel(db, { id: "forum", type: "forum" });
+ insertMessage(db, "opener", "forum", 1);
+ db.pragma("foreign_keys = OFF");
+ insertChannel(db, {
+ id: "child",
+ type: "thread",
+ parentChannelId: "missing",
+ parentMessageId: "opener",
+ });
+ db.pragma("foreign_keys = ON");
+ },
+ },
+ {
+ label: "non-thread child relation",
+ arrange(db: Sqlite.Database) {
+ insertChannel(db, { id: "forum", type: "forum" });
+ insertMessage(db, "opener", "forum", 1);
+ insertChannel(db, {
+ id: "child",
+ type: "text",
+ parentChannelId: "forum",
+ parentMessageId: "opener",
+ });
+ },
+ },
+ {
+ label: "server mismatch",
+ arrange(db: Sqlite.Database) {
+ db.prepare("INSERT INTO community_server (id) VALUES (?)").run("server_2");
+ insertChannel(db, { id: "forum", type: "forum", serverId: "server_1" });
+ insertMessage(db, "opener", "forum", 1);
+ insertChannel(db, {
+ id: "child",
+ type: "thread",
+ serverId: "server_2",
+ parentChannelId: "forum",
+ parentMessageId: "opener",
+ });
+ },
+ },
+ ])("aborts before schema mutation for $label", ({ arrange }) => {
+ sqlite = new Sqlite(":memory:");
+ createCurrentSchema(sqlite);
+ sqlite.prepare("INSERT INTO community_server (id) VALUES (?)").run("server_1");
+ arrange(sqlite);
+ const before = listChannels(sqlite);
+
+ expect(() => applyMigration(sqlite!)).toThrow(/community_channel parent_message_id audit failed/i);
+
+ expect(listChannels(sqlite)).toEqual(before);
+ expect(sqlite.prepare("PRAGMA table_info('community_channel')").all()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ name: "parent_message_id" })]),
+ );
+ const fks = sqlite.pragma("foreign_key_list('community_channel')") as Array<{ from: string }>;
+ expect(fks.some((fk) => fk.from === "parent_message_id")).toBe(false);
+ });
+});
diff --git a/src/web/migrations/0089_community_channel_parent_message_fk.sql b/src/web/migrations/0089_community_channel_parent_message_fk.sql
new file mode 100644
index 000000000..80b9a5725
--- /dev/null
+++ b/src/web/migrations/0089_community_channel_parent_message_fk.sql
@@ -0,0 +1,82 @@
+-- Canonical forum-post deletion is rooted at the opener message. Before the
+-- FK is added, prove every child-channel relation is the supported one-level
+-- shape. Abort on anomalies; never filter, repair, or silently drop a row.
+PRAGMA defer_foreign_keys = ON;
+
+CREATE TABLE _channel_parent_message_audit (dummy INTEGER);
+CREATE TRIGGER _channel_parent_message_audit_trg
+ BEFORE INSERT ON _channel_parent_message_audit
+ WHEN EXISTS (
+ SELECT 1
+ FROM community_channel AS child
+ LEFT JOIN community_channel AS parent
+ ON parent.id = child.parent_channel_id
+ LEFT JOIN community_message AS opener
+ ON opener.id = child.parent_message_id
+ WHERE
+ (child.type = 'thread'
+ OR child.parent_channel_id IS NOT NULL
+ OR child.parent_message_id IS NOT NULL)
+ AND (
+ child.type != 'thread'
+ OR child.parent_channel_id IS NULL
+ OR child.parent_message_id IS NULL
+ OR parent.id IS NULL
+ OR parent.parent_channel_id IS NOT NULL
+ OR parent.type NOT IN ('text', 'forum')
+ OR opener.id IS NULL
+ OR opener.channel_id != child.parent_channel_id
+ OR child.server_id IS NOT parent.server_id
+ )
+ )
+BEGIN
+ SELECT RAISE(ABORT, 'community_channel parent_message_id audit failed');
+END;
+INSERT INTO _channel_parent_message_audit (dummy) VALUES (1);
+DROP TRIGGER _channel_parent_message_audit_trg;
+DROP TABLE _channel_parent_message_audit;
+
+-- Native column evolution avoids DROP/CREATE of community_channel. Rebuilding
+-- that root table would fire its existing ON DELETE CASCADE children inside a
+-- D1 migration even with defer_foreign_keys enabled (the failure 0068 had to
+-- work around). The temporary column starts nullable as SQLite requires for a
+-- REFERENCES column added to a populated table.
+ALTER TABLE community_channel
+ ADD COLUMN parent_message_id_cascade TEXT
+ REFERENCES community_message(id) ON DELETE CASCADE;
+
+UPDATE community_channel
+SET parent_message_id_cascade = parent_message_id;
+
+-- Every index that names or predicates on the old column must be removed
+-- before SQLite will DROP it, then recreated byte-for-byte on the renamed FK.
+DROP INDEX IF EXISTS idx_channel_parent_message;
+DROP INDEX IF EXISTS uq_community_channel_parent_message;
+DROP INDEX IF EXISTS idx_channel_forum_created;
+
+ALTER TABLE community_channel DROP COLUMN parent_message_id;
+ALTER TABLE community_channel
+ RENAME COLUMN parent_message_id_cascade TO parent_message_id;
+
+CREATE UNIQUE INDEX idx_channel_parent_message
+ ON community_channel(parent_message_id)
+ WHERE parent_message_id IS NOT NULL;
+CREATE UNIQUE INDEX uq_community_channel_parent_message
+ ON community_channel(parent_channel_id, parent_message_id)
+ WHERE parent_channel_id IS NOT NULL AND parent_message_id IS NOT NULL;
+CREATE INDEX idx_channel_forum_created
+ ON community_channel(parent_channel_id, created_at DESC, id DESC)
+ WHERE type = 'thread' AND archived = 0 AND parent_message_id IS NOT NULL;
+
+-- `PRAGMA foreign_key_check` returning rows would not itself fail a migration,
+-- so turn it into the same one-shot hard assertion used for the preflight.
+CREATE TABLE _channel_parent_message_fk_check (dummy INTEGER);
+CREATE TRIGGER _channel_parent_message_fk_check_trg
+ BEFORE INSERT ON _channel_parent_message_fk_check
+ WHEN EXISTS (SELECT 1 FROM pragma_foreign_key_check)
+BEGIN
+ SELECT RAISE(ABORT, 'community_channel parent_message_id foreign key check failed');
+END;
+INSERT INTO _channel_parent_message_fk_check (dummy) VALUES (1);
+DROP TRIGGER _channel_parent_message_fk_check_trg;
+DROP TABLE _channel_parent_message_fk_check;
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index a47ab5992..dff16d733 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -362,63 +362,29 @@ describe("DELETE /channels/[id]", () => {
expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
})
- it("admin deletes any post (thread under a forum) → 204 and broadcasts", async () => {
- mockResolveChannelAccessContext.mockResolvedValue(
- accessCtx({ role: "admin", canManage: true, creatorId: "someone_else" }),
- )
- const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(204)
- expect(mockDeleteChannel).toHaveBeenCalled()
- expect(mockFanOutToServerMembers).toHaveBeenCalled()
- })
-
- it("a PUBLIC post's creator (no canManage) can delete it via the carve-out", async () => {
+ it("returns 409 for a direct forum-child delete by the post creator", async () => {
mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))
const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(204)
- expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "c1")
- expect(mockGetChannelType).toHaveBeenCalledWith(expect.anything(), "forum_1")
- })
-
- it("a private post's creator can delete it (canManage already true)", async () => {
- // Private post creator: canManage = isPrivate && isCreator → true anyway.
- mockResolveChannelAccessContext.mockResolvedValue({
- ...forumPostCtx({ isCreator: true }),
- isPrivate: true,
- })
- mockIsChannelPrivate.mockResolvedValue(true)
- mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])
- const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(204)
- expect(mockDeleteChannel).toHaveBeenCalled()
- })
-
- it("a non-creator non-admin cannot delete a post → 403", async () => {
- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: false }))
- const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(403)
+ expect(res.status).toBe(409)
expect(mockDeleteChannel).not.toHaveBeenCalled()
+ expect(mockGetChannelType).toHaveBeenCalledWith(expect.anything(), "forum_1")
})
- it("the FORUM creator cannot delete a post they didn't author (isCreator is access-only)", async () => {
- // Regression guard: the delete carve-out keys off the POST's own creator
- // (`channel.creatorId`), not the collapsed access `isCreator` (= forum creator).
+ it("returns 409 for a direct forum-child delete by an admin/manager", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
- ...forumPostCtx({ isCreator: false }), // post authored by "someone_else"
- isCreator: true, // caller u1 is the forum/anchor creator (access flag)
+ ...forumPostCtx({ isCreator: false }),
+ member: { role: "admin" },
+ canManage: true,
})
const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(403)
+ expect(res.status).toBe(409)
expect(mockDeleteChannel).not.toHaveBeenCalled()
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
- // SECURITY REGRESSION GUARD (Aigneis's catch): the carve-out must NOT widen
- // to "any thread's creator". A thread opened incidentally by replying in an
- // ordinary text channel is a conversation side-effect, not an intentional
- // "post" — its creator must NOT gain delete power over the whole thread
- // (which would cascade-delete every reply in it) just because they
- // triggered it. Only a thread whose PARENT is a forum carries the
- // deliberate creation semantics the old forum_post carve-out covered.
+ // SECURITY REGRESSION GUARD: an ordinary text thread's creator never gains
+ // whole-thread delete authority merely by having opened the thread.
it("a thread's creator under a PLAIN CHANNEL (not a forum) cannot delete it via the carve-out → 403", async () => {
mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))
mockGetChannelType.mockResolvedValue("text") // parent is a plain channel, not a forum
@@ -427,18 +393,6 @@ describe("DELETE /channels/[id]", () => {
expect(mockDeleteChannel).not.toHaveBeenCalled()
})
- it("the broadcast CHANNEL_DELETE payload carries parentChannelId", async () => {
- mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))
- const res = await DELETE(delReq(), ctx)
- expect(res.status).toBe(204)
- const event = mockFanOutToServerMembers.mock.calls[0]?.[1]
- expect(event).toMatchObject({
- type: "community:channel.delete",
- channelId: "c1",
- parentChannelId: "forum_1",
- })
- })
-
it("the carve-out does NOT let a non-creator delete a normal (non-thread) channel", async () => {
// canManage=false + type="text" + not creator → still 403 (carve-out is
// scoped to threads-under-a-forum only).
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index a395f2ea6..4d542ecf5 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -163,24 +163,16 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const access = await requireChannelAccess(db, channelId, ctx.userId)
if (!access.ok) return writeError(access.error, access.status)
const channel = access.value.channel
- // A post's OWN creator may delete their own post — this carve-out predates
- // forum_post's collapse into thread; a post is now a thread rooted under a
- // forum, so its shape is `isThread(channel.type) && parent is a forum`.
- // ⚠ MUST NOT widen to "any thread's creator" (Aigneis's catch): the
- // carve-out is a session-authed HTTP DELETE, not a UI-gated action — anyone
- // who replies to a message in an ordinary channel incidentally becomes a
- // thread's creator, and that person must NOT gain the power to delete the
- // whole thread (cascading every reply in it) just because they happened to
- // trigger it. Only a thread whose PARENT is a forum carries the deliberate,
- // intentional-creation semantics the old forum_post carve-out was actually
- // scoped to. `access.value.isCreator` is the ACCESS creator (the parent's
- // creator), so derive the unit-own-creator directly from `channel.creatorId`.
- let canDeletePost = false
- if (isThread(channel.type) && channel.creatorId === ctx.userId && channel.parentChannelId) {
+ if (isThread(channel.type) && channel.parentChannelId) {
const parentType = await queries.communityChannel.getChannelType(db, channel.parentChannelId)
- canDeletePost = isForum(parentType)
+ if (isForum(parentType)) {
+ return writeError("delete the forum opener message instead", 409)
+ }
}
- if (!access.value.canManage && !canDeletePost) return writeError("forbidden", 403)
+ // Forum posts are deleted only through DELETE /messages/{openerId}. The
+ // remaining channel route is manager-only; never widen ordinary thread
+ // creators into whole-thread deletion authority.
+ if (!access.value.canManage) return writeError("forbidden", 403)
// Resolve the private-channel audience BEFORE deleting (the member rows
// cascade away with the channel row), so the delete event still reaches
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index 70f744bfb..004f6f111 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -1,8 +1,18 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+const cloudflareMocks = vi.hoisted(() => ({
+ mediaDelete: vi.fn(),
+ waitUntil: vi.fn<(promise: Promise<unknown>) => void>(),
+}))
vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+ getCloudflareContext: vi.fn(async () => ({
+ env: {
+ DB: {},
+ COMMUNITY_MEDIA: { delete: (...args: unknown[]) => cloudflareMocks.mediaDelete(...args) },
+ },
+ ctx: { waitUntil: (promise: Promise<unknown>) => cloudflareMocks.waitUntil(promise) },
+ })),
}))
const mockGetMessage = vi.fn()
@@ -12,6 +22,10 @@ const mockGetChannelForMember = vi.fn()
const mockGetChannelType = vi.fn()
const mockGetChannel = vi.fn()
const mockGetThreadChannelByParentMessage = vi.fn()
+const mockDeleteForumPost = vi.fn()
+const mockGetMember = vi.fn()
+const mockIsChannelPrivate = vi.fn()
+const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMPeer = vi.fn()
const mockIsBlocked = vi.fn()
@@ -21,6 +35,8 @@ const mockGetMessageByChannelAndSeq = vi.fn()
const mockToAgentMessage = vi.fn()
const mockResolveTargetForMember = vi.fn()
const mockFanOutToChannel = vi.fn()
+const mockFanOutToServerMembers = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -29,6 +45,8 @@ vi.mock("@/lib/community/resolve-ref", () => ({
}))
vi.mock("@/lib/community/fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),
+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
vi.mock("@alook/shared", async () => {
@@ -41,6 +59,8 @@ vi.mock("@alook/shared", async () => {
getChannelType: (...a: unknown[]) => mockGetChannelType(...a),
getChannel: (...a: unknown[]) => mockGetChannel(...a),
getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),
+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),
+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
communityMessage: {
getMessage: (...a: unknown[]) => mockGetMessage(...a),
@@ -57,6 +77,12 @@ vi.mock("@alook/shared", async () => {
communityReaction: {
listReactionsByMessageIds: (...a: unknown[]) => mockListReactionsByMessageIds(...a),
},
+ communityMember: {
+ getMember: (...a: unknown[]) => mockGetMember(...a),
+ },
+ communityForumPostDelete: {
+ deleteForumPost: (...a: unknown[]) => mockDeleteForumPost(...a),
+ },
communityDm: {
getDM: (...a: unknown[]) => mockGetDM(...a),
getDMPeer: (...a: unknown[]) => mockGetDMPeer(...a),
@@ -77,7 +103,14 @@ vi.mock("@/lib/middleware/community-actor", () => ({
const actor = authz.startsWith("Bearer crk_")
? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }
: { kind: "human", userId: "u1", email: "[email protected]" }
- return handler(req, { env: { DB: {} }, actor, params })
+ return handler(req, {
+ env: {
+ DB: {},
+ COMMUNITY_MEDIA: { delete: (...a: unknown[]) => cloudflareMocks.mediaDelete(...a) },
+ },
+ actor,
+ params,
+ })
},
}))
@@ -89,7 +122,7 @@ vi.mock("@/lib/middleware/helpers", () => {
}
})
-import { GET, PATCH } from "./route"
+import { DELETE, GET, PATCH } from "./route"
function req() {
return new NextRequest("http://localhost/api/community/messages/m1", { method: "GET" })
@@ -453,3 +486,143 @@ describe("PATCH /api/community/messages/[id]", () => {
expect((await PATCH(editReq(" "), { params: { id: "m1" } } as any)).status).toBe(400)
})
})
+
+describe("DELETE /api/community/messages/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ cloudflareMocks.mediaDelete.mockResolvedValue(undefined)
+ mockGetMessage.mockResolvedValue({
+ id: "opener_1",
+ channelId: "forum_1",
+ authorId: "u1",
+ seq: 3,
+ })
+ mockGetChannel.mockResolvedValue({ id: "forum_1", serverId: "server_1", type: "forum" })
+ mockGetChannelForMember.mockResolvedValue({ id: "forum_1", serverId: "server_1", type: "forum" })
+ mockGetThreadChannelByParentMessage.mockResolvedValue({
+ id: "child_1",
+ serverId: "server_1",
+ type: "thread",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ })
+ mockGetMember.mockResolvedValue({ userId: "u1", serverId: "server_1", role: "member" })
+ mockIsChannelPrivate.mockResolvedValue(false)
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])
+ mockDeleteForumPost.mockResolvedValue({
+ deleted: true,
+ mediaKeys: ["opener/original", "opener/thumb"],
+ })
+ mockFanOutToServerMembers.mockResolvedValue(undefined)
+ mockBroadcastToUserSafe.mockResolvedValue(undefined)
+ })
+
+ function deleteReq(bot = false) {
+ return new NextRequest("http://localhost/api/community/messages/opener_1", {
+ method: "DELETE",
+ headers: bot ? { Authorization: "Bearer crk_x" } : undefined,
+ })
+ }
+
+ it("lets the author delete the canonical opener, then schedules media and broadcasts the post unit", async () => {
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(204)
+ expect(mockDeleteForumPost).toHaveBeenCalledWith(expect.anything(), {
+ openerId: "opener_1",
+ openerSeq: 3,
+ forumChannelId: "forum_1",
+ childChannelId: "child_1",
+ })
+ expect(cloudflareMocks.waitUntil).toHaveBeenCalledTimes(1)
+ await cloudflareMocks.waitUntil.mock.calls[0]![0]
+ expect(cloudflareMocks.mediaDelete).toHaveBeenCalledWith(["opener/original", "opener/thumb"])
+ expect(mockFanOutToServerMembers).toHaveBeenCalledWith("server_1", {
+ type: "community:channel.delete",
+ serverId: "server_1",
+ channelId: "child_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ })
+ })
+
+ it("lets an accessible owner/admin delete another author's post", async () => {
+ mockGetMessage.mockResolvedValue({ id: "opener_1", channelId: "forum_1", authorId: "u2", seq: 3 })
+ mockGetMember.mockResolvedValue({ userId: "u1", serverId: "server_1", role: "admin" })
+
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(204)
+ expect(mockDeleteForumPost).toHaveBeenCalledTimes(1)
+ })
+
+ it("rejects an ordinary member deleting another author's post before D1/R2", async () => {
+ mockGetMessage.mockResolvedValue({ id: "opener_1", channelId: "forum_1", authorId: "u2", seq: 3 })
+
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(403)
+ expect(mockDeleteForumPost).not.toHaveBeenCalled()
+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["ordinary message", { id: "text_1", serverId: "server_1", type: "text" }],
+ ["reply/child message", { id: "child_1", serverId: "server_1", type: "thread" }],
+ ])("returns 409 for an accessible %s", async (_label, channel) => {
+ mockGetMessage.mockResolvedValue({ id: "opener_1", channelId: channel.id, authorId: "u1", seq: 3 })
+ mockGetChannel.mockResolvedValue(channel)
+ mockGetChannelForMember.mockResolvedValue(channel)
+
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(409)
+ expect(mockGetThreadChannelByParentMessage).not.toHaveBeenCalled()
+ expect(mockDeleteForumPost).not.toHaveBeenCalled()
+ })
+
+ it("rejects bot credentials before resolving the message", async () => {
+ const res = await DELETE(deleteReq(true), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(401)
+ expect(mockGetMessage).not.toHaveBeenCalled()
+ })
+
+ it("fans a private forum delete only to the captured pre-delete audience", async () => {
+ mockIsChannelPrivate.mockResolvedValue(true)
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1", "u2"])
+
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(204)
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(2)
+ expect(mockBroadcastToUserSafe.mock.calls.map((call) => call[0])).toEqual(["u1", "u2"])
+ expect(mockBroadcastToUserSafe.mock.calls[0]![1]).toMatchObject({
+ channelId: "child_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ })
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ })
+
+ it("treats a concurrently-resolved losing batch as idempotent without duplicate side effects", async () => {
+ mockDeleteForumPost.mockResolvedValue({ deleted: false, mediaKeys: [] })
+
+ const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
+
+ expect(res.status).toBe(204)
+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 for a missing opener and 409 for a forum message without a unique child", async () => {
+ mockGetMessage.mockResolvedValueOnce(null)
+ expect((await DELETE(deleteReq(), { params: { id: "missing" } } as any)).status).toBe(404)
+
+ mockGetMessage.mockResolvedValue({ id: "opener_1", channelId: "forum_1", authorId: "u1", seq: 3 })
+ mockGetThreadChannelByParentMessage.mockResolvedValueOnce(null)
+ expect((await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)).status).toBe(409)
+ expect(mockDeleteForumPost).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index 55a2000ba..4a51bffda 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -1,14 +1,25 @@
import { NextRequest } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from "@alook/shared"
-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
+import { canManageServer, queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from "@alook/shared"
+import {
+ requireChannelMember,
+ requireDMAccess,
+ requireMessageSurfaceAccess,
+ requireServerMember,
+} from "@/lib/community/permissions"
import { resolveTargetForMember } from "@/lib/community/resolve-ref"
import { isDmTarget } from "@/lib/community/message-handler"
-import { fanOutToChannel } from "@/lib/community/fanout"
+import {
+ broadcastToUserSafe,
+ fanOutToChannel,
+ fanOutToServerMembers,
+} from "@/lib/community/fanout"
import { groupAttachments, groupReactions } from "@/lib/community/messages"
import { mapMessageForApi } from "@/lib/community/message-payload"
+import { scheduleForumPostMediaCleanup } from "@/lib/community/forum-post-media-cleanup"
// A bot addresses by ref-in-query (`?ref=` + `?seq=`, the folded `resolve`
// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`
@@ -109,6 +120,95 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
return writeJSON({ message: updated })
})
+/**
+ * DELETE /api/community/messages/[id] — delete one canonical forum post.
+ *
+ * The path id is the opener MESSAGE, never the child channel. The server
+ * resolves the unique child from the indexed parent-message relation, gates
+ * the parent forum, then runs one D1 batch. Ordinary messages/DMs/replies and
+ * text-channel thread openers deliberately remain unsupported in this first
+ * version.
+ */
+export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
+ if (ctx.actor.kind !== "human") return writeError("human session required", 401)
+ const openerId = ctx.params?.id
+ if (!openerId || openerId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)
+
+ const db = getDb(ctx.env.DB)
+ const opener = await queries.communityMessage.getMessage(db, openerId)
+ if (!opener) return writeError("message not found", 404)
+
+ // Scope/visibility before ownership: a real but inaccessible message returns
+ // the established per-surface 403/404 contract before we inspect its shape.
+ const access = await requireMessageSurfaceAccess(db, opener.channelId, ctx.actor.userId)
+ if (!access.ok) return writeError(access.error, access.status)
+ if (access.value.surface !== "channel" || access.value.channel.type !== "forum") {
+ return writeError("forum opener required", 409)
+ }
+
+ const forum = access.value.channel
+ const child = await queries.communityChannel.getThreadChannelByParentMessage(
+ db,
+ forum.id,
+ openerId,
+ )
+ if (
+ !child ||
+ child.type !== "thread" ||
+ child.parentChannelId !== forum.id ||
+ child.parentMessageId !== openerId ||
+ !forum.serverId ||
+ child.serverId !== forum.serverId
+ ) {
+ return writeError("forum opener required", 409)
+ }
+
+ const membership = await requireServerMember(db, forum.serverId, ctx.actor.userId)
+ if (!membership.ok) return writeError(membership.error, membership.status)
+ if (opener.authorId !== ctx.actor.userId && !canManageServer(membership.value?.role)) {
+ return writeError("forbidden", 403)
+ }
+
+ // Resolve the private audience before D1 cascades remove child/access rows.
+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, forum.id)
+ const audience = isPrivate
+ ? await queries.communityChannel.getPrivateChannelAudienceUserIds(db, forum.id)
+ : null
+
+ const result = await queries.communityForumPostDelete.deleteForumPost(db, {
+ openerId,
+ openerSeq: opener.seq,
+ forumChannelId: forum.id,
+ childChannelId: child.id,
+ })
+
+ if (result.deleted) {
+ if (result.mediaKeys.length > 0) {
+ const { ctx: executionContext } = await getCloudflareContext({ async: true })
+ scheduleForumPostMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {
+ openerId,
+ childChannelId: child.id,
+ keys: result.mediaKeys,
+ })
+ }
+
+ const event = {
+ type: WS_EVENTS.CHANNEL_DELETE,
+ serverId: forum.serverId,
+ channelId: child.id,
+ parentChannelId: forum.id,
+ parentMessageId: openerId,
+ } as const
+ if (audience) {
+ await Promise.all(audience.map((userId) => broadcastToUserSafe(userId, event)))
+ } else {
+ await fanOutToServerMembers(forum.serverId, event)
+ }
+ }
+
+ return new Response(null, { status: 204 })
+})
+
/**
* Human arm — messageId in the path, `mapMessageForApi` shape. Unchanged from
* the pre-fold route (the 403/404 split is a correct pre-existing contract).
diff --git a/src/web/src/components/community/channels/forum-channel-surface.test.ts b/src/web/src/components/community/channels/forum-channel-surface.test.ts
index 9bb52ac31..736f7d28f 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/forum-channel-surface.test.ts
@@ -152,6 +152,7 @@ describe("ForumChannelSurface ownership", () => {
forumChannelId: "forum_1",
serverId: "srv_1",
threadId: "post_1",
+ openerMessageId: "opener_1",
}, expect.any(Object))
expect(renderer!.root.findByProps({ "data-manage-dialog": true })).toBeTruthy()
})
diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsx
index c3fc0f250..9028f4340 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.tsx
+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx
@@ -132,7 +132,12 @@ export function ForumChannelSurface({
deletingPost={deleteForumThreadMut.isPending ? deleteForumThreadMut.variables?.threadId ?? null : null}
onDeletePost={(post) => {
deleteForumThreadMut.mutate(
- { serverId, forumChannelId: channelId, threadId: post.id },
+ {
+ serverId,
+ forumChannelId: channelId,
+ threadId: post.id,
+ openerMessageId: post.openerMessageId,
+ },
{ onError: (error) => toastApiError(error, "Failed to delete post") },
)
}}
diff --git a/src/web/src/hooks/community/community-ws/cache.ts b/src/web/src/hooks/community/community-ws/cache.ts
index 8c182f383..7375e14a3 100644
--- a/src/web/src/hooks/community/community-ws/cache.ts
+++ b/src/web/src/hooks/community/community-ws/cache.ts
@@ -70,11 +70,17 @@ export function patchMessageContentInCache(cache: PageCache | undefined, message
return touched ? { ...cache, pages } : cache
}
-export function removeThreadFromCache(cache: PageCache | undefined, threadId: string): PageCache | undefined {
+export function removeThreadFromCache(
+ cache: PageCache | undefined,
+ threadId: string,
+ openerMessageId?: string,
+): PageCache | undefined {
if (!cache) return cache
let touched = false
const pages = cache.pages.map((page) => {
- const messages = page.messages.filter((message) => message.thread?.id !== threadId)
+ const messages = page.messages.filter((message) => (
+ message.thread?.id !== threadId && message.id !== openerMessageId
+ ))
if (messages.length === page.messages.length) return page
touched = true
return { ...page, messages }
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
index 10789a408..8c123e0b2 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
@@ -3,6 +3,15 @@ import { communityKeys } from "@/lib/query-keys"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { useCommunityStore } from "@/stores/community"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+import { clearLastChannel } from "@/lib/community/last-channel"
+import { channelHref } from "@/lib/community/community-route"
+import type { PageCache } from "./cache"
+import { removeThreadFromCache } from "./cache"
+import {
+ removeForumPostFromFeed,
+ type ForumFeedPage,
+} from "@/hooks/community/use-forum-feed"
+import type { InfiniteData } from "@tanstack/react-query"
import {
isKnownNonForumSidebarChannel,
removeForumSidebarChildrenForParent,
@@ -18,31 +27,7 @@ export function projectChannelScopeEviction(
channelId: string,
) {
projection.project(() => {
- const nonForum = isKnownNonForumSidebarChannel(queryClient, serverId, channelId)
- if (!nonForum) {
- removeForumSidebarUnreadChild(queryClient, serverId, channelId)
- removeForumSidebarChildrenForParent(queryClient, serverId, channelId)
- removeForumSidebarThreadExact(queryClient, serverId, channelId)
- } else {
- queryClient.removeQueries({
- queryKey: communityKeys.channelMeta(serverId, channelId),
- exact: true,
- })
- }
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(serverId),
- (server) => {
- if (!server) return server
- let changed = false
- const categories = server.categories.map((category) => {
- const channels = category.channels.filter((channel) => channel.id !== channelId)
- if (channels.length === category.channels.length) return category
- changed = true
- return { ...category, channels }
- })
- return changed ? { ...server, categories } : server
- },
- )
+ evictChannelScopeQueryCaches(queryClient, serverId, channelId)
if (useCommunityStore.getState().currentChannelId === channelId) {
useCommunityStore.getState().setCurrentChannelMeta(null)
}
@@ -56,3 +41,118 @@ export function projectChannelScopeEviction(
queryClient.removeQueries({ queryKey: communityKeys.threads(channelId) })
})
}
+
+function evictChannelScopeQueryCaches(
+ queryClient: QueryClient,
+ serverId: string,
+ channelId: string,
+) {
+ const nonForum = isKnownNonForumSidebarChannel(queryClient, serverId, channelId)
+ if (!nonForum) {
+ removeForumSidebarUnreadChild(queryClient, serverId, channelId)
+ removeForumSidebarChildrenForParent(queryClient, serverId, channelId)
+ removeForumSidebarThreadExact(queryClient, serverId, channelId)
+ } else {
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(serverId, channelId),
+ exact: true,
+ })
+ }
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(serverId),
+ (server) => {
+ if (!server) return server
+ let changed = false
+ const categories = server.categories.map((category) => {
+ const channels = category.channels.filter((channel) => channel.id !== channelId)
+ if (channels.length === category.channels.length) return category
+ changed = true
+ return { ...category, channels }
+ })
+ return changed ? { ...server, categories } : server
+ },
+ )
+ queryClient.removeQueries({ queryKey: communityKeys.channelMessages(channelId) })
+ queryClient.removeQueries({ queryKey: communityKeys.pins(channelId) })
+ queryClient.removeQueries({ queryKey: communityKeys.threads(channelId) })
+}
+
+export type ForumPostUnitIdentity = {
+ serverId: string
+ forumChannelId: string
+ childChannelId: string
+ openerMessageId: string
+}
+
+/** Query-only post-unit eviction, shared by optimistic HTTP and WS success. */
+export function evictForumPostUnitQueryCaches(
+ queryClient: QueryClient,
+ unit: ForumPostUnitIdentity,
+) {
+ evictChannelScopeQueryCaches(queryClient, unit.serverId, unit.childChannelId)
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(unit.forumChannelId) },
+ (cache) => removeThreadFromCache(cache, unit.childChannelId, unit.openerMessageId),
+ )
+ queryClient.setQueriesData<InfiniteData<ForumFeedPage>>(
+ { queryKey: communityKeys.forumFeeds(unit.forumChannelId) },
+ (cache) => removeForumPostFromFeed(
+ cache,
+ unit.childChannelId,
+ unit.openerMessageId,
+ ),
+ )
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumOpenerHint(unit.serverId, unit.openerMessageId),
+ exact: true,
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.message(unit.openerMessageId),
+ exact: true,
+ })
+}
+
+/** Canonical WS projection: evict one forum post and eject an active child. */
+export function projectForumPostUnitEviction(
+ projection: CommunityWsProjectionTransaction,
+ queryClient: QueryClient,
+ unit: ForumPostUnitIdentity,
+) {
+ projection.project(() => {
+ applyForumPostUnitClientEffects(queryClient, unit)
+ })
+}
+
+/**
+ * Idempotent success-side effects shared by the HTTP initiator and WS peers.
+ * The initiator calls this after 204 so correctness never depends on receiving
+ * its own fan-out frame; an eventual self frame simply converges again.
+ */
+export function applyForumPostUnitClientEffects(
+ queryClient: QueryClient,
+ unit: ForumPostUnitIdentity,
+) {
+ evictForumPostUnitQueryCaches(queryClient, unit)
+ useMessageStreamStore.getState().removeScope({
+ kind: "channel",
+ id: unit.childChannelId,
+ serverId: unit.serverId,
+ })
+ useMessageStreamStore.getState().dispatch({
+ kind: "channel",
+ id: unit.forumChannelId,
+ serverId: unit.serverId,
+ }, {
+ type: "messageRemoved",
+ messageId: unit.openerMessageId,
+ })
+ const store = useCommunityStore.getState()
+ if (store.currentChannelId === unit.childChannelId) {
+ store.setCurrentChannelMeta(null)
+ store.setCurrentChannelId(unit.forumChannelId)
+ clearLastChannel(unit.serverId)
+ store.uiHandlers.replacePath?.(
+ channelHref(unit.serverId, unit.forumChannelId),
+ )
+ }
+}
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
index b051bc7c3..db8403955 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
@@ -247,6 +247,101 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
unsubscribe()
}
})
+
+ it("projects a canonical forum-post delete as one unit and ejects the active child", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ const replacePath = vi.fn()
+ useCommunityStore.getState().registerUiHandlers({ replacePath })
+ useCommunityStore.getState().setCurrentServerId("srv_1")
+ useCommunityStore.getState().setCurrentChannelId("post_1")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Post",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener-post_1",
+ })
+ const feed = {
+ pages: [{
+ messages: [
+ { id: "opener-post_1", thread: { id: "post_1" } },
+ { id: "opener-keep", thread: { id: "post_keep" } },
+ ],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("forum_1"), feed)
+ const forumFeed = {
+ pages: [{
+ serverId: "srv_1",
+ parentType: "forum",
+ threads: [
+ { id: "post_1", parentMessageId: "opener-post_1" },
+ { id: "post_keep", parentMessageId: "opener-keep" },
+ ],
+ included: {
+ parentMessages: [{ id: "opener-post_1" }, { id: "opener-keep" }],
+ firstMessages: [{ channelId: "post_1" }, { channelId: "post_keep" }],
+ tags: [{ messageId: "opener-post_1" }, { messageId: "opener-keep" }],
+ participants: [{ channelId: "post_1" }, { channelId: "post_keep" }],
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
+ capturedQueryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), forumFeed)
+ capturedQueryClient.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] })
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarThreads("srv_1"),
+ forumSidebarFixture(["post_1", "post_keep"]),
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumOpenerHint("srv_1", "opener-post_1"),
+ { id: "opener-post_1", content: "Post" },
+ )
+ useMessageStreamStore.getState().dispatch({
+ kind: "channel",
+ id: "forum_1",
+ serverId: "srv_1",
+ }, {
+ type: "wsMessage",
+ message: {
+ id: "opener-post_1",
+ seq: 1,
+ type: "chat",
+ authorId: "u1",
+ authorName: "Alice",
+ content: "Post",
+ createdAt: "2026-08-23T00:00:00.000Z",
+ thread: { id: "post_1", name: "Post", messageCount: 1 },
+ },
+ })
+
+ capturedOnMessage!({
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "post_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener-post_1",
+ } satisfies CommunityChannelDelete)
+
+ expect(capturedQueryClient.getQueryData<typeof feed>(communityKeys.channelMessages("forum_1"))
+ ?.pages[0].messages.map((message) => message.id)).toEqual(["opener-keep"])
+ expect(capturedQueryClient.getQueryData<typeof forumFeed>(communityKeys.forumFeed("forum_1", "bug"))
+ ?.pages[0].threads.map((thread) => thread.id)).toEqual(["post_keep"])
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(
+ communityKeys.forumSidebarThreads("srv_1"),
+ )?.threads.map((thread) => thread.id)).toEqual(["post_keep"])
+ expect(capturedQueryClient.getQueryData(
+ communityKeys.forumOpenerHint("srv_1", "opener-post_1"),
+ )).toBeUndefined()
+ expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "srv_1" })
+ .liveById.has("opener-post_1")).toBe(false)
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
+ expect(replacePath).toHaveBeenCalledWith("/c/channels/srv_1/forum_1")
+ expect(capturedQueryClient.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated)
+ .toBe(true)
+ })
})
describe("useCommunityWs — child_create patches parent thread badge with count 0", () => {
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index 1a9aea6fc..7c8d8a9b5 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -32,7 +32,10 @@ import {
type PageCache,
} from "@/hooks/community/community-ws/cache"
import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"
-import { projectChannelScopeEviction } from "./channel-scope-projection"
+import {
+ projectChannelScopeEviction,
+ projectForumPostUnitEviction,
+} from "./channel-scope-projection"
import {
invalidateChannelMessages,
invalidateChannelRefDirectory,
@@ -315,16 +318,31 @@ export function handleChannelEvent(
// subsequent same-id revive (rare, but the server can reuse ids)
// would surface stale rows.
if (event.type === "community:channel.delete") {
- projectChannelScopeEviction(
- projection,
- queryClient,
- event.serverId,
- event.channelId,
- )
+ if (event.parentChannelId && event.parentMessageId) {
+ projectForumPostUnitEviction(projection, queryClient, {
+ serverId: event.serverId,
+ forumChannelId: event.parentChannelId,
+ childChannelId: event.channelId,
+ openerMessageId: event.parentMessageId,
+ })
+ invalidateChannelMessages(projection, event.parentChannelId)
+ invalidateThreads(projection, event.parentChannelId)
+ projection.invalidate("forum-post-delete:tags", {
+ queryKey: communityKeys.forumTags(event.parentChannelId),
+ exact: true,
+ })
+ } else {
+ projectChannelScopeEviction(
+ projection,
+ queryClient,
+ event.serverId,
+ event.channelId,
+ )
+ }
// When a child thread is deleted, refresh the
// PARENT's list so the deleted card disappears from the feed on
// every client. Absent on older events / top-level channels.
- if (event.parentChannelId) {
+ if (event.parentChannelId && !event.parentMessageId) {
queryClient.setQueriesData<PageCache>(
{ queryKey: communityKeys.channelMessages(event.parentChannelId) },
(cache) => removeThreadFromCache(cache, event.channelId),
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index a68023d9e..0781ca64f 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -7,6 +7,13 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+const { clearLastChannelMock } = vi.hoisted(() => ({
+ clearLastChannelMock: vi.fn(),
+}))
+vi.mock("@/lib/community/last-channel", () => ({
+ clearLastChannel: (...args: unknown[]) => clearLastChannelMock(...args),
+}))
+
vi.mock("react", () => ({
useRef: (initial: unknown) => ({ current: initial }),
useCallback: (fn: unknown) => fn,
@@ -21,8 +28,10 @@ vi.mock("@/lib/api/client", () => ({
type MutConfig<Args> = {
mutationFn?: (args: Args) => unknown
- onSuccess?: (data: unknown, args: Args) => unknown
- onError?: (err: unknown, args: Args) => unknown
+ onMutate?: (args: Args) => unknown
+ onSuccess?: (data: unknown, args: Args, context?: unknown) => unknown
+ onError?: (err: unknown, args: Args, context?: unknown) => unknown
+ onSettled?: (data: unknown, err: unknown, args: Args, context?: unknown) => unknown
}
let capturedConfig: MutConfig<unknown> | null = null
let capturedQc: QueryClient
@@ -40,19 +49,24 @@ vi.mock("@tanstack/react-query", async () => {
async function runMutation<Args>(args: Args) {
const cfg = capturedConfig as MutConfig<Args>
+ const context = cfg.onMutate ? await cfg.onMutate(args) : undefined
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
- cfg.onSuccess?.(data, args)
+ cfg.onSuccess?.(data, args, context)
+ cfg.onSettled?.(data, null, args, context)
return data
}
async function runMutationExpectError<Args>(args: Args) {
const cfg = capturedConfig as MutConfig<Args>
+ const context = cfg.onMutate ? await cfg.onMutate(args) : undefined
try {
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
- cfg.onSuccess?.(data, args)
+ cfg.onSuccess?.(data, args, context)
+ cfg.onSettled?.(data, null, args, context)
throw new Error("expected mutationFn to reject")
} catch (err) {
- cfg.onError?.(err, args)
+ cfg.onError?.(err, args, context)
+ cfg.onSettled?.(undefined, err, args, context)
return err
}
}
@@ -66,6 +80,7 @@ beforeEach(() => {
apiFetchMock.mockReset()
capturedConfig = null
capturedQc = new QueryClient()
+ clearLastChannelMock.mockClear()
})
describe("useCreateForumThread", () => {
@@ -197,12 +212,97 @@ describe("useUpdatePostTags", () => {
})
describe("useDeleteForumThread", () => {
- it("DELETEs the post channel and invalidates the canonical feed on success", async () => {
+ it("applies full local success effects without self-WS and remains idempotent when it arrives", async () => {
const { useDeleteForumThread } = await load()
+ const { useCommunityStore } = await import("@/stores/community")
+ const { getMessageOverlay, useMessageStreamStore } = await import("@/stores/community/message-stream")
+ const { applyForumPostUnitClientEffects } = await import("@/hooks/community/community-ws/channel-scope-projection")
+ useCommunityStore.getState().reset()
+ useMessageStreamStore.getState().resetAll()
+ const replacePath = vi.fn()
+ useCommunityStore.getState().registerUiHandlers({ replacePath })
+ useCommunityStore.getState().setCurrentServerId("server_1")
+ useCommunityStore.getState().setCurrentChannelId("p2")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Post",
+ parentChannelId: "forum_1",
+ parentMessageId: "m_p2",
+ })
+ const opener = {
+ id: "m_p2",
+ seq: 1,
+ type: "chat" as const,
+ authorId: "u1",
+ authorName: "Alice",
+ content: "Post",
+ createdAt: "2026-08-23T00:00:00.000Z",
+ }
+ useMessageStreamStore.getState().dispatch(
+ { kind: "channel", id: "forum_1", serverId: "server_1" },
+ { type: "wsMessage", message: opener },
+ )
+ useMessageStreamStore.getState().dispatch(
+ { kind: "channel", id: "p2", serverId: "server_1" },
+ { type: "wsMessage", message: { ...opener, id: "reply_1" } },
+ )
useDeleteForumThread()
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const args = {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "m_p2",
+ }
- capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
- capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [], pageParams: [] })
+ await runMutation(args)
+
+ expect(useMessageStreamStore.getState().entries.has("channel:p2")).toBe(false)
+ expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "server_1" })
+ .liveById.has("m_p2")).toBe(false)
+ expect(useCommunityStore.getState().currentChannelId).toBe("forum_1")
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
+ expect(clearLastChannelMock).toHaveBeenCalledOnce()
+ expect(replacePath).toHaveBeenCalledOnce()
+ expect(replacePath).toHaveBeenCalledWith("/c/channels/server_1/forum_1")
+
+ applyForumPostUnitClientEffects(capturedQc, {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ childChannelId: "p2",
+ openerMessageId: "m_p2",
+ })
+ expect(clearLastChannelMock).toHaveBeenCalledOnce()
+ expect(replacePath).toHaveBeenCalledOnce()
+ })
+
+ it("optimistically evicts the post unit and DELETEs the canonical opener", async () => {
+ const { useDeleteForumThread } = await load()
+ useDeleteForumThread()
+
+ const feed = {
+ pages: [{ messages: [{ id: "m_p2", thread: { id: "p2" } }, { id: "m_keep", thread: { id: "keep" } }] }],
+ pageParams: [null],
+ }
+ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), feed)
+ const forumFeed = {
+ pages: [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: [
+ { id: "p2", parentMessageId: "m_p2" },
+ { id: "keep", parentMessageId: "m_keep" },
+ ],
+ included: {
+ parentMessages: [{ id: "m_p2" }, { id: "m_keep" }],
+ firstMessages: [{ channelId: "p2" }, { channelId: "keep" }],
+ tags: [{ messageId: "m_p2" }, { messageId: "m_keep" }],
+ participants: [{ channelId: "p2" }, { channelId: "keep" }],
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), forumFeed)
const sidebarKey = communityKeys.forumSidebarThreads("server_1")
capturedQc.setQueryData(sidebarKey, {
channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
@@ -211,26 +311,72 @@ describe("useDeleteForumThread", () => {
})
apiFetchMock.mockResolvedValueOnce(undefined)
- await runMutation({ serverId: "server_1", forumChannelId: "forum_1", threadId: "p2" })
+ await runMutation({
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "m_p2",
+ })
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/p2", { method: "DELETE" })
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/m_p2", { method: "DELETE" })
+ expect(capturedQc.getQueryData<typeof feed>(communityKeys.channelMessages("forum_1"))
+ ?.pages[0].messages.map((message) => message.id)).toEqual(["m_keep"])
+ const projectedFeed = capturedQc.getQueryData<typeof forumFeed>(communityKeys.forumFeed("forum_1", null))
+ expect(projectedFeed?.pages[0].threads.map((thread) => thread.id)).toEqual(["keep"])
+ expect(projectedFeed?.pages[0].included).toEqual({
+ parentMessages: [{ id: "m_keep" }],
+ firstMessages: [{ channelId: "keep" }],
+ tags: [{ messageId: "m_keep" }],
+ participants: [{ channelId: "keep" }],
+ })
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryData<{ threads: unknown[] }>(sidebarKey)?.threads).toEqual([])
})
- it("leaves the cache untouched when the DELETE fails", async () => {
+ it("restores exact feed/sidebar/meta snapshots when the DELETE fails", async () => {
const { useDeleteForumThread } = await load()
useDeleteForumThread()
const before = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }
+ const feedBefore = {
+ pages: [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: [{ id: "p2", parentMessageId: "m_p2" }],
+ included: {
+ parentMessages: [{ id: "m_p2" }],
+ firstMessages: [{ channelId: "p2" }],
+ tags: [{ messageId: "m_p2" }],
+ participants: [{ channelId: "p2" }],
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), before)
- capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), before)
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), feedBefore)
+ const sidebarKey = communityKeys.forumSidebarThreads("server_1")
+ const sidebarBefore = {
+ channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: [{ id: "p2", parentChannelId: "forum_1", parentMessageId: "m_p2" }],
+ }
+ const metaKey = communityKeys.channelMeta("server_1", "p2")
+ capturedQc.setQueryData(sidebarKey, sidebarBefore)
+ capturedQc.setQueryData(metaKey, { id: "p2", parentMessageId: "m_p2" })
apiFetchMock.mockRejectedValueOnce(new Error("500"))
- await runMutationExpectError({ serverId: "server_1", forumChannelId: "forum_1", threadId: "p2" })
+ await runMutationExpectError({
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "m_p2",
+ })
expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(before)
- expect(capturedQc.getQueryData(communityKeys.forumFeed("forum_1", null))).toEqual(before)
+ expect(capturedQc.getQueryData(communityKeys.forumFeed("forum_1", null))).toEqual(feedBefore)
+ expect(capturedQc.getQueryData(sidebarKey)).toEqual(sidebarBefore)
+ expect(capturedQc.getQueryData(metaKey)).toEqual({ id: "p2", parentMessageId: "m_p2" })
})
})
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 6e9dbc4fd..a935c0b97 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -1,14 +1,24 @@
"use client"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
+import {
+ hashKey,
+ useMutation,
+ useQueryClient,
+ type Query,
+ type QueryKey,
+} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"
import type { MentionType } from "@alook/shared"
import {
- removeForumSidebarThreadExact,
- removeForumSidebarUnreadChild,
+ restoreForumSidebarThreadInflight,
} from "@/hooks/community/use-forum-sidebar-threads"
+import {
+ applyForumPostUnitClientEffects,
+ evictForumPostUnitQueryCaches,
+ type ForumPostUnitIdentity,
+} from "@/hooks/community/community-ws/channel-scope-projection"
export type CreateForumThreadArgs = {
nonce: string
@@ -98,25 +108,96 @@ export type DeleteForumThreadArgs = {
forumChannelId: string
// The post channel being deleted.
threadId: string
+ // Canonical post identity addressed by the server DELETE route.
+ openerMessageId: string
+}
+
+type DeleteForumThreadContext = {
+ snapshot: Array<readonly [QueryKey, unknown]>
+}
+
+function toPostUnit(args: DeleteForumThreadArgs): ForumPostUnitIdentity {
+ return {
+ serverId: args.serverId,
+ forumChannelId: args.forumChannelId,
+ childChannelId: args.threadId,
+ openerMessageId: args.openerMessageId,
+ }
+}
+
+function startsWithQueryKey(queryKey: QueryKey, prefix: QueryKey) {
+ return prefix.length <= queryKey.length
+ && hashKey(queryKey.slice(0, prefix.length)) === hashKey(prefix)
+}
+
+function isForumPostUnitQuery(query: Query, unit: ForumPostUnitIdentity) {
+ const key = query.queryKey
+ const exactKeys: QueryKey[] = [
+ communityKeys.server(unit.serverId),
+ communityKeys.forumSidebarThreads(unit.serverId),
+ communityKeys.forumSidebarUnreadFallbacks(unit.serverId),
+ communityKeys.forumSidebarRetained(unit.serverId, unit.childChannelId),
+ communityKeys.channelMeta(unit.serverId, unit.childChannelId),
+ communityKeys.forumOpenerHint(unit.serverId, unit.openerMessageId),
+ communityKeys.message(unit.openerMessageId),
+ ]
+ return exactKeys.some((candidate) => hashKey(candidate) === hashKey(key)) || [
+ communityKeys.channelMessages(unit.forumChannelId),
+ communityKeys.forumFeeds(unit.forumChannelId),
+ communityKeys.channelMessages(unit.childChannelId),
+ communityKeys.pins(unit.childChannelId),
+ communityKeys.threads(unit.childChannelId),
+ ].some((prefix) => startsWithQueryKey(key, prefix))
+}
+
+function snapshotForumPostUnit(queryClient: ReturnType<typeof useQueryClient>, unit: ForumPostUnitIdentity) {
+ return queryClient.getQueryCache().findAll({
+ predicate: (query) => isForumPostUnitQuery(query, unit),
+ }).map((query) => [query.queryKey, query.state.data] as const)
+}
+
+function restoreForumPostUnit(
+ queryClient: ReturnType<typeof useQueryClient>,
+ unit: ForumPostUnitIdentity,
+ snapshot: DeleteForumThreadContext["snapshot"],
+) {
+ queryClient.removeQueries({ predicate: (query) => isForumPostUnitQuery(query, unit) })
+ for (const [queryKey, data] of snapshot) queryClient.setQueryData(queryKey, data)
+ restoreForumSidebarThreadInflight(unit.serverId, unit.childChannelId)
}
/**
- * Delete a single forum thread through the canonical child-channel resource.
- * On success (204) the post is filtered out of
- * the forum's cached list so the card disappears without a refetch; the
- * server-side WS `channel.delete` also invalidates for other clients.
+ * Delete a canonical forum post through its opener-message resource. Every
+ * touched query family is snapshotted before synchronous post-unit eviction;
+ * an HTTP failure restores those exact snapshots. The canonical WS event
+ * applies the same eviction for other clients and active-route ejection.
*/
export function useDeleteForumThread() {
const queryClient = useQueryClient()
- return useMutation<void, Error, DeleteForumThreadArgs>({
- mutationFn: async ({ threadId }) => {
- await apiFetch(`/api/community/channels/${threadId}`, { method: "DELETE" })
+ return useMutation<void, Error, DeleteForumThreadArgs, DeleteForumThreadContext>({
+ mutationFn: async ({ openerMessageId }) => {
+ await apiFetch(`/api/community/messages/${openerMessageId}`, { method: "DELETE" })
+ },
+ onMutate: async (args) => {
+ const unit = toPostUnit(args)
+ await queryClient.cancelQueries({
+ predicate: (query) => isForumPostUnitQuery(query, unit),
+ })
+ const snapshot = snapshotForumPostUnit(queryClient, unit)
+ evictForumPostUnitQueryCaches(queryClient, unit)
+ return { snapshot }
+ },
+ onError: (_error, args, context) => {
+ if (context) restoreForumPostUnit(queryClient, toPostUnit(args), context.snapshot)
},
onSuccess: (_data, args) => {
+ applyForumPostUnitClientEffects(queryClient, toPostUnit(args))
+ },
+ onSettled: (_data, _error, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })
void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.forumChannelId) })
- removeForumSidebarUnreadChild(queryClient, args.serverId, args.threadId)
- removeForumSidebarThreadExact(queryClient, args.serverId, args.threadId)
+ void queryClient.invalidateQueries({ queryKey: communityKeys.forumTags(args.forumChannelId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.ts
index 6880f7fdb..0c11b223d 100644
--- a/src/web/src/hooks/community/use-forum-feed.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.test.ts
@@ -8,6 +8,7 @@ vi.mock("@/lib/api/client", () => ({
import {
forumFeedPageQueryFn,
mapForumFeedPages,
+ removeForumPostFromFeed,
type ForumFeedPage,
} from "./use-forum-feed"
@@ -36,6 +37,50 @@ describe("forumFeedPageQueryFn", () => {
})
describe("mapForumFeedPages", () => {
+ it("removes a post and every included row owned by its opener/child unit", () => {
+ const thread = (id: string, parentMessageId: string) => ({
+ id,
+ name: id,
+ creatorId: "creator",
+ messageCount: 1,
+ parentMessageId,
+ lastMessageAt: null,
+ createdAt: "2026-08-23T00:00:00.000Z",
+ activityAt: "2026-08-23T00:00:00.000Z",
+ })
+ const data = {
+ pages: [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: [thread("delete", "m_delete"), thread("keep", "m_keep")],
+ included: {
+ parentMessages: [
+ { id: "m_delete", channelId: "forum", seq: 1, content: "delete", authorId: "u", authorName: "U", authorImage: null },
+ { id: "m_keep", channelId: "forum", seq: 2, content: "keep", authorId: "u", authorName: "U", authorImage: null },
+ ],
+ firstMessages: [{ channelId: "delete", content: "delete" }, { channelId: "keep", content: "keep" }],
+ tags: [{ messageId: "m_delete", tag: "delete" }, { messageId: "m_keep", tag: "keep" }],
+ participants: [
+ { channelId: "delete", userId: "u", userName: "U", userImage: null },
+ { channelId: "keep", userId: "u", userName: "U", userImage: null },
+ ],
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
+
+ const projected = removeForumPostFromFeed(data, "delete", "m_delete")!
+
+ expect(projected.pages[0].threads.map((row) => row.id)).toEqual(["keep"])
+ expect(projected.pages[0].included).toEqual({
+ parentMessages: [expect.objectContaining({ id: "m_keep" })],
+ firstMessages: [{ channelId: "keep", content: "keep" }],
+ tags: [{ messageId: "m_keep", tag: "keep" }],
+ participants: [expect.objectContaining({ channelId: "keep" })],
+ })
+ })
+
it("joins included resources, deduplicates pages, and keeps newest-created first", () => {
const pages: ForumFeedPage[] = [
{
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 553a81e37..a895250e8 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -55,6 +55,43 @@ export type ForumFeedPage = {
nextCursor?: string
}
+/** Remove one canonical forum post and every included row owned by its unit. */
+export function removeForumPostFromFeed(
+ data: InfiniteData<ForumFeedPage> | undefined,
+ childChannelId: string,
+ openerMessageId: string,
+): InfiniteData<ForumFeedPage> | undefined {
+ if (!data) return data
+ let touched = false
+ const pages = data.pages.map((page) => {
+ if (!page.threads.some((thread) => (
+ thread.id === childChannelId || thread.parentMessageId === openerMessageId
+ ))) return page
+ touched = true
+ return {
+ ...page,
+ threads: page.threads.filter((thread) => (
+ thread.id !== childChannelId && thread.parentMessageId !== openerMessageId
+ )),
+ included: {
+ parentMessages: page.included.parentMessages.filter(
+ (message) => message.id !== openerMessageId,
+ ),
+ firstMessages: page.included.firstMessages.filter(
+ (message) => message.channelId !== childChannelId,
+ ),
+ tags: page.included.tags.filter(
+ (tag) => tag.messageId !== openerMessageId,
+ ),
+ participants: page.included.participants.filter(
+ (participant) => participant.channelId !== childChannelId,
+ ),
+ },
+ }
+ })
+ return touched ? { ...data, pages } : data
+}
+
export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
return ({ pageParam }: { pageParam: string | null }) => {
const params = new URLSearchParams({
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
index 6f53f4f5f..fd37d33c1 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
@@ -19,6 +19,7 @@ import {
recordForumSidebarChildUnread,
removeForumSidebarThread,
removeForumSidebarUnreadChild,
+ restoreForumSidebarThreadInflight,
resolveForumSidebarRouteCandidate,
setForumSidebarParentUnreadBase,
type ForumSidebarQueryData,
@@ -983,6 +984,33 @@ describe("forum sidebar Stage B resources", () => {
renderer!.unmount()
})
+ it("allows a failed optimistic removal to accept the restored server row", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
+ restoreForumSidebarThreadInflight("server-1", "base-1")
+ await act(async () => resolveRequest?.(envelope(["base-1"])))
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads.map((thread) => thread.id)).toEqual(["base-1"])
+ renderer!.unmount()
+ })
+
it("restarts a cold request when the route candidate changes", async () => {
let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index dae00b8c4..2623970f6 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -660,6 +660,16 @@ export function removeForumSidebarThreadExact(
}
}
+/** Undo only the in-flight removal tombstone after an optimistic HTTP failure. */
+export function restoreForumSidebarThreadInflight(
+ serverId: string,
+ childId: string,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.removed.delete(childId)
+ })
+}
+
export function removeForumSidebarChildrenForParent(
queryClient: QueryClient,
serverId: string,
diff --git a/src/web/src/lib/community/forum-post-media-cleanup.test.ts b/src/web/src/lib/community/forum-post-media-cleanup.test.ts
new file mode 100644
index 000000000..2f3feac76
--- /dev/null
+++ b/src/web/src/lib/community/forum-post-media-cleanup.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { warn } = vi.hoisted(() => ({ warn: vi.fn() }));
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ createLogger: () => ({ warn }),
+ };
+});
+
+import {
+ COMMUNITY_MEDIA_DELETE_BATCH_SIZE,
+ scheduleForumPostMediaCleanup,
+} from "./forum-post-media-cleanup";
+
+describe("scheduleForumPostMediaCleanup", () => {
+ const deleteObjects = vi.fn<(keys: string[]) => Promise<void>>();
+ const waitUntil = vi.fn<(promise: Promise<unknown>) => void>();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ deleteObjects.mockResolvedValue(undefined);
+ });
+
+ it("deduplicates keys and registers the complete delete with waitUntil", async () => {
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ {
+ openerId: "opener_1",
+ childChannelId: "child_1",
+ keys: ["original", "thumbnail", "original", ""],
+ },
+ );
+
+ expect(waitUntil).toHaveBeenCalledTimes(1);
+ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined();
+ expect(deleteObjects).toHaveBeenCalledWith(["original", "thumbnail"]);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("chunks at the R2 1000-key multi-delete limit", async () => {
+ const keys = Array.from(
+ { length: COMMUNITY_MEDIA_DELETE_BATCH_SIZE + 1 },
+ (_, index) => `key-${index}`,
+ );
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ { openerId: "opener_1", childChannelId: "child_1", keys },
+ );
+
+ await waitUntil.mock.calls[0]![0];
+ expect(deleteObjects).toHaveBeenCalledTimes(2);
+ expect(deleteObjects.mock.calls[0]![0]).toHaveLength(COMMUNITY_MEDIA_DELETE_BATCH_SIZE);
+ expect(deleteObjects.mock.calls[1]![0]).toEqual([`key-${COMMUNITY_MEDIA_DELETE_BATCH_SIZE}`]);
+ });
+
+ it("does not register work for an empty key set", () => {
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ { openerId: "opener_1", childChannelId: "child_1", keys: [""] },
+ );
+
+ expect(waitUntil).not.toHaveBeenCalled();
+ expect(deleteObjects).not.toHaveBeenCalled();
+ });
+
+ it("absorbs R2 failure and logs only a non-secret error category", async () => {
+ deleteObjects.mockRejectedValueOnce(new Error("secret/key/original: provider detail"));
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ {
+ openerId: "opener_1",
+ childChannelId: "child_1",
+ keys: ["original", "thumbnail"],
+ },
+ );
+
+ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith("forum_post_media_cleanup_failed", {
+ openerId: "opener_1",
+ childChannelId: "child_1",
+ keyCount: 2,
+ errorCategory: "Error",
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret/key/original");
+ expect(JSON.stringify(warn.mock.calls)).not.toContain("provider detail");
+ });
+
+ it("sanitizes non-Error rejections", async () => {
+ deleteObjects.mockRejectedValueOnce("secret provider rejection");
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ { openerId: "opener_1", childChannelId: "child_1", keys: ["original"] },
+ );
+
+ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined();
+ expect(warn).toHaveBeenCalledWith("forum_post_media_cleanup_failed", {
+ openerId: "opener_1",
+ childChannelId: "child_1",
+ keyCount: 1,
+ errorCategory: "NonError",
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret provider rejection");
+ });
+
+ it("classifies TypeError rejections without logging their message", async () => {
+ deleteObjects.mockRejectedValueOnce(new TypeError("secret type detail"));
+ scheduleForumPostMediaCleanup(
+ { delete: deleteObjects } as Pick<R2Bucket, "delete">,
+ { waitUntil },
+ { openerId: "opener_1", childChannelId: "child_1", keys: ["original"] },
+ );
+
+ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined();
+ expect(warn).toHaveBeenCalledWith("forum_post_media_cleanup_failed", {
+ openerId: "opener_1",
+ childChannelId: "child_1",
+ keyCount: 1,
+ errorCategory: "TypeError",
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret type detail");
+ });
+});
diff --git a/src/web/src/lib/community/forum-post-media-cleanup.ts b/src/web/src/lib/community/forum-post-media-cleanup.ts
new file mode 100644
index 000000000..5d230b7a9
--- /dev/null
+++ b/src/web/src/lib/community/forum-post-media-cleanup.ts
@@ -0,0 +1,46 @@
+import { createLogger } from "@alook/shared";
+
+const log = createLogger({ service: "community-forum-post-delete" });
+export const COMMUNITY_MEDIA_DELETE_BATCH_SIZE = 1000;
+
+export type ForumPostMediaCleanup = {
+ openerId: string;
+ childChannelId: string;
+ keys: string[];
+};
+
+function cleanupErrorCategory(err: unknown): "Error" | "TypeError" | "NonError" {
+ if (err instanceof TypeError) return "TypeError";
+ if (err instanceof Error) return "Error";
+ return "NonError";
+}
+
+/**
+ * Schedule best-effort R2 cleanup after the authoritative D1 batch commits.
+ * R2 multi-delete is idempotent for missing objects, so duplicate delivery is
+ * harmless. The complete chunk chain is registered with the real Worker
+ * ExecutionContext; callers must not await it before returning the HTTP 204.
+ */
+export function scheduleForumPostMediaCleanup(
+ bucket: Pick<R2Bucket, "delete">,
+ executionContext: Pick<ExecutionContext, "waitUntil">,
+ input: ForumPostMediaCleanup,
+): void {
+ const keys = [...new Set(input.keys.filter((key) => key.length > 0))];
+ if (keys.length === 0) return;
+
+ const cleanup = (async () => {
+ for (let offset = 0; offset < keys.length; offset += COMMUNITY_MEDIA_DELETE_BATCH_SIZE) {
+ await bucket.delete(keys.slice(offset, offset + COMMUNITY_MEDIA_DELETE_BATCH_SIZE));
+ }
+ })().catch((err) => {
+ log.warn("forum_post_media_cleanup_failed", {
+ openerId: input.openerId,
+ childChannelId: input.childChannelId,
+ keyCount: keys.length,
+ errorCategory: cleanupErrorCategory(err),
+ });
+ });
+
+ executionContext.waitUntil(cleanup);
+}
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index a16c58605..a786b73b1 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -77,6 +77,41 @@ function ack(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): Messa
}
describe("message stream monotonic visibility", () => {
+ it("removes a canonical live row after a post-unit delete", () => {
+ let state = apply(emptyMessageOverlay(), {
+ type: "wsMessage",
+ message: canonical("m_delete", 11, "delete"),
+ }).state
+
+ state = apply(state, { type: "messageRemoved", messageId: "m_delete" }).state
+
+ expect(state.liveById.has("m_delete")).toBe(false)
+ expect(ids([], state)).toEqual([])
+ })
+
+ it("revokes preview URLs when a removed server message still has an outbox intent", () => {
+ let state = submit(emptyMessageOverlay(), intent("delete", 1, {
+ localUploads: [{
+ file: {} as File,
+ previewObjectUrl: "blob:delete-preview",
+ }],
+ }))
+ const outboxByNonce = new Map(state.outboxByNonce)
+ outboxByNonce.set("delete", {
+ ...outboxByNonce.get("delete")!,
+ serverMessageId: "m_delete",
+ })
+ state = { ...state, outboxByNonce }
+
+ const transition = apply(state, { type: "messageRemoved", messageId: "m_delete" })
+
+ expect(transition.state.outboxByNonce.has("delete")).toBe(false)
+ expect(transition.effects).toEqual([{
+ type: "revokeObjectUrl",
+ url: "blob:delete-preview",
+ }])
+ })
+
it("keeps a pending row when an anchor snapshot started first and resolves without it", () => {
let state = submit(emptyMessageOverlay())
state = apply(state, {
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 7a34d972c..e4412549c 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -72,6 +72,7 @@ export type MessageOverlayEvent =
| { type: "wsMessage"; message: CanonicalMessage }
| { type: "liveRefreshed"; message: CanonicalMessage }
| { type: "messageEdited"; messageId: string; content: string }
+ | { type: "messageRemoved"; messageId: string }
| { type: "baseChanged"; messages: CanonicalMessage[]; latestSeq?: number }
| { type: "dismissFailed"; nonce: string }
| { type: "clear" }
@@ -453,6 +454,23 @@ export function reduceMessageOverlay(
: unchanged(state)
}
+ case "messageRemoved": {
+ let changed = false
+ const liveById = new Map(state.liveById)
+ if (liveById.delete(event.messageId)) changed = true
+ const outboxByNonce = new Map(state.outboxByNonce)
+ const effects: MessageOverlayEffect[] = []
+ for (const [nonce, intent] of outboxByNonce) {
+ if ((intent.serverMessageId ?? intent.tempId) !== event.messageId) continue
+ outboxByNonce.delete(nonce)
+ effects.push(...revokeEffects(intent))
+ changed = true
+ }
+ return changed
+ ? { state: { liveById, outboxByNonce }, effects }
+ : unchanged(state)
+ }
+
case "baseChanged": {
const baseById = new Map(event.messages.map((message) => [message.id, message]))
const baseByIdentity = new Map(
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 7dd7e0878..07ab66e89 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -83,8 +83,10 @@ export const communityKeys = {
[...communityKeys.all, "channel", channelId, "pins"] as const,
threads: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "threads"] as const,
+ forumFeeds: (channelId: string) =>
+ [...communityKeys.threads(channelId), "feed"] as const,
forumFeed: (channelId: string, tag: string | null) =>
- [...communityKeys.threads(channelId), "feed", tag] as const,
+ [...communityKeys.forumFeeds(channelId), tag] as const,
forumTags: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "forum-tags"] as const,
// #3: the viewer's `communityReadState` row for a single channel, fetched
diff --git a/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts
new file mode 100644
index 000000000..c76072ae1
--- /dev/null
+++ b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts
@@ -0,0 +1,144 @@
+import type { Page, WebSocket } from "@playwright/test"
+import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import {
+ seedCategory,
+ seedChannel,
+ seedChannelMember,
+ seedForumThread,
+ seedJoinServer,
+ seedServer,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+import { WEB_URL } from "./_setup/paths"
+
+type ChannelDeleteFrame = {
+ type: "community:channel.delete"
+ serverId: string
+ channelId: string
+ parentChannelId?: string
+ parentMessageId?: string
+}
+
+function captureChannelDeletes(page: Page) {
+ const frames: ChannelDeleteFrame[] = []
+ const sockets = new Set<WebSocket>()
+ page.on("websocket", (socket) => {
+ sockets.add(socket)
+ socket.on("framereceived", ({ payload }) => {
+ try {
+ const frame = JSON.parse(payload.toString()) as ChannelDeleteFrame
+ if (frame.type === "community:channel.delete") frames.push(frame)
+ } catch {}
+ })
+ })
+ return { frames, sockets }
+}
+
+async function resolveOpener(forumId: string, childId: string): Promise<string> {
+ const response = await fetch(
+ `${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,
+ { headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } },
+ )
+ expect(response.status).toBe(200)
+ const body = await response.json() as {
+ threads: Array<{ id: string; parentMessageId: string | null }>
+ }
+ const openerId = body.threads.find((thread) => thread.id === childId)?.parentMessageId
+ expect(openerId).toBeTruthy()
+ return openerId!
+}
+
+async function deletePostThroughUi(page: Page, childId: string, openerId: string) {
+ const responsePromise = page.waitForResponse((response) => (
+ response.request().method() === "DELETE"
+ && new URL(response.url()).pathname === `/api/community/messages/${openerId}`
+ ))
+ await page.getByTestId(tid.forumThreadDeleteBtn(childId)).click()
+ await expect(page.getByRole("heading", { name: "Delete post?" })).toBeVisible()
+ await page.getByRole("button", { name: "Delete post", exact: true }).click()
+ // The mutation's onMutate projection removes the card before the round-trip
+ // settles; the response below still proves the canonical HTTP door.
+ await expect(page.getByTestId(tid.forumThreadCard(childId))).toHaveCount(0)
+ const response = await responsePromise
+ expect(response.status()).toBe(204)
+}
+
+test("canonical forum-post delete converges author, manager, private WS, and active routes", async ({ asUser }) => {
+ test.setTimeout(150_000)
+ const serverId = await seedServer("alice", `Canonical delete ${Date.now()}`)
+ const categoryId = await seedCategory("alice", serverId, "Private forum", { private: true })
+ const forumId = await seedChannel("alice", serverId, "canonical-delete", "forum", categoryId)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
+ await seedChannelMember("alice", forumId, userId("bob"))
+
+ const authorChildId = await seedForumThread("bob", forumId, "Author deletes", "author body")
+ const managerChildId = await seedForumThread("bob", forumId, "Manager deletes", "manager body")
+ const [authorOpenerId, managerOpenerId] = await Promise.all([
+ resolveOpener(forumId, authorChildId),
+ resolveOpener(forumId, managerChildId),
+ ])
+ const forumRoute = `/c/channels/${serverId}/${forumId}`
+
+ const alice = await asUser("alice")
+ const bob = await asUser("bob")
+ const carol = await asUser("carol")
+ const aliceDeletes = captureChannelDeletes(alice.page)
+ const bobDeletes = captureChannelDeletes(bob.page)
+ const carolDeletes = captureChannelDeletes(carol.page)
+
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${authorChildId}`)
+ await gotoAfterUserWsAuth(bob.page, forumRoute)
+ await gotoAfterUserWsAuth(carol.page, "/c")
+ await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toBeVisible({ timeout: 20_000 })
+
+ const unauthorizedStatus = await carol.page.evaluate(async (openerId) => {
+ const response = await fetch(`/api/community/messages/${openerId}`, { method: "DELETE" })
+ return response.status
+ }, authorOpenerId)
+ expect(unauthorizedStatus).toBe(403)
+
+ const legacyStatus = await bob.page.evaluate(async (childId) => {
+ const response = await fetch(`/api/community/channels/${childId}`, { method: "DELETE" })
+ return response.status
+ }, authorChildId)
+ expect(legacyStatus).toBe(409)
+ await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toBeVisible()
+
+ await deletePostThroughUi(bob.page, authorChildId, authorOpenerId)
+ await expect(alice.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${forumId}$`), {
+ timeout: 20_000,
+ })
+ await expect(alice.page.getByTestId(tid.forumNewPost)).toBeVisible()
+ await expect.poll(() => aliceDeletes.frames.filter((frame) => frame.channelId === authorChildId))
+ .toEqual([{
+ type: "community:channel.delete",
+ serverId,
+ channelId: authorChildId,
+ parentChannelId: forumId,
+ parentMessageId: authorOpenerId,
+ }])
+ await expect.poll(() => bobDeletes.frames.filter((frame) => frame.channelId === authorChildId))
+ .toHaveLength(1)
+ expect(carolDeletes.frames.filter((frame) => frame.channelId === authorChildId)).toEqual([])
+
+ await bob.page.reload()
+ await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toHaveCount(0)
+ const deletedChildStatus = await bob.page.evaluate(async (childId) => {
+ const response = await fetch(`/api/community/channels/${childId}`)
+ return response.status
+ }, authorChildId)
+ expect(deletedChildStatus).toBe(404)
+
+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${managerChildId}`)
+ await gotoAfterUserWsAuth(alice.page, forumRoute)
+ await expect(alice.page.getByTestId(tid.forumThreadCard(managerChildId))).toBeVisible({ timeout: 20_000 })
+ await deletePostThroughUi(alice.page, managerChildId, managerOpenerId)
+ await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${forumId}$`), {
+ timeout: 20_000,
+ })
+ await expect.poll(() => bobDeletes.frames.filter((frame) => frame.channelId === managerChildId))
+ .toHaveLength(1)
+ await expect(alice.page.getByTestId(tid.forumThreadCard(managerChildId))).toHaveCount(0)
+})
diff --git a/src/web/src/test/e2e-ui/_setup/services.ts b/src/web/src/test/e2e-ui/_setup/services.ts
index 936b43073..f2c7b1c86 100644
--- a/src/web/src/test/e2e-ui/_setup/services.ts
+++ b/src/web/src/test/e2e-ui/_setup/services.ts
@@ -16,8 +16,9 @@ export interface ServiceDefinition {
}
// Reuse a server the developer already has running (local iteration). CI
-// always starts fresh, so REUSE is off there.
-export const REUSE_EXISTING = !process.env.CI
+// always starts fresh. Migration-sensitive focused journeys may opt into the
+// same fresh path locally; backupState/restoreState preserve developer data.
+export const REUSE_EXISTING = !process.env.CI && !process.env.ALOOK_E2E_FORCE_FRESH
export const SINGLE_RUNTIME = !!process.env.CI
// Local D1/DO state that `db:reset` wipes. Backing it up to a sibling path
diff --git a/src/web/test-runtime/forum-post-delete.runtime.test.ts b/src/web/test-runtime/forum-post-delete.runtime.test.ts
new file mode 100644
index 000000000..63f936df6
--- /dev/null
+++ b/src/web/test-runtime/forum-post-delete.runtime.test.ts
@@ -0,0 +1,236 @@
+/// <reference types="@cloudflare/vitest-plugin/types" />
+
+import { env } from "cloudflare:workers";
+import { afterEach, describe, expect, it } from "vitest";
+import { createDb, queries } from "@alook/shared";
+
+const runtimeEnv = env as unknown as CloudflareEnv;
+const createdServers: string[] = [];
+const createdUsers: string[] = [];
+
+async function run(statement: string, ...bindings: unknown[]): Promise<void> {
+ await runtimeEnv.DB.prepare(statement).bind(...bindings).run();
+}
+
+async function first<T>(statement: string, ...bindings: unknown[]): Promise<T | null> {
+ return runtimeEnv.DB.prepare(statement).bind(...bindings).first<T>();
+}
+
+function ids() {
+ const stamp = crypto.randomUUID().replaceAll("-", "");
+ return {
+ owner: `fpd_owner_${stamp}`,
+ reader: `fpd_reader_${stamp}`,
+ server: `fpd_server_${stamp}`,
+ forum: `fpd_forum_${stamp}`,
+ opener: `fpd_opener_${stamp}`,
+ prior: `fpd_prior_${stamp}`,
+ siblingOpener: `fpd_sibling_opener_${stamp}`,
+ child: `fpd_child_${stamp}`,
+ siblingChild: `fpd_sibling_child_${stamp}`,
+ reply: `fpd_reply_${stamp}`,
+ };
+}
+
+async function seedCanonicalPost() {
+ const id = ids();
+ createdServers.push(id.server);
+ createdUsers.push(id.owner, id.reader);
+ const t1 = "2026-08-23T01:00:00.000Z";
+ const t2 = "2026-08-23T01:01:00.000Z";
+ const t3 = "2026-08-23T01:02:00.000Z";
+ const childTime = "2026-08-23T01:03:00.000Z";
+
+ await run("INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Owner', ?)", id.owner, `${id.owner}@example.com`, stamp4(id.owner));
+ await run("INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Reader', ?)", id.reader, `${id.reader}@example.com`, stamp4(id.reader));
+ await run(
+ "INSERT INTO community_server (id, name, description, owner_id, created_at, discriminator) VALUES (?, ?, '', ?, ?, ?)",
+ id.server,
+ id.server,
+ id.owner,
+ t1,
+ stamp4(id.server),
+ );
+ await run(
+ `INSERT INTO community_channel
+ (id, server_id, name, type, message_count, last_message_at, created_at)
+ VALUES (?, ?, 'forum-delete', 'forum', 3, ?, ?)`,
+ id.forum,
+ id.server,
+ t3,
+ t1,
+ );
+ await run(
+ `INSERT INTO community_message
+ (id, author_id, content, created_at, channel_id, seq)
+ VALUES (?, ?, 'prior', ?, ?, 1), (?, ?, 'sibling', ?, ?, 2), (?, ?, 'delete me', ?, ?, 3)`,
+ id.prior, id.owner, t1, id.forum,
+ id.siblingOpener, id.owner, t2, id.forum,
+ id.opener, id.owner, t3, id.forum,
+ );
+ await run(
+ `INSERT INTO community_channel
+ (id, server_id, name, type, parent_channel_id, creator_id, message_count,
+ parent_message_id, last_message_at, created_at)
+ VALUES (?, ?, 'delete child', 'thread', ?, ?, 1, ?, ?, ?),
+ (?, ?, 'sibling child', 'thread', ?, ?, 0, ?, NULL, ?)`,
+ id.child, id.server, id.forum, id.owner, id.opener, childTime, childTime,
+ id.siblingChild, id.server, id.forum, id.owner, id.siblingOpener, childTime,
+ );
+ await run(
+ `INSERT INTO community_message
+ (id, author_id, content, created_at, channel_id, seq)
+ VALUES (?, ?, 'reply', ?, ?, 1)`,
+ id.reply,
+ id.reader,
+ childTime,
+ id.child,
+ );
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES (?, ?, ?, ?, ?, 3), (?, ?, ?, ?, ?, 3)`,
+ `rs_owner_${id.opener}`, id.owner, id.forum, t3, id.opener,
+ `rs_reader_${id.opener}`, id.reader, id.forum, t3, id.opener,
+ );
+ await run(
+ `INSERT INTO community_attachment
+ (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'opener.png', ?),
+ (?, ?, ?, ?, ?, ?, 'reply.png', ?),
+ (?, NULL, ?, ?, ?, ?, 'pending.png', ?)`,
+ `att_opener_${id.opener}`, id.opener, id.owner, id.child, `${id.opener}/original`, `${id.opener}/thumb`, t3,
+ `att_reply_${id.opener}`, id.reply, id.reader, id.child, `${id.reply}/original`, `${id.reply}/thumb`, childTime,
+ `att_pending_${id.opener}`, id.owner, id.child, `${id.child}/pending-original`, `${id.child}/pending-thumb`, childTime,
+ );
+ await run(
+ `INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, source, added_at)
+ VALUES (?, ?, ?, 'notify', 'spoke', ?)`,
+ `participant_${id.opener}`, id.child, id.reader, childTime,
+ );
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES (?, ?, ?, ?, ?, 1)`,
+ `rs_child_${id.opener}`, id.reader, id.child, childTime, id.reply,
+ );
+ await run(
+ `INSERT INTO community_pin (id, channel_id, message_id, pinned_by, created_at)
+ VALUES (?, ?, ?, ?, ?)`,
+ `pin_${id.opener}`, id.child, id.reply, id.owner, childTime,
+ );
+ await run(
+ `INSERT INTO community_mention (id, message_id, user_id, kind, read)
+ VALUES (?, ?, ?, 'mention', 0)`,
+ `mention_${id.opener}`, id.reply, id.owner,
+ );
+ await run(
+ `INSERT INTO community_message_mark (id, user_id, channel_id, message_id, created_at)
+ VALUES (?, ?, ?, ?, ?)`,
+ `mark_${id.opener}`, id.reader, id.child, id.reply, childTime,
+ );
+ await run(
+ `INSERT INTO community_message_tag (id, message_id, tag)
+ VALUES (?, ?, 'delete-me')`,
+ `tag_${id.opener}`, id.opener,
+ );
+ await run(
+ `INSERT INTO community_reaction (id, message_id, user_id, emoji, created_at)
+ VALUES (?, ?, ?, 'x', ?)`,
+ `reaction_${id.opener}`, id.reply, id.owner, childTime,
+ );
+ return { id, t2 };
+}
+
+function stamp4(value: string): string {
+ let hash = 0;
+ for (const char of value) hash = (hash * 31 + char.charCodeAt(0)) % 10_000;
+ return String(hash).padStart(4, "0");
+}
+
+afterEach(async () => {
+ for (const serverId of createdServers.splice(0)) {
+ await runtimeEnv.DB.prepare("DELETE FROM community_server WHERE id = ?").bind(serverId).run();
+ }
+ for (const userId of createdUsers.splice(0)) {
+ await runtimeEnv.DB.prepare("DELETE FROM user WHERE id = ?").bind(userId).run();
+ }
+});
+
+describe("deleteForumPost real D1 batch", () => {
+ it("captures all media keys, repairs parent truth, and cascades only the selected post", async () => {
+ const { id, t2 } = await seedCanonicalPost();
+ const db = createDb(runtimeEnv.DB);
+
+ const result = await queries.communityForumPostDelete.deleteForumPost(db, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ });
+
+ expect(result.deleted).toBe(true);
+ expect(new Set(result.mediaKeys)).toEqual(new Set([
+ `${id.opener}/original`,
+ `${id.opener}/thumb`,
+ `${id.reply}/original`,
+ `${id.reply}/thumb`,
+ `${id.child}/pending-original`,
+ `${id.child}/pending-thumb`,
+ ]));
+ expect(await first<{ message_count: number; last_message_at: string }>(
+ "SELECT message_count, last_message_at FROM community_channel WHERE id = ?",
+ id.forum,
+ )).toEqual({ message_count: 2, last_message_at: t2 });
+ expect(await first("SELECT id FROM community_channel WHERE id = ?", id.child)).toBeNull();
+ expect(await first("SELECT id FROM community_message WHERE id IN (?, ?)", id.opener, id.reply)).toBeNull();
+ expect(await first("SELECT id FROM community_attachment WHERE target_id = ?", id.child)).toBeNull();
+ for (const [table, rowId] of [
+ ["community_channel_member", `participant_${id.opener}`],
+ ["community_read_state", `rs_child_${id.opener}`],
+ ["community_pin", `pin_${id.opener}`],
+ ["community_mention", `mention_${id.opener}`],
+ ["community_message_mark", `mark_${id.opener}`],
+ ["community_message_tag", `tag_${id.opener}`],
+ ["community_reaction", `reaction_${id.opener}`],
+ ] as const) {
+ expect(await first(`SELECT id FROM ${table} WHERE id = ?`, rowId), table).toBeNull();
+ }
+ expect(await first<{ last_read_message_id: string; last_read_seq: number; last_read_at: string }>(
+ "SELECT last_read_message_id, last_read_seq, last_read_at FROM community_read_state WHERE user_id = ? AND channel_id = ?",
+ id.reader,
+ id.forum,
+ )).toEqual({
+ last_read_message_id: id.siblingOpener,
+ last_read_seq: 2,
+ last_read_at: t2,
+ });
+ expect(await first("SELECT id FROM community_channel WHERE id = ?", id.siblingChild)).not.toBeNull();
+ expect(await first("SELECT id FROM community_message WHERE id = ?", id.siblingOpener)).not.toBeNull();
+ });
+
+ it("serializes concurrent winners without double-decrementing or returning duplicate cleanup keys", async () => {
+ const { id, t2 } = await seedCanonicalPost();
+ const db = createDb(runtimeEnv.DB);
+ const input = {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ };
+
+ const results = await Promise.all([
+ queries.communityForumPostDelete.deleteForumPost(db, input),
+ queries.communityForumPostDelete.deleteForumPost(db, input),
+ ]);
+
+ expect(results.filter((result) => result.deleted)).toHaveLength(1);
+ expect(results.filter((result) => result.mediaKeys.length > 0)).toHaveLength(1);
+ expect(await first<{ message_count: number; last_message_at: string }>(
+ "SELECT message_count, last_message_at FROM community_channel WHERE id = ?",
+ id.forum,
+ )).toEqual({ message_count: 2, last_message_at: t2 });
+ expect(await first("SELECT id FROM community_channel WHERE id = ?", id.child)).toBeNull();
+ });
+});