Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): clean media for existing community deletes (#531)
Genere5e2f1975457
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 9b94a8a68..56b81467c 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -35,6 +35,7 @@ export const SPEC_SECONDS = {"25-composer-accessory-rail-occupancy.spec.ts": 60,"26-mobile-forum-post-actions.spec.ts": 45,"27-canonical-forum-post-delete.spec.ts": 30,+ "28-community-delete-media-cleanup.spec.ts": 45,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 971a7f76c..e502e1d98 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([188, 192, 192, 193, 193])+ expect(totals.sort((left, right) => left - right)).toEqual([198, 200, 201, 202, 202])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 09693c9bd..9afa497b1 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -38,6 +38,7 @@ 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 communityDeleteMedia from "./queries/community/delete-media";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/attachment.ts b/src/shared/src/db/queries/community/attachment.tsindex 6d8358b07..c5960c16d 100644--- a/src/shared/src/db/queries/community/attachment.ts+++ b/src/shared/src/db/queries/community/attachment.ts@@ -1,7 +1,7 @@import { and, asc, count, eq, inArray, isNull, sql } from "drizzle-orm";import { alias } from "drizzle-orm/sqlite-core";import { nanoid } from "nanoid";-import { communityAttachment } from "../../community-schema";+import { communityAttachment, communityChannel } from "../../community-schema";import type { Database } from "../../index";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";@@ -26,24 +26,34 @@ export async function createPendingAttachment(height?: number | null;}) {+ const id = data.id ?? nanoid();+ const createdAt = new Date().toISOString();+ const candidate = db+ .select({+ id: sql<string>`${id}`.as("id"),+ messageId: sql<string | null>`NULL`.as("message_id"),+ uploaderId: sql<string>`${data.uploaderId}`.as("uploader_id"),+ targetId: communityChannel.id,+ r2Key: sql<string>`${data.r2Key}`.as("r2_key"),+ thumbnailR2Key: sql<string | null>`${data.thumbnailR2Key ?? null}`.as("thumbnail_r2_key"),+ filename: sql<string>`${data.filename}`.as("filename"),+ contentType: sql<string | null>`${data.contentType ?? null}`.as("content_type"),+ size: sql<number | null>`${data.size ?? null}`.as("size"),+ width: sql<number | null>`${data.width ?? null}`.as("width"),+ height: sql<number | null>`${data.height ?? null}`.as("height"),+ position: sql<number | null>`NULL`.as("position"),+ createdAt: sql<string>`${createdAt}`.as("created_at"),+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, data.targetId))+ .limit(1);+const [row] = await db.insert(communityAttachment)- .values({- id: data.id ?? nanoid(),- messageId: null,- uploaderId: data.uploaderId,- targetId: data.targetId,- r2Key: data.r2Key,- thumbnailR2Key: data.thumbnailR2Key ?? null,- filename: data.filename,- position: null,- contentType: data.contentType ?? null,- size: data.size ?? null,- width: data.width ?? null,- height: data.height ?? null,- })+ .select(candidate).returning();- return row!;+ if (!row) throw new Error("attachment target no longer exists");+ return row;}/**diff --git a/src/shared/src/db/queries/community/delete-media.ts b/src/shared/src/db/queries/community/delete-media.tsnew file mode 100644index 000000000..e969c5342--- /dev/null+++ b/src/shared/src/db/queries/community/delete-media.ts@@ -0,0 +1,171 @@+import { and, eq, exists, inArray, isNull, or } from "drizzle-orm"+import {+ communityAttachment,+ communityChannel,+ communityMessage,+ communityServer,+} from "../../community-schema"+import type { Database } from "../../index"++export type DeleteCommunityMediaResult = {+ deleted: boolean+ mediaKeys: string[]+}++export type DeleteServerWithMediaResult = DeleteCommunityMediaResult & {+ iconKey: string | null+}++function flattenMediaRows(+ rows: Array<{ r2Key: string; thumbnailR2Key: string | null }>,+): string[] {+ return rows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]+ .filter((key): key is string => key !== null && key.length > 0))+}++export async function deleteChannelWithMedia(+ db: Database,+ input: { channelId: string; serverId: string },+): Promise<DeleteCommunityMediaResult> {+ const rootQuery = db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(and(+ eq(communityChannel.id, input.channelId),+ eq(communityChannel.serverId, input.serverId),+ ))+ .limit(1)+ const rootStillExists = exists(rootQuery)+ const scopedChannelIds = db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(and(+ eq(communityChannel.serverId, input.serverId),+ or(+ eq(communityChannel.id, input.channelId),+ eq(communityChannel.parentChannelId, input.channelId),+ ),+ ))+ const scopedMessageIds = db+ .select({ id: communityMessage.id })+ .from(communityMessage)+ .where(inArray(communityMessage.channelId, scopedChannelIds))++ const mediaSnapshot = db+ .select({+ r2Key: communityAttachment.r2Key,+ thumbnailR2Key: communityAttachment.thumbnailR2Key,+ })+ .from(communityAttachment)+ .where(and(+ rootStillExists,+ or(+ inArray(communityAttachment.messageId, scopedMessageIds),+ and(+ isNull(communityAttachment.messageId),+ inArray(communityAttachment.targetId, scopedChannelIds),+ ),+ ),+ ))++ const removePendingAttachments = db+ .delete(communityAttachment)+ .where(and(+ rootStillExists,+ isNull(communityAttachment.messageId),+ inArray(communityAttachment.targetId, scopedChannelIds),+ ))++ const deleteRoot = db+ .delete(communityChannel)+ .where(and(+ eq(communityChannel.id, input.channelId),+ eq(communityChannel.serverId, input.serverId),+ ))+ .returning({ id: communityChannel.id })++ const results = (await db.batch([+ mediaSnapshot,+ removePendingAttachments,+ deleteRoot,+ ] as any)) as unknown[]+ const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>+ const deletedRows = results[2] as Array<{ id: string }>+ const deleted = deletedRows.length > 0++ return {+ deleted,+ mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],+ }+}++export async function deleteServerWithMedia(+ db: Database,+ input: { serverId: string; ownerId: string },+): Promise<DeleteServerWithMediaResult> {+ const ownedServerQuery = db+ .select({ id: communityServer.id })+ .from(communityServer)+ .where(and(+ eq(communityServer.id, input.serverId),+ eq(communityServer.ownerId, input.ownerId),+ ))+ .limit(1)+ const ownedServerStillExists = exists(ownedServerQuery)+ const scopedChannelIds = db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(eq(communityChannel.serverId, input.serverId))+ const scopedMessageIds = db+ .select({ id: communityMessage.id })+ .from(communityMessage)+ .where(inArray(communityMessage.channelId, scopedChannelIds))++ const mediaSnapshot = db+ .select({+ r2Key: communityAttachment.r2Key,+ thumbnailR2Key: communityAttachment.thumbnailR2Key,+ })+ .from(communityAttachment)+ .where(and(+ ownedServerStillExists,+ or(+ inArray(communityAttachment.messageId, scopedMessageIds),+ and(+ isNull(communityAttachment.messageId),+ inArray(communityAttachment.targetId, scopedChannelIds),+ ),+ ),+ ))++ const removePendingAttachments = db+ .delete(communityAttachment)+ .where(and(+ ownedServerStillExists,+ isNull(communityAttachment.messageId),+ inArray(communityAttachment.targetId, scopedChannelIds),+ ))++ const deleteServer = db+ .delete(communityServer)+ .where(and(+ eq(communityServer.id, input.serverId),+ eq(communityServer.ownerId, input.ownerId),+ ))+ .returning({ id: communityServer.id, icon: communityServer.icon })++ const results = (await db.batch([+ mediaSnapshot,+ removePendingAttachments,+ deleteServer,+ ] as any)) as unknown[]+ const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>+ const deletedRows = results[2] as Array<{ id: string; icon: string | null }>+ const deleted = deletedRows.length > 0++ return {+ deleted,+ mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],+ iconKey: deleted ? deletedRows[0]!.icon : null,+ }+}diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex a0230f98e..aa1e3d95e 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -1,4 +1,4 @@-import { eq, and, asc, inArray, sql, count } from "drizzle-orm";+import { eq, and, asc, inArray, isNull, sql, count } from "drizzle-orm";import {communityServer,communityCategory,@@ -169,6 +169,27 @@ export async function updateServer(return rows[0] ?? null;}+export async function updateServerIconIfCurrent(+ db: Database,+ input: {+ serverId: string;+ expectedIcon: string | null;+ nextIcon: string;+ }+) {+ const rows = await db+ .update(communityServer)+ .set({ icon: input.nextIcon })+ .where(and(+ eq(communityServer.id, input.serverId),+ input.expectedIcon === null+ ? isNull(communityServer.icon)+ : eq(communityServer.icon, input.expectedIcon)+ ))+ .returning();+ return rows[0] ?? null;+}+export async function deleteServer(db: Database, serverId: string) {const rows = await db.delete(communityServer)diff --git a/src/shared/test/queries/community-attachment-thumbnail.test.ts b/src/shared/test/queries/community-attachment-thumbnail.test.tsindex 1881a28ab..6834048f8 100644--- a/src/shared/test/queries/community-attachment-thumbnail.test.ts+++ b/src/shared/test/queries/community-attachment-thumbnail.test.ts@@ -1,19 +1,28 @@import { describe, expect, it, vi } from "vitest"import { createPendingAttachment } from "../../src/db/queries/community/attachment"-function database() {- const chain: any = {}- chain.values = vi.fn((value) => {- chain.value = value- return chain- })- chain.returning = vi.fn(async () => [{ ...chain.value, id: chain.value.id ?? "generated" }])- return { insert: vi.fn(() => chain), chain }+function database(row: Record<string, unknown> | null) {+ const candidate: any = {}+ candidate.from = vi.fn(() => candidate)+ candidate.where = vi.fn(() => candidate)+ candidate.limit = vi.fn(() => candidate)+ const insert: any = {}+ insert.select = vi.fn(() => insert)+ insert.returning = vi.fn(async () => row ? [row] : [])+ return {+ select: vi.fn(() => candidate),+ insert: vi.fn(() => insert),+ candidate,+ insertChain: insert,+ }}describe("community attachment thumbnail persistence", () => {it("preserves an exact thumbnail key without changing the original", async () => {- const db = database()+ const db = database({+ id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",+ thumbnailR2Key: "original-key.thumbnail.jpg", filename: "photo.png", messageId: null,+ })const row = await createPendingAttachment(db as any, {id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",thumbnailR2Key: "original-key.thumbnail.jpg", filename: "photo.png",@@ -26,10 +35,21 @@ describe("community attachment thumbnail persistence", () => {})it("writes null for legacy/original-only uploads", async () => {- const db = database()+ const db = database({+ id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",+ thumbnailR2Key: null, filename: "file.txt", messageId: null,+ })const row = await createPendingAttachment(db as any, {id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key", filename: "file.txt",})expect(row.thumbnailR2Key).toBeNull()})++ it("throws when the target-exists INSERT SELECT returns no row", async () => {+ const db = database(null)+ await expect(createPendingAttachment(db as any, {+ id: "a1", uploaderId: "u1", targetId: "deleted", r2Key: "original-key", filename: "file.txt",+ })).rejects.toThrow("attachment target no longer exists")+ expect(db.insertChain.select).toHaveBeenCalledWith(db.candidate)+ })})diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex f641ec442..cc2faf1d3 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -83,6 +83,42 @@ describe("community/server exports", () => {it("exports createServer", () => {expect(typeof serverQueries.createServer).toBe("function");});++ it("exports the old-value icon CAS", () => {+ expect(typeof serverQueries.updateServerIconIfCurrent).toBe("function");+ });+});++describe("updateServerIconIfCurrent", () => {+ function updateDb(rows: unknown[]) {+ const chain: any = {};+ chain.set = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.returning = vi.fn(async () => rows);+ return { db: { update: vi.fn(() => chain) }, chain };+ }++ it.each([null, "server-icon/s1/old"])("returns the winner row for expected icon %s", async (expectedIcon) => {+ const winner = { id: "s1", icon: "server-icon/s1/new" };+ const { db, chain } = updateDb([winner]);++ await expect(serverQueries.updateServerIconIfCurrent(db as any, {+ serverId: "s1",+ expectedIcon,+ nextIcon: "server-icon/s1/new",+ })).resolves.toEqual(winner);+ expect(chain.set).toHaveBeenCalledWith({ icon: "server-icon/s1/new" });+ expect(chain.where).toHaveBeenCalledTimes(1);+ });++ it("returns null when the old-value predicate loses", async () => {+ const { db } = updateDb([]);+ await expect(serverQueries.updateServerIconIfCurrent(db as any, {+ serverId: "s1",+ expectedIcon: "server-icon/s1/old",+ nextIcon: "server-icon/s1/new",+ })).resolves.toBeNull();+ });});describe("createServer", () => {diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.tsindex a0160b783..f221a5585 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts@@ -217,7 +217,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacsize: 10,})mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))- mockR2Delete.mockRejectedValueOnce(new Error("cleanup failed"))+ mockR2Delete.mockRejectedValueOnce(new Error("secret provider detail"))const response = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }),@@ -228,9 +228,15 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacconst cleanupLog = mockLogError.mock.calls.find(([event]) => event === "attachment_route_r2_cleanup_failed",)- expect(cleanupLog?.[1]).toEqual(expect.objectContaining({ objectCount: 2 }))+ expect(cleanupLog?.[1]).toEqual({+ route: "channels/[id]/attachments",+ actor: "bot",+ objectCount: 2,+ errorCategory: "Error",+ })expect(JSON.stringify(cleanupLog)).not.toContain("secret-original-key")expect(JSON.stringify(cleanupLog)).not.toContain("secret-thumbnail-key")+ expect(JSON.stringify(cleanupLog)).not.toContain("secret provider detail")})it("pre-R2 throw (resolveTargetForMember errors) → 500 JSON, R2 delete NOT called", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.tsindex 713bf8c89..a3b7f6be4 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts@@ -5,6 +5,7 @@ import { withCommunityActor, requireBot, type CommunityActor } from "@/lib/middlimport { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"import { handleAttachmentUpload, runAttachmentUpload } from "@/lib/community/upload"+import { communityMediaCleanupErrorCategory } from "@/lib/community/community-media-cleanup"const log = createLogger({ service: "community-attachments-upload" })@@ -133,9 +134,9 @@ async function handleBotAttachmentUpload(} catch (cleanupErr) {log.error("attachment_route_r2_cleanup_failed", {route: "channels/[id]/attachments",- botUserId,+ actor: "bot",objectCount: r2KeysToCleanUp.length,- cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ errorCategory: communityMediaCleanupErrorCategory(cleanupErr),})}}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.tsindex dff16d733..34c1dcc2d 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@@ -1,8 +1,10 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+const mockWaitUntil = vi.fn()+const mockGetCloudflareContext = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ getCloudflareContext: (...a: unknown[]) => mockGetCloudflareContext(...a),}))const mockResolveChannelAccessContext = vi.fn()@@ -12,11 +14,12 @@ const mockGetChannelType = vi.fn()const mockIsChannelPrivate = vi.fn(() => false)const mockGetCategory = vi.fn()const mockUpdateChannel = vi.fn()-const mockDeleteChannel = vi.fn()+const mockDeleteChannelWithMedia = vi.fn()const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockFanOutToServerMembers = vi.fn()const mockFanOutToChannel = vi.fn()const mockBroadcastToUserSafe = vi.fn()+const mockScheduleMediaCleanup = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -32,10 +35,12 @@ vi.mock("@alook/shared", async () => {getChannelType: (...a: unknown[]) => mockGetChannelType(...a),isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),updateChannel: (...a: unknown[]) => mockUpdateChannel(...a),- deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},communityCategory: { getCategory: (...a: unknown[]) => mockGetCategory(...a) },+ communityDeleteMedia: {+ deleteChannelWithMedia: (...a: unknown[]) => mockDeleteChannelWithMedia(...a),+ },},}})@@ -46,10 +51,28 @@ vi.mock("@/lib/community/fanout", () => ({broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),}))+vi.mock("@/lib/community/community-media-cleanup", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/community-media-cleanup")>(+ "@/lib/community/community-media-cleanup",+ )+ return {+ ...actual,+ scheduleCommunityMediaCleanup: (...a: Parameters<typeof actual.scheduleCommunityMediaCleanup>) => {+ mockScheduleMediaCleanup(...a)+ return actual.scheduleCommunityMediaCleanup(...a)+ },+ }+})+vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ return handler(req, {+ env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },+ userId: "u1",+ email: "[email protected]",+ params,+ })}),}))@@ -330,7 +353,14 @@ describe("PATCH /channels/[id] — categoryId move", () => {describe("DELETE /channels/[id]", () => {beforeEach(() => {vi.clearAllMocks()- mockDeleteChannel.mockResolvedValue({ id: "c1" })+ mockWaitUntil.mockReset()+ mockScheduleMediaCleanup.mockReset()+ mockGetCloudflareContext.mockReset()+ mockGetCloudflareContext.mockResolvedValue({+ env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },+ ctx: { waitUntil: mockWaitUntil },+ })+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [] })mockIsChannelPrivate.mockResolvedValue(false)mockGetChannelType.mockResolvedValue("forum")})@@ -339,7 +369,7 @@ describe("DELETE /channels/[id]", () => {mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(403)- expect(mockDeleteChannel).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()})it("manager deletes a public channel; fans out server-wide", async () => {@@ -348,6 +378,35 @@ describe("DELETE /channels/[id]", () => {expect(res.status).toBe(204)expect(mockFanOutToServerMembers).toHaveBeenCalled()expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).toHaveBeenCalledWith(expect.anything(), {+ channelId: "c1",+ serverId: "s1",+ })+ })++ it("returns 500 without mutating D1 when execution context acquisition fails", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))+ mockGetCloudflareContext.mockRejectedValueOnce(new Error("context unavailable"))++ const res = await DELETE(delReq(), ctx)++ expect(res.status).toBe(500)+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()+ })++ it("keeps the winner 204 and fanout when waitUntil throws synchronously", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: ["original"] })+ mockWaitUntil.mockImplementationOnce(() => {+ throw new TypeError("secret registration detail")+ })++ const res = await DELETE(delReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockDeleteChannelWithMedia).toHaveBeenCalledOnce()+ expect(mockFanOutToServerMembers).toHaveBeenCalledOnce()})it("private-channel delete fans out to the resolved audience only", async () => {@@ -366,7 +425,7 @@ describe("DELETE /channels/[id]", () => {mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(409)- expect(mockDeleteChannel).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()expect(mockGetChannelType).toHaveBeenCalledWith(expect.anything(), "forum_1")})@@ -378,7 +437,7 @@ describe("DELETE /channels/[id]", () => {})const res = await DELETE(delReq(), ctx)expect(res.status).toBe(409)- expect(mockDeleteChannel).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()expect(mockFanOutToServerMembers).not.toHaveBeenCalled()expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()})@@ -390,7 +449,7 @@ describe("DELETE /channels/[id]", () => {mockGetChannelType.mockResolvedValue("text") // parent is a plain channel, not a forumconst res = await DELETE(delReq(), ctx)expect(res.status).toBe(403)- expect(mockDeleteChannel).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()})it("the carve-out does NOT let a non-creator delete a normal (non-thread) channel", async () => {@@ -399,6 +458,46 @@ describe("DELETE /channels/[id]", () => {mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))const res = await DELETE(delReq(), ctx)expect(res.status).toBe(403)- expect(mockDeleteChannel).not.toHaveBeenCalled()+ expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()+ })++ it("schedules winner media cleanup before the existing public fanout", async () => {+ const order: string[] = []+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))+ mockDeleteChannelWithMedia.mockImplementation(async () => {+ order.push("delete")+ return { deleted: true, mediaKeys: ["original", "thumbnail"] }+ })+ mockScheduleMediaCleanup.mockImplementation(() => order.push("cleanup"))+ mockFanOutToServerMembers.mockImplementation(async () => {+ order.push("fanout")+ })++ const res = await DELETE(delReq(), ctx)++ expect(res.status).toBe(204)+ expect(order).toEqual(["delete", "cleanup", "fanout"])+ expect(mockScheduleMediaCleanup).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ waitUntil: mockWaitUntil }),+ {+ keys: ["original", "thumbnail"],+ warning: {+ event: "community_channel_media_cleanup_failed",+ fields: { serverId: "s1", channelId: "c1" },+ },+ },+ )+ })++ it("returns 404 and never schedules or broadcasts when the D1 delete loses", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [] })++ const res = await DELETE(delReq(), ctx)++ expect(res.status).toBe(404)+ expect(mockScheduleMediaCleanup).not.toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex 4d542ecf5..00e3b733d 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -1,4 +1,5 @@import { NextRequest } from "next/server"+import { getCloudflareContext } from "@opennextjs/cloudflare"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"@@ -15,6 +16,7 @@ import {} from "@alook/shared"import { fanOutToServerMembers, fanOutToChannel, broadcastToUserSafe } from "@/lib/community/fanout"import { requireChannelAccess, requireChannelMember } from "@/lib/community/permissions"+import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"/*** GET /api/community/channels/[id] — single channel metadata (the@@ -182,8 +184,28 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {? await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId): null- const deleted = await queries.communityChannel.deleteChannel(db, channelId)- if (!deleted) return writeError("channel not found", 404)+ let executionContext: ExecutionContext+ try {+ ({ ctx: executionContext } = await getCloudflareContext({ async: true }))+ } catch {+ return writeError("internal error", 500)+ }++ const result = await queries.communityDeleteMedia.deleteChannelWithMedia(db, {+ channelId,+ serverId: channel.serverId,+ })+ if (!result.deleted) return writeError("channel not found", 404)++ if (result.mediaKeys.length > 0) {+ scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {+ keys: result.mediaKeys,+ warning: {+ event: "community_channel_media_cleanup_failed",+ fields: { serverId: channel.serverId, channelId },+ },+ })+ }const event = {type: WS_EVENTS.CHANNEL_DELETE,diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts b/src/web/src/app/api/community/servers/[id]/icon/route.test.tsindex 13fa52b28..d0c3ec407 100644--- a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/icon/route.test.ts@@ -2,18 +2,24 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockGetServer = vi.fn()-const mockUpdateServer = vi.fn()+const mockUpdateServerIconIfCurrent = vi.fn()const mockGetMember = vi.fn()const mockHandleServerIconUpload = vi.fn()+const { warn } = vi.hoisted(() => ({ warn: vi.fn() }))const mediaGet = vi.fn()const mediaDelete = vi.fn()const mediaList = vi.fn()const mediaPut = vi.fn()const mockWaitUntil = vi.fn<(promise: Promise<unknown>) => void>()+const mockGetCloudflareContext = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({+ getCloudflareContext: (...a: unknown[]) => mockGetCloudflareContext(...a),+}))++function cloudflareContext() {+ return {env: {DB: {},COMMUNITY_MEDIA: {@@ -24,8 +30,8 @@ vi.mock("@opennextjs/cloudflare", () => ({},},ctx: { waitUntil: (p: Promise<unknown>) => mockWaitUntil(p) },- })),-}))+ }+}vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -33,10 +39,11 @@ vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {...actual,+ createLogger: () => ({ warn }),queries: {communityServer: {getServer: (...a: unknown[]) => mockGetServer(...a),- updateServer: (...a: unknown[]) => mockUpdateServer(...a),+ updateServerIconIfCurrent: (...a: unknown[]) => mockUpdateServerIconIfCurrent(...a),},communityMember: {getMember: (...a: unknown[]) => mockGetMember(...a),@@ -96,9 +103,18 @@ function ctx() {return { params: Promise.resolve({ id: "s1" }) } as any}+function deferred() {+ let resolve!: () => void+ const promise = new Promise<void>((done) => { resolve = done })+ return { promise, resolve }+}+describe("GET /api/community/servers/[id]/icon", () => {beforeEach(() => {vi.clearAllMocks()+ mockWaitUntil.mockReset()+ mockGetCloudflareContext.mockReset()+ mockGetCloudflareContext.mockResolvedValue(cloudflareContext())isAuthed = truemockGetServer.mockResolvedValue({ id: "s1", icon: "server-icon/s1/abc" })mediaGet.mockResolvedValue({@@ -150,9 +166,9 @@ describe("POST /api/community/servers/[id]/icon", () => {isAuthed = truemockGetMember.mockResolvedValue({ id: "m1", userId: "u1", role: "owner" })mockGetServer.mockResolvedValue({ id: "s1", icon: null })- mockUpdateServer.mockImplementation(async (_db, id, changes) => ({- id,- icon: changes.icon,+ mockUpdateServerIconIfCurrent.mockImplementation(async (_db, input) => ({+ id: input.serverId,+ icon: input.nextIcon,}))mockHandleServerIconUpload.mockResolvedValue({ok: true,@@ -172,10 +188,22 @@ describe("POST /api/community/servers/[id]/icon", () => {const body = await res.json() as { url: string }expect(body.url).toBe("/api/community/servers/s1/icon")- expect(mockUpdateServer).toHaveBeenCalledTimes(1)- const [, , changes] = mockUpdateServer.mock.calls[0]- expect(changes.icon).toMatch(/^server-icon\//)- expect(changes.icon).not.toMatch(/^\/api\//)+ expect(mockUpdateServerIconIfCurrent).toHaveBeenCalledTimes(1)+ expect(mockUpdateServerIconIfCurrent).toHaveBeenCalledWith(expect.anything(), {+ serverId: "s1",+ expectedIcon: null,+ nextIcon: "server-icon/s1/new-id",+ })+ })++ it("returns 500 without uploading or mutating D1 when execution context acquisition fails", async () => {+ mockGetCloudflareContext.mockRejectedValueOnce(new Error("context unavailable"))++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(500)+ expect(mockHandleServerIconUpload).not.toHaveBeenCalled()+ expect(mockUpdateServerIconIfCurrent).not.toHaveBeenCalled()})it("deletes the previous R2 object exactly once when replacing an icon", async () => {@@ -185,7 +213,7 @@ describe("POST /api/community/servers/[id]/icon", () => {expect(res.status).toBe(200)expect(mediaDelete).toHaveBeenCalledTimes(1)- expect(mediaDelete).toHaveBeenCalledWith("server-icon/s1/old")+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/old"])})it("wraps the previous R2 key delete in ctx.waitUntil", async () => {@@ -201,7 +229,43 @@ describe("POST /api/community/servers/[id]/icon", () => {const promise = mockWaitUntil.mock.calls[0][0]expect(promise).toBeInstanceOf(Promise)await expect(promise).resolves.toBeUndefined()- expect(mediaDelete).toHaveBeenCalledWith("server-icon/s1/old")+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/old"])+ })++ it("keeps a successful replacement committed when old-key cleanup rejects", async () => {+ mockGetServer.mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ mediaDelete.mockRejectedValueOnce(new Error("secret provider detail"))++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(200)+ await expect(mockWaitUntil.mock.calls[0]![0]).resolves.toBeUndefined()+ expect(warn).toHaveBeenCalledWith("community_server_icon_cleanup_failed", {+ serverId: "s1",+ phase: "old_key_cleanup",+ keyCount: 1,+ errorCategory: "Error",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")+ })++ it("keeps a successful replacement committed when waitUntil throws synchronously", async () => {+ mockGetServer.mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ mockWaitUntil.mockImplementationOnce(() => {+ throw new TypeError("secret registration detail")+ })++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(200)+ expect(mockUpdateServerIconIfCurrent).toHaveBeenCalledOnce()+ expect(warn).toHaveBeenCalledWith("community_server_icon_cleanup_failed", {+ serverId: "s1",+ phase: "old_key_cleanup",+ keyCount: 1,+ errorCategory: "TypeError",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")})it("does not call waitUntil when there is no previous key to delete", async () => {@@ -213,10 +277,13 @@ describe("POST /api/community/servers/[id]/icon", () => {expect(mediaDelete).not.toHaveBeenCalled()})- it("does not delete legacy URL-shaped previous values", async () => {- // Rows that predate the migration hold `/api/community/servers/…` — the- // `startsWith("server-icon/")` guard should skip them.- mockGetServer.mockResolvedValueOnce({ id: "s1", icon: "/api/community/servers/s1/icon" })+ it.each([+ "/api/community/servers/s1/icon",+ "server-icon/other/old",+ "server-icon/s1/nested/old",+ "server-icon/s1/",+ ])("does not delete a non-owned previous value %s", async (previous) => {+ mockGetServer.mockResolvedValueOnce({ id: "s1", icon: previous })const res = await POST(postReq(), ctx())expect(res.status).toBe(200)@@ -230,4 +297,184 @@ describe("POST /api/community/servers/[id]/icon", () => {expect(res.status).toBe(200)expect(mediaDelete).not.toHaveBeenCalled()})++ it("CAS loss with a deleted server compensates only the just-put key and returns 404", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce(null)+ mockUpdateServerIconIfCurrent.mockResolvedValue(null)++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(404)+ expect(mediaDelete).toHaveBeenCalledTimes(1)+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/new-id"])+ expect(mediaDelete).not.toHaveBeenCalledWith(expect.arrayContaining(["server-icon/s1/old"]))+ })++ it("CAS loss to another live key compensates only the just-put key and returns 409", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/winner" })+ mockUpdateServerIconIfCurrent.mockResolvedValue(null)++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({ error: "server icon changed; retry" })+ expect(mediaDelete).toHaveBeenCalledTimes(1)+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/new-id"])+ })++ it("CAS loss never deletes the current winner when it equals the just-put key", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/new-id" })+ mockUpdateServerIconIfCurrent.mockResolvedValue(null)++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(409)+ expect(mediaDelete).not.toHaveBeenCalled()+ })++ it("defensively returns 409 and compensates when a live row still has expectedIcon", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ mockUpdateServerIconIfCurrent.mockResolvedValue(null)++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(409)+ expect(mediaDelete).toHaveBeenCalledTimes(1)+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/new-id"])+ })++ it("keeps the frozen 409 when compensation fails and logs no raw detail or key", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/winner" })+ mockUpdateServerIconIfCurrent.mockResolvedValue(null)+ mediaDelete.mockRejectedValueOnce(new Error("secret/key provider detail"))++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(409)+ expect(warn).toHaveBeenCalledWith("community_server_icon_cleanup_failed", {+ serverId: "s1",+ phase: "cas_compensation",+ keyCount: 1,+ errorCategory: "Error",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret/key")+ expect(JSON.stringify(warn.mock.calls)).not.toContain("provider detail")+ })++ it("compensates a just-put key when the CAS query throws before rethrowing", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ mockUpdateServerIconIfCurrent.mockRejectedValueOnce(new Error("d1 failed"))++ await expect(POST(postReq(), ctx())).rejects.toThrow("d1 failed")+ expect(mediaDelete).toHaveBeenCalledWith(["server-icon/s1/new-id"])+ })++ it("does not risk deleting an ambiguous winner when the CAS and verification read both throw", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockRejectedValueOnce(new Error("verification unavailable"))+ mockUpdateServerIconIfCurrent.mockRejectedValueOnce(new Error("ambiguous d1 failure"))++ await expect(POST(postReq(), ctx())).rejects.toThrow("ambiguous d1 failure")+ expect(mediaDelete).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith("community_server_icon_cas_state_verification_failed", {+ serverId: "s1",+ phase: "cas_error_verification",+ objectState: "retained_unverified",+ errorCategory: "Error",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("verification unavailable")+ })++ it("retains an unverified CAS=0 upload and emits one sanitized state warning", async () => {+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: "server-icon/s1/old" })+ .mockRejectedValueOnce(new TypeError("secret verification provider detail"))+ mockUpdateServerIconIfCurrent.mockResolvedValueOnce(null)++ const res = await POST(postReq(), ctx())++ expect(res.status).toBe(500)+ expect(mediaDelete).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledTimes(1)+ expect(warn).toHaveBeenCalledWith("community_server_icon_cas_state_verification_failed", {+ serverId: "s1",+ phase: "cas_zero_verification",+ objectState: "retained_unverified",+ errorCategory: "TypeError",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")+ expect(JSON.stringify(warn.mock.calls)).not.toContain("provider detail")+ })++ it("linearizes concurrent replacements when the first upload wins", async () => {+ let liveIcon = "server-icon/s1/old"+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: liveIcon })+ .mockResolvedValueOnce({ id: "s1", icon: liveIcon })+ .mockImplementation(async () => ({ id: "s1", icon: liveIcon }))+ mockHandleServerIconUpload+ .mockResolvedValueOnce({ ok: true, key: "server-icon/s1/b" })+ .mockResolvedValueOnce({ ok: true, key: "server-icon/s1/c" })+ mockUpdateServerIconIfCurrent.mockImplementation(async (_db, input) => {+ if (liveIcon !== input.expectedIcon) return null+ liveIcon = input.nextIcon+ return { id: input.serverId, icon: input.nextIcon }+ })++ const [first, second] = await Promise.all([POST(postReq(), ctx()), POST(postReq(), ctx())])++ expect([first.status, second.status]).toEqual([200, 409])+ expect(liveIcon).toBe("server-icon/s1/b")+ await Promise.all(mockWaitUntil.mock.calls.map(([promise]) => promise))+ expect(mediaDelete.mock.calls.map(([keys]) => keys)).toEqual(expect.arrayContaining([+ ["server-icon/s1/old"],+ ["server-icon/s1/c"],+ ]))+ expect(mediaDelete).not.toHaveBeenCalledWith(["server-icon/s1/b"])+ })++ it("linearizes concurrent replacements when the second upload wins", async () => {+ let liveIcon = "server-icon/s1/old"+ const releaseFirstCas = deferred()+ mockGetServer+ .mockResolvedValueOnce({ id: "s1", icon: liveIcon })+ .mockResolvedValueOnce({ id: "s1", icon: liveIcon })+ .mockImplementation(async () => ({ id: "s1", icon: liveIcon }))+ mockHandleServerIconUpload+ .mockResolvedValueOnce({ ok: true, key: "server-icon/s1/b" })+ .mockResolvedValueOnce({ ok: true, key: "server-icon/s1/c" })+ let casCall = 0+ mockUpdateServerIconIfCurrent.mockImplementation(async (_db, input) => {+ casCall += 1+ if (casCall === 1) await releaseFirstCas.promise+ if (liveIcon !== input.expectedIcon) return null+ liveIcon = input.nextIcon+ releaseFirstCas.resolve()+ return { id: input.serverId, icon: input.nextIcon }+ })++ const [first, second] = await Promise.all([POST(postReq(), ctx()), POST(postReq(), ctx())])++ expect([first.status, second.status]).toEqual([409, 200])+ expect(liveIcon).toBe("server-icon/s1/c")+ await Promise.all(mockWaitUntil.mock.calls.map(([promise]) => promise))+ expect(mediaDelete.mock.calls.map(([keys]) => keys)).toEqual(expect.arrayContaining([+ ["server-icon/s1/old"],+ ["server-icon/s1/b"],+ ]))+ expect(mediaDelete).not.toHaveBeenCalledWith(["server-icon/s1/c"])+ })})diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.ts b/src/web/src/app/api/community/servers/[id]/icon/route.tsindex b99fa43b9..b0b7b03a5 100644--- a/src/web/src/app/api/community/servers/[id]/icon/route.ts+++ b/src/web/src/app/api/community/servers/[id]/icon/route.ts@@ -6,7 +6,12 @@ import { getDb } from "@/lib/db"import { queries, CACHE_SHORT, createLogger } from "@alook/shared"import { requireServerAdmin } from "@/lib/community/permissions"import { handleServerIconUpload } from "@/lib/community/upload"-import { serverIconUrl } from "@/lib/community/storage"+import { isOwnedServerIconKey, serverIconUrl } from "@/lib/community/storage"+import {+ communityMediaCleanupErrorCategory,+ deleteCommunityMediaObjects,+ scheduleCommunityMediaCleanup,+} from "@/lib/community/community-media-cleanup"const log = createLogger({ service: "community-server-icon" })@@ -37,32 +42,93 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const auth = await requireServerAdmin(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- // Snapshot the previous key BEFORE upload so we can sweep it after the- // update commits. The `startsWith` guard on cleanup skips legacy URL-shaped- // rows that predate the migration.+ // This pre-upload value is the CAS expectation and the only old object a+ // successful winner may later clean.const previousKey = (await queries.communityServer.getServer(db, serverId))?.icon ?? null+ let executionContext: ExecutionContext+ try {+ ({ ctx: executionContext } = await getCloudflareContext({ async: true }))+ } catch {+ return writeError("internal error", 500)+ }+const result = await handleServerIconUpload(req, ctx.env, serverId)if (!result.ok) return result.responseconst iconKey = result.key- const updated = await queries.communityServer.updateServer(db, serverId, { icon: iconKey })- if (!updated) return writeError("server not found", 404)+ let updated+ try {+ updated = await queries.communityServer.updateServerIconIfCurrent(db, {+ serverId,+ expectedIcon: previousKey,+ nextIcon: iconKey,+ })+ } catch (error) {+ let live+ try {+ live = await queries.communityServer.getServer(db, serverId)+ } catch (verificationError) {+ log.warn("community_server_icon_cas_state_verification_failed", {+ serverId,+ phase: "cas_error_verification",+ objectState: "retained_unverified",+ errorCategory: communityMediaCleanupErrorCategory(verificationError),+ })+ throw error+ }+ if (live?.icon !== iconKey) {+ await compensateServerIcon(ctx.env.COMMUNITY_MEDIA, serverId, iconKey)+ }+ throw error+ }- if (previousKey && previousKey !== iconKey && previousKey.startsWith("server-icon/")) {- // Wrap in waitUntil so the CF runtime explicitly extends the worker- // lifetime past the response for the R2 delete to complete.- const deletePromise = ctx.env.COMMUNITY_MEDIA.delete(previousKey).catch((err) =>- log.warn("server_icon_delete_failed", { err, serverId, previousKey }),- )+ if (!updated) {+ let livetry {- const { ctx: cfCtx } = await getCloudflareContext({ async: true })- cfCtx.waitUntil(deletePromise)- } catch {- // Not in a CF context (tests / non-worker runtime) — the promise still- // runs on its own; the fire-and-forget behaviour matches the prior code.+ live = await queries.communityServer.getServer(db, serverId)+ } catch (error) {+ log.warn("community_server_icon_cas_state_verification_failed", {+ serverId,+ phase: "cas_zero_verification",+ objectState: "retained_unverified",+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ return writeError("internal error", 500)}+ if (live?.icon !== iconKey) {+ await compensateServerIcon(ctx.env.COMMUNITY_MEDIA, serverId, iconKey)+ }+ if (!live) return writeError("server not found", 404)+ return writeError("server icon changed; retry", 409)+ }++ if (previousKey && previousKey !== iconKey && isOwnedServerIconKey(previousKey, serverId)) {+ scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {+ keys: [previousKey],+ warning: {+ event: "community_server_icon_cleanup_failed",+ fields: { serverId, phase: "old_key_cleanup" },+ },+ })}return writeJSON({ url: serverIconUrl({ id: serverId, icon: iconKey }) })})++async function compensateServerIcon(+ bucket: Pick<R2Bucket, "delete">,+ serverId: string,+ iconKey: string,+): Promise<void> {+ try {+ await deleteCommunityMediaObjects(bucket, [iconKey])+ } catch (error) {+ log.warn("community_server_icon_cleanup_failed", {+ serverId,+ phase: "cas_compensation",+ keyCount: 1,+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ }+}diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.tsindex c87d83742..c11572579 100644--- a/src/web/src/app/api/community/servers/[id]/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts@@ -4,12 +4,15 @@ import { NextRequest } from "next/server"const mockGetMember = vi.fn()const mockListMemberUserIds = vi.fn()const mockUpdateServer = vi.fn()-const mockDeleteServer = vi.fn()+const mockDeleteServerWithMedia = vi.fn()const mockFanOut = vi.fn()const mockFanOutToUsers = vi.fn()+const mockScheduleMediaCleanup = vi.fn()+const mockWaitUntil = vi.fn()+const mockGetCloudflareContext = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ getCloudflareContext: (...a: unknown[]) => mockGetCloudflareContext(...a),}))vi.mock("@/lib/db", () => ({@@ -27,7 +30,9 @@ vi.mock("@alook/shared", async () => {},communityServer: {updateServer: (...a: unknown[]) => mockUpdateServer(...a),- deleteServer: (...a: unknown[]) => mockDeleteServer(...a),+ },+ communityDeleteMedia: {+ deleteServerWithMedia: (...a: unknown[]) => mockDeleteServerWithMedia(...a),},},}@@ -38,10 +43,28 @@ vi.mock("@/lib/community/fanout", () => ({fanOutToUsers: (...a: unknown[]) => mockFanOutToUsers(...a),}))+vi.mock("@/lib/community/community-media-cleanup", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/community-media-cleanup")>(+ "@/lib/community/community-media-cleanup",+ )+ return {+ ...actual,+ scheduleCommunityMediaCleanup: (...a: Parameters<typeof actual.scheduleCommunityMediaCleanup>) => {+ mockScheduleMediaCleanup(...a)+ return actual.scheduleCommunityMediaCleanup(...a)+ },+ }+})+vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ return handler(req, {+ env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },+ userId: "u1",+ email: "[email protected]",+ params,+ })}),}))@@ -103,9 +126,16 @@ describe("PATCH /api/community/servers/[id]", () => {describe("DELETE /api/community/servers/[id]", () => {beforeEach(() => {vi.clearAllMocks()+ mockWaitUntil.mockReset()+ mockScheduleMediaCleanup.mockReset()+ mockGetCloudflareContext.mockReset()+ mockGetCloudflareContext.mockResolvedValue({+ env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },+ ctx: { waitUntil: mockWaitUntil },+ })mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })mockListMemberUserIds.mockResolvedValue(["u1", "u2"])- mockDeleteServer.mockResolvedValue({ id: "s1" })+ mockDeleteServerWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [], iconKey: null })mockFanOutToUsers.mockResolvedValue(undefined)})@@ -115,9 +145,9 @@ describe("DELETE /api/community/servers/[id]", () => {order.push("recipients")return ["u1", "u2"]})- mockDeleteServer.mockImplementation(async () => {+ mockDeleteServerWithMedia.mockImplementation(async () => {order.push("delete")- return { id: "s1" }+ return { deleted: true, mediaKeys: [], iconKey: null }})mockFanOutToUsers.mockImplementation(async () => {order.push("fanout")@@ -132,4 +162,92 @@ describe("DELETE /api/community/servers/[id]", () => {serverId: "s1",})})++ it("returns 500 without mutating D1 when execution context acquisition fails", async () => {+ mockGetCloudflareContext.mockRejectedValueOnce(new Error("context unavailable"))++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(500)+ expect(mockDeleteServerWithMedia).not.toHaveBeenCalled()+ expect(mockFanOutToUsers).not.toHaveBeenCalled()+ })++ it("keeps the winner 204 and fanout when waitUntil throws synchronously", async () => {+ mockDeleteServerWithMedia.mockResolvedValue({+ deleted: true,+ mediaKeys: ["channel/s1/a"],+ iconKey: null,+ })+ mockWaitUntil.mockImplementationOnce(() => {+ throw new TypeError("secret registration detail")+ })++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockDeleteServerWithMedia).toHaveBeenCalledOnce()+ expect(mockFanOutToUsers).toHaveBeenCalledOnce()+ })++ it("schedules attachment and strictly-owned icon cleanup after the winner and before fanout", async () => {+ const order: string[] = []+ mockDeleteServerWithMedia.mockImplementation(async () => {+ order.push("delete")+ return {+ deleted: true,+ mediaKeys: ["channel/s1/a", "channel/s1/a.thumbnail.jpg"],+ iconKey: "server-icon/s1/icon-a",+ }+ })+ mockScheduleMediaCleanup.mockImplementation(() => order.push("cleanup"))+ mockFanOutToUsers.mockImplementation(async () => order.push("fanout"))++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(order).toEqual(["delete", "cleanup", "fanout"])+ expect(mockDeleteServerWithMedia).toHaveBeenCalledWith(expect.anything(), {+ serverId: "s1",+ ownerId: "u1",+ })+ expect(mockScheduleMediaCleanup).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ waitUntil: mockWaitUntil }),+ {+ keys: ["channel/s1/a", "channel/s1/a.thumbnail.jpg", "server-icon/s1/icon-a"],+ warning: {+ event: "community_server_media_cleanup_failed",+ fields: { serverId: "s1" },+ },+ },+ )+ })++ it("does not enqueue a legacy or cross-server icon key", async () => {+ mockDeleteServerWithMedia.mockResolvedValue({+ deleted: true,+ mediaKeys: ["channel/s1/a"],+ iconKey: "server-icon/other/icon-a",+ })++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockScheduleMediaCleanup).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.objectContaining({ keys: ["channel/s1/a"] }),+ )+ })++ it("returns 404 without cleanup or fanout when the owner-scoped delete loses", async () => {+ mockDeleteServerWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [], iconKey: null })++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(404)+ expect(mockScheduleMediaCleanup).not.toHaveBeenCalled()+ expect(mockFanOutToUsers).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.tsindex 7c9e13b80..8123e9b29 100644--- a/src/web/src/app/api/community/servers/[id]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/route.ts@@ -1,4 +1,5 @@import { NextRequest } from "next/server"+import { getCloudflareContext } from "@opennextjs/cloudflare"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"@@ -12,6 +13,8 @@ import {} from "@alook/shared"import { fanOutToServerMembers, fanOutToUsers } from "@/lib/community/fanout"import { requireServerAdmin } from "@/lib/community/permissions"+import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"+import { isOwnedServerIconKey } from "@/lib/community/storage"export const PATCH = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.id@@ -84,8 +87,34 @@ export const DELETE = withAuth(async (_req, ctx) => {const recipients = await queries.communityMember.listMemberUserIds(db, serverId)- const deleted = await queries.communityServer.deleteServer(db, serverId)- if (!deleted) return writeError("server not found", 404)+ let executionContext: ExecutionContext+ try {+ ({ ctx: executionContext } = await getCloudflareContext({ async: true }))+ } catch {+ return writeError("internal error", 500)+ }++ const result = await queries.communityDeleteMedia.deleteServerWithMedia(db, {+ serverId,+ ownerId: ctx.userId,+ })+ if (!result.deleted) return writeError("server not found", 404)++ const mediaKeys = [+ ...result.mediaKeys,+ ...(result.iconKey && isOwnedServerIconKey(result.iconKey, serverId)+ ? [result.iconKey]+ : []),+ ]+ if (mediaKeys.length > 0) {+ scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {+ keys: mediaKeys,+ warning: {+ event: "community_server_media_cleanup_failed",+ fields: { serverId },+ },+ })+ }await fanOutToUsers(recipients, {type: WS_EVENTS.SERVER_DELETE,diff --git a/src/web/src/lib/community/community-media-cleanup.test.ts b/src/web/src/lib/community/community-media-cleanup.test.tsnew file mode 100644index 000000000..641234bd1--- /dev/null+++ b/src/web/src/lib/community/community-media-cleanup.test.ts@@ -0,0 +1,106 @@+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,+ deleteCommunityMediaObjects,+ scheduleCommunityMediaCleanup,+} from "./community-media-cleanup"++describe("community media cleanup", () => {+ const deleteObjects = vi.fn<(keys: string | string[]) => Promise<void>>()+ const waitUntil = vi.fn<(promise: Promise<unknown>) => void>()++ beforeEach(() => {+ vi.clearAllMocks()+ waitUntil.mockReset()+ deleteObjects.mockResolvedValue(undefined)+ })++ it("deduplicates, filters empty keys, and registers one complete waitUntil chain", async () => {+ scheduleCommunityMediaCleanup({ delete: deleteObjects }, { waitUntil }, {+ keys: ["original", "thumbnail", "original", ""],+ warning: { event: "cleanup_failed", fields: { channelId: "c1" } },+ })++ expect(waitUntil).toHaveBeenCalledTimes(1)+ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined()+ expect(deleteObjects).toHaveBeenCalledTimes(1)+ expect(deleteObjects).toHaveBeenCalledWith(["original", "thumbnail"])+ })++ it("deletes sequential chunks at the current R2 1000-key limit", async () => {+ const keys = Array.from(+ { length: COMMUNITY_MEDIA_DELETE_BATCH_SIZE + 1 },+ (_, index) => `key-${index}`,+ )+ scheduleCommunityMediaCleanup({ delete: deleteObjects }, { waitUntil }, {+ keys,+ warning: { event: "cleanup_failed", fields: { serverId: "s1" } },+ })++ 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 no keys", () => {+ scheduleCommunityMediaCleanup({ delete: deleteObjects }, { waitUntil }, {+ keys: [""],+ warning: { event: "cleanup_failed", fields: { serverId: "s1" } },+ })+ expect(waitUntil).not.toHaveBeenCalled()+ expect(deleteObjects).not.toHaveBeenCalled()+ })++ it("swallows a synchronous waitUntil rejection and logs once without raw detail", async () => {+ waitUntil.mockImplementationOnce(() => {+ throw new TypeError("secret registration detail")+ })++ expect(() => scheduleCommunityMediaCleanup({ delete: deleteObjects }, { waitUntil }, {+ keys: ["secret/key"],+ warning: { event: "cleanup_failed", fields: { serverId: "s1" } },+ })).not.toThrow()+ await vi.waitFor(() => expect(deleteObjects).toHaveBeenCalledWith(["secret/key"]))+ expect(warn).toHaveBeenCalledTimes(1)+ expect(warn).toHaveBeenCalledWith("cleanup_failed", {+ serverId: "s1",+ keyCount: 1,+ errorCategory: "TypeError",+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")+ })++ it.each([+ [new TypeError("secret type detail"), "TypeError"],+ [new Error("secret provider detail"), "Error"],+ ["secret non-error detail", "NonError"],+ ] as const)("sanitizes a rejected cleanup as %s", async (rejection, category) => {+ deleteObjects.mockRejectedValueOnce(rejection)+ scheduleCommunityMediaCleanup({ delete: deleteObjects }, { waitUntil }, {+ keys: ["secret/key"],+ warning: { event: "cleanup_failed", fields: { serverId: "s1" } },+ })++ await expect(waitUntil.mock.calls[0]![0]).resolves.toBeUndefined()+ expect(warn).toHaveBeenCalledTimes(1)+ expect(warn).toHaveBeenCalledWith("cleanup_failed", {+ serverId: "s1",+ keyCount: 1,+ errorCategory: category,+ })+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")+ })++ it("exposes an awaited delete path for CAS compensation", async () => {+ await deleteCommunityMediaObjects({ delete: deleteObjects }, ["new", "new", ""])+ expect(deleteObjects).toHaveBeenCalledWith(["new"])+ })+})diff --git a/src/web/src/lib/community/community-media-cleanup.ts b/src/web/src/lib/community/community-media-cleanup.tsnew file mode 100644index 000000000..15a519ae1--- /dev/null+++ b/src/web/src/lib/community/community-media-cleanup.ts@@ -0,0 +1,62 @@+import { createLogger } from "@alook/shared"++const log = createLogger({ service: "community-media-cleanup" })++export const COMMUNITY_MEDIA_DELETE_BATCH_SIZE = 1000++export type CommunityMediaCleanupErrorCategory = "Error" | "TypeError" | "NonError"++export type CommunityMediaCleanupWarning = {+ event: string+ fields: Record<string, string | number>+}++export function communityMediaCleanupErrorCategory(+ error: unknown,+): CommunityMediaCleanupErrorCategory {+ if (error instanceof TypeError) return "TypeError"+ if (error instanceof Error) return "Error"+ return "NonError"+}++function normalizeCommunityMediaKeys(keys: string[]): string[] {+ return [...new Set(keys.filter((key) => key.length > 0))]+}++export async function deleteCommunityMediaObjects(+ bucket: Pick<R2Bucket, "delete">,+ keys: string[],+): Promise<void> {+ const normalized = normalizeCommunityMediaKeys(keys)+ for (let offset = 0; offset < normalized.length; offset += COMMUNITY_MEDIA_DELETE_BATCH_SIZE) {+ await bucket.delete(normalized.slice(offset, offset + COMMUNITY_MEDIA_DELETE_BATCH_SIZE))+ }+}++export function scheduleCommunityMediaCleanup(+ bucket: Pick<R2Bucket, "delete">,+ executionContext: Pick<ExecutionContext, "waitUntil">,+ input: { keys: string[]; warning: CommunityMediaCleanupWarning },+): void {+ const keys = normalizeCommunityMediaKeys(input.keys)+ if (keys.length === 0) return++ let warned = false+ const warnOnce = (error: unknown) => {+ if (warned) return+ warned = true+ log.warn(input.warning.event, {+ ...input.warning.fields,+ keyCount: keys.length,+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ }++ const cleanup = deleteCommunityMediaObjects(bucket, keys).catch(warnOnce)++ try {+ executionContext.waitUntil(cleanup)+ } catch (error) {+ warnOnce(error)+ }+}diff --git a/src/web/src/lib/community/forum-post-media-cleanup.ts b/src/web/src/lib/community/forum-post-media-cleanup.tsindex 5d230b7a9..77863df33 100644--- a/src/web/src/lib/community/forum-post-media-cleanup.ts+++ b/src/web/src/lib/community/forum-post-media-cleanup.ts@@ -1,18 +1,14 @@-import { createLogger } from "@alook/shared";+import {+ COMMUNITY_MEDIA_DELETE_BATCH_SIZE,+ scheduleCommunityMediaCleanup,+} from "./community-media-cleanup"-const log = createLogger({ service: "community-forum-post-delete" });-export const COMMUNITY_MEDIA_DELETE_BATCH_SIZE = 1000;+export { COMMUNITY_MEDIA_DELETE_BATCH_SIZE }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";+ openerId: string+ childChannelId: string+ keys: string[]}/**@@ -26,21 +22,14 @@ export function scheduleForumPostMediaCleanup(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);+ scheduleCommunityMediaCleanup(bucket, executionContext, {+ keys: input.keys,+ warning: {+ event: "forum_post_media_cleanup_failed",+ fields: {+ openerId: input.openerId,+ childChannelId: input.childChannelId,+ },+ },+ })}diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.tsindex 948e6b4dc..1f62e1024 100644--- a/src/web/src/lib/community/storage.test.ts+++ b/src/web/src/lib/community/storage.test.ts@@ -10,6 +10,7 @@ import {sanitizeAttachmentFilename,userAvatarUrl,botAvatarUrl,+ isOwnedServerIconKey,} from "./storage"describe("buildUserAvatarKey", () => {@@ -86,6 +87,22 @@ describe("buildMediaKey", () => {})})+describe("isOwnedServerIconKey", () => {+ it("accepts exactly one non-empty suffix under the expected server", () => {+ expect(isOwnedServerIconKey("server-icon/s1/icon-a", "s1")).toBe(true)+ })++ it.each([+ "server-icon/s1/",+ "server-icon/s1/nested/icon-a",+ "server-icon/other/icon-a",+ "/api/community/servers/s1/icon",+ "server-icon/s1",+ ])("rejects non-owned or non-canonical key %s", (key) => {+ expect(isOwnedServerIconKey(key, "s1")).toBe(false)+ })+})+describe("attachmentUrl", () => {it("builds the id-addressed canonical attachments-door URL from targetId + attachmentId", () => {expect(attachmentUrl("c1", "att_1")).toBe("/api/community/channels/c1/attachments/att_1")diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.tsindex 70d6e2bc1..e70d98962 100644--- a/src/web/src/lib/community/storage.ts+++ b/src/web/src/lib/community/storage.ts@@ -48,6 +48,13 @@ export function buildServerIconKey(serverId: string, fileId: string): string {return `server-icon/${serverId}/${fileId}`}+export function isOwnedServerIconKey(key: string, serverId: string): boolean {+ const prefix = `server-icon/${serverId}/`+ if (!key.startsWith(prefix)) return false+ const suffix = key.slice(prefix.length)+ return suffix.length > 0 && !suffix.includes("/")+}+// Deterministic keys — unlike server icons (random `fileId`, old key deleted// on replace), user/bot avatars overwrite the same R2 object in place, so the// routable URL stored on the DB row never changes across re-uploads.diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex 6e79cad7c..da3063833 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -198,19 +198,39 @@ describe("handleAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it("deletes the original when the thumbnail put fails", async () => {- const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("r2 thumbnail"))- const del = vi.fn().mockResolvedValue(undefined)+ it.each([+ { uploader: "user" as const, uploaderUserId: "u1" },+ { uploader: "bot" as const, uploaderUserId: "bot_ada" },+ ])("sanitizes $uploader original-compensation failures after a thumbnail put rejects", async (uploaderTag) => {+ const thumbnailFailure = new Error("r2 thumbnail")+ const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(thumbnailFailure)+ const cleanupSecret = "provider-secret channel/c1/original.png"+ const del = vi.fn().mockRejectedValueOnce(new TypeError(cleanupSecret))const thumbnail = {...fakeFile("thumbnail.jpg", "image/jpeg", 4),arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,}- await expect(handleAttachmentUpload(+ const upload = handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- envWithR2(put, del), "channel", "c1", USER_TAG,- )).rejects.toThrow("r2 thumbnail")- expect(del).toHaveBeenCalledOnce()- expect(del.mock.calls[0]?.[0]).toMatch(/\/hi\.png$/)+ envWithR2(put, del), "channel", "c1", uploaderTag,+ )++ await expect(upload).rejects.toBe(thumbnailFailure)+ const originalKey = put.mock.calls[0]?.[0]+ expect(originalKey).toMatch(/^channel\/c1\/[0-9a-f-]+\/hi\.png$/)+ expect(del).toHaveBeenCalledTimes(1)+ expect(del).toHaveBeenCalledWith(originalKey)+ expect(mockLogError).toHaveBeenCalledTimes(1)+ expect(mockLogError).toHaveBeenCalledWith("attachment_thumbnail_put_cleanup_failed", {+ uploader: uploaderTag.uploader,+ route: "channels/[id]/attachments",+ phase: "thumbnail_put_original_compensation",+ objectCount: 1,+ errorCategory: "TypeError",+ })+ const serializedWarning = JSON.stringify(mockLogError.mock.calls)+ expect(serializedWarning).not.toContain(cleanupSecret)+ expect(serializedWarning).not.toContain(String(originalKey))})it("stamps customMetadata.uploader=bot + bot_user_id when the caller is a bot", async () => {@@ -666,7 +686,7 @@ describe("runAttachmentUpload", () => {surfaceChannel("text")mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))const put = vi.fn().mockResolvedValue(undefined)- const del = vi.fn().mockRejectedValueOnce(new Error("cleanup failed"))+ const del = vi.fn().mockRejectedValueOnce(new TypeError("secret provider detail"))const thumbnail = {...fakeFile("thumbnail.jpg", "image/jpeg", 4),arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,@@ -682,7 +702,13 @@ describe("runAttachmentUpload", () => {const cleanupLog = mockLogError.mock.calls.find(([event]) => event === "attachment_upload_r2_cleanup_failed",)- expect(cleanupLog?.[1]).toEqual(expect.objectContaining({ objectCount: 2 }))+ expect(cleanupLog?.[1]).toEqual({+ route: "channels/[id]/attachments",+ actor: "human",+ objectCount: 2,+ errorCategory: "TypeError",+ })for (const key of keys) expect(JSON.stringify(cleanupLog)).not.toContain(key)+ expect(JSON.stringify(cleanupLog)).not.toContain("secret provider detail")})})diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex dd8e8b312..86d80c718 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -14,6 +14,7 @@ import { writeError, writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import type { AuthContext } from "@/lib/middleware/auth"import { isInlineAttachmentContentType } from "./attachment-content-type"+import { communityMediaCleanupErrorCategory } from "./community-media-cleanup"import {buildMediaKey,buildAttachmentThumbnailKey,@@ -214,7 +215,10 @@ export async function handleAttachmentUpload(} catch (cleanupErr) {log.error("attachment_thumbnail_put_cleanup_failed", {uploader: uploaderTag.uploader,- cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ route: "channels/[id]/attachments",+ phase: "thumbnail_put_original_compensation",+ objectCount: 1,+ errorCategory: communityMediaCleanupErrorCategory(cleanupErr),})}throw err@@ -449,9 +453,9 @@ export async function runAttachmentUpload(} catch (cleanupErr) {log.error("attachment_upload_r2_cleanup_failed", {route: "channels/[id]/attachments",- userId: ctx.userId,+ actor: "human",objectCount: r2KeysToCleanUp.length,- cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ errorCategory: communityMediaCleanupErrorCategory(cleanupErr),})}}diff --git a/src/web/src/test/architecture/community-delete-media-boundary.test.ts b/src/web/src/test/architecture/community-delete-media-boundary.test.tsnew file mode 100644index 000000000..3747b361f--- /dev/null+++ b/src/web/src/test/architecture/community-delete-media-boundary.test.ts@@ -0,0 +1,34 @@+import { readFileSync } from "node:fs"+import { resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { describe, expect, it } from "vitest"++const repositoryRoot = fileURLToPath(new URL("../../../../../", import.meta.url))+const c1Sources = [+ "src/shared/src/db/queries/community/attachment.ts",+ "src/shared/src/db/queries/community/delete-media.ts",+ "src/shared/src/db/queries/community/server.ts",+ "src/web/src/app/api/community/channels/[id]/route.ts",+ "src/web/src/app/api/community/servers/[id]/route.ts",+ "src/web/src/app/api/community/servers/[id]/icon/route.ts",+ "src/web/src/lib/community/community-media-cleanup.ts",+] as const++describe("existing delete media C1 boundary", () => {+ it("cannot cross into bot, machine, diagnostic, or BUG_REPORTS storage", () => {+ const source = c1Sources+ .map((path) => readFileSync(resolve(repositoryRoot, path), "utf8"))+ .join("\n")++ for (const forbidden of [+ "BUG_REPORTS",+ "communityDiagnosticReport",+ "bot-avatar/",+ "communityMachine",+ "deleteMachine",+ ".list(",+ ]) {+ expect(source).not.toContain(forbidden)+ }+ })+})diff --git a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.tsnew file mode 100644index 000000000..3d421ddd1--- /dev/null+++ b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts@@ -0,0 +1,204 @@+import type { Page, WebSocket } from "@playwright/test"+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"++type DeleteFrame = {+ type: "community:channel.delete" | "community:server.delete"+ serverId: string+ channelId?: string+}++function captureDeletes(page: Page) {+ const frames: DeleteFrame[] = []+ const sockets = new Set<WebSocket>()+ page.on("websocket", (socket) => {+ sockets.add(socket)+ socket.on("framereceived", ({ payload }) => {+ try {+ const frame = JSON.parse(payload.toString()) as DeleteFrame+ if (frame.type === "community:channel.delete" || frame.type === "community:server.delete") {+ frames.push(frame)+ }+ } catch {}+ })+ })+ return { frames, sockets }+}++function headers(key: "alice" | "bob" | "carol") {+ return { Cookie: sessionCookie(key), Origin: WEB_URL }+}++async function uploadPending(+ key: "alice" | "bob" | "carol",+ channelId: string,+ name: string,+ withThumbnail: boolean,+): Promise<string> {+ const form = new FormData()+ form.append("file", new Blob([`original:${name}`], { type: "image/png" }), name)+ if (withThumbnail) {+ form.append(+ "thumbnail",+ new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" }),+ `${name}.thumbnail.jpg`,+ )+ }+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/attachments`, {+ method: "POST",+ headers: headers(key),+ body: form,+ })+ expect(response.status).toBe(200)+ const body = await response.json() as { id: string }+ return body.id+}++async function linkAttachment(+ key: "alice" | "bob" | "carol",+ channelId: string,+ attachmentId: string,+): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {+ method: "POST",+ headers: { ...headers(key), "Content-Type": "application/json" },+ body: JSON.stringify({+ content: `media ${attachmentId}`,+ attachments: [attachmentId],+ nonce: `e2e:${crypto.randomUUID()}`,+ }),+ })+ expect(response.status).toBe(201)+}++async function uploadServerIcon(serverId: string): Promise<void> {+ const form = new FormData()+ form.append("file", new Blob(["server icon"], { type: "image/png" }), "server.png")+ const response = await fetch(`${WEB_URL}/api/community/servers/${serverId}/icon`, {+ method: "POST",+ headers: headers("alice"),+ body: form,+ })+ expect(response.status).toBe(200)+}++async function status(+ key: "alice" | "bob" | "carol",+ path: string,+ method = "GET",+): Promise<number> {+ return (await fetch(`${WEB_URL}${path}`, { method, headers: headers(key) })).status+}++test("existing channel/server deletes converge UI, WS, pending rows, linked media, and icon reads", async ({ asUser }) => {+ test.setTimeout(150_000)+ const stamp = Date.now()+ const channelServerId = await seedServer("alice", `C1 channel ${stamp}`)+ const channelId = await seedChannel("alice", channelServerId, `delete-media-${stamp}`, "text")+ await seedJoinServer("alice", "bob", channelServerId)+ const linkedChannelAttachment = await uploadPending("alice", channelId, "linked-channel.png", true)+ const pendingChannelAttachment = await uploadPending("alice", channelId, "pending-channel.png", true)+ await linkAttachment("alice", channelId, linkedChannelAttachment)++ const serverId = await seedServer("alice", `C1 server ${stamp}`)+ const serverChannelId = await seedChannel("alice", serverId, `delete-server-${stamp}`, "text")+ await seedJoinServer("alice", "bob", serverId)+ const linkedServerAttachment = await uploadPending("alice", serverChannelId, "linked-server.png", true)+ const pendingServerAttachment = await uploadPending("alice", serverChannelId, "pending-server.png", true)+ await linkAttachment("alice", serverChannelId, linkedServerAttachment)+ await uploadServerIcon(serverId)++ const alice = await asUser("alice")+ const bob = await asUser("bob")+ const aliceDeletes = captureDeletes(alice.page)+ const bobDeletes = captureDeletes(bob.page)++ await gotoAfterUserWsAuth(alice.page, `/c/channels/${channelServerId}/${channelId}`)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${channelServerId}/${channelId}`)+ await expect(bob.page.getByTestId(tid.channelRow(channelId))).toBeVisible()++ expect(await status("bob", `/api/community/channels/${channelId}`, "DELETE")).toBe(403)+ expect(await status("carol", `/api/community/channels/${channelId}`, "DELETE")).toBe(403)+ expect(await status("alice", `/api/community/channels/${channelId}/attachments/${linkedChannelAttachment}`)).toBe(200)++ const channelDeleteResponse = alice.page.waitForResponse((response) => (+ response.request().method() === "DELETE"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}`+ ))+ await alice.page.getByTestId(tid.channelRow(channelId)).click({ button: "right" })+ await alice.page.getByRole("menuitem", { name: "Delete channel" }).click()+ await alice.page.getByRole("button", { name: "Delete channel", exact: true }).click()+ expect((await channelDeleteResponse).status()).toBe(204)++ await expect(alice.page.getByTestId(tid.channelRow(channelId))).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.channelRow(channelId))).toHaveCount(0)+ await expect(alice.page).not.toHaveURL(new RegExp(`/${channelId}$`))+ await expect.poll(() => aliceDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)+ await expect.poll(() => bobDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)+ expect(await status("alice", `/api/community/channels/${channelId}/attachments/${linkedChannelAttachment}`)).toBe(404)+ expect(await status("alice", `/api/community/channels/${channelId}/attachments/${pendingChannelAttachment}`)).toBe(404)++ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${serverChannelId}`)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${serverChannelId}`)+ await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toBeVisible()+ expect(await status("bob", `/api/community/servers/${serverId}`, "DELETE")).toBe(403)+ expect(await status("carol", `/api/community/servers/${serverId}`, "DELETE")).toBe(403)+ expect(await status("alice", `/api/community/servers/${serverId}/icon`)).toBe(200)++ const serverDeleteResponse = alice.page.waitForResponse((response) => (+ response.request().method() === "DELETE"+ && new URL(response.url()).pathname === `/api/community/servers/${serverId}`+ ))+ await alice.page.getByTestId(tid.serverIcon(serverId)).click({ button: "right" })+ await alice.page.getByTestId(tid.serverSettingsOpen).click()+ await expect(alice.page.getByTestId(tid.settingsShell)).toBeVisible()+ await alice.page.getByRole("button", { name: "Delete Server", exact: true }).click()+ await alice.page.getByRole("dialog").getByRole("button", {+ name: "Delete Server",+ exact: true,+ }).click()+ expect((await serverDeleteResponse).status()).toBe(204)++ await expect(alice.page).toHaveURL(/\/c\/me(?:\/friends)?$/)+ await expect(alice.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.channelRow(serverChannelId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)+ await expect.poll(() => aliceDeletes.frames.filter((frame) => (+ frame.type === "community:server.delete" && frame.serverId === serverId+ ))).toHaveLength(1)+ await expect.poll(() => bobDeletes.frames.filter((frame) => (+ frame.type === "community:server.delete" && frame.serverId === serverId+ ))).toHaveLength(1)+ expect(await status("alice", `/api/community/servers/${serverId}/icon`)).toBe(404)+ expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${linkedServerAttachment}`)).toBe(404)+ expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${pendingServerAttachment}`)).toBe(404)++ await alice.page.goBack()+ await expect(alice.page).not.toHaveURL(new RegExp(`/c/channels/${serverId}/`))+ await expect(alice.page).toHaveURL(/\/c\/channels\/[^/]+\/[^/]+$/)+ const siblingRoute = new URL(alice.page.url()).pathname.match(/^\/c\/channels\/([^/]+)\/([^/]+)$/)+ expect(siblingRoute).not.toBeNull()+ const [, siblingServerId, siblingChannelId] = siblingRoute!+ expect(siblingServerId).not.toBe(serverId)+ expect(siblingChannelId).not.toBe(channelId)+ expect(siblingChannelId).not.toBe(serverChannelId)+ const liveServersResponse = await fetch(`${WEB_URL}/api/community/servers`, { headers: headers("alice") })+ expect(liveServersResponse.status).toBe(200)+ const liveServers = await liveServersResponse.json() as { servers: Array<{ id: string }> }+ expect(liveServers.servers.some(({ id }) => id === siblingServerId)).toBe(true)+ expect(liveServers.servers.some(({ id }) => id === serverId)).toBe(false)+ expect(await status("alice", `/api/community/channels/${siblingChannelId}`)).toBe(200)+ await expect(alice.page.getByTestId(tid.serverIcon(siblingServerId))).toBeVisible()+ await expect(alice.page.getByTestId(tid.channelRow(siblingChannelId))).toBeVisible()+ await alice.page.reload()+ await expect(alice.page).toHaveURL(new RegExp(`/c/channels/${siblingServerId}/${siblingChannelId}$`))+ await expect(alice.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.channelRow(serverChannelId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.serverIcon(siblingServerId))).toBeVisible()+ await expect(alice.page.getByTestId(tid.channelRow(siblingChannelId))).toBeVisible()+ await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()+})diff --git a/src/web/test-runtime/community-delete-media.runtime.test.ts b/src/web/test-runtime/community-delete-media.runtime.test.tsnew file mode 100644index 000000000..b37be2658--- /dev/null+++ b/src/web/test-runtime/community-delete-media.runtime.test.ts@@ -0,0 +1,288 @@+/// <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 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")+}++async function seedOwnerAndServer(icon: string | null = null) {+ const stamp = crypto.randomUUID().replaceAll("-", "")+ const owner = `cdm_owner_${stamp}`+ const server = `cdm_server_${stamp}`+ createdUsers.push(owner)+ createdServers.push(server)+ await run(+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Owner', ?)",+ owner,+ `${owner}@example.com`,+ stamp4(owner),+ )+ await run(+ "INSERT INTO community_server (id, name, description, icon, owner_id, discriminator, created_at) VALUES (?, ?, '', ?, ?, ?, '2026-08-23T00:00:00.000Z')",+ server,+ server,+ icon,+ owner,+ stamp4(server),+ )+ return { owner, server, stamp }+}++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("existing delete media real D1 batches", () => {+ it("channel deletion snapshots root/child linked and pending keys for exactly one winner", async () => {+ const { owner, server, stamp } = await seedOwnerAndServer()+ const root = `cdm_root_${stamp}`+ const child = `cdm_child_${stamp}`+ const unrelated = `cdm_other_${stamp}`+ const rootMessage = `cdm_rm_${stamp}`+ const childMessage = `cdm_cm_${stamp}`+ const unrelatedMessage = `cdm_um_${stamp}`+ await run(+ `INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES+ (?, ?, 'root', 'text', '2026-08-23T00:00:00.000Z'),+ (?, ?, 'child', 'thread', '2026-08-23T00:00:00.000Z'),+ (?, ?, 'other', 'text', '2026-08-23T00:00:00.000Z')`,+ root, server,+ child, server,+ unrelated, server,+ )+ await run("UPDATE community_channel SET parent_channel_id = ? WHERE id = ?", root, child)+ await run(+ `INSERT INTO community_message (id, author_id, content, channel_id, seq, created_at) VALUES+ (?, ?, 'root', ?, 1, '2026-08-23T00:00:00.000Z'),+ (?, ?, 'child', ?, 1, '2026-08-23T00:00:00.000Z'),+ (?, ?, 'other', ?, 1, '2026-08-23T00:00:00.000Z')`,+ rootMessage, owner, root,+ childMessage, owner, child,+ unrelatedMessage, owner, unrelated,+ )+ await run(+ `INSERT INTO community_attachment+ (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at) VALUES+ (?, ?, ?, ?, 'root/original', 'root/thumb', 'root.png', '2026-08-23T00:00:00.000Z'),+ (?, ?, ?, ?, 'child/original', 'child/thumb', 'child.png', '2026-08-23T00:00:00.000Z'),+ (?, NULL, ?, ?, 'root/pending', 'root/pending-thumb', 'pending-root.png', '2026-08-23T00:00:00.000Z'),+ (?, NULL, ?, ?, 'child/pending', NULL, 'pending-child.png', '2026-08-23T00:00:00.000Z'),+ (?, ?, ?, ?, 'other/original', 'other/thumb', 'other.png', '2026-08-23T00:00:00.000Z')`,+ `att_root_${stamp}`, rootMessage, owner, unrelated,+ `att_child_${stamp}`, childMessage, owner, unrelated,+ `att_pending_root_${stamp}`, owner, root,+ `att_pending_child_${stamp}`, owner, child,+ `att_other_${stamp}`, unrelatedMessage, owner, unrelated,+ )++ const db = createDb(runtimeEnv.DB)+ const results = await Promise.all([+ queries.communityDeleteMedia.deleteChannelWithMedia(db, { channelId: root, serverId: server }),+ queries.communityDeleteMedia.deleteChannelWithMedia(db, { channelId: root, serverId: server }),+ ])++ expect(results.filter((result) => result.deleted)).toHaveLength(1)+ const winner = results.find((result) => result.deleted)!+ expect(new Set(winner.mediaKeys)).toEqual(new Set([+ "root/original", "root/thumb", "child/original", "child/thumb",+ "root/pending", "root/pending-thumb", "child/pending",+ ]))+ expect(results.find((result) => !result.deleted)?.mediaKeys).toEqual([])+ expect(await first("SELECT id FROM community_channel WHERE id = ?", root)).toBeNull()+ expect(await first("SELECT id FROM community_channel WHERE id = ?", child)).toBeNull()+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_pending_child_${stamp}`)).toBeNull()+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_other_${stamp}`)).not.toBeNull()+ })++ it("server deletion is owner-scoped and returns attachment keys plus the winner icon once", async () => {+ const icon = "server-icon/runtime/icon-a"+ const { owner, server, stamp } = await seedOwnerAndServer(icon)+ const channel = `cdm_server_channel_${stamp}`+ const message = `cdm_server_message_${stamp}`+ await run(+ "INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, 'all', 'text', '2026-08-23T00:00:00.000Z')",+ channel, server,+ )+ await run(+ "INSERT INTO community_message (id, author_id, content, channel_id, seq, created_at) VALUES (?, ?, 'hello', ?, 1, '2026-08-23T00:00:00.000Z')",+ message, owner, channel,+ )+ await run(+ `INSERT INTO community_attachment+ (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at) VALUES+ (?, ?, ?, ?, 'server/original', 'server/thumb', 'linked.png', '2026-08-23T00:00:00.000Z'),+ (?, NULL, ?, ?, 'server/pending', NULL, 'pending.png', '2026-08-23T00:00:00.000Z')`,+ `att_server_${stamp}`, message, owner, channel,+ `att_server_pending_${stamp}`, owner, channel,+ )++ const db = createDb(runtimeEnv.DB)+ await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {+ serverId: server,+ ownerId: "not-owner",+ })).resolves.toEqual({ deleted: false, mediaKeys: [], iconKey: null })++ const results = await Promise.all([+ queries.communityDeleteMedia.deleteServerWithMedia(db, { serverId: server, ownerId: owner }),+ queries.communityDeleteMedia.deleteServerWithMedia(db, { serverId: server, ownerId: owner }),+ ])+ expect(results.filter((result) => result.deleted)).toHaveLength(1)+ expect(results.find((result) => result.deleted)).toEqual({+ deleted: true,+ mediaKeys: ["server/original", "server/thumb", "server/pending"],+ iconKey: icon,+ })+ expect(results.find((result) => !result.deleted)).toEqual({+ deleted: false,+ mediaKeys: [],+ iconKey: null,+ })+ expect(await first("SELECT id FROM community_server WHERE id = ?", server)).toBeNull()+ })+})++describe("guarded pending insert and server icon CAS in real D1", () => {+ it("accepts a live DM target with type=dm and server_id NULL", async () => {+ const { owner, stamp } = await seedOwnerAndServer()+ const dm = `cdm_dm_${stamp}`+ const attachment = `att_dm_${stamp}`+ await run(+ "INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, NULL, NULL, 'dm', '2026-08-23T00:00:00.000Z')",+ dm,+ )++ const db = createDb(runtimeEnv.DB)+ await expect(queries.communityAttachment.createPendingAttachment(db, {+ id: attachment,+ uploaderId: owner,+ targetId: dm,+ r2Key: "pending/dm-live",+ filename: "dm-live.png",+ })).resolves.toMatchObject({ id: attachment, targetId: dm, messageId: null })+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", attachment)).not.toBeNull()++ await run("DELETE FROM community_attachment WHERE id = ?", attachment)+ await run("DELETE FROM community_channel WHERE id = ?", dm)+ })++ it("inserts only while the target channel exists", async () => {+ const { owner, server, stamp } = await seedOwnerAndServer()+ const channel = `cdm_pending_${stamp}`+ await run(+ "INSERT INTO community_channel (id, server_id, name, type, created_at) VALUES (?, ?, 'pending', 'text', '2026-08-23T00:00:00.000Z')",+ channel, server,+ )+ const db = createDb(runtimeEnv.DB)+ const inserted = await queries.communityAttachment.createPendingAttachment(db, {+ id: `att_live_${stamp}`,+ uploaderId: owner,+ targetId: channel,+ r2Key: "pending/live",+ thumbnailR2Key: "pending/live-thumb",+ filename: "live.png",+ })+ expect(inserted.targetId).toBe(channel)++ await queries.communityDeleteMedia.deleteChannelWithMedia(db, {+ channelId: channel,+ serverId: server,+ })+ await expect(queries.communityAttachment.createPendingAttachment(db, {+ id: `att_deleted_${stamp}`,+ uploaderId: owner,+ targetId: channel,+ r2Key: "pending/deleted",+ filename: "deleted.png",+ })).rejects.toThrow("attachment target no longer exists")+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_deleted_${stamp}`)).toBeNull()+ })++ it("uses a null-safe old-value CAS with exactly one concurrent winner", async () => {+ const { server } = await seedOwnerAndServer(null)+ const db = createDb(runtimeEnv.DB)+ const contenders = await Promise.all([+ queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: null,+ nextIcon: `server-icon/${server}/b`,+ }),+ queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: null,+ nextIcon: `server-icon/${server}/c`,+ }),+ ])+ expect(contenders.filter(Boolean)).toHaveLength(1)+ const live = await first<{ icon: string }>("SELECT icon FROM community_server WHERE id = ?", server)+ expect([`server-icon/${server}/b`, `server-icon/${server}/c`]).toContain(live?.icon)++ await expect(queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: null,+ nextIcon: `server-icon/${server}/stale`,+ })).resolves.toBeNull()+ await expect(queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: live!.icon,+ nextIcon: `server-icon/${server}/next`,+ })).resolves.toMatchObject({ icon: `server-icon/${server}/next` })+ })++ it("linearizes icon replacement before server deletion at the CAS", async () => {+ const { owner, server } = await seedOwnerAndServer(`server-icon/runtime/${crypto.randomUUID()}`)+ const db = createDb(runtimeEnv.DB)+ const replacement = `server-icon/${server}/replacement`++ await expect(queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: (await first<{ icon: string }>(+ "SELECT icon FROM community_server WHERE id = ?",+ server,+ ))!.icon,+ nextIcon: replacement,+ })).resolves.toMatchObject({ icon: replacement })++ await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {+ serverId: server,+ ownerId: owner,+ })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: replacement })+ })++ it("linearizes server deletion before a stale icon replacement at the delete", async () => {+ const original = `server-icon/runtime/${crypto.randomUUID()}`+ const { owner, server } = await seedOwnerAndServer(original)+ const db = createDb(runtimeEnv.DB)++ await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {+ serverId: server,+ ownerId: owner,+ })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: original })+ await expect(queries.communityServer.updateServerIconIfCurrent(db, {+ serverId: server,+ expectedIcon: original,+ nextIcon: `server-icon/${server}/stale-replacement`,+ })).resolves.toBeNull()+ })+})