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 bot avatars on delete (#532)
Genera676f4a0e5d1
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 56b81467c..78f7e564f 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -36,6 +36,7 @@ export const SPEC_SECONDS = {"26-mobile-forum-post-actions.spec.ts": 45,"27-canonical-forum-post-delete.spec.ts": 30,"28-community-delete-media-cleanup.spec.ts": 45,+ "29-community-bot-avatar-cleanup.spec.ts": 15,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex e502e1d98..1e13a6623 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([198, 200, 201, 202, 202])+ expect(totals.sort((left, right) => left - right)).toEqual([202, 203, 204, 204, 205])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 16e0c2ee8..d41eadbda 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -176,6 +176,32 @@ export async function getBotOwnedBy(};}+/**+ * Public-read projection for the canonical bot-avatar door.+ *+ * This is the deliberate non-owner exception: authenticated server members+ * and DM peers may render a live bot's avatar. The predicate still fails+ * closed for missing, human, and tombstoned user rows, and the projection is+ * intentionally limited to the two fields the door needs.+ */+export async function getLiveBotAvatar(+ db: Database,+ botId: string+): Promise<{ id: string; image: string | null } | null> {+ const rows = await db+ .select({ id: user.id, image: user.image })+ .from(user)+ .where(+ and(+ eq(user.id, botId),+ eq(user.isBot, true),+ isNull(user.deletedAt)+ )+ )+ .limit(1);+ return rows[0] ?? null;+}+/** Cheap ownership probe used by ack/error paths. */export async function countLiveBotsForOwner(db: Database,diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex e81ae21dd..f72b797d8 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -18,6 +18,7 @@ describe("community/bot exports", () => {it("exposes read helpers", () => {expect(typeof q.listBotsForOwner).toBe("function")expect(typeof q.getBotOwnedBy).toBe("function")+ expect(typeof q.getLiveBotAvatar).toBe("function")expect(typeof q.countLiveBotsForOwner).toBe("function")expect(typeof q.getBotBinding).toBe("function")expect(typeof q.listBotsForMachine).toBe("function")diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.test.tsindex fec41dea9..3db97293e 100644--- a/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts@@ -3,8 +3,9 @@ import { NextRequest } from "next/server"const mediaGet = vi.fn()const mockGetBotOwnedBy = vi.fn()-const mockUpdateBot = vi.fn()+const mockGetLiveBotAvatar = vi.fn()const mockHandleBotAvatarUpload = vi.fn()+const mockPersistUploadedBotAvatar = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } } })),@@ -19,7 +20,7 @@ vi.mock("@alook/shared", async () => {queries: {communityBot: {getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),- updateBot: (...a: unknown[]) => mockUpdateBot(...a),+ getLiveBotAvatar: (...a: unknown[]) => mockGetLiveBotAvatar(...a),},},}@@ -29,6 +30,10 @@ vi.mock("@/lib/community/upload", () => ({handleBotAvatarUpload: (...a: unknown[]) => mockHandleBotAvatarUpload(...a),}))+vi.mock("@/lib/community/bot-avatar-persistence", () => ({+ persistUploadedBotAvatar: (...a: unknown[]) => mockPersistUploadedBotAvatar(...a),+}))+let isAuthed = truevi.mock("@/lib/middleware/auth", () => ({@@ -71,6 +76,10 @@ describe("GET /api/community/bots/[id]/avatar", () => {beforeEach(() => {vi.clearAllMocks()isAuthed = true+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ })mediaGet.mockResolvedValue({body: new ReadableStream(),httpMetadata: { contentType: "image/webp" },@@ -85,12 +94,27 @@ describe("GET /api/community/bots/[id]/avatar", () => {expect(mediaGet).not.toHaveBeenCalled()})- it("serves the avatar by the deterministic bot-avatar/{botId} key with no ownership check (DM peers/members need it)", async () => {+ it("serves a live canonical avatar by the deterministic key without an owner check", async () => {const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(200)expect(res.headers.get("Content-Type")).toBe("image/webp")expect(mediaGet).toHaveBeenCalledWith("bot-avatar/b1")expect(mockGetBotOwnedBy).not.toHaveBeenCalled()+ expect(mockGetLiveBotAvatar).toHaveBeenCalledWith(expect.anything(), "b1")+ })++ it("returns 404 before R2 for a missing, tombstoned, or non-bot row", async () => {+ mockGetLiveBotAvatar.mockResolvedValue(null)+ const res = await GET(getReq(), ctx("b1"))+ expect(res.status).toBe(404)+ expect(mediaGet).not.toHaveBeenCalled()+ })++ it("returns 404 before R2 for a live bot with a noncanonical image", async () => {+ mockGetLiveBotAvatar.mockResolvedValue({ id: "b1", image: "avatar:beam-seed" })+ const res = await GET(getReq(), ctx("b1"))+ expect(res.status).toBe(404)+ expect(mediaGet).not.toHaveBeenCalled()})it("returns 400 when the bot id route param is missing", async () => {@@ -128,7 +152,7 @@ describe("POST /api/community/bots/[id]/avatar", () => {vi.clearAllMocks()isAuthed = truemockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerId: "u1" })- mockUpdateBot.mockResolvedValue(undefined)+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "persisted" })mockHandleBotAvatarUpload.mockResolvedValue({ok: true,id: "b1",@@ -162,7 +186,7 @@ describe("POST /api/community/bots/[id]/avatar", () => {})const res = await POST(postReq(), ctx("b1"))expect(res.status).toBe(413)- expect(mockUpdateBot).not.toHaveBeenCalled()+ expect(mockPersistUploadedBotAvatar).not.toHaveBeenCalled()})it("uploads and updates the bot's image to the routable avatar URL", async () => {@@ -170,6 +194,22 @@ describe("POST /api/community/bots/[id]/avatar", () => {expect(res.status).toBe(200)const body = await res.json() as { url: string }expect(body.url).toBe("/api/community/bots/b1/avatar")- expect(mockUpdateBot).toHaveBeenCalledWith(expect.anything(), "b1", "u1", { image: "/api/community/bots/b1/avatar" })+ expect(mockPersistUploadedBotAvatar).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ { botId: "b1", ownerId: "u1" },+ )+ })++ it("returns 404 when the upload loses to delete after R2 PUT", async () => {+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "not_found" })+ const res = await POST(postReq(), ctx("b1"))+ expect(res.status).toBe(404)+ })++ it("returns 500 for an ambiguous D1 persistence failure", async () => {+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "failed" })+ const res = await POST(postReq(), ctx("b1"))+ expect(res.status).toBe(500)})})diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.tsindex 99a13a424..c921104ef 100644--- a/src/web/src/app/api/community/bots/[id]/avatar/route.ts+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.ts@@ -5,6 +5,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { handleBotAvatarUpload } from "@/lib/community/upload"import { buildBotAvatarKey, botAvatarUrl } from "@/lib/community/storage"+import { persistUploadedBotAvatar } from "@/lib/community/bot-avatar-persistence"// No ownership check — other members/DM peers need to see a bot's avatar.//@@ -15,6 +16,12 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const botId = ctx.params?.idif (!botId) return writeError("missing bot id", 400)+ const db = getDb(ctx.env.DB)+ const bot = await queries.communityBot.getLiveBotAvatar(db, botId)+ if (!bot || bot.image !== botAvatarUrl(botId)) {+ return writeError("not found", 404)+ }+const obj = await ctx.env.COMMUNITY_MEDIA.get(buildBotAvatarKey(botId))if (!obj) return writeError("not found", 404)@@ -44,7 +51,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!result.ok) return result.responseconst url = botAvatarUrl(botId)- await queries.communityBot.updateBot(db, botId, ctx.userId, { image: url })+ const persisted = await persistUploadedBotAvatar(db, ctx.env.COMMUNITY_MEDIA, {+ botId,+ ownerId: ctx.userId,+ })+ if (persisted.kind === "not_found") return writeError("bot not found", 404)+ if (persisted.kind === "failed") return writeError("internal error", 500)return writeJSON({ url })})diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.tsindex 5fe176d6f..3f848b5c4 100644--- a/src/web/src/app/api/community/bots/[id]/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts@@ -12,9 +12,15 @@ const mockPushBotEventToMachine = vi.fn()const mockPushAgentModelSwitchToMachine = vi.fn()const mockPushAgentProviderSwitchToMachine = vi.fn()const mockLogError = vi.fn()+const mockListBotServerMemberships = vi.fn()+const mockSoftDeleteBot = vi.fn()+const mockFanOutToServerMembers = vi.fn()+const mockGetCloudflareContext = vi.fn()+const mockWaitUntil = vi.fn()+const mockMediaDelete = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ getCloudflareContext: (...args: unknown[]) => mockGetCloudflareContext(...args),}))vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -36,6 +42,8 @@ vi.mock("@alook/shared", async () => {updateBotModel: (...a: unknown[]) => mockUpdateBotModel(...a),updateBotRuntime: (...a: unknown[]) => mockUpdateBotRuntime(...a),getMachineForOwner: (...a: unknown[]) => mockGetMachineForOwner(...a),+ listBotServerMemberships: (...a: unknown[]) => mockListBotServerMemberships(...a),+ softDeleteBot: (...a: unknown[]) => mockSoftDeleteBot(...a),},communityMachine: {isBotOnline: (...a: unknown[]) => mockIsBotOnline(...a),@@ -56,13 +64,18 @@ vi.mock("@/lib/broadcast", () => ({broadcastToUser: vi.fn(),}))vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: vi.fn(),+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),}))vi.mock("@/lib/middleware/auth", () => ({withAuth: (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: (...a: unknown[]) => mockMediaDelete(...a) } },+ userId: "u1",+ email: "[email protected]",+ params,+ })},}))@@ -76,7 +89,7 @@ vi.mock("@/lib/middleware/helpers", async () => {}})-import { PATCH } from "./route"+import { DELETE, PATCH } from "./route"function patchReq(body: unknown) {return new NextRequest("http://localhost/api/community/bots/b1", {@@ -347,3 +360,95 @@ describe("PATCH /api/community/bots/[id]", () => {expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()})})++describe("DELETE /api/community/bots/[id]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCloudflareContext.mockResolvedValue({ ctx: { waitUntil: mockWaitUntil } })+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1",+ ownerUserId: "u1",+ machineId: "mac1",+ })+ mockListBotServerMemberships.mockResolvedValue(["s1", "s2"])+ mockSoftDeleteBot.mockResolvedValue(true)+ mockMediaDelete.mockResolvedValue(undefined)+ mockPushBotEventToMachine.mockResolvedValue(undefined)+ })++ function deleteReq() {+ return new NextRequest("http://localhost/api/community/bots/b1", { method: "DELETE" })+ }++ it("fails before D1 mutation, WS, daemon, and R2 when ExecutionContext is unavailable", async () => {+ mockGetCloudflareContext.mockRejectedValue(new Error("no context"))++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(500)+ expect(mockSoftDeleteBot).not.toHaveBeenCalled()+ expect(mockMediaDelete).not.toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()+ })++ it("registers fixed-key cleanup only for the D1 winner, then preserves existing events", async () => {+ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockSoftDeleteBot).toHaveBeenCalledWith(expect.anything(), "b1", "u1")+ expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockWaitUntil).toHaveBeenCalledOnce()+ expect(mockFanOutToServerMembers).toHaveBeenCalledTimes(2)+ expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {+ type: "community:member.leave",+ serverId: "s1",+ userId: "b1",+ })+ expect(mockPushBotEventToMachine).toHaveBeenCalledWith(+ expect.anything(),+ "mac1",+ { type: "bot:removed", botId: "b1" },+ )+ expect(mockMediaDelete.mock.invocationCallOrder[0]!).toBeLessThan(+ mockFanOutToServerMembers.mock.invocationCallOrder[0]!,+ )+ })++ it("returns 404 with no cleanup or events for an already-deleted loser", async () => {+ mockSoftDeleteBot.mockResolvedValue(false)++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(404)+ expect(mockMediaDelete).not.toHaveBeenCalled()+ expect(mockWaitUntil).not.toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()+ })++ it("keeps the committed 204 and events when waitUntil throws synchronously", async () => {+ mockWaitUntil.mockImplementation(() => {+ throw new Error("sync waitUntil failure")+ })++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockFanOutToServerMembers).toHaveBeenCalledTimes(2)+ expect(mockPushBotEventToMachine).toHaveBeenCalledOnce()+ })++ it("keeps the committed 204 when background R2 deletion rejects", async () => {+ mockMediaDelete.mockRejectedValue(new Error("provider secret"))++ const res = await DELETE(deleteReq(), ctx)+ const cleanup = mockWaitUntil.mock.calls[0]![0] as Promise<void>+ await expect(cleanup).resolves.toBeUndefined()++ expect(res.status).toBe(204)+ expect(mockFanOutToServerMembers).toHaveBeenCalledTimes(2)+ expect(mockPushBotEventToMachine).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex ba1ffbe8f..a8edc5521 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -1,5 +1,6 @@import { NextRequest } from "next/server"import { NextResponse } from "next/server"+import { getCloudflareContext } from "@opennextjs/cloudflare"import { nanoid } from "nanoid"import {queries,@@ -19,6 +20,8 @@ import {pushAgentProviderSwitchToMachine,} from "@/lib/community/bot-push"import { fanOutToServerMembers } from "@/lib/community/fanout"+import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"+import { buildBotAvatarKey } from "@/lib/community/storage"const log = createLogger({ service: "community-bot-update" })@@ -184,9 +187,24 @@ export const DELETE = withAuth(async (_req, ctx) => {ctx.userId,)+ let executionContext: ExecutionContext+ try {+ ({ ctx: executionContext } = await getCloudflareContext({ async: true }))+ } catch {+ return writeError("internal error", 500)+ }+const ok = await queries.communityBot.softDeleteBot(db, id, ctx.userId)if (!ok) return writeError("bot not found", 404)+ scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {+ keys: [buildBotAvatarKey(id)],+ warning: {+ event: "community_bot_avatar_cleanup_failed",+ fields: { botId: id, phase: "bot_delete" },+ },+ })+for (const serverId of priorMemberships) {fanOutToServerMembers(serverId, {type: WS_EVENTS.MEMBER_LEAVE,diff --git a/src/web/src/app/api/community/machines/[id]/route.test.ts b/src/web/src/app/api/community/machines/[id]/route.test.tsnew file mode 100644index 000000000..d69506219--- /dev/null+++ b/src/web/src/app/api/community/machines/[id]/route.test.ts@@ -0,0 +1,208 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const mockGetCloudflareContext = vi.fn()+const mockWaitUntil = vi.fn()+const mockMediaDelete = vi.fn()+const mockGetMachineByIdForUser = vi.fn()+const mockListBotsBoundToMachine = vi.fn()+const mockListBotServerMemberships = vi.fn()+const mockSoftDeleteBot = vi.fn()+const mockRevokeCredentialsForMachine = vi.fn()+const mockRevokeRunnerKeysForMachine = vi.fn()+const mockDeleteMachineForUser = vi.fn()+const mockForceCloseCommunityMachinesByDoNames = vi.fn()+const mockFanOutToServerMembers = vi.fn()+const mockBroadcastToUserSafe = vi.fn()++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: (...args: unknown[]) => mockGetCloudflareContext(...args),+}))++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: {+ listBotsBoundToMachine: (...args: unknown[]) => mockListBotsBoundToMachine(...args),+ listBotServerMemberships: (...args: unknown[]) => mockListBotServerMemberships(...args),+ softDeleteBot: (...args: unknown[]) => mockSoftDeleteBot(...args),+ },+ communityMachine: {+ getMachineByIdForUser: (...args: unknown[]) => mockGetMachineByIdForUser(...args),+ revokeCredentialsForMachine: (...args: unknown[]) => mockRevokeCredentialsForMachine(...args),+ revokeRunnerKeysForMachine: (...args: unknown[]) => mockRevokeRunnerKeysForMachine(...args),+ deleteMachineForUser: (...args: unknown[]) => mockDeleteMachineForUser(...args),+ },+ },+ }+})++vi.mock("@/lib/community/machine-disconnect", () => ({+ forceCloseCommunityMachinesByDoNames: (...args: unknown[]) =>+ mockForceCloseCommunityMachinesByDoNames(...args),+}))++vi.mock("@/lib/community/fanout", () => ({+ fanOutToServerMembers: (...args: unknown[]) => mockFanOutToServerMembers(...args),+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),+}))++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, {+ env: { DB: {}, COMMUNITY_MEDIA: { delete: (...args: unknown[]) => mockMediaDelete(...args) } },+ userId: "u1",+ email: "[email protected]",+ params,+ })+ },+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { DELETE } from "./route"++function request(cascade?: boolean) {+ return new NextRequest("http://localhost/api/community/machines/m1", {+ method: "DELETE",+ headers: cascade === undefined ? undefined : { "Content-Type": "application/json" },+ body: cascade === undefined ? undefined : JSON.stringify({ cascade }),+ })+}++const ctx = { params: Promise.resolve({ id: "m1" }) } as any++describe("DELETE /api/community/machines/[id]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMachineByIdForUser.mockResolvedValue({ id: "m1", userId: "u1" })+ mockListBotsBoundToMachine.mockResolvedValue([])+ mockListBotServerMemberships.mockResolvedValue([])+ mockSoftDeleteBot.mockResolvedValue(true)+ mockRevokeCredentialsForMachine.mockResolvedValue({ doNames: ["do-1"] })+ mockRevokeRunnerKeysForMachine.mockResolvedValue(undefined)+ mockForceCloseCommunityMachinesByDoNames.mockResolvedValue(undefined)+ mockDeleteMachineForUser.mockResolvedValue({ id: "m1" })+ mockBroadcastToUserSafe.mockResolvedValue(undefined)+ mockMediaDelete.mockResolvedValue(undefined)+ mockGetCloudflareContext.mockResolvedValue({ ctx: { waitUntil: mockWaitUntil } })+ })++ it("keeps the existing 409 and does not acquire context when bots exist without cascade", async () => {+ mockListBotsBoundToMachine.mockResolvedValue([{ id: "b1", name: "Bot" }])++ const res = await DELETE(request(), ctx)++ expect(res.status).toBe(409)+ expect(await res.json()).toEqual({+ error: "MACHINE_HAS_BOTS",+ bots: [{ id: "b1", name: "Bot" }],+ })+ expect(mockGetCloudflareContext).not.toHaveBeenCalled()+ expect(mockSoftDeleteBot).not.toHaveBeenCalled()+ expect(mockDeleteMachineForUser).not.toHaveBeenCalled()+ })++ it("keeps the zero-bot path free of ExecutionContext and avatar cleanup", async () => {+ const res = await DELETE(request(), ctx)++ expect(res.status).toBe(204)+ expect(mockGetCloudflareContext).not.toHaveBeenCalled()+ expect(mockWaitUntil).not.toHaveBeenCalled()+ expect(mockMediaDelete).not.toHaveBeenCalled()+ expect(mockDeleteMachineForUser).toHaveBeenCalledWith(expect.anything(), "u1", "m1")+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {+ type: "community:machine.removed",+ machineId: "m1",+ })+ })++ it("fails before the first bot mutation when nonempty cascade cannot acquire context", async () => {+ mockListBotsBoundToMachine.mockResolvedValue([{ id: "b1", name: "Bot" }])+ mockGetCloudflareContext.mockRejectedValue(new Error("no context"))++ const res = await DELETE(request(true), ctx)++ expect(res.status).toBe(500)+ expect(mockListBotServerMemberships).not.toHaveBeenCalled()+ expect(mockSoftDeleteBot).not.toHaveBeenCalled()+ expect(mockRevokeCredentialsForMachine).not.toHaveBeenCalled()+ expect(mockDeleteMachineForUser).not.toHaveBeenCalled()+ })++ it("cleans and fans out only per-bot D1 winners in a mixed cascade", async () => {+ mockListBotsBoundToMachine.mockResolvedValue([+ { id: "b1", name: "One" },+ { id: "b2", name: "Two" },+ ])+ mockListBotServerMemberships+ .mockResolvedValueOnce(["s1"])+ .mockResolvedValueOnce(["s2"])+ mockSoftDeleteBot.mockResolvedValueOnce(true).mockResolvedValueOnce(false)++ const res = await DELETE(request(true), ctx)++ expect(res.status).toBe(204)+ expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockWaitUntil).toHaveBeenCalledOnce()+ expect(mockFanOutToServerMembers).toHaveBeenCalledOnce()+ expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {+ type: "community:member.leave",+ serverId: "s1",+ userId: "b1",+ })+ })++ it("finally registers earlier winner cleanup when a later bot delete throws", async () => {+ mockListBotsBoundToMachine.mockResolvedValue([+ { id: "b1", name: "One" },+ { id: "b2", name: "Two" },+ ])+ mockSoftDeleteBot+ .mockResolvedValueOnce(true)+ .mockRejectedValueOnce(new Error("later D1 failure"))++ await expect(DELETE(request(true), ctx)).rejects.toThrow("later D1 failure")++ expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockWaitUntil).toHaveBeenCalledOnce()+ expect(mockRevokeCredentialsForMachine).not.toHaveBeenCalled()+ })++ it("finally registers the current winner before a synchronous member fanout failure escapes", async () => {+ mockListBotsBoundToMachine.mockResolvedValue([{ id: "b1", name: "One" }])+ mockListBotServerMemberships.mockResolvedValue(["s1"])+ mockFanOutToServerMembers.mockImplementation(() => {+ throw new Error("fanout setup failure")+ })++ await expect(DELETE(request(true), ctx)).rejects.toThrow("fanout setup failure")++ expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockWaitUntil).toHaveBeenCalledOnce()+ })++ it("characterizes the existing machine-level duplicate winner behavior without changing it", async () => {+ mockDeleteMachineForUser.mockResolvedValue(null)++ const res = await DELETE(request(), ctx)++ expect(res.status).toBe(204)+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {+ type: "community:machine.removed",+ machineId: "m1",+ })+ })+})diff --git a/src/web/src/app/api/community/machines/[id]/route.ts b/src/web/src/app/api/community/machines/[id]/route.tsindex 564f1afb7..f5d4768e2 100644--- a/src/web/src/app/api/community/machines/[id]/route.ts+++ b/src/web/src/app/api/community/machines/[id]/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from "next/server"+import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, WS_EVENTS } from "@alook/shared"import type { CommunityWsEvent } from "@alook/shared"import { getDb } from "@/lib/db"@@ -6,6 +7,8 @@ import { withAuth } from "@/lib/middleware/auth"import { writeError, writeJSON } from "@/lib/middleware/helpers"import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"+import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"+import { buildBotAvatarKey } from "@/lib/community/storage"export const DELETE = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)@@ -31,18 +34,42 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ error: "MACHINE_HAS_BOTS", bots }, 409)}+ let executionContext: ExecutionContext | null = null+ if (bots.length > 0) {+ try {+ ({ ctx: executionContext } = await getCloudflareContext({ async: true }))+ } catch {+ return writeError("internal error", 500)+ }+ }+// Soft-delete every bot bound to this machine (bots page cascade). Snapshot// each bot's server memberships BEFORE the delete removes them, so we can// fan out MEMBER_LEAVE per (server, botId) after each delete commits.- for (const bot of bots) {- const priorMemberships =- await queries.communityBot.listBotServerMemberships(db, bot.id, ctx.userId)- await queries.communityBot.softDeleteBot(db, bot.id, ctx.userId)- for (const serverId of priorMemberships) {- fanOutToServerMembers(serverId, {- type: WS_EVENTS.MEMBER_LEAVE,- serverId,- userId: bot.id,+ const avatarKeys: string[] = []+ try {+ for (const bot of bots) {+ const priorMemberships =+ await queries.communityBot.listBotServerMemberships(db, bot.id, ctx.userId)+ const deleted = await queries.communityBot.softDeleteBot(db, bot.id, ctx.userId)+ if (!deleted) continue+ avatarKeys.push(buildBotAvatarKey(bot.id))+ for (const serverId of priorMemberships) {+ fanOutToServerMembers(serverId, {+ type: WS_EVENTS.MEMBER_LEAVE,+ serverId,+ userId: bot.id,+ })+ }+ }+ } finally {+ if (executionContext && avatarKeys.length > 0) {+ scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {+ keys: avatarKeys,+ warning: {+ event: "community_bot_avatar_cleanup_failed",+ fields: { machineId: id, phase: "machine_cascade" },+ },})}}diff --git a/src/web/src/app/api/community/users/me/avatar/route.test.ts b/src/web/src/app/api/community/users/me/avatar/route.test.tsindex 734fa1fdb..bb909a3a6 100644--- a/src/web/src/app/api/community/users/me/avatar/route.test.ts+++ b/src/web/src/app/api/community/users/me/avatar/route.test.ts@@ -3,7 +3,8 @@ import { NextRequest } from "next/server"const mockHandleUserAvatarUpload = vi.fn()const mockHandleBotAvatarUpload = vi.fn()-const mockUpdateUser = vi.fn()+const mockGetBotOwnedBy = vi.fn()+const mockPersistUploadedBotAvatar = vi.fn()const mockAuthUpdateUser = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({@@ -23,8 +24,10 @@ vi.mock("@alook/shared", async () => {return {...actual,queries: {- user: {- updateUser: (...a: unknown[]) => mockUpdateUser(...a),+ ...actual.queries,+ communityBot: {+ ...actual.queries.communityBot,+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),},},}@@ -35,6 +38,10 @@ vi.mock("@/lib/community/upload", () => ({handleBotAvatarUpload: (...a: unknown[]) => mockHandleBotAvatarUpload(...a),}))+vi.mock("@/lib/community/bot-avatar-persistence", () => ({+ persistUploadedBotAvatar: (...a: unknown[]) => mockPersistUploadedBotAvatar(...a),+}))+let isAuthed = truelet actorKind: "human" | "bot" = "human"@@ -46,7 +53,7 @@ vi.mock("@/lib/middleware/community-actor", () => ({}const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.paramsreturn handler(req, {- env: { DB: {} },+ env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },actor: actorKind === "bot"? { kind: "bot", userId: "b1", ownerUserId: "u1", machineId: "m1" }: { kind: "human", userId: "u1", email: "[email protected]" },@@ -74,7 +81,8 @@ describe("POST /api/community/users/me/avatar", () => {vi.clearAllMocks()isAuthed = trueactorKind = "human"- mockUpdateUser.mockResolvedValue(undefined)+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerUserId: "u1" })+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "persisted" })mockAuthUpdateUser.mockResolvedValue({ headers: new Headers() })})@@ -94,7 +102,7 @@ describe("POST /api/community/users/me/avatar", () => {})const res = await POST(postReq(), {} as never)expect(res.status).toBe(413)- expect(mockUpdateUser).not.toHaveBeenCalled()+ expect(mockPersistUploadedBotAvatar).not.toHaveBeenCalled()expect(mockAuthUpdateUser).not.toHaveBeenCalled()})@@ -121,10 +129,28 @@ describe("POST /api/community/users/me/avatar", () => {body: { image: "/api/community/users/u1/avatar" },returnHeaders: true,}))- expect(mockUpdateUser).not.toHaveBeenCalled()+ expect(mockPersistUploadedBotAvatar).not.toHaveBeenCalled()expect(res.headers.getSetCookie()).toContain("better-auth.session_data=fresh; Path=/")})+ it("keeps a successful human response when Better Auth emits no replacement cookie", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue({+ ok: true,+ id: "u1",+ key: "user-avatar/u1",+ url: "/api/community/media/user-avatar/u1",+ filename: "me.png",+ contentType: "image/png",+ size: 10,+ })++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ url: "/api/community/users/u1/avatar" })+ expect(res.headers.getSetCookie()).toEqual([])+ })+it("uses the bot avatar key and URL for a bot actor", async () => {actorKind = "bot"mockHandleBotAvatarUpload.mockResolvedValue({@@ -141,7 +167,71 @@ describe("POST /api/community/users/me/avatar", () => {expect(await res.json()).toEqual({ url: "/api/community/bots/b1/avatar" })expect(mockHandleBotAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "b1")expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()- expect(mockUpdateUser).toHaveBeenCalledWith(expect.anything(), "b1", { image: "/api/community/bots/b1/avatar" })+ expect(mockGetBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "b1", "u1")+ expect(mockPersistUploadedBotAvatar).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ { botId: "b1", ownerId: "u1" },+ )expect(mockAuthUpdateUser).not.toHaveBeenCalled()})++ it("returns 404 before bot R2 PUT when the runner actor no longer owns a live bot", async () => {+ actorKind = "bot"+ mockGetBotOwnedBy.mockResolvedValue(null)++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(404)+ expect(mockHandleBotAvatarUpload).not.toHaveBeenCalled()+ expect(mockPersistUploadedBotAvatar).not.toHaveBeenCalled()+ })++ it("forwards bot upload failures before attempting D1 persistence", async () => {+ const { NextResponse } = await import("next/server")+ actorKind = "bot"+ mockHandleBotAvatarUpload.mockResolvedValue({+ ok: false,+ response: NextResponse.json({ error: "avatar too large (max 8MB)" }, { status: 413 }),+ })++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(413)+ expect(mockPersistUploadedBotAvatar).not.toHaveBeenCalled()+ })++ it("returns 404 when bot self-upload loses to delete after R2 PUT", async () => {+ actorKind = "bot"+ mockHandleBotAvatarUpload.mockResolvedValue({+ ok: true,+ id: "b1",+ key: "bot-avatar/b1",+ url: "/api/community/bots/b1/avatar",+ filename: "bot.png",+ contentType: "image/png",+ size: 10,+ })+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "not_found" })++ const res = await POST(postReq(), {} as never)+ expect(res.status).toBe(404)+ })++ it("returns 500 when bot self-upload persistence is ambiguous", async () => {+ actorKind = "bot"+ mockHandleBotAvatarUpload.mockResolvedValue({+ ok: true,+ id: "b1",+ key: "bot-avatar/b1",+ url: "/api/community/bots/b1/avatar",+ filename: "bot.png",+ contentType: "image/png",+ size: 10,+ })+ mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "failed" })++ const res = await POST(postReq(), {} as never)+ expect(res.status).toBe(500)+ })})diff --git a/src/web/src/app/api/community/users/me/avatar/route.ts b/src/web/src/app/api/community/users/me/avatar/route.tsindex 2b40a8c33..84de7ec5d 100644--- a/src/web/src/app/api/community/users/me/avatar/route.ts+++ b/src/web/src/app/api/community/users/me/avatar/route.ts@@ -1,40 +1,54 @@import { NextRequest, NextResponse } from "next/server"import { queries } from "@alook/shared"import { withCommunityActor } from "@/lib/middleware/community-actor"-import { writeJSON } from "@/lib/middleware/helpers"+import { writeError, writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"import { handleBotAvatarUpload, handleUserAvatarUpload } from "@/lib/community/upload"import { botAvatarUrl, userAvatarUrl } from "@/lib/community/storage"+import { persistUploadedBotAvatar } from "@/lib/community/bot-avatar-persistence"export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const userId = ctx.actor.userId- const result = ctx.actor.kind === "bot"- ? await handleBotAvatarUpload(req, ctx.env, userId)- : await handleUserAvatarUpload(req, ctx.env, userId)- if (!result.ok) return result.response-const db = getDb(ctx.env.DB)- const url = ctx.actor.kind === "bot" ? botAvatarUrl(userId) : userAvatarUrl(userId)- let sessionHeaders: Headers | undefined+if (ctx.actor.kind === "bot") {- await queries.user.updateUser(db, userId, { image: url })- } else {- // Better Auth updates the row and re-signs its cached session payload.- // Without forwarding that cookie, a full /c remount starts from the old- // session image and briefly paints a generated avatar until the canonical- // profile request finishes.- const auth = createAuth(ctx.env)- const result = (await auth.api.updateUser({- body: { image: url },- headers: req.headers,- returnHeaders: true,- })) as { headers: Headers }- sessionHeaders = result.headers+ const before = await queries.communityBot.getBotOwnedBy(+ db,+ userId,+ ctx.actor.ownerUserId,+ )+ if (!before) return writeError("bot not found", 404)++ const upload = await handleBotAvatarUpload(req, ctx.env, userId)+ if (!upload.ok) return upload.response++ const persisted = await persistUploadedBotAvatar(db, ctx.env.COMMUNITY_MEDIA, {+ botId: userId,+ ownerId: ctx.actor.ownerUserId,+ })+ if (persisted.kind === "not_found") return writeError("bot not found", 404)+ if (persisted.kind === "failed") return writeError("internal error", 500)+ return writeJSON({ url: botAvatarUrl(userId) })}+ const result = await handleUserAvatarUpload(req, ctx.env, userId)+ if (!result.ok) return result.response++ const url = userAvatarUrl(userId)+ // Better Auth updates the row and re-signs its cached session payload.+ // Without forwarding that cookie, a full /c remount starts from the old+ // session image and briefly paints a generated avatar until the canonical+ // profile request finishes.+ const auth = createAuth(ctx.env)+ const authResult = (await auth.api.updateUser({+ body: { image: url },+ headers: req.headers,+ returnHeaders: true,+ })) as { headers: Headers }+const res = writeJSON({ url })- const setCookies = sessionHeaders?.getSetCookie() ?? []+ const setCookies = authResult.headers.getSetCookie()if (setCookies.length === 0) return resconst response = new NextResponse(res.body, res)diff --git a/src/web/src/lib/community/bot-avatar-persistence.test.ts b/src/web/src/lib/community/bot-avatar-persistence.test.tsnew file mode 100644index 000000000..20b094dd9--- /dev/null+++ b/src/web/src/lib/community/bot-avatar-persistence.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockUpdateBot = vi.fn()+const mockGetLiveBotAvatar = vi.fn()+const mockWarn = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ createLogger: () => ({+ info: vi.fn(),+ warn: (...args: unknown[]) => mockWarn(...args),+ error: vi.fn(),+ debug: vi.fn(),+ }),+ queries: {+ ...actual.queries,+ communityBot: {+ ...actual.queries.communityBot,+ updateBot: (...args: unknown[]) => mockUpdateBot(...args),+ getLiveBotAvatar: (...args: unknown[]) => mockGetLiveBotAvatar(...args),+ },+ },+ }+})++import { persistUploadedBotAvatar } from "./bot-avatar-persistence"++const db = {} as never++describe("persistUploadedBotAvatar", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it("returns persisted when the live owner-scoped update wins", async () => {+ mockUpdateBot.mockResolvedValue({ botId: "b1" })+ const remove = vi.fn()++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "persisted" })++ expect(mockUpdateBot).toHaveBeenCalledWith(db, "b1", "u1", {+ image: "/api/community/bots/b1/avatar",+ })+ expect(mockGetLiveBotAvatar).not.toHaveBeenCalled()+ expect(remove).not.toHaveBeenCalled()+ })++ it("inline-compensates and returns not_found when delete won before the update", async () => {+ mockUpdateBot.mockResolvedValue(null)+ const remove = vi.fn().mockResolvedValue(undefined)++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "not_found" })++ expect(remove).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockGetLiveBotAvatar).not.toHaveBeenCalled()+ })++ it("keeps the 404 outcome when zero-row compensation rejects and logs no raw error or key", async () => {+ mockUpdateBot.mockResolvedValue(null)+ const remove = vi.fn().mockRejectedValue(new TypeError("secret bot-avatar/b1"))++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "not_found" })++ expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_cleanup_failed", {+ botId: "b1",+ phase: "zero_row_delete_winner",+ keyCount: 1,+ errorCategory: "TypeError",+ })+ expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("secret")+ expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("bot-avatar/b1")+ })++ it("compensates only after a thrown update verifies the bot is missing", async () => {+ mockUpdateBot.mockRejectedValue(new Error("secret ambiguous commit"))+ mockGetLiveBotAvatar.mockResolvedValue(null)+ const remove = vi.fn().mockResolvedValue(undefined)++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "failed" })++ expect(remove).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_persist_failed", {+ botId: "b1",+ phase: "d1_error_live_verification",+ objectState: "compensated_tombstoned",+ errorCategory: "Error",+ })+ expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("secret")+ expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("bot-avatar/b1")+ })++ it("retains after a thrown update verifies a live canonical row", async () => {+ mockUpdateBot.mockRejectedValue(new Error("ambiguous commit"))+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ })+ const remove = vi.fn()++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "failed" })++ expect(remove).not.toHaveBeenCalled()+ expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_persist_failed", {+ botId: "b1",+ phase: "d1_error_live_verification",+ objectState: "retained_live_canonical",+ errorCategory: "Error",+ })+ })++ it("retains a live noncanonical fixed key because R2 delete has no CAS", async () => {+ mockUpdateBot.mockRejectedValue(new Error("ambiguous commit"))+ mockGetLiveBotAvatar.mockResolvedValue({ id: "b1", image: "avatar:beam-seed" })+ const remove = vi.fn()++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "failed" })++ expect(remove).not.toHaveBeenCalled()+ expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_persist_failed", {+ botId: "b1",+ phase: "d1_error_live_verification",+ objectState: "retained_live_noncanonical",+ errorCategory: "Error",+ })+ })++ it("retains unverified bytes when both update and verification throw", async () => {+ mockUpdateBot.mockRejectedValue(new Error("persist secret"))+ mockGetLiveBotAvatar.mockRejectedValue(new TypeError("verify secret"))+ const remove = vi.fn()++ await expect(persistUploadedBotAvatar(db, { delete: remove }, {+ botId: "b1",+ ownerId: "u1",+ })).resolves.toEqual({ kind: "failed" })++ expect(remove).not.toHaveBeenCalled()+ expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_persist_verification_failed", {+ botId: "b1",+ phase: "d1_error_verification",+ objectState: "retained_unverified",+ persistErrorCategory: "Error",+ verificationErrorCategory: "TypeError",+ })+ expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("secret")+ })+})diff --git a/src/web/src/lib/community/bot-avatar-persistence.ts b/src/web/src/lib/community/bot-avatar-persistence.tsnew file mode 100644index 000000000..1a8650d74--- /dev/null+++ b/src/web/src/lib/community/bot-avatar-persistence.ts@@ -0,0 +1,97 @@+import { createLogger, queries, type Database } from "@alook/shared"+import {+ communityMediaCleanupErrorCategory,+ deleteCommunityMediaObjects,+} from "./community-media-cleanup"+import { buildBotAvatarKey, botAvatarUrl } from "./storage"++const log = createLogger({ service: "community-bot-avatar" })++export type BotAvatarPersistenceOutcome =+ | { kind: "persisted" }+ | { kind: "not_found" }+ | { kind: "failed" }++async function compensateBotAvatar(+ bucket: Pick<R2Bucket, "delete">,+ botId: string,+ phase: "zero_row_delete_winner" | "d1_error_tombstoned",+): Promise<void> {+ try {+ await deleteCommunityMediaObjects(bucket, [buildBotAvatarKey(botId)])+ } catch (error) {+ log.warn("community_bot_avatar_cleanup_failed", {+ botId,+ phase,+ keyCount: 1,+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ }+}++/**+ * Persist a fixed-key bot-avatar upload after R2 PUT.+ *+ * The owner-scoped live UPDATE is the linearization point. A zero-row result+ * can only mean the bot lost to delete after the caller's live-owner preflight,+ * so inline deletion is safe. A thrown write has unknown commit state: verify+ * the live row and delete only when the bot is definitely gone. R2 fixed-key+ * deletion has no CAS, so every live verification result must retain the+ * object to avoid deleting a later concurrent upload.+ */+export async function persistUploadedBotAvatar(+ db: Database,+ bucket: Pick<R2Bucket, "delete">,+ input: { botId: string; ownerId: string },+): Promise<BotAvatarPersistenceOutcome> {+ const url = botAvatarUrl(input.botId)++ try {+ const updated = await queries.communityBot.updateBot(+ db,+ input.botId,+ input.ownerId,+ { image: url },+ )+ if (updated) return { kind: "persisted" }+ } catch (error) {+ let live: { id: string; image: string | null } | null+ try {+ live = await queries.communityBot.getLiveBotAvatar(db, input.botId)+ } catch (verificationError) {+ log.warn("community_bot_avatar_persist_verification_failed", {+ botId: input.botId,+ phase: "d1_error_verification",+ objectState: "retained_unverified",+ persistErrorCategory: communityMediaCleanupErrorCategory(error),+ verificationErrorCategory: communityMediaCleanupErrorCategory(verificationError),+ })+ return { kind: "failed" }+ }++ if (!live) {+ await compensateBotAvatar(bucket, input.botId, "d1_error_tombstoned")+ log.warn("community_bot_avatar_persist_failed", {+ botId: input.botId,+ phase: "d1_error_live_verification",+ objectState: "compensated_tombstoned",+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ return { kind: "failed" }+ }++ log.warn("community_bot_avatar_persist_failed", {+ botId: input.botId,+ phase: "d1_error_live_verification",+ objectState:+ live.image === url+ ? "retained_live_canonical"+ : "retained_live_noncanonical",+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ return { kind: "failed" }+ }++ await compensateBotAvatar(bucket, input.botId, "zero_row_delete_winner")+ return { kind: "not_found" }+}diff --git a/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts b/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.tsnew file mode 100644index 000000000..91ed8fff1--- /dev/null+++ b/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts@@ -0,0 +1,56 @@+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 c2Sources = [+ "src/shared/src/db/queries/community/bot.ts",+ "src/web/src/lib/community/bot-avatar-persistence.ts",+ "src/web/src/app/api/community/bots/[id]/avatar/route.ts",+ "src/web/src/app/api/community/bots/[id]/route.ts",+ "src/web/src/app/api/community/machines/[id]/route.ts",+ "src/web/src/app/api/community/users/me/avatar/route.ts",+] as const++function source(path: string): string {+ return readFileSync(resolve(repositoryRoot, path), "utf8")+}++describe("bot and machine-cascade avatar cleanup C2 boundary", () => {+ it("cannot touch diagnostics, BUG_REPORTS, or unrelated media namespaces", () => {+ const combined = c2Sources.map(source).join("\n")+ for (const forbidden of [+ "BUG_REPORTS",+ "communityDiagnosticReport",+ "user-avatar/",+ "server-icon/",+ "communityAttachment",+ "deleteChannelWithMedia",+ "deleteServerWithMedia",+ ".list(",+ ]) {+ expect(combined).not.toContain(forbidden)+ }+ })++ it("derives every C2 cleanup key through buildBotAvatarKey", () => {+ for (const path of c2Sources.slice(1)) {+ expect(source(path)).not.toContain("bot-avatar/")+ }+ expect(source("src/web/src/lib/community/bot-avatar-persistence.ts"))+ .toContain("buildBotAvatarKey(botId)")+ expect(source("src/web/src/app/api/community/bots/[id]/route.ts"))+ .toContain("buildBotAvatarKey(id)")+ expect(source("src/web/src/app/api/community/machines/[id]/route.ts"))+ .toContain("buildBotAvatarKey(bot.id)")+ })++ it("keeps the human self-avatar branch on Better Auth and user storage", () => {+ const meAvatar = source("src/web/src/app/api/community/users/me/avatar/route.ts")+ expect(meAvatar).toContain("handleUserAvatarUpload(req, ctx.env, userId)")+ expect(meAvatar).toContain("const auth = createAuth(ctx.env)")+ expect(meAvatar).toContain("auth.api.updateUser")+ expect(meAvatar).toContain("userAvatarUrl(userId)")+ })+})diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.tsnew file mode 100644index 000000000..6ee6ea0fc--- /dev/null+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts@@ -0,0 +1,159 @@+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { WEB_URL } from "./_setup/paths"++const ONE_PIXEL_PNG_BASE64 =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII="++function aliceHeaders(extra?: Record<string, string>) {+ return {+ Cookie: sessionCookie("alice"),+ Origin: WEB_URL,+ ...extra,+ }+}++async function pairMachine(): Promise<string> {+ const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {+ method: "POST",+ headers: aliceHeaders(),+ })+ expect(pair.status).toBe(200)+ const { tokenId } = await pair.json() as { tokenId: string }++ const activate = await fetch(`${WEB_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${tokenId}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ hostname: `avatar-e2e-${Date.now()}`,+ platform: "darwin",+ arch: "arm64",+ runtimeReport: [{ id: "codex", status: "healthy" }],+ }),+ })+ expect(activate.status).toBe(200)+ const body = await activate.json() as { machineId: string }+ return body.machineId+}++async function createBot(machineId: string, name: string): Promise<string> {+ const response = await fetch(`${WEB_URL}/api/community/bots`, {+ method: "POST",+ headers: aliceHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({ name, machineId, runtime: "codex" }),+ })+ expect(response.status).toBe(201)+ const body = await response.json() as { bot: { id: string } }+ return body.bot.id+}++async function uploadAvatar(page: import("@playwright/test").Page, botId: string): Promise<number> {+ return page.evaluate(async (+ { id, base64 }: { id: string; base64: string },+ ) => {+ const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0))+ const form = new FormData()+ form.append("file", new File([bytes], "avatar.png", { type: "image/png" }))+ return (await fetch(`/api/community/bots/${id}/avatar`, {+ method: "POST",+ body: form,+ credentials: "include",+ })).status+ }, { id: botId, base64: ONE_PIXEL_PNG_BASE64 })+}++test("real bot avatars become unreadable after single delete and authenticated machine cascade", async ({ asUser }) => {+ test.setTimeout(120_000)+ const machineId = await pairMachine()+ const botName = `Avatar cleanup ${Date.now()}`+ const botId = await createBot(machineId, botName)+ const avatarPath = `/api/community/bots/${botId}/avatar`+ const alice = await asUser("alice")++ await gotoAfterUserWsAuth(alice.page, "/c/me/bots")+ const uploadStatus = await uploadAvatar(alice.page, botId)+ expect(uploadStatus).toBe(200)++ await alice.page.reload()+ await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()+ const avatar = alice.page.locator(`img[src="${avatarPath}"]`)+ await expect(avatar).toBeVisible()+ await expect.poll(() => avatar.evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth)).toBe(1)+ expect(await alice.page.evaluate(async (path) => (+ await fetch(`${path}?before=${crypto.randomUUID()}`, { cache: "no-store" })+ ).status, avatarPath)).toBe(200)++ const deleteStatus = await alice.page.evaluate(async (id) => (+ await fetch(`/api/community/bots/${id}`, {+ method: "DELETE",+ credentials: "include",+ })+ ).status, botId)+ expect(deleteStatus).toBe(204)++ expect(await alice.page.evaluate(async (path) => (+ await fetch(`${path}?after=${crypto.randomUUID()}`, { cache: "no-store" })+ ).status, avatarPath)).toBe(404)++ await alice.page.reload()+ await expect(alice.page.getByText(botName, { exact: true })).toHaveCount(0)+ await expect(alice.page.locator(`img[src="${avatarPath}"]`)).toHaveCount(0)+ expect(await alice.page.evaluate(async (path) => (+ await fetch(`${path}?reload=${crypto.randomUUID()}`, { cache: "no-store" })+ ).status, avatarPath)).toBe(404)++ const machineDelete = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, {+ method: "DELETE",+ headers: aliceHeaders(),+ })+ expect(machineDelete.status).toBe(204)++ const cascadeMachineId = await pairMachine()+ const cascadeBotName = `Cascade ${Date.now()}`+ const cascadeBotId = await createBot(cascadeMachineId, cascadeBotName)+ const cascadeAvatarPath = `/api/community/bots/${cascadeBotId}/avatar`+ expect(await uploadAvatar(alice.page, cascadeBotId)).toBe(200)+ await alice.page.reload()+ await expect(alice.page.getByText(cascadeBotName, { exact: true })).toBeVisible()+ expect(await alice.page.evaluate(async (path) => (+ await fetch(`${path}?before-cascade=${crypto.randomUUID()}`, { cache: "no-store" })+ ).status, cascadeAvatarPath)).toBe(200)++ const preflightStatus = await alice.page.evaluate(async (id) => (+ await fetch(`/api/community/machines/${id}`, {+ method: "DELETE",+ credentials: "include",+ })+ ).status, cascadeMachineId)+ expect(preflightStatus).toBe(409)++ const cascadeStatus = await alice.page.evaluate(async (id) => (+ await fetch(`/api/community/machines/${id}`, {+ method: "DELETE",+ credentials: "include",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ cascade: true }),+ })+ ).status, cascadeMachineId)+ expect(cascadeStatus).toBe(204)++ expect(await alice.page.evaluate(async (path) => (+ await fetch(`${path}?after-cascade=${crypto.randomUUID()}`, { cache: "no-store" })+ ).status, cascadeAvatarPath)).toBe(404)+ const listedBotIds = await alice.page.evaluate(async () => {+ const response = await fetch("/api/community/bots", {+ credentials: "include",+ cache: "no-store",+ })+ if (!response.ok) throw new Error(`bot list failed: ${response.status}`)+ const body = await response.json() as { bots: Array<{ id: string }> }+ return body.bots.map((bot) => bot.id)+ })+ expect(listedBotIds).not.toContain(cascadeBotId)+ await alice.page.reload()+ await expect(alice.page.getByText(cascadeBotName, { exact: true })).toHaveCount(0)+})diff --git a/src/web/test-runtime/community-bot-avatar-cleanup.runtime.test.ts b/src/web/test-runtime/community-bot-avatar-cleanup.runtime.test.tsnew file mode 100644index 000000000..4ca998e57--- /dev/null+++ b/src/web/test-runtime/community-bot-avatar-cleanup.runtime.test.ts@@ -0,0 +1,217 @@+/// <reference types="@cloudflare/vitest-plugin/types" />++import { env } from "cloudflare:workers"+import { afterEach, describe, expect, it } from "vitest"+import { createDb, queries } from "@alook/shared"+import { deleteCommunityMediaObjects } from "../src/lib/community/community-media-cleanup"+import { persistUploadedBotAvatar } from "../src/lib/community/bot-avatar-persistence"+import { buildBotAvatarKey, botAvatarUrl } from "../src/lib/community/storage"++const runtimeEnv = env as unknown as CloudflareEnv+const createdUsers: string[] = []+const createdMachines: string[] = []+const mediaKeys: string[] = []+const bugReportKeys: 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 seedOwner(): Promise<string> {+ const owner = `bac_owner_${crypto.randomUUID().replaceAll("-", "")}`+ createdUsers.push(owner)+ await run(+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, ?, ?)",+ owner,+ `${owner}@example.com`,+ owner,+ stamp4(owner),+ )+ return owner+}++async function seedMachine(ownerId: string): Promise<string> {+ const machine = `bac_machine_${crypto.randomUUID().replaceAll("-", "")}`+ createdMachines.push(machine)+ await run(+ `INSERT INTO community_machine+ (id, user_id, available_runtimes, created_at, updated_at)+ VALUES (?, ?, ?, '2026-08-24T00:00:00.000Z', '2026-08-24T00:00:00.000Z')`,+ machine,+ ownerId,+ JSON.stringify([{ id: "codex", status: "healthy" }]),+ )+ return machine+}++async function seedBot(+ ownerId: string,+ machineId: string,+ input: { image?: string | null; deletedAt?: string | null } = {},+): Promise<string> {+ const bot = `bac_bot_${crypto.randomUUID().replaceAll("-", "")}`+ createdUsers.push(bot)+ await run(+ `INSERT INTO user+ (id, email, name, discriminator, isBot, ownerUserId, image, deletedAt)+ VALUES (?, ?, ?, ?, 1, ?, ?, ?)`,+ bot,+ `${bot}@bots.alook.local`,+ bot,+ stamp4(bot),+ ownerId,+ input.image ?? null,+ input.deletedAt ?? null,+ )+ if (!input.deletedAt) {+ await run(+ `INSERT INTO community_bot_binding+ (user_id, machine_id, runtime, created_at)+ VALUES (?, ?, 'codex', '2026-08-24T00:00:00.000Z')`,+ bot,+ machineId,+ )+ }+ return bot+}++async function putMedia(key: string, value: string): Promise<void> {+ mediaKeys.push(key)+ await runtimeEnv.COMMUNITY_MEDIA.put(key, value)+}++afterEach(async () => {+ for (const key of mediaKeys.splice(0)) await runtimeEnv.COMMUNITY_MEDIA.delete(key)+ for (const key of bugReportKeys.splice(0)) await runtimeEnv.BUG_REPORTS.delete(key)+ for (const userId of createdUsers) {+ await runtimeEnv.DB.prepare("DELETE FROM community_bot_binding WHERE user_id = ?")+ .bind(userId)+ .run()+ }+ for (const machineId of createdMachines.splice(0)) {+ await runtimeEnv.DB.prepare("DELETE FROM community_machine WHERE id = ?")+ .bind(machineId)+ .run()+ }+ for (const userId of createdUsers.splice(0).reverse()) {+ await runtimeEnv.DB.prepare("DELETE FROM user WHERE id = ?").bind(userId).run()+ }+})++describe("bot avatar query and winner semantics in real D1", () => {+ it("returns only live bot id/image and exactly one scoped soft-delete winner", async () => {+ const owner = await seedOwner()+ const otherOwner = await seedOwner()+ const machine = await seedMachine(owner)+ const canonicalBot = await seedBot(owner, machine, {+ image: "/api/community/bots/placeholder/avatar",+ })+ await run(+ "UPDATE user SET image = ? WHERE id = ?",+ botAvatarUrl(canonicalBot),+ canonicalBot,+ )+ const deletedBot = await seedBot(owner, machine, {+ image: "/api/community/bots/deleted/avatar",+ deletedAt: "2026-08-24T00:00:00.000Z",+ })+ const human = `bac_human_${crypto.randomUUID().replaceAll("-", "")}`+ createdUsers.push(human)+ await run(+ "INSERT INTO user (id, email, name, discriminator, image) VALUES (?, ?, ?, ?, ?)",+ human,+ `${human}@example.com`,+ human,+ stamp4(human),+ botAvatarUrl(human),+ )++ const db = createDb(runtimeEnv.DB)+ await expect(queries.communityBot.getLiveBotAvatar(db, canonicalBot)).resolves.toEqual({+ id: canonicalBot,+ image: botAvatarUrl(canonicalBot),+ })+ await expect(queries.communityBot.getLiveBotAvatar(db, deletedBot)).resolves.toBeNull()+ await expect(queries.communityBot.getLiveBotAvatar(db, human)).resolves.toBeNull()+ await expect(queries.communityBot.getLiveBotAvatar(db, "missing")).resolves.toBeNull()+ await expect(queries.communityBot.softDeleteBot(db, canonicalBot, otherOwner)).resolves.toBe(false)++ const results = await Promise.all([+ queries.communityBot.softDeleteBot(db, canonicalBot, owner),+ queries.communityBot.softDeleteBot(db, canonicalBot, owner),+ ])+ expect(results.filter(Boolean)).toHaveLength(1)+ await expect(queries.communityBot.softDeleteBot(db, canonicalBot, owner)).resolves.toBe(false)+ await expect(queries.communityBot.getLiveBotAvatar(db, canonicalBot)).resolves.toBeNull()+ })+})++describe("bot avatar D1 to R2 containment in real workerd", () => {+ it("persists a live upload and deletes only the winning bot fixed key", async () => {+ const owner = await seedOwner()+ const machine = await seedMachine(owner)+ const bot = await seedBot(owner, machine)+ const unrelatedBot = await seedBot(owner, machine, { image: "avatar:beam-seed" })+ const botKey = buildBotAvatarKey(bot)+ const userKey = `user-avatar/${bot}`+ const unrelatedBotKey = buildBotAvatarKey(unrelatedBot)+ const attachmentKey = `channel/runtime/${bot}/attachment.png`+ const serverIconKey = `server-icon/runtime-${bot}/icon`+ const bugKey = `bug-reports/${owner}/runtime-${bot}.ndjson.gz`+ for (const [key, value] of [+ [botKey, "bot"],+ [userKey, "human"],+ [unrelatedBotKey, "other-bot"],+ [attachmentKey, "attachment"],+ [serverIconKey, "server-icon"],+ ] as const) {+ await putMedia(key, value)+ }+ bugReportKeys.push(bugKey)+ await runtimeEnv.BUG_REPORTS.put(bugKey, "diagnostic-sentinel")++ const db = createDb(runtimeEnv.DB)+ await expect(persistUploadedBotAvatar(db, runtimeEnv.COMMUNITY_MEDIA, {+ botId: bot,+ ownerId: owner,+ })).resolves.toEqual({ kind: "persisted" })+ expect((await first<{ image: string }>("SELECT image FROM user WHERE id = ?", bot))?.image)+ .toBe(botAvatarUrl(bot))++ const won = await queries.communityBot.softDeleteBot(db, bot, owner)+ expect(won).toBe(true)+ if (won) await deleteCommunityMediaObjects(runtimeEnv.COMMUNITY_MEDIA, [botKey])++ expect(await runtimeEnv.COMMUNITY_MEDIA.get(botKey)).toBeNull()+ await expect((await runtimeEnv.COMMUNITY_MEDIA.get(userKey))!.text()).resolves.toBe("human")+ await expect((await runtimeEnv.COMMUNITY_MEDIA.get(unrelatedBotKey))!.text()).resolves.toBe("other-bot")+ await expect((await runtimeEnv.COMMUNITY_MEDIA.get(attachmentKey))!.text()).resolves.toBe("attachment")+ await expect((await runtimeEnv.COMMUNITY_MEDIA.get(serverIconKey))!.text()).resolves.toBe("server-icon")+ await expect((await runtimeEnv.BUG_REPORTS.get(bugKey))!.text()).resolves.toBe("diagnostic-sentinel")+ })++ it("inline-compensates an upload whose live D1 update loses to delete", async () => {+ const owner = await seedOwner()+ const machine = await seedMachine(owner)+ const bot = await seedBot(owner, machine)+ const botKey = buildBotAvatarKey(bot)+ await queries.communityBot.softDeleteBot(createDb(runtimeEnv.DB), bot, owner)+ await putMedia(botKey, "late-upload")++ await expect(persistUploadedBotAvatar(createDb(runtimeEnv.DB), runtimeEnv.COMMUNITY_MEDIA, {+ botId: bot,+ ownerId: owner,+ })).resolves.toEqual({ kind: "not_found" })+ expect(await runtimeEnv.COMMUNITY_MEDIA.get(botKey)).toBeNull()+ })+})