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): version avatar identity updates (#616)
Gener37a72d2590f9
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex af5cd9568..137792295 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -54,6 +54,7 @@ export const SPEC_SECONDS = {"40-mobile-server-header-hierarchy.spec.ts": 28,"40-server-rail-unread.spec.ts": 60,"41-community-initial-load-module-skeletons.spec.ts": 30,+ "42-versioned-avatar-identity.spec.ts": 50,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex de27f9eab..90c847879 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([355, 356, 359, 360, 360])+ expect(totals.sort((left, right) => left - right)).toEqual([366, 367, 367, 370, 370])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex 2727c5688..6101275c3 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -135,6 +135,14 @@"strategy": "exact-chunk","fixedParams": 10},+ {+ "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:1",+ "strategy": "subquery"+ },+ {+ "key": "src/shared/src/db/queries/community/bot.ts:publishOwnedBotAvatar:inArray:2",+ "strategy": "subquery"+ },{"key": "src/shared/src/db/queries/community/bot.ts:softDeleteBot:inArray:1","strategy": "subquery"diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 09f722c12..70e4315cc 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -11,6 +11,7 @@ const friendApprovalProfileSchema = z.strictObject({name: string,discriminator: string,image: nullableString,+ avatarVersion: z.number().int().nonnegative(),})export const FriendApprovalPayloadSchema = z.strictObject({@@ -39,6 +40,7 @@ const messageSchema = z.strictObject({authorId: string,authorName: string,authorAvatar: string.optional(),+ authorAvatarVersion: z.number().int().nonnegative(),content: string,type: z.enum(["chat", "system"]),systemKind: z.literal("thread").optional(),@@ -271,6 +273,7 @@ const communityMemberJoinSchema = z.strictObject({name: string,discriminator: string,avatar: string.optional(),+ avatarVersion: z.number().int().nonnegative(),role: string,joinedAt: string,}),@@ -394,6 +397,13 @@ const communityStatusUpdateSchema = z.strictObject({statusText: nullableString,})+const communityIdentityUpdateSchema = z.strictObject({+ type: z.literal("community:identity.update"),+ userId: string,+ avatar: string,+ avatarVersion: z.number().int().positive(),+})+const machineRuntimeSchema = CommunityMachineRuntimeSchema.strict()export const CommunityMachineSummarySchema = z.strictObject({@@ -489,6 +499,7 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [communityInboxChangedSchema,communityPresenceUpdateSchema,communityStatusUpdateSchema,+ communityIdentityUpdateSchema,communityMachineCreatedSchema,communityMachineStatusSchema,communityMachineUpdatedSchema,@@ -555,6 +566,7 @@ export type CommunityReadStateAdvanced = Extract<CommunityWsEvent, { type: "commexport type CommunityInboxChanged = Extract<CommunityWsEvent, { type: "community:inbox.changed" }>export type CommunityPresenceUpdate = Extract<CommunityWsEvent, { type: "community:presence.update" }>export type CommunityStatusUpdate = Extract<CommunityWsEvent, { type: "community:status.update" }>+export type CommunityIdentityUpdate = Extract<CommunityWsEvent, { type: "community:identity.update" }>export type CommunityMachineCreated = Extract<CommunityWsEvent, { type: "community:machine.created" }>export type CommunityMachineStatus = Extract<CommunityWsEvent, { type: "community:machine.status" }>export type CommunityMachineUpdated = Extract<CommunityWsEvent, { type: "community:machine.updated" }>@@ -627,6 +639,7 @@ export const WS_EVENTS = {INBOX_CHANGED: "community:inbox.changed",PRESENCE_UPDATE: "community:presence.update",STATUS_UPDATE: "community:status.update",+ IDENTITY_UPDATE: "community:identity.update",MACHINE_CREATED: "community:machine.created",MACHINE_STATUS: "community:machine.status",MACHINE_UPDATED: "community:machine.updated",diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex dd1b060b6..f3b8a8a71 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -50,6 +50,7 @@ export type BotRow = {name: string;discriminator: string;image: string | null;+ avatarVersion: number;ownerUserId: string;description: string;createdAt: string;@@ -102,6 +103,7 @@ export async function listBotsForOwner(name: user.name,discriminator: user.discriminator,image: user.image,+ avatarVersion: user.avatarVersion,ownerUserId: user.ownerUserId,createdAt: user.createdAt,updatedAt: user.updatedAt,@@ -127,6 +129,7 @@ export async function listBotsForOwner(name: r.name,discriminator: r.discriminator,image: r.image,+ avatarVersion: r.avatarVersion,ownerUserId: r.ownerUserId!,description: r.description ?? "",createdAt: r.createdAt,@@ -193,6 +196,7 @@ export async function getBotOwnedBy(modelName: string | null;reasoningEffort: ReasoningEffort | null;runtimeConfigRevision: number;+ avatarObjectKey: string | null;}) | null> {const rows = await db.select({@@ -200,6 +204,8 @@ export async function getBotOwnedBy(name: user.name,discriminator: user.discriminator,image: user.image,+ avatarVersion: user.avatarVersion,+ avatarObjectKey: user.avatarObjectKey,ownerUserId: user.ownerUserId,createdAt: user.createdAt,updatedAt: user.updatedAt,@@ -229,6 +235,8 @@ export async function getBotOwnedBy(name: r.name,discriminator: r.discriminator,image: r.image,+ avatarVersion: r.avatarVersion,+ avatarObjectKey: r.avatarObjectKey,ownerUserId: r.ownerUserId!,description: r.description ?? "",createdAt: r.createdAt,@@ -253,9 +261,19 @@ export async function getBotOwnedBy(export async function getLiveBotAvatar(db: Database,botId: string-): Promise<{ id: string; image: string | null } | null> {+): Promise<{+ id: string;+ image: string | null;+ avatarVersion: number;+ avatarObjectKey: string | null;+} | null> {const rows = await db- .select({ id: user.id, image: user.image })+ .select({+ id: user.id,+ image: user.image,+ avatarVersion: user.avatarVersion,+ avatarObjectKey: user.avatarObjectKey,+ }).from(user).where(and(@@ -268,6 +286,60 @@ export async function getLiveBotAvatar(return rows[0] ?? null;}+export async function publishOwnedBotAvatar(+ db: Database,+ botId: string,+ ownerId: string,+ input: { objectKey: string; stableUrl: string },+): Promise<{+ previous: { avatarVersion: number; avatarObjectKey: string | null };+ current: {+ id: string;+ image: string | null;+ avatarVersion: number;+ avatarObjectKey: string | null;+ };+} | null> {+ const ownerScopedIds = db+ .select({ id: user.id })+ .from(user)+ .where(+ and(+ eq(user.id, botId),+ eq(user.ownerUserId, ownerId),+ eq(user.isBot, true),+ isNull(user.deletedAt),+ ),+ );+ const before = db+ .select({+ avatarVersion: user.avatarVersion,+ avatarObjectKey: user.avatarObjectKey,+ })+ .from(user)+ .where(inArray(user.id, ownerScopedIds))+ .limit(1);+ const publish = db+ .update(user)+ .set({+ image: input.stableUrl,+ avatarVersion: sql`${user.avatarVersion} + 1`,+ avatarObjectKey: input.objectKey,+ updatedAt: new Date().toISOString(),+ })+ .where(inArray(user.id, ownerScopedIds))+ .returning({+ id: user.id,+ image: user.image,+ avatarVersion: user.avatarVersion,+ avatarObjectKey: user.avatarObjectKey,+ });+ const results = (await db.batch([before, publish] as any)) as any[];+ const previous = Array.isArray(results[0]) ? results[0][0] : undefined;+ const current = Array.isArray(results[1]) ? results[1][0] : undefined;+ return previous && current ? { previous, current } : null;+}+/** Cheap ownership probe used by ack/error paths. */export async function countLiveBotsForOwner(db: Database,@@ -671,14 +743,14 @@ export async function updateBot(botId: string,ownerId: string,data: { name?: string; description?: string; image?: string | null }-): Promise<{ botId: string; name: string; discriminator: string; description: string; image: string | null } | null> {+): Promise<{ botId: string; name: string; discriminator: string; description: string; image: string | null; avatarVersion: number } | null> {const set: { name?: string; image?: string | null; updatedAt: string } = {updatedAt: new Date().toISOString(),};if (data.name !== undefined) set.name = data.name;if (data.image !== undefined) set.image = data.image;- let rows: Array<{ id: string; name: string; discriminator: string; image: string | null }>;+ let rows: Array<{ id: string; name: string; discriminator: string; image: string | null; avatarVersion: number }>;if (data.description !== undefined) {const ownerScopedIds = db.select({ id: user.id })@@ -712,7 +784,13 @@ export async function updateBot(inArray(user.id, ownerScopedBindingIds)))- .returning({ id: user.id, name: user.name, discriminator: user.discriminator, image: user.image });+ .returning({+ id: user.id,+ name: user.name,+ discriminator: user.discriminator,+ image: user.image,+ avatarVersion: user.avatarVersion,+ });const results = (await db.batch([s1, s2] as any)) as any[];const bindingRows = Array.isArray(results?.[0]) ? results[0] : [];rows = Array.isArray(results?.[1]) ? results[1] : [];@@ -729,7 +807,13 @@ export async function updateBot(isNull(user.deletedAt)))- .returning({ id: user.id, name: user.name, discriminator: user.discriminator, image: user.image });+ .returning({+ id: user.id,+ name: user.name,+ discriminator: user.discriminator,+ image: user.image,+ avatarVersion: user.avatarVersion,+ });}if (rows.length === 0) return null;@@ -750,6 +834,7 @@ export async function updateBot(discriminator: rows[0]!.discriminator,description,image: rows[0]!.image,+ avatarVersion: rows[0]!.avatarVersion,};}diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.tsindex c0660628c..d2e61dbb4 100644--- a/src/shared/src/db/queries/community/dm.ts+++ b/src/shared/src/db/queries/community/dm.ts@@ -168,6 +168,52 @@ export async function listDmChannelIdsForUser(return rows.map((r) => r.channelId);}+export async function listDmPeerUserIds(+ db: Database,+ userId: string,+): Promise<string[]> {+ const self = alias(communityChannelMember, "identity_dm_self")+ const peer = alias(communityChannelMember, "identity_dm_peer")+ const block = alias(communityFriendship, "identity_dm_block")+ const rows = await db+ .selectDistinct({ userId: user.id })+ .from(communityChannel)+ .innerJoin(+ self,+ and(+ eq(self.channelId, communityChannel.id),+ eq(self.userId, userId),+ eq(self.relation, "access"),+ ),+ )+ .innerJoin(+ peer,+ and(+ eq(peer.channelId, communityChannel.id),+ ne(peer.userId, userId),+ eq(peer.relation, "access"),+ ),+ )+ .innerJoin(user, eq(user.id, peer.userId))+ .where(and(+ eq(communityChannel.type, "dm"),+ isNull(user.deletedAt),+ notExists(+ db+ .select({ requesterId: block.requesterId })+ .from(block)+ .where(and(+ eq(block.status, "blocked"),+ or(+ and(eq(block.requesterId, userId), eq(block.addresseeId, peer.userId)),+ and(eq(block.requesterId, peer.userId), eq(block.addresseeId, userId)),+ ),+ )),+ ),+ ))+ return rows.map((row) => row.userId)+}+export async function listDMs(db: Database, userId: string) {const selfMember = alias(communityChannelMember, "dm_list_self");const peerMember = alias(communityChannelMember, "dm_list_peer");@@ -178,6 +224,7 @@ export async function listDMs(db: Database, userId: string) {otherUserName: user.name,otherUserEmail: user.email,otherUserImage: user.image,+ otherUserAvatarVersion: user.avatarVersion,otherUserDiscriminator: user.discriminator,lastMessageAt: communityChannel.lastMessageAt,createdAt: communityChannel.createdAt,diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 747dc492d..820fdcf3f 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -54,6 +54,7 @@ async function loadProfiles(name: user.name,discriminator: user.discriminator,image: user.image,+ avatarVersion: user.avatarVersion,isBot: user.isBot,ownerUserId: user.ownerUserId,})@@ -67,6 +68,7 @@ async function loadProfiles(name: r.name,discriminator: r.discriminator,image: r.image,+ avatarVersion: r.avatarVersion,isBot: !!r.isBot,ownerUserId: r.ownerUserId,},@@ -83,7 +85,13 @@ function toCardStatus(status: string): FriendApprovalPayload["status"] {}function toProfile(p: ProfileWithFlags): FriendApprovalProfile {- return { id: p.id, name: p.name, discriminator: p.discriminator, image: p.image };+ return {+ id: p.id,+ name: p.name,+ discriminator: p.discriminator,+ image: p.image,+ avatarVersion: p.avatarVersion,+ };}/**@@ -441,6 +449,7 @@ export async function sendRequest(seq: msg.seq,authorId: botId,authorName: botP?.name ?? "",+ authorAvatarVersion: botP?.avatarVersion ?? 0,content: msg.content,type: "chat",createdAt: msg.createdAt,@@ -675,6 +684,7 @@ export async function listFriends(db: Database, userId: string) {friendName: user.name,friendEmail: user.email,friendImage: user.image,+ friendAvatarVersion: user.avatarVersion,friendDiscriminator: user.discriminator,statusEmoji: communityUserProfile.statusEmoji,statusText: communityUserProfile.statusText,@@ -697,6 +707,7 @@ export async function listFriends(db: Database, userId: string) {friendName: user.name,friendEmail: user.email,friendImage: user.image,+ friendAvatarVersion: user.avatarVersion,friendDiscriminator: user.discriminator,statusEmoji: communityUserProfile.statusEmoji,statusText: communityUserProfile.statusText,@@ -723,6 +734,7 @@ export async function listFriends(db: Database, userId: string) {botName: user.name,botEmail: user.email,botImage: user.image,+ botAvatarVersion: user.avatarVersion,botDiscriminator: user.discriminator,statusEmoji: communityUserProfile.statusEmoji,statusText: communityUserProfile.statusText,@@ -742,6 +754,7 @@ export async function listFriends(db: Database, userId: string) {friendName: b.botName,friendEmail: b.botEmail,friendImage: b.botImage,+ friendAvatarVersion: b.botAvatarVersion,friendDiscriminator: b.botDiscriminator,statusEmoji: b.statusEmoji,statusText: b.statusText,@@ -910,6 +923,7 @@ export async function listBlocked(db: Database, userId: string) {blockedUserId: user.id,blockedName: user.name,blockedImage: user.image,+ blockedAvatarVersion: user.avatarVersion,}).from(communityFriendship).innerJoin(user, eq(user.id, communityFriendship.addresseeId))@@ -927,6 +941,7 @@ export async function listBlocked(db: Database, userId: string) {blockedUserId: user.id,blockedName: user.name,blockedImage: user.image,+ blockedAvatarVersion: user.avatarVersion,}).from(communityFriendship).innerJoin(user, eq(user.id, communityFriendship.requesterId))@@ -974,6 +989,7 @@ export async function listPending(db: Database, userId: string) {userId: user.id,name: user.name,image: user.image,+ avatarVersion: user.avatarVersion,createdAt: communityFriendship.createdAt,needsOwnerApproval: communityFriendship.needsOwnerApproval,requesterId: communityFriendship.requesterId,@@ -1103,6 +1119,7 @@ export async function ownerDecideOnRow(seq: msg.seq,authorId: row.addresseeId,authorName: botP?.name ?? "",+ authorAvatarVersion: botP?.avatarVersion ?? 0,content: msg.content,type: "chat",createdAt: msg.createdAt,@@ -1355,6 +1372,7 @@ export type AgentFriendPeerRow = {name: string;discriminator: string;image: string | null;+ avatarVersion: number;aboutMe: string | null;statusEmoji: string | null;statusText: string | null;@@ -1383,6 +1401,7 @@ export async function listAgentFriends(name: user.name,discriminator: user.discriminator,image: user.image,+ avatarVersion: user.avatarVersion,aboutMe: communityUserProfile.aboutMe,statusEmoji: communityUserProfile.statusEmoji,statusText: communityUserProfile.statusText,diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex b38934c7e..39ae9ba18 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -542,6 +542,7 @@ export interface UnreadDmRow {otherUserName: string;otherUserDiscriminator: string;otherUserImage: string | null;+ otherUserAvatarVersion: number;lastMessageAt: string;}@@ -600,6 +601,7 @@ export async function listUnreadDms(otherUserName: user.name,otherUserDiscriminator: user.discriminator,otherUserImage: user.image,+ otherUserAvatarVersion: user.avatarVersion,}).from(communityChannel).innerJoin(@@ -646,6 +648,7 @@ export async function listUnreadDms(otherUserName: r.otherUserName,otherUserDiscriminator: r.otherUserDiscriminator,otherUserImage: r.otherUserImage,+ otherUserAvatarVersion: r.otherUserAvatarVersion,lastMessageAt: r.lastMessageAt!,}));}@@ -679,6 +682,7 @@ export async function listEligibleUnreadDms(otherUserName: user.name,otherUserDiscriminator: user.discriminator,otherUserImage: user.image,+ otherUserAvatarVersion: user.avatarVersion,lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,}).from(communityMessage)diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.tsindex d546f5cb4..19d2f0217 100644--- a/src/shared/src/db/queries/community/invite.ts+++ b/src/shared/src/db/queries/community/invite.ts@@ -172,7 +172,12 @@ export async function useInvite(// Join the joined-user row so WS listeners can render name/avatar without// waiting for the next /members refetch.const userRows = await db- .select({ name: user.name, image: user.image, discriminator: user.discriminator })+ .select({+ name: user.name,+ image: user.image,+ avatarVersion: user.avatarVersion,+ discriminator: user.discriminator,+ }).from(user).where(eq(user.id, userId));const userRow = userRows[0];@@ -183,6 +188,7 @@ export async function useInvite(...insertedMember,userName: userRow?.name ?? "",userImage: userRow?.image ?? null,+ userAvatarVersion: userRow?.avatarVersion ?? 0,discriminator: userRow?.discriminator ?? null,},};@@ -202,6 +208,7 @@ export async function listServerInvites(db: Database, serverId: string) {creatorName: user.name,creatorEmail: user.email,creatorImage: user.image,+ creatorAvatarVersion: user.avatarVersion,}).from(communityServerInvite).leftJoin(user, eq(user.id, communityServerInvite.createdBy))diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 1a5b56812..1dcbe44ca 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -125,6 +125,7 @@ export async function listMembers(db: Database, serverId: string) {userName: user.name,userEmail: user.email,userImage: user.image,+ userAvatarVersion: user.avatarVersion,userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,discriminator: user.discriminator,@@ -154,6 +155,7 @@ export async function getMembersByUserIds(userName: user.name,userEmail: user.email,userImage: user.image,+ userAvatarVersion: user.avatarVersion,userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,discriminator: user.discriminator,@@ -216,6 +218,7 @@ export async function listMembersPaginated(userName: string | null;userEmail: string;userImage: string | null;+ userAvatarVersion: number;userIsBot: boolean;userOwnerUserId: string | null;discriminator: string | null;@@ -256,6 +259,7 @@ export async function listMembersPaginated(userName: user.name,userEmail: user.email,userImage: user.image,+ userAvatarVersion: user.avatarVersion,userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,discriminator: user.discriminator,@@ -327,6 +331,7 @@ export async function searchMembers(userName: user.name,userEmail: user.email,userImage: user.image,+ userAvatarVersion: user.avatarVersion,discriminator: user.discriminator,statusEmoji: communityUserProfile.statusEmoji,statusText: communityUserProfile.statusText,@@ -381,6 +386,7 @@ export async function getMemberById(userName: user.name,userEmail: user.email,userImage: user.image,+ userAvatarVersion: user.avatarVersion,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 99d9384c1..35c74efe6 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -485,6 +485,7 @@ const listedMessageProjection = {authorName: user.name,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,} as const;export type ListedMessageRow = {@@ -503,6 +504,7 @@ export type ListedMessageRow = {authorName: string;authorEmail: string;authorImage: string | null;+ authorAvatarVersion: number;};function parseEmbeds(r: { id: string; embeds: string | null } & Record<string, unknown>): ListedMessageRow {@@ -969,6 +971,7 @@ export async function getMessage(db: Database, messageId: string) {authorName: user.name,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1022,6 +1025,7 @@ export async function getMessageByAuthorAndNonce(authorName: user.name,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1079,6 +1083,7 @@ export async function getMessagesByIds(db: Database, ids: string[]) {authorName: user.name,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1168,6 +1173,7 @@ export async function getMessageInScope(db: Database, messageId: string, scope:authorName: user.name,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1201,6 +1207,7 @@ export async function getMessagesByIdsInScope(db: Database, ids: string[], scopediscriminator: user.discriminator,authorEmail: user.email,authorImage: user.image,+ authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex aa1e3d95e..8b4906f72 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -30,6 +30,7 @@ export async function createServer(joinedAt: string;userName: string;userImage: string | null;+ userAvatarVersion: number;userDiscriminator: string;};}> {@@ -128,7 +129,12 @@ export async function createServer(// scoped select is honest about intent and avoids `.find` disambiguation// in the caller.const [userRow] = await db- .select({ name: user.name, image: user.image, discriminator: user.discriminator })+ .select({+ name: user.name,+ image: user.image,+ avatarVersion: user.avatarVersion,+ discriminator: user.discriminator,+ }).from(user).where(eq(user.id, data.ownerId));@@ -142,6 +148,7 @@ export async function createServer(// and the createUser/updateUser guards — the `?? ""` is defensive.userName: userRow?.name ?? "",userImage: userRow?.image ?? null,+ userAvatarVersion: userRow?.avatarVersion ?? 0,// NOT NULL column; `?? "0000"` mirrors the schema default defensively.userDiscriminator: userRow?.discriminator ?? "0000",},diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 2cbdd211c..e44f90b4c 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -110,6 +110,7 @@ export async function listThreadParticipants(addedAt: communityChannelMember.addedAt,userName: user.name,userImage: user.image,+ userAvatarVersion: user.avatarVersion,discriminator: user.discriminator,}).from(communityChannelMember)@@ -146,6 +147,7 @@ export async function listParticipantsForChannels(addedAt: communityChannelMember.addedAt,userName: user.name,userImage: user.image,+ userAvatarVersion: user.avatarVersion,participantCount: sql<number>`count(*) over (partition by ${communityChannelMember.channelId})`.as("participant_count"),rank: sql<number>`row_number() over (partition by ${communityChannelMember.channelId} order by ${communityChannelMember.addedAt}, ${communityChannelMember.userId})`.as("participant_rank"),})@@ -163,6 +165,7 @@ export async function listParticipantsForChannels(addedAt: ranked.addedAt,userName: ranked.userName,userImage: ranked.userImage,+ userAvatarVersion: ranked.userAvatarVersion,participantCount: ranked.participantCount,}).from(ranked)@@ -182,6 +185,7 @@ export async function listParticipantsForChannels(addedAt: communityChannelMember.addedAt,userName: user.name,userImage: user.image,+ userAvatarVersion: user.avatarVersion,}).from(communityChannelMember).innerJoin(user, eq(user.id, communityChannelMember.userId))diff --git a/src/shared/src/db/queries/community/user-profile.ts b/src/shared/src/db/queries/community/user-profile.tsindex 55bf65920..ba16f176a 100644--- a/src/shared/src/db/queries/community/user-profile.ts+++ b/src/shared/src/db/queries/community/user-profile.ts@@ -18,6 +18,7 @@ export type PublicProfileForViewer = {name: string;discriminator: string;image: string | null;+ avatarVersion: number;aboutMe: string;bannerColor: string | null;statusEmoji: string | null;@@ -48,6 +49,7 @@ export async function getPublicProfileForViewer(name: target.name,discriminator: target.discriminator,image: target.image,+ avatarVersion: target.avatarVersion,isBot: target.isBot,aboutMe: communityUserProfile.aboutMe,bannerColor: communityUserProfile.bannerColor,@@ -92,6 +94,7 @@ export async function getPublicProfileForViewer(name: row.name,discriminator: row.discriminator,image: row.image,+ avatarVersion: row.avatarVersion,aboutMe: row.aboutMe ?? "",bannerColor: row.bannerColor ?? null,statusEmoji: row.statusEmoji ?? null,diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.tsindex 3648a12dd..87e9c3227 100644--- a/src/shared/src/db/queries/user.ts+++ b/src/shared/src/db/queries/user.ts@@ -38,6 +38,7 @@ const publicUserColumns = {email: user.email,emailVerified: user.emailVerified,image: user.image,+ avatarVersion: user.avatarVersion,createdAt: user.createdAt,updatedAt: user.updatedAt,discriminator: user.discriminator,@@ -56,6 +57,7 @@ export type PublicUser = {email: string;emailVerified: boolean | null;image: string | null;+ avatarVersion: number;createdAt: string;updatedAt: string;discriminator: string;@@ -67,6 +69,69 @@ export type InternalUserFields = {deletedAt: string | null;};+export type AvatarPublishState = {+ id: string;+ image: string | null;+ avatarVersion: number;+ avatarObjectKey: string | null;+};++const avatarPublishColumns = {+ id: user.id,+ image: user.image,+ avatarVersion: user.avatarVersion,+ avatarObjectKey: user.avatarObjectKey,+} as const;++export async function getLiveHumanAvatarState(+ db: Database,+ userId: string+): Promise<AvatarPublishState | null> {+ const rows = await db+ .select(avatarPublishColumns)+ .from(user)+ .where(+ and(+ eq(user.id, userId),+ eq(user.isBot, false),+ isNull(user.deletedAt)+ )+ )+ .limit(1);+ return rows[0] ?? null;+}++export async function publishHumanAvatar(+ db: Database,+ userId: string,+ input: { objectKey: string; stableUrl: string }+): Promise<{ previous: AvatarPublishState; current: AvatarPublishState } | null> {+ const scope = and(+ eq(user.id, userId),+ eq(user.isBot, false),+ isNull(user.deletedAt)+ );+ const before = db.select(avatarPublishColumns).from(user).where(scope).limit(1);+ const publish = db+ .update(user)+ .set({+ image: input.stableUrl,+ avatarVersion: sql`${user.avatarVersion} + 1`,+ avatarObjectKey: input.objectKey,+ updatedAt: new Date().toISOString(),+ })+ .where(scope)+ .returning(avatarPublishColumns);+ const results = (await db.batch([before, publish] as any)) as any[];+ const previous = (Array.isArray(results[0]) ? results[0][0] : undefined) as+ | AvatarPublishState+ | undefined;+ const current = (Array.isArray(results[1]) ? results[1][0] : undefined) as+ | AvatarPublishState+ | undefined;+ return previous && current ? { previous, current } : null;+}+export type InternalUser = PublicUser & InternalUserFields;// ─── Public vs. self lookups (as of 2026-07-09) ─────────────────────────────diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 119d1cc2d..97dbd87c8 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -32,6 +32,8 @@ export const user = sqliteTable(email: text("email").unique().notNull(),emailVerified: integer("emailVerified", { mode: "boolean" }),image: text("image"),+ avatarVersion: integer("avatarVersion").notNull().default(0),+ avatarObjectKey: text("avatarObjectKey"),createdAt: text("createdAt").notNull().$defaultFn(() => new Date().toISOString()),updatedAt: text("updatedAt").notNull().$defaultFn(() => new Date().toISOString()),isBot: integer("isBot", { mode: "boolean" }).notNull().default(false),diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 72fc9da39..67a925a67 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -602,6 +602,7 @@ export type {FriendApprovalProfile,CommunityPresenceUpdate,CommunityStatusUpdate,+ CommunityIdentityUpdate,CommunityMentionCreate,CommunityUnreadBump,CommunityReadStateAdvanced,diff --git a/src/shared/test/community-message-delivery.test.ts b/src/shared/test/community-message-delivery.test.tsindex 542b7cce9..5c1f33307 100644--- a/src/shared/test/community-message-delivery.test.ts+++ b/src/shared/test/community-message-delivery.test.ts@@ -11,6 +11,7 @@ const messageEvent = {seq: 4,authorId: "u1",authorName: "Alice",+ authorAvatarVersion: 0,content: "hello",type: "chat" as const,createdAt: "2026-08-18T00:00:00.000Z",diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.tsindex 523370676..7608087f2 100644--- a/src/shared/test/community-ws-bundle.contract.test.ts+++ b/src/shared/test/community-ws-bundle.contract.test.ts@@ -88,7 +88,7 @@ describe("community WS batch transport contract", () => {expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)})- it("round-trips one strict outer frame without entering the 43-event union", async () => {+ it("round-trips one strict outer frame without entering the 44-event union", async () => {const operationId = await deriveCommunityDeliveryOperationId("message-1")const prepared = await prepareCommunityDeliveryEvents(children)expect(prepared.ok).toBe(true)@@ -116,7 +116,7 @@ describe("community WS batch transport contract", () => {})expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)- expect(Object.values(WS_EVENTS)).toHaveLength(43)+ expect(Object.values(WS_EVENTS)).toHaveLength(44)})it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.tsindex ea955f9f2..405d606fc 100644--- a/src/shared/test/community-ws-events.contract.test.ts+++ b/src/shared/test/community-ws-events.contract.test.ts@@ -65,13 +65,13 @@ describe("Community browser event runtime contract", () => {const fixtures = Object.values(communityWsEventFixtures)const names = Object.values(WS_EVENTS).sort()- it("locks the exact 43-event inventory", () => {- expect(names).toHaveLength(43)+ it("locks the exact 44-event inventory", () => {+ expect(names).toHaveLength(44)expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)})- it("decodes and canonically encodes all 43 current event fixtures", () => {+ it("decodes and canonically encodes all 44 current event fixtures", () => {for (const fixture of fixtures) {expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })const encoded = encodeCommunityBrowserEvent(fixture)diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.tsindex 04e6481cc..b20183827 100644--- a/src/shared/test/community-ws-events.fixtures.ts+++ b/src/shared/test/community-ws-events.fixtures.ts@@ -4,8 +4,8 @@ const approval = {friendshipId: "friendship-1",status: "pending" as const,waitingOn: "you" as const,- otherProfile: { id: "user-2", name: "Other", discriminator: "0002", image: null },- botProfile: { id: "bot-1", name: "Bot", discriminator: "0001", image: null },+ otherProfile: { id: "user-2", name: "Other", discriminator: "0002", image: null, avatarVersion: 0 },+ botProfile: { id: "bot-1", name: "Bot", discriminator: "0001", image: null, avatarVersion: 0 },}const machine = {@@ -33,6 +33,7 @@ export const communityWsEventFixtures = {seq: 1,authorId: "user-1",authorName: "Author",+ authorAvatarVersion: 0,content: "hello",type: "chat",attachments: [{@@ -181,6 +182,7 @@ export const communityWsEventFixtures = {userId: "user-1",name: "Member",discriminator: "0001",+ avatarVersion: 0,role: "member",joinedAt: "2026-01-01T00:00:00.000Z",},@@ -248,6 +250,12 @@ export const communityWsEventFixtures = {statusEmoji: null,statusText: null,},+ "community:identity.update": {+ type: "community:identity.update",+ userId: "user-1",+ avatar: "/api/community/users/user-1/avatar?v=2",+ avatarVersion: 2,+ },"community:machine.created": {type: "community:machine.created",machine,@@ -312,6 +320,7 @@ export const requiredFixturePaths = {"community:inbox.changed": ["reason"],"community:presence.update": ["online"],"community:status.update": ["statusText"],+ "community:identity.update": ["avatarVersion"],"community:machine.created": ["machine"],"community:machine.status": ["lastSeenAt"],"community:machine.updated": ["machine"],diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.tsindex e79db3511..513f035c6 100644--- a/src/shared/test/community-ws-events.test.ts+++ b/src/shared/test/community-ws-events.test.ts@@ -64,7 +64,7 @@ describe("CommunityMessageEdited address contract", () => {describe("isCommunityEvent", () => {it("accepts every exact event declared by WS_EVENTS", () => {- expect(Object.values(WS_EVENTS)).toHaveLength(43);+ expect(Object.values(WS_EVENTS)).toHaveLength(44);for (const type of Object.values(WS_EVENTS)) {expect(isCommunityEvent({ type })).toBe(true);}diff --git a/src/shared/test/queries/community-bot-instruction.test.ts b/src/shared/test/queries/community-bot-instruction.test.tsindex 5ff6663e1..48880647e 100644--- a/src/shared/test/queries/community-bot-instruction.test.ts+++ b/src/shared/test/queries/community-bot-instruction.test.ts@@ -16,6 +16,8 @@ describe("bot owner instruction updates", () => {email TEXT NOT NULL UNIQUE,emailVerified INTEGER,image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0,+ avatarObjectKey TEXT,createdAt TEXT NOT NULL,updatedAt TEXT NOT NULL,isBot INTEGER NOT NULL DEFAULT 0,diff --git a/src/shared/test/queries/community-dm-mark-visibility.test.ts b/src/shared/test/queries/community-dm-mark-visibility.test.tsindex 52d9912bf..bec7c6400 100644--- a/src/shared/test/queries/community-dm-mark-visibility.test.ts+++ b/src/shared/test/queries/community-dm-mark-visibility.test.ts@@ -2,7 +2,10 @@ import Sqlite from "better-sqlite3"import { drizzle } from "drizzle-orm/better-sqlite3"import { afterEach, beforeEach, describe, expect, it } from "vitest"import type { Database } from "../../src/db"-import { listDmChannelIdsForUser } from "../../src/db/queries/community/dm"+import {+ listDmChannelIdsForUser,+ listDmPeerUserIds,+} from "../../src/db/queries/community/dm"describe("listDmChannelIdsForUser — readable mark scope", () => {let sqlite: Sqlite.Database@@ -25,6 +28,10 @@ describe("listDmChannelIdsForUser — readable mark scope", () => {addressee_id TEXT NOT NULL,status TEXT NOT NULL);+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ deletedAt TEXT+ );INSERT INTO community_channel (id, type) VALUES('dm_open', 'dm'),('dm_peer_blocked_me', 'dm'),@@ -39,6 +46,11 @@ describe("listDmChannelIdsForUser — readable mark scope", () => {INSERT INTO community_friendship (requester_id, addressee_id, status) VALUES('peer_blocker', 'me', 'blocked'),('me', 'peer_blocked', 'blocked');+ INSERT INTO user (id, deletedAt) VALUES+ ('me', NULL),+ ('open_peer', NULL),+ ('peer_blocker', NULL),+ ('peer_blocked', NULL);`)db = drizzle(sqlite) as unknown as Database})@@ -48,4 +60,8 @@ describe("listDmChannelIdsForUser — readable mark scope", () => {it("excludes both peer-to-viewer and viewer-to-peer blocks with one batched anti-join", async () => {await expect(listDmChannelIdsForUser(db, "me")).resolves.toEqual(["dm_open"])})++ it("uses the same readable-DM boundary for identity fanout peers", async () => {+ await expect(listDmPeerUserIds(db, "me")).resolves.toEqual(["open_peer"])+ })})diff --git a/src/shared/test/queries/community-forum-message-pagination.test.ts b/src/shared/test/queries/community-forum-message-pagination.test.tsindex 53f750781..0928beb0b 100644--- a/src/shared/test/queries/community-forum-message-pagination.test.ts+++ b/src/shared/test/queries/community-forum-message-pagination.test.ts@@ -17,6 +17,8 @@ describe("forum opener message pagination against real SQLite", () => {name TEXT NOT NULL,email TEXT NOT NULL,image TEXT+ ,avatarVersion INTEGER NOT NULL DEFAULT 0+ ,avatarObjectKey TEXT);CREATE TABLE community_message (id TEXT PRIMARY KEY,diff --git a/src/shared/test/queries/community-friendship-avatar-version.test.ts b/src/shared/test/queries/community-friendship-avatar-version.test.tsnew file mode 100644index 000000000..c617fe500--- /dev/null+++ b/src/shared/test/queries/community-friendship-avatar-version.test.ts@@ -0,0 +1,144 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ createOrGetDM: vi.fn(),+ createMessage: vi.fn(),+ listMessagesReferencingFriendship: vi.fn(),+}))++vi.mock("../../src/db/queries/community/dm", () => ({+ createOrGetDM: (...args: unknown[]) => mocks.createOrGetDM(...args),+}))++vi.mock("../../src/db/queries/community/message", () => ({+ createMessage: (...args: unknown[]) => mocks.createMessage(...args),+ listMessagesReferencingFriendship: (...args: unknown[]) =>+ mocks.listMessagesReferencingFriendship(...args),+}))++import * as friendship from "../../src/db/queries/community/friendship"++function fakeDb(selectRows: unknown[][], updateRows: unknown[][] = []) {+ let selectIndex = 0+ let updateIndex = 0+ const db: any = {+ select: vi.fn(() => {+ const chain: any = {}+ chain.from = vi.fn(() => chain)+ chain.innerJoin = vi.fn(() => chain)+ chain.where = vi.fn(() => Promise.resolve(selectRows[selectIndex++] ?? []))+ chain.limit = vi.fn(() => Promise.resolve(selectRows[selectIndex++] ?? []))+ return chain+ }),+ update: vi.fn(() => {+ const chain: any = {}+ chain.set = vi.fn(() => chain)+ chain.where = vi.fn(() => chain)+ chain.returning = vi.fn(() => Promise.resolve(updateRows[updateIndex++] ?? []))+ return chain+ }),+ insert: vi.fn(() => {+ const chain: any = {}+ chain.values = vi.fn(() => chain)+ chain.returning = vi.fn(() => Promise.resolve([]))+ return chain+ }),+ batch: vi.fn(),+ }+ return db+}++beforeEach(() => {+ vi.clearAllMocks()+ mocks.createOrGetDM.mockResolvedValue({ id: "dm1" })+ mocks.createMessage.mockResolvedValue({+ id: "message1",+ seq: 1,+ content: "approval",+ createdAt: "2026-08-29T00:00:00.000Z",+ })+ mocks.listMessagesReferencingFriendship.mockResolvedValue([])+})++describe("friend approval MESSAGE_CREATE identity", () => {+ it("includes the gating bot avatar version on a newly created approval card", async () => {+ const inserted = {+ id: "friendship1",+ requesterId: "human1",+ addresseeId: "bot1",+ status: "pending",+ needsOwnerApproval: "owner1",+ createdAt: "2026-08-29T00:00:00.000Z",+ updatedAt: "2026-08-29T00:00:00.000Z",+ resolvedAt: null,+ }+ const db = fakeDb([+ [],+ [+ { id: "human1", isBot: false, ownerUserId: null, name: "Human" },+ { id: "bot1", isBot: true, ownerUserId: "owner1", name: "Bot" },+ ],+ [+ { id: "human1", name: "Human", discriminator: "0001", image: null, avatarVersion: 0, isBot: false, ownerUserId: null },+ { id: "bot1", name: "Bot", discriminator: "0002", image: "/bot", avatarVersion: 7, isBot: true, ownerUserId: "owner1" },+ { id: "owner1", name: "Owner", discriminator: "0003", image: null, avatarVersion: 0, isBot: false, ownerUserId: null },+ ],+ ])+ db.batch.mockResolvedValue([[], [inserted]])++ const result = await friendship.sendRequest(db, {+ requesterId: "human1",+ addresseeId: "bot1",+ })++ expect(result.broadcasts[0]?.event).toMatchObject({+ type: "community:message.create",+ message: {+ authorId: "bot1",+ authorAvatarVersion: 7,+ },+ })+ })++ it("includes the second bot avatar version when a two-hop gate advances", async () => {+ const row = {+ id: "friendship2",+ requesterId: "bot1",+ addresseeId: "bot2",+ status: "pending",+ needsOwnerApproval: "owner1",+ createdAt: "2026-08-29T00:00:00.000Z",+ updatedAt: "2026-08-29T00:00:00.000Z",+ resolvedAt: null,+ }+ const updated = { ...row, needsOwnerApproval: "owner2" }+ const db = fakeDb([+ [row],+ [+ { id: "bot1", isBot: true, ownerUserId: "owner1", name: "Bot One" },+ { id: "bot2", isBot: true, ownerUserId: "owner2", name: "Bot Two" },+ ],+ [+ { id: "bot1", name: "Bot One", discriminator: "0001", image: "/bot1", avatarVersion: 4, isBot: true, ownerUserId: "owner1" },+ { id: "bot2", name: "Bot Two", discriminator: "0002", image: "/bot2", avatarVersion: 9, isBot: true, ownerUserId: "owner2" },+ { id: "owner2", name: "Owner Two", discriminator: "0003", image: null, avatarVersion: 0, isBot: false, ownerUserId: null },+ ],+ ], [[updated]])++ const result = await friendship.ownerDecideOnRow(db, {+ friendshipId: "friendship2",+ actorId: "owner1",+ decision: "approve",+ })++ expect(result).toMatchObject({ ok: true })+ if (!result.ok) throw new Error("expected owner decision to succeed")+ expect(result.broadcasts[0]?.event).toMatchObject({+ type: "community:message.create",+ message: {+ authorId: "bot2",+ authorAvatarVersion: 9,+ },+ })+ })+})diff --git a/src/shared/test/queries/community-invite.test.ts b/src/shared/test/queries/community-invite.test.tsindex 9c8c506de..769374738 100644--- a/src/shared/test/queries/community-invite.test.ts+++ b/src/shared/test/queries/community-invite.test.ts@@ -14,6 +14,8 @@ describe("community invite quota consumption", () => {id TEXT PRIMARY KEY,name TEXT NOT NULL,image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0,+ avatarObjectKey TEXT,discriminator TEXT);CREATE TABLE community_server_invite (diff --git a/src/shared/test/queries/community-member-search-sqlite.test.ts b/src/shared/test/queries/community-member-search-sqlite.test.tsindex c6d63ee7f..8153b131d 100644--- a/src/shared/test/queries/community-member-search-sqlite.test.ts+++ b/src/shared/test/queries/community-member-search-sqlite.test.ts@@ -17,6 +17,8 @@ describe("searchMembers literal prefixes against real SQLite", () => {name TEXT NOT NULL,email TEXT NOT NULL UNIQUE,image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0,+ avatarObjectKey TEXT,isBot INTEGER NOT NULL DEFAULT 0,ownerUserId TEXT,discriminator TEXT NOT NULL DEFAULT '0000'diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex 90239e6b1..61f84cad8 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -52,6 +52,8 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {id TEXT PRIMARY KEY,name TEXT NOT NULL,image TEXT+ ,avatarVersion INTEGER NOT NULL DEFAULT 0+ ,avatarObjectKey TEXT);CREATE TABLE community_channel_member (id TEXT PRIMARY KEY,diff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.tsindex b4a20bcfc..04075ad71 100644--- a/src/shared/test/queries/community-user-profile.test.ts+++ b/src/shared/test/queries/community-user-profile.test.ts@@ -43,6 +43,8 @@ describe("getPublicProfileForViewer", () => {email TEXT NOT NULL UNIQUE,emailVerified INTEGER,image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0,+ avatarObjectKey TEXT,createdAt TEXT NOT NULL,updatedAt TEXT NOT NULL,isBot INTEGER NOT NULL DEFAULT 0,@@ -90,6 +92,7 @@ describe("getPublicProfileForViewer", () => {name: "Human",discriminator: "0002",image: "human.png",+ avatarVersion: 0,aboutMe: "",bannerColor: null,statusEmoji: null,@@ -105,6 +108,7 @@ describe("getPublicProfileForViewer", () => {name: "Helper",discriminator: "0100",image: "bot.png",+ avatarVersion: 0,aboutMe: "backend bot",bannerColor: "#123456",statusEmoji: "🛠️",diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex cc2faf1d3..9e7d8c90e 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -162,6 +162,7 @@ describe("createServer", () => {joinedAt: memberRow.joinedAt,userName: "Alice",userImage: "https://avatars/alice.png",+ userAvatarVersion: 0,userDiscriminator: "0042",});});diff --git a/src/web/migrations/0093_user_avatar_version.sql b/src/web/migrations/0093_user_avatar_version.sqlnew file mode 100644index 000000000..f437e155c--- /dev/null+++ b/src/web/migrations/0093_user_avatar_version.sql@@ -0,0 +1,2 @@+ALTER TABLE `user` ADD `avatarVersion` integer DEFAULT 0 NOT NULL;+ALTER TABLE `user` ADD `avatarObjectKey` text;diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.tsindex aac9d622d..59422d28c 100644--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts@@ -4,6 +4,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { fanOutToServerMembers } from "@/lib/community/fanout"+import { canonicalUserImage } from "@/lib/community/storage"/*** Approve a pending bot approval request. After migration 0065 only the@@ -50,7 +51,8 @@ export const POST = withAuth(async (_req, ctx) => {userId: botId,name: bot.name,discriminator: bot.discriminator,- avatar: bot.image ?? undefined,+ avatar: canonicalUserImage(bot.id, bot.image, bot.avatarVersion) ?? undefined,+ avatarVersion: bot.avatarVersion,role: added.role ?? ROLES.MEMBER,joinedAt: added.joinedAt,},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 3db97293e..5a159a916 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@@ -6,6 +6,9 @@ const mockGetBotOwnedBy = vi.fn()const mockGetLiveBotAvatar = vi.fn()const mockHandleBotAvatarUpload = vi.fn()const mockPersistUploadedBotAvatar = vi.fn()+const mockEnsureAvatarAliasPresent = vi.fn()+const mockScheduleAvatarMediaReconciliation = vi.fn()+const mockFanOutIdentityUpdate = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } } })),@@ -34,6 +37,15 @@ vi.mock("@/lib/community/bot-avatar-persistence", () => ({persistUploadedBotAvatar: (...a: unknown[]) => mockPersistUploadedBotAvatar(...a),}))+vi.mock("@/lib/community/avatar-media-reconciliation", () => ({+ ensureAvatarAliasPresent: (...a: unknown[]) => mockEnsureAvatarAliasPresent(...a),+ scheduleAvatarMediaReconciliation: (...a: unknown[]) => mockScheduleAvatarMediaReconciliation(...a),+}))++vi.mock("@/lib/community/fanout", () => ({+ fanOutIdentityUpdate: (...a: unknown[]) => mockFanOutIdentityUpdate(...a),+}))+let isAuthed = truevi.mock("@/lib/middleware/auth", () => ({@@ -62,8 +74,9 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET, POST } from "./route"-function getReq() {- return new NextRequest("http://localhost/api/community/bots/b1/avatar", { method: "GET" })+function getReq(version?: number) {+ const suffix = version === undefined ? "" : `?v=${version}`+ return new NextRequest(`http://localhost/api/community/bots/b1/avatar${suffix}`, { method: "GET" })}function postReq() {return new NextRequest("http://localhost/api/community/bots/b1/avatar", { method: "POST" })@@ -79,6 +92,8 @@ describe("GET /api/community/bots/[id]/avatar", () => {mockGetLiveBotAvatar.mockResolvedValue({id: "b1",image: "/api/community/bots/b1/avatar",+ avatarVersion: 0,+ avatarObjectKey: null,})mediaGet.mockResolvedValue({body: new ReadableStream(),@@ -111,12 +126,31 @@ describe("GET /api/community/bots/[id]/avatar", () => {})it("returns 404 before R2 for a live bot with a noncanonical image", async () => {- mockGetLiveBotAvatar.mockResolvedValue({ id: "b1", image: "avatar:beam-seed" })+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "avatar:beam-seed",+ avatarVersion: 0,+ avatarObjectKey: null,+ })const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(404)expect(mediaGet).not.toHaveBeenCalled()})+ it("returns 404 before R2 for an inconsistent version/object-key pair", async () => {+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ avatarVersion: 4,+ avatarObjectKey: null,+ })++ const res = await GET(getReq(4), ctx("b1"))++ expect(res.status).toBe(404)+ expect(mediaGet).not.toHaveBeenCalled()+ })+it("returns 400 when the bot id route param is missing", async () => {const res = await GET(getReq(), ctx(undefined))expect(res.status).toBe(400)@@ -129,6 +163,45 @@ describe("GET /api/community/bots/[id]/avatar", () => {expect(res.status).toBe(404)})+ it("redirects the stable route to the authoritative immutable version", async () => {+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ avatarVersion: 4,+ avatarObjectKey: "bot-avatar/b1/objects/object-4",+ })++ const res = await GET(getReq(), ctx("b1"))++ expect(res.status).toBe(307)+ expect(res.headers.get("Location")).toBe("/api/community/bots/b1/avatar?v=4")+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")+ expect(mediaGet).not.toHaveBeenCalled()+ })++ it("serves only the authoritative immutable child for the matching version", async () => {+ mockGetLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ avatarVersion: 4,+ avatarObjectKey: "bot-avatar/b1/objects/object-4",+ })++ const res = await GET(getReq(4), ctx("b1"))++ expect(res.status).toBe(200)+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")+ expect(mediaGet).toHaveBeenCalledWith("bot-avatar/b1/objects/object-4")+ })++ it("redirects a version query away from a legacy alias", async () => {+ const res = await GET(getReq(4), ctx("b1"))++ expect(res.status).toBe(307)+ expect(res.headers.get("Location")).toBe("/api/community/bots/b1/avatar")+ expect(mediaGet).not.toHaveBeenCalled()+ })+it("serves cached bytes while revalidating the deterministic URL in the background", async () => {const res = await GET(getReq(), ctx("b1"))expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")@@ -152,11 +225,18 @@ describe("POST /api/community/bots/[id]/avatar", () => {vi.clearAllMocks()isAuthed = truemockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerId: "u1" })- mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "persisted" })+ mockPersistUploadedBotAvatar.mockResolvedValue({+ kind: "persisted",+ avatarVersion: 2,+ avatarObjectKey: "bot-avatar/b1/objects/object-2",+ previousObjectKey: null,+ })+ mockEnsureAvatarAliasPresent.mockResolvedValue(true)+ mockScheduleAvatarMediaReconciliation.mockResolvedValue(undefined)mockHandleBotAvatarUpload.mockResolvedValue({ok: true,id: "b1",- key: "bot-avatar/b1",+ key: "bot-avatar/b1/objects/object-2",url: "/api/community/media/bot-avatar/b1",filename: "bot.png",contentType: "image/png",@@ -192,12 +272,17 @@ describe("POST /api/community/bots/[id]/avatar", () => {it("uploads and updates the bot's image to the routable avatar URL", async () => {const res = await POST(postReq(), ctx("b1"))expect(res.status).toBe(200)- const body = await res.json() as { url: string }- expect(body.url).toBe("/api/community/bots/b1/avatar")+ const body = await res.json() as { url: string; avatarVersion: number }+ expect(body).toEqual({ url: "/api/community/bots/b1/avatar?v=2", avatarVersion: 2 })expect(mockPersistUploadedBotAvatar).toHaveBeenCalledWith(expect.anything(),expect.anything(),- { botId: "b1", ownerId: "u1" },+ { botId: "b1", ownerId: "u1", objectKey: "bot-avatar/b1/objects/object-2" },+ )+ expect(mockFanOutIdentityUpdate).toHaveBeenCalledWith(+ "b1",+ "/api/community/bots/b1/avatar?v=2",+ 2,)})@@ -212,4 +297,14 @@ describe("POST /api/community/bots/[id]/avatar", () => {const res = await POST(postReq(), ctx("b1"))expect(res.status).toBe(500)})++ it("fails closed when the immutable child cannot publish its stable alias", async () => {+ mockEnsureAvatarAliasPresent.mockResolvedValue(false)++ const res = await POST(postReq(), ctx("b1"))++ expect(res.status).toBe(500)+ expect(mockScheduleAvatarMediaReconciliation).not.toHaveBeenCalled()+ expect(mockFanOutIdentityUpdate).not.toHaveBeenCalled()+ })})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 c921104ef..7c9fb2037 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@@ -1,39 +1,73 @@import { NextRequest } from "next/server"-import { queries, CACHE_REVALIDATE } from "@alook/shared"+import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"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 {+ ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,+ buildBotAvatarKey,+ botAvatarUrl,+ isOwnedBotAvatarObjectKey,+} from "@/lib/community/storage"import { persistUploadedBotAvatar } from "@/lib/community/bot-avatar-persistence"+import {+ ensureAvatarAliasPresent,+ scheduleAvatarMediaReconciliation,+} from "@/lib/community/avatar-media-reconciliation"+import { fanOutIdentityUpdate } from "@/lib/community/fanout"++const log = createLogger({ service: "community-bot-avatar-route" })+const PRIVATE_NO_STORE = "private, no-store"-// No ownership check — other members/DM peers need to see a bot's avatar.-//-// The URL never changes across re-uploads (deterministic key). Let the browser-// paint stale bytes while it revalidates the R2 ETag in the background, so a-// warm avatar never waits behind a network round trip.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)) {+ const state = await queries.communityBot.getLiveBotAvatar(db, botId)+ if (!state || state.image !== botAvatarUrl(botId)) return writeError("not found", 404)++ const legacy = state.avatarVersion === 0 && state.avatarObjectKey === null+ const versioned = state.avatarVersion > 0+ && state.avatarObjectKey !== null+ && isOwnedBotAvatarObjectKey(state.avatarObjectKey, botId)+ if (!legacy && !versioned) {+ log.warn("community_bot_avatar_state_inconsistent", { stateKind: "invalid_pair" })return writeError("not found", 404)}- const obj = await ctx.env.COMMUNITY_MEDIA.get(buildBotAvatarKey(botId))- if (!obj) return writeError("not found", 404)+ let key = buildBotAvatarKey(botId)+ let cacheControl = CACHE_REVALIDATE+ if (versioned) {+ if (req.nextUrl.searchParams.get("v") !== String(state.avatarVersion)) {+ return new Response(null, {+ status: 307,+ headers: {+ Location: botAvatarUrl(botId, state.avatarVersion),+ "Cache-Control": PRIVATE_NO_STORE,+ },+ })+ }+ key = state.avatarObjectKey!+ cacheControl = ATTACHMENT_PRIVATE_IMMUTABLE_CACHE+ } else if (req.nextUrl.searchParams.has("v")) {+ return new Response(null, {+ status: 307,+ headers: { Location: botAvatarUrl(botId), "Cache-Control": PRIVATE_NO_STORE },+ })+ }+ const obj = await ctx.env.COMMUNITY_MEDIA.get(key)+ if (!obj) return writeError("not found", 404)const etag = obj.httpEtagif (etag && req.headers.get("if-none-match") === etag) {- return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": CACHE_REVALIDATE } })+ return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": cacheControl } })}-return new Response(obj.body, {headers: {"Content-Type": obj.httpMetadata?.contentType ?? "image/png",- "Cache-Control": CACHE_REVALIDATE,+ "Cache-Control": cacheControl,...(etag ? { ETag: etag } : {}),},})@@ -44,19 +78,31 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!botId) return writeError("missing bot id", 400)const db = getDb(ctx.env.DB)- const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)- if (!bot) return writeError("bot not found", 404)-- const result = await handleBotAvatarUpload(req, ctx.env, botId)- if (!result.ok) return result.response+ if (!(await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId))) {+ return writeError("bot not found", 404)+ }- const url = botAvatarUrl(botId)+ const upload = await handleBotAvatarUpload(req, ctx.env, botId)+ if (!upload.ok) return upload.responseconst persisted = await persistUploadedBotAvatar(db, ctx.env.COMMUNITY_MEDIA, {botId,ownerId: ctx.userId,+ objectKey: upload.key,})if (persisted.kind === "not_found") return writeError("bot not found", 404)if (persisted.kind === "failed") return writeError("internal error", 500)- return writeJSON({ url })+ const subject = { kind: "bot" as const, id: botId }+ if (!(await ensureAvatarAliasPresent(db, ctx.env.COMMUNITY_MEDIA, subject))) {+ log.warn("community_bot_avatar_alias_unavailable", { phase: "before_response" })+ return writeError("internal error", 500)+ }+ void scheduleAvatarMediaReconciliation(db, ctx.env.COMMUNITY_MEDIA, {+ subject,+ candidates: [persisted.previousObjectKey, persisted.avatarObjectKey],+ })++ const url = botAvatarUrl(botId, persisted.avatarVersion)+ void fanOutIdentityUpdate(botId, url, persisted.avatarVersion)+ return writeJSON({ url, avatarVersion: persisted.avatarVersion })})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 b97fc3fbc..47a3d34ce 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@@ -93,7 +93,7 @@ vi.mock("@/lib/middleware/helpers", async () => {}})-import { DELETE, PATCH } from "./route"+import { DELETE, GET, PATCH } from "./route"function patchReq(body: unknown) {return new NextRequest("http://localhost/api/community/bots/b1", {@@ -103,6 +103,38 @@ function patchReq(body: unknown) {}const ctx = { params: { id: "b1" } } as any+describe("GET /api/community/bots/[id]", () => {+ it("returns the owned bot with a canonical versioned avatar", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1",+ name: "Bot",+ discriminator: "0042",+ image: "/api/community/bots/b1/avatar",+ avatarVersion: 4,+ description: "helper",+ machineId: "mac1",+ runtime: "codex",+ modelName: null,+ reasoningEffort: null,+ runtimeConfigRevision: 2,+ })++ const res = await GET(+ new NextRequest("http://localhost/api/community/bots/b1"),+ ctx,+ )++ expect(res.status).toBe(200)+ expect(await res.json()).toMatchObject({+ bot: {+ id: "b1",+ image: "/api/community/bots/b1/avatar?v=4",+ avatarVersion: 4,+ },+ })+ })+})+describe("PATCH /api/community/bots/[id]", () => {beforeEach(() => {vi.clearAllMocks()@@ -655,6 +687,23 @@ describe("DELETE /api/community/bots/[id]", () => {)})+ it("cleans the owned immutable child together with the stable alias", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1",+ ownerUserId: "u1",+ machineId: null,+ avatarObjectKey: "bot-avatar/b1/objects/object-7",+ })++ const res = await DELETE(deleteReq(), ctx)++ expect(res.status).toBe(204)+ expect(mockMediaDelete).toHaveBeenCalledWith([+ "bot-avatar/b1/objects/object-7",+ "bot-avatar/b1",+ ])+ })+it("returns 404 with no cleanup or events for an already-deleted loser", async () => {mockSoftDeleteBot.mockResolvedValue(false)diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex 9be2ebf4b..7e29ae616 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -1,6 +1,11 @@import { NextRequest } from "next/server"import { NextResponse } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"+import {+ buildBotAvatarKey,+ canonicalUserImage,+ isOwnedBotAvatarObjectKey,+} from "@/lib/community/storage"import { nanoid } from "nanoid"import {queries,@@ -23,7 +28,6 @@ import {} 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" })@@ -32,7 +36,25 @@ export const GET = withAuth(async (_req, ctx) => {const id = ctx.params?.id as stringconst bot = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)if (!bot) return writeError("bot not found", 404)- return writeJSON({ bot })+ return writeJSON({+ bot: {+ id: bot.id,+ name: bot.name,+ discriminator: bot.discriminator,+ image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),+ avatarVersion: bot.avatarVersion,+ ownerUserId: bot.ownerUserId,+ description: bot.description,+ createdAt: bot.createdAt,+ updatedAt: bot.updatedAt,+ lastRefreshContextAt: bot.lastRefreshContextAt,+ machineId: bot.machineId,+ runtime: bot.runtime,+ modelName: bot.modelName,+ reasoningEffort: bot.reasoningEffort,+ runtimeConfigRevision: bot.runtimeConfigRevision,+ },+ })})export const PATCH = withAuth(async (req: NextRequest, ctx) => {@@ -213,7 +235,8 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {id,name: updated.name,description: updated.description,- image: updated.image,+ image: canonicalUserImage(id, updated.image, updated.avatarVersion),+ avatarVersion: updated.avatarVersion,runtime: targetRuntime,modelName: storedModel,reasoningEffort: storedEffort,@@ -255,7 +278,8 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {id,name: updated.name,description: updated.description,- image: updated.image,+ image: canonicalUserImage(id, updated.image, updated.avatarVersion),+ avatarVersion: updated.avatarVersion,runtime: targetRuntime,modelName: nextModel !== undefined ? nextModel : (before.modelName ?? null),reasoningEffort: storedEffort,@@ -296,7 +320,12 @@ export const DELETE = withAuth(async (_req, ctx) => {if (!ok) return writeError("bot not found", 404)scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {- keys: [buildBotAvatarKey(id)],+ keys: [+ ...(before.avatarObjectKey && isOwnedBotAvatarObjectKey(before.avatarObjectKey, id)+ ? [before.avatarObjectKey]+ : []),+ buildBotAvatarKey(id),+ ],warning: {event: "community_bot_avatar_cleanup_failed",fields: { botId: id, phase: "bot_delete" },diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex be6aed441..4c926dc44 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -10,6 +10,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"import { pushBotEventToMachine } from "@/lib/community/bot-push"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)@@ -36,6 +37,7 @@ export const GET = withAuth(async (_req, ctx) => {)const withActivity = bots.map((bot) => ({...bot,+ image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),dailyActivity: activityByBot.get(bot.id) ?? [],usage: {capability: (["claude", "codex", "opencode"] as string[]).includes(bot.runtime)@@ -169,6 +171,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {name: created.name,description: created.description,image: created.image,+ avatarVersion: 0,machineId: body.machineId,runtime: body.runtime,modelName,diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.tsindex b8b5766a2..b8425b07c 100644--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts@@ -7,6 +7,7 @@ import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"import { requirePinnableSurface } from "@/lib/community/channel-write-guard"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (_req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -31,7 +32,9 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {// why the pinned panel showed no avatar for image-less authors.authorId: r.author.id,authorName: r.author.name,- authorAvatar: r.author.image ?? avatarInitial(r.author.name),+ authorAvatar: canonicalUserImage(r.author.id, r.author.image, r.author.avatarVersion)+ ?? avatarInitial(r.author.name),+ authorAvatarVersion: r.author.avatarVersion,content: r.message.content,createdAt: r.message.createdAt,}))diff --git a/src/web/src/app/api/community/friends/accepted/route.ts b/src/web/src/app/api/community/friends/accepted/route.tsindex 37ce586db..fd361855c 100644--- a/src/web/src/app/api/community/friends/accepted/route.ts+++ b/src/web/src/app/api/community/friends/accepted/route.ts@@ -3,6 +3,7 @@ import { queries, readOrStale } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"/**@@ -46,7 +47,9 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {userId: f.friendUserId,name: f.friendName,discriminator: f.friendDiscriminator,- avatar: f.friendImage ?? avatarInitial(f.friendName),+ avatar: canonicalUserImage(f.friendUserId, f.friendImage, f.friendAvatarVersion)+ ?? avatarInitial(f.friendName),+ avatarVersion: f.friendAvatarVersion,status: "offline" as const,sub: "",statusEmoji: f.statusEmoji ?? null,diff --git a/src/web/src/app/api/community/friends/blocked/route.ts b/src/web/src/app/api/community/friends/blocked/route.tsindex 226ec5c46..8da81e585 100644--- a/src/web/src/app/api/community/friends/blocked/route.ts+++ b/src/web/src/app/api/community/friends/blocked/route.ts@@ -3,6 +3,7 @@ import { queries, readOrStale } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"/*** GET /api/community/friends/blocked — the blocked bucket (route/disc trunk,@@ -30,7 +31,9 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {id: b.id,userId: b.blockedUserId,name: b.blockedName,- avatar: b.blockedImage ?? avatarInitial(b.blockedName),+ avatar: canonicalUserImage(b.blockedUserId, b.blockedImage, b.blockedAvatarVersion)+ ?? avatarInitial(b.blockedName),+ avatarVersion: b.blockedAvatarVersion,}))return NextResponse.json(stale ? { blocked, stale: true } : { blocked })})diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.tsindex 004dd945f..f66117769 100644--- a/src/web/src/app/api/community/friends/pending/route.ts+++ b/src/web/src/app/api/community/friends/pending/route.ts@@ -3,6 +3,7 @@ import { queries, readOrStale } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"/**@@ -50,7 +51,8 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {id: r.id,userId: r.userId,name: r.name,- avatar: r.image ?? avatarInitial(r.name),+ avatar: canonicalUserImage(r.userId, r.image, r.avatarVersion) ?? avatarInitial(r.name),+ avatarVersion: r.avatarVersion,kind: r.kind,needsOwnerApproval: r.needsOwnerApproval,}))diff --git a/src/web/src/app/api/community/invites/[token]/info/route.ts b/src/web/src/app/api/community/invites/[token]/info/route.tsindex fca5febd7..95846c05f 100644--- a/src/web/src/app/api/community/invites/[token]/info/route.ts+++ b/src/web/src/app/api/community/invites/[token]/info/route.ts@@ -2,7 +2,7 @@ import { withOptionalAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { serverIconUrl } from "@/lib/community/storage"+import { canonicalUserImage, serverIconUrl } from "@/lib/community/storage"import { avatarInitial } from "@/lib/community/avatar"// How many member avatars the landing page previews. A small strip ("who's@@ -57,7 +57,9 @@ export const GET = withOptionalAuth(async (_req, ctx) => {const members = await queries.communityMember.listMembers(db, invite.serverId)const memberPreview = members.slice(0, MEMBER_PREVIEW_LIMIT).map((m) => ({id: m.userId,- avatar: m.userImage ?? avatarInitial(m.userName),+ avatar: canonicalUserImage(m.userId, m.userImage, m.userAvatarVersion)+ ?? avatarInitial(m.userName),+ avatarVersion: m.userAvatarVersion,}))return writeJSON({@@ -68,7 +70,13 @@ export const GET = withOptionalAuth(async (_req, ctx) => {memberCount,memberPreview,inviter: inviter- ? { id: inviter.id, name: inviter.name, avatar: inviter.image ?? avatarInitial(inviter.name) }+ ? {+ id: inviter.id,+ name: inviter.name,+ avatar: canonicalUserImage(inviter.id, inviter.image, inviter.avatarVersion)+ ?? avatarInitial(inviter.name),+ avatarVersion: inviter.avatarVersion,+ }: null,})})diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.tsindex 6f80c32c2..c455c9001 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts@@ -4,6 +4,7 @@ import { queries, ROLES, WS_EVENTS, isUniqueConstraintError } from "@alook/shareimport type { CommunityMemberJoin } from "@alook/shared"import { withCommunityActor } from "@/lib/middleware/community-actor"import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"+import { canonicalUserImage } from "@/lib/community/storage"/*** POST /api/community/invites/[token]/join — the unified join route (plan §4@@ -70,7 +71,12 @@ export const POST = withCommunityActor(async (_req, ctx) => {userId: result.member.userId,name: result.member.userName ?? "",discriminator: result.member.discriminator ?? undefined,- avatar: result.member.userImage ?? undefined,+ avatar: canonicalUserImage(+ result.member.userId,+ result.member.userImage,+ result.member.userAvatarVersion,+ ) ?? undefined,+ avatarVersion: result.member.userAvatarVersion,role: result.member.role ?? ROLES.MEMBER,joinedAt: result.member.joinedAt,},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.tsindex d69506219..53597b091 100644--- a/src/web/src/app/api/community/machines/[id]/route.test.ts+++ b/src/web/src/app/api/community/machines/[id]/route.test.ts@@ -6,6 +6,7 @@ const mockWaitUntil = vi.fn()const mockMediaDelete = vi.fn()const mockGetMachineByIdForUser = vi.fn()const mockListBotsBoundToMachine = vi.fn()+const mockGetBotOwnedBy = vi.fn()const mockListBotServerMemberships = vi.fn()const mockSoftDeleteBot = vi.fn()const mockRevokeCredentialsForMachine = vi.fn()@@ -27,6 +28,7 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityBot: {+ getBotOwnedBy: (...args: unknown[]) => mockGetBotOwnedBy(...args),listBotsBoundToMachine: (...args: unknown[]) => mockListBotsBoundToMachine(...args),listBotServerMemberships: (...args: unknown[]) => mockListBotServerMemberships(...args),softDeleteBot: (...args: unknown[]) => mockSoftDeleteBot(...args),@@ -89,6 +91,10 @@ describe("DELETE /api/community/machines/[id]", () => {vi.clearAllMocks()mockGetMachineByIdForUser.mockResolvedValue({ id: "m1", userId: "u1" })mockListBotsBoundToMachine.mockResolvedValue([])+ mockGetBotOwnedBy.mockImplementation(async (_db: unknown, id: string) => ({+ id,+ avatarObjectKey: null,+ }))mockListBotServerMemberships.mockResolvedValue([])mockSoftDeleteBot.mockResolvedValue(true)mockRevokeCredentialsForMachine.mockResolvedValue({ doNames: ["do-1"] })@@ -151,11 +157,17 @@ describe("DELETE /api/community/machines/[id]", () => {.mockResolvedValueOnce(["s1"]).mockResolvedValueOnce(["s2"])mockSoftDeleteBot.mockResolvedValueOnce(true).mockResolvedValueOnce(false)+ mockGetBotOwnedBy+ .mockResolvedValueOnce({ id: "b1", avatarObjectKey: "bot-avatar/b1/objects/current" })+ .mockResolvedValueOnce({ id: "b2", avatarObjectKey: "bot-avatar/b2/objects/current" })const res = await DELETE(request(true), ctx)expect(res.status).toBe(204)- expect(mockMediaDelete).toHaveBeenCalledWith(["bot-avatar/b1"])+ expect(mockMediaDelete).toHaveBeenCalledWith([+ "bot-avatar/b1/objects/current",+ "bot-avatar/b1",+ ])expect(mockWaitUntil).toHaveBeenCalledOnce()expect(mockFanOutToServerMembers).toHaveBeenCalledOnce()expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {diff --git a/src/web/src/app/api/community/machines/[id]/route.ts b/src/web/src/app/api/community/machines/[id]/route.tsindex f5d4768e2..3f606e638 100644--- a/src/web/src/app/api/community/machines/[id]/route.ts+++ b/src/web/src/app/api/community/machines/[id]/route.ts@@ -8,7 +8,7 @@ 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"+import { buildBotAvatarKey, isOwnedBotAvatarObjectKey } from "@/lib/community/storage"export const DELETE = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)@@ -49,10 +49,18 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const avatarKeys: string[] = []try {for (const bot of bots) {+ const before = await queries.communityBot.getBotOwnedBy(db, bot.id, ctx.userId)+ if (!before) continueconst priorMemberships =await queries.communityBot.listBotServerMemberships(db, bot.id, ctx.userId)const deleted = await queries.communityBot.softDeleteBot(db, bot.id, ctx.userId)if (!deleted) continue+ if (+ before.avatarObjectKey+ && isOwnedBotAvatarObjectKey(before.avatarObjectKey, bot.id)+ ) {+ avatarKeys.push(before.avatarObjectKey)+ }avatarKeys.push(buildBotAvatarKey(bot.id))for (const serverId of priorMemberships) {fanOutToServerMembers(serverId, {diff --git a/src/web/src/app/api/community/messages/search/route.test.ts b/src/web/src/app/api/community/messages/search/route.test.tsindex dc0d88c92..d966fd92a 100644--- a/src/web/src/app/api/community/messages/search/route.test.ts+++ b/src/web/src/app/api/community/messages/search/route.test.ts@@ -8,6 +8,10 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetMember = vi.fn()const mockListVisibleChannelIds = vi.fn()const mockSearchMessagesInServer = vi.fn()+const mockSearchMessages = vi.fn()+const mockRequireServerMember = vi.fn()+const mockRequireChannelMember = vi.fn()+const mockRequireDMAccess = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -18,7 +22,10 @@ vi.mock("@alook/shared", async () => {queries: {communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },communityChannel: { listVisibleChannelIds: (...a: unknown[]) => mockListVisibleChannelIds(...a) },- communitySearch: { searchMessagesInServer: (...a: unknown[]) => mockSearchMessagesInServer(...a) },+ communitySearch: {+ searchMessagesInServer: (...a: unknown[]) => mockSearchMessagesInServer(...a),+ searchMessages: (...a: unknown[]) => mockSearchMessages(...a),+ },},}})@@ -30,6 +37,12 @@ vi.mock("@/lib/middleware/auth", () => ({}),}))+vi.mock("@/lib/community/permissions", () => ({+ requireServerMember: (...a: unknown[]) => mockRequireServerMember(...a),+ requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),+ requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),+}))+vi.mock("@/lib/middleware/helpers", () => {const { NextResponse } = require("next/server")return {@@ -46,6 +59,10 @@ describe("GET /api/community/messages/search — server scope", () => {mockGetMember.mockResolvedValue({ id: "m1", role: "member" })mockListVisibleChannelIds.mockResolvedValue(["c_pub", "c_priv_mine"])mockSearchMessagesInServer.mockResolvedValue([])+ mockSearchMessages.mockResolvedValue([])+ mockRequireServerMember.mockResolvedValue({ ok: true, value: { id: "m1" } })+ mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1" } })+ mockRequireDMAccess.mockResolvedValue({ ok: true, value: { id: "dm1" } })})it("scopes the server search to the viewer's visible channel ids", async () => {@@ -77,4 +94,64 @@ describe("GET /api/community/messages/search — server scope", () => {expect.anything(), "s1", "u1",)})++ it("returns only canonical versioned author identity fields", async () => {+ mockSearchMessagesInServer.mockResolvedValue([{+ message: { id: "message-1", content: "hello" },+ author: {+ id: "author-1",+ name: "Alice",+ discriminator: "0001",+ image: "/api/community/users/author-1/avatar",+ avatarVersion: 4,+ avatarObjectKey: "user-avatar/author-1/objects/private-key",+ },+ }])++ const res = await GET(+ new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),+ { params: {} } as any,+ )++ expect(await res.json()).toEqual({+ results: [{+ message: { id: "message-1", content: "hello" },+ author: {+ id: "author-1",+ name: "Alice",+ discriminator: "0001",+ image: "/api/community/users/author-1/avatar?v=4",+ avatarVersion: 4,+ },+ }],+ })+ })++ it("projects channel-scoped search results", async () => {+ const res = await GET(+ new NextRequest("http://localhost/api/community/messages/search?q=hello&channelId=c1"),+ { params: {} } as any,+ )++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ results: [] })+ expect(mockSearchMessages).toHaveBeenCalledWith(+ expect.anything(),+ { query: "hello", channelId: "c1" },+ )+ })++ it("projects DM-scoped search results", async () => {+ const res = await GET(+ new NextRequest("http://localhost/api/community/messages/search?q=hello&dmConversationId=dm1"),+ { params: {} } as any,+ )++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ results: [] })+ expect(mockSearchMessages).toHaveBeenCalledWith(+ expect.anything(),+ { query: "hello", channelId: "dm1" },+ )+ })})diff --git a/src/web/src/app/api/community/messages/search/route.ts b/src/web/src/app/api/community/messages/search/route.tsindex 2dfa3ef2a..efc6cb4f4 100644--- a/src/web/src/app/api/community/messages/search/route.ts+++ b/src/web/src/app/api/community/messages/search/route.ts@@ -3,6 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"+import { canonicalUserImage } from "@/lib/community/storage"import {requireServerMember,requireChannelMember,@@ -44,7 +45,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {serverId,visibleChannelIds,})- return writeJSON({ results })+ return writeJSON({ results: projectResults(results) })}if (channelId) {@@ -54,7 +55,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {query: q,channelId,})- return writeJSON({ results })+ return writeJSON({ results: projectResults(results) })}// A DM is a `type=dm` channel now; the `dmConversationId` query param IS the@@ -66,5 +67,18 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {query: q,channelId: dmConversationId!,})- return writeJSON({ results })+ return writeJSON({ results: projectResults(results) })})++function projectResults(results: Awaited<ReturnType<typeof queries.communitySearch.searchMessages>>) {+ return results.map(({ message, author }) => ({+ message,+ author: {+ id: author.id,+ name: author.name,+ discriminator: author.discriminator,+ image: canonicalUserImage(author.id, author.image, author.avatarVersion),+ avatarVersion: author.avatarVersion,+ },+ }))+}diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts b/src/web/src/app/api/community/servers/[id]/bots/route.test.tsindex cc9171ff4..c9edd4e64 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts@@ -17,6 +17,7 @@ const mockCreateOrGetDM = vi.fn()const mockCreateApprovalRequestStatement = vi.fn()const mockHardDeleteMessage = vi.fn()const mockLogError = vi.fn()+const mockFanOutToServerMembers = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -55,7 +56,7 @@ vi.mock("@alook/shared", async () => {})vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: vi.fn(),+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),broadcastToUserSafe: vi.fn(),}))@@ -154,4 +155,76 @@ describe("POST /servers/[id]/bots — approval-request rollback failure", () =>expect(order).toEqual(["approval", "dispatch"])expect(broadcast).toHaveBeenCalledTimes(1)})++ it("owner-add fans out the bot's canonical versioned identity", async () => {+ mockGetMember+ .mockResolvedValueOnce({ id: "caller-member", nickname: "Owner" })+ .mockResolvedValueOnce(null)+ mockGetUserInternal.mockResolvedValue({+ id: "bot1",+ isBot: true,+ deletedAt: null,+ ownerUserId: "u1",+ name: "Bot",+ })+ mockAddMember.mockResolvedValue({+ id: "bot-member",+ role: "member",+ joinedAt: "2026-01-02T00:00:00Z",+ })+ mockGetUserSelf.mockResolvedValue({+ id: "bot1",+ name: "Bot",+ discriminator: "0042",+ image: "/api/community/bots/bot1/avatar",+ avatarVersion: 5,+ })++ const res = await POST(req({ botId: "bot1" }), ctx)++ expect(res.status).toBe(201)+ expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {+ type: "community:member.join",+ serverId: "s1",+ member: expect.objectContaining({+ userId: "bot1",+ avatar: "/api/community/bots/bot1/avatar?v=5",+ avatarVersion: 5,+ }),+ })+ })++ it("owner-add falls back to an empty identity when the bot profile disappears", async () => {+ mockGetMember+ .mockResolvedValueOnce({ id: "caller-member", nickname: "Owner" })+ .mockResolvedValueOnce(null)+ mockGetUserInternal.mockResolvedValue({+ id: "bot1",+ isBot: true,+ deletedAt: null,+ ownerUserId: "u1",+ name: "Bot",+ })+ mockAddMember.mockResolvedValue({+ id: "bot-member",+ role: "member",+ joinedAt: "2026-01-02T00:00:00Z",+ })+ mockGetUserSelf.mockResolvedValue(null)++ const res = await POST(req({ botId: "bot1" }), ctx)++ expect(res.status).toBe(201)+ expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {+ type: "community:member.join",+ serverId: "s1",+ member: expect.objectContaining({+ userId: "bot1",+ name: "",+ discriminator: "0000",+ avatar: undefined,+ avatarVersion: 0,+ }),+ })+ })})diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex 982eae4ee..4fecc3897 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -12,6 +12,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"import { fanOutToServerMembers } from "@/lib/community/fanout"import { createCommunityMessage } from "@/lib/community/message-handler"+import { canonicalUserImage } from "@/lib/community/storage"const log = createLogger({ service: "community-bots-server-add" })@@ -62,7 +63,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {userId: botId,name: bot?.name ?? "",discriminator: bot?.discriminator ?? "0000",- avatar: bot?.image ?? undefined,+ avatar: bot+ ? canonicalUserImage(bot.id, bot.image, bot.avatarVersion) ?? undefined+ : undefined,+ avatarVersion: bot?.avatarVersion ?? 0,role: added.role ?? ROLES.MEMBER,joinedAt: added.joinedAt,},diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.tsindex a35bc9efe..d7d8849c2 100644--- a/src/web/src/app/api/community/servers/route.ts+++ b/src/web/src/app/api/community/servers/route.ts@@ -12,7 +12,7 @@ import {} from "@alook/shared"import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"import { fanOutToServerMembers } from "@/lib/community/fanout"-import { serverIconUrl } from "@/lib/community/storage"+import { canonicalUserImage, serverIconUrl } from "@/lib/community/storage"export const GET = withCommunityActor(async (_req, ctx) => {const db = getDb(ctx.env.DB)@@ -91,7 +91,12 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {userId: ctx.actor.userId,name: ownerMember.userName,discriminator: ownerMember.userDiscriminator,- avatar: ownerMember.userImage ?? undefined,+ avatar: canonicalUserImage(+ ownerMember.userId,+ ownerMember.userImage,+ ownerMember.userAvatarVersion,+ ) ?? undefined,+ avatarVersion: ownerMember.userAvatarVersion,role: ROLES.OWNER,joinedAt: ownerMember.joinedAt,},diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.test.tsindex 67f6c1437..2f81765e5 100644--- a/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts@@ -2,11 +2,28 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mediaGet = vi.fn()+const mockGetLiveHumanAvatarState = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } } })),}))+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: {+ ...actual.queries,+ user: {+ ...actual.queries.user,+ getLiveHumanAvatarState: (...a: unknown[]) => mockGetLiveHumanAvatarState(...a),+ },+ },+ }+})+let isAuthed = truevi.mock("@/lib/middleware/auth", () => ({@@ -34,8 +51,9 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-function getReq() {- return new NextRequest("http://localhost/api/community/users/u1/avatar", { method: "GET" })+function getReq(version?: number) {+ const suffix = version === undefined ? "" : `?v=${version}`+ return new NextRequest(`http://localhost/api/community/users/u1/avatar${suffix}`, { method: "GET" })}function ctx(userId?: string) {return { params: Promise.resolve(userId ? { userId } : {}) } as any@@ -45,6 +63,10 @@ describe("GET /api/community/users/[userId]/avatar", () => {beforeEach(() => {vi.clearAllMocks()isAuthed = true+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 0,+ avatarObjectKey: null,+ })mediaGet.mockResolvedValue({body: new ReadableStream(),httpMetadata: { contentType: "image/webp" },@@ -78,6 +100,53 @@ describe("GET /api/community/users/[userId]/avatar", () => {expect(res.status).toBe(404)})+ it("returns 404 before R2 for an inconsistent version/object-key pair", async () => {+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 4,+ avatarObjectKey: null,+ })++ const res = await GET(getReq(4), ctx("u1"))++ expect(res.status).toBe(404)+ expect(mediaGet).not.toHaveBeenCalled()+ })++ it("redirects a stable versioned URL to the authoritative immutable version", async () => {+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 3,+ avatarObjectKey: "user-avatar/u1/objects/object-3",+ })++ const res = await GET(getReq(), ctx("u1"))++ expect(res.status).toBe(307)+ expect(res.headers.get("Location")).toBe("/api/community/users/u1/avatar?v=3")+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")+ expect(mediaGet).not.toHaveBeenCalled()+ })++ it("serves only the authoritative immutable child for the matching version", async () => {+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 3,+ avatarObjectKey: "user-avatar/u1/objects/object-3",+ })++ const res = await GET(getReq(3), ctx("u1"))++ expect(res.status).toBe(200)+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")+ expect(mediaGet).toHaveBeenCalledWith("user-avatar/u1/objects/object-3")+ })++ it("redirects a version query away from a legacy alias", async () => {+ const res = await GET(getReq(3), ctx("u1"))++ expect(res.status).toBe(307)+ expect(res.headers.get("Location")).toBe("/api/community/users/u1/avatar")+ expect(mediaGet).not.toHaveBeenCalled()+ })+it("serves cached bytes while revalidating the deterministic URL in the background", async () => {const res = await GET(getReq(), ctx("u1"))expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.tsindex 1e85c3e33..ea4d947ae 100644--- a/src/web/src/app/api/community/users/[userId]/avatar/route.ts+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.ts@@ -1,32 +1,68 @@import { NextRequest } from "next/server"-import { CACHE_REVALIDATE } from "@alook/shared"+import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"-import { buildUserAvatarKey } from "@/lib/community/storage"--// Any authenticated user can fetch — mirrors the server-icon serve route's-// "readable by any authenticated user" gate. Message authors, member lists,-// DM peers, etc. all need to render this avatar without an ownership check.-//-// The URL never changes across re-uploads (deterministic key). Let the browser-// paint stale bytes while it revalidates the R2 ETag in the background, so a-// warm avatar never waits behind a network round trip.+import { getDb } from "@/lib/db"+import {+ ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,+ buildUserAvatarKey,+ isOwnedUserAvatarObjectKey,+ userAvatarUrl,+} from "@/lib/community/storage"++const log = createLogger({ service: "community-user-avatar" })+const PRIVATE_NO_STORE = "private, no-store"+export const GET = withAuth(async (req: NextRequest, ctx) => {const userId = ctx.params?.userIdif (!userId) return writeError("missing user id", 400)- const obj = await ctx.env.COMMUNITY_MEDIA.get(buildUserAvatarKey(userId))+ const state = await queries.user.getLiveHumanAvatarState(getDb(ctx.env.DB), userId)+ if (!state) return writeError("not found", 404)++ const legacy = state.avatarVersion === 0 && state.avatarObjectKey === null+ const versioned = state.avatarVersion > 0+ && state.avatarObjectKey !== null+ && isOwnedUserAvatarObjectKey(state.avatarObjectKey, userId)+ if (!legacy && !versioned) {+ log.warn("community_user_avatar_state_inconsistent", { stateKind: "invalid_pair" })+ return writeError("not found", 404)+ }++ let key = buildUserAvatarKey(userId)+ let cacheControl = CACHE_REVALIDATE+ if (versioned) {+ const requestedVersion = req.nextUrl.searchParams.get("v")+ if (requestedVersion !== String(state.avatarVersion)) {+ return new Response(null, {+ status: 307,+ headers: {+ Location: userAvatarUrl(userId, state.avatarVersion),+ "Cache-Control": PRIVATE_NO_STORE,+ },+ })+ }+ key = state.avatarObjectKey!+ cacheControl = ATTACHMENT_PRIVATE_IMMUTABLE_CACHE+ } else if (req.nextUrl.searchParams.has("v")) {+ return new Response(null, {+ status: 307,+ headers: { Location: userAvatarUrl(userId), "Cache-Control": PRIVATE_NO_STORE },+ })+ }++ const obj = await ctx.env.COMMUNITY_MEDIA.get(key)if (!obj) return writeError("not found", 404)const etag = obj.httpEtagif (etag && req.headers.get("if-none-match") === etag) {- return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": CACHE_REVALIDATE } })+ return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": cacheControl } })}return new Response(obj.body, {headers: {"Content-Type": obj.httpMetadata?.contentType ?? "image/png",- "Cache-Control": CACHE_REVALIDATE,+ "Cache-Control": cacheControl,...(etag ? { ETag: etag } : {}),},})diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.tsindex d01c1480a..647bbc62f 100644--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts@@ -2,6 +2,7 @@ import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (_req, ctx) => {const id = ctx.params?.userId@@ -29,7 +30,8 @@ export const GET = withAuth(async (_req, ctx) => {id: profile.id,name: profile.name,discriminator: profile.discriminator,- image: profile.image,+ image: canonicalUserImage(profile.id, profile.image, profile.avatarVersion),+ avatarVersion: profile.avatarVersion,aboutMe: profile.aboutMe,bannerColor: profile.bannerColor,mutualServers,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 bb909a3a6..4826a72a5 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@@ -6,6 +6,12 @@ const mockHandleBotAvatarUpload = vi.fn()const mockGetBotOwnedBy = vi.fn()const mockPersistUploadedBotAvatar = vi.fn()const mockAuthUpdateUser = vi.fn()+const mockPublishHumanAvatar = vi.fn()+const mockGetLiveHumanAvatarState = vi.fn()+const mockCleanupAvatarCandidate = vi.fn()+const mockEnsureAvatarAliasPresent = vi.fn()+const mockScheduleAvatarMediaReconciliation = vi.fn()+const mockFanOutIdentityUpdate = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -29,6 +35,11 @@ vi.mock("@alook/shared", async () => {...actual.queries.communityBot,getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),},+ user: {+ ...actual.queries.user,+ publishHumanAvatar: (...a: unknown[]) => mockPublishHumanAvatar(...a),+ getLiveHumanAvatarState: (...a: unknown[]) => mockGetLiveHumanAvatarState(...a),+ },},}})@@ -42,6 +53,16 @@ vi.mock("@/lib/community/bot-avatar-persistence", () => ({persistUploadedBotAvatar: (...a: unknown[]) => mockPersistUploadedBotAvatar(...a),}))+vi.mock("@/lib/community/avatar-media-reconciliation", () => ({+ cleanupAvatarCandidate: (...a: unknown[]) => mockCleanupAvatarCandidate(...a),+ ensureAvatarAliasPresent: (...a: unknown[]) => mockEnsureAvatarAliasPresent(...a),+ scheduleAvatarMediaReconciliation: (...a: unknown[]) => mockScheduleAvatarMediaReconciliation(...a),+}))++vi.mock("@/lib/community/fanout", () => ({+ fanOutIdentityUpdate: (...a: unknown[]) => mockFanOutIdentityUpdate(...a),+}))+let isAuthed = truelet actorKind: "human" | "bot" = "human"@@ -76,13 +97,48 @@ function postReq() {return new NextRequest("http://localhost/api/community/users/me/avatar", { method: "POST" })}+function humanUpload(key = "user-avatar/u1/objects/object-1") {+ return {+ ok: true as const,+ id: "u1",+ key,+ url: "/api/community/media/user-avatar/u1",+ filename: "me.png",+ contentType: "image/png",+ size: 10,+ }+}++function botUpload() {+ return {+ ok: true as const,+ id: "b1",+ key: "bot-avatar/b1/objects/object-2",+ url: "/api/community/media/bot-avatar/b1",+ filename: "bot.png",+ contentType: "image/png",+ size: 10,+ }+}+describe("POST /api/community/users/me/avatar", () => {beforeEach(() => {vi.clearAllMocks()isAuthed = trueactorKind = "human"mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerUserId: "u1" })- mockPersistUploadedBotAvatar.mockResolvedValue({ kind: "persisted" })+ mockPersistUploadedBotAvatar.mockResolvedValue({+ kind: "persisted",+ avatarVersion: 2,+ avatarObjectKey: "bot-avatar/b1/objects/object-2",+ previousObjectKey: null,+ })+ mockPublishHumanAvatar.mockResolvedValue({+ previous: { avatarVersion: 0, avatarObjectKey: null },+ current: { avatarVersion: 1, avatarObjectKey: "user-avatar/u1/objects/object-1" },+ })+ mockEnsureAvatarAliasPresent.mockResolvedValue(true)+ mockScheduleAvatarMediaReconciliation.mockResolvedValue(undefined)mockAuthUpdateUser.mockResolvedValue({ headers: new Headers() })})@@ -113,7 +169,7 @@ describe("POST /api/community/users/me/avatar", () => {mockHandleUserAvatarUpload.mockResolvedValue({ok: true,id: "u1",- key: "user-avatar/u1",+ key: "user-avatar/u1/objects/object-1",url: "/api/community/media/user-avatar/u1",filename: "me.png",contentType: "image/png",@@ -121,8 +177,8 @@ describe("POST /api/community/users/me/avatar", () => {})const res = await POST(postReq(), {} as never)expect(res.status).toBe(200)- const body = await res.json() as { url: string }- expect(body.url).toBe("/api/community/users/u1/avatar")+ const body = await res.json() as { url: string; avatarVersion: number }+ expect(body).toEqual({ url: "/api/community/users/u1/avatar?v=1", avatarVersion: 1 })expect(mockHandleUserAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "u1")expect(mockAuthUpdateUser).toHaveBeenCalledWith(expect.objectContaining({@@ -137,7 +193,7 @@ describe("POST /api/community/users/me/avatar", () => {mockHandleUserAvatarUpload.mockResolvedValue({ok: true,id: "u1",- key: "user-avatar/u1",+ key: "user-avatar/u1/objects/object-1",url: "/api/community/media/user-avatar/u1",filename: "me.png",contentType: "image/png",@@ -147,7 +203,10 @@ describe("POST /api/community/users/me/avatar", () => {const res = await POST(postReq(), {} as never)expect(res.status).toBe(200)- expect(await res.json()).toEqual({ url: "/api/community/users/u1/avatar" })+ expect(await res.json()).toEqual({+ url: "/api/community/users/u1/avatar?v=1",+ avatarVersion: 1,+ })expect(res.headers.getSetCookie()).toEqual([])})@@ -156,7 +215,7 @@ describe("POST /api/community/users/me/avatar", () => {mockHandleBotAvatarUpload.mockResolvedValue({ok: true,id: "b1",- key: "bot-avatar/b1",+ key: "bot-avatar/b1/objects/object-2",url: "/api/community/bots/b1/avatar",filename: "bot.png",contentType: "image/png",@@ -164,14 +223,17 @@ describe("POST /api/community/users/me/avatar", () => {})const res = await POST(postReq(), {} as never)expect(res.status).toBe(200)- expect(await res.json()).toEqual({ url: "/api/community/bots/b1/avatar" })+ expect(await res.json()).toEqual({+ url: "/api/community/bots/b1/avatar?v=2",+ avatarVersion: 2,+ })expect(mockHandleBotAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "b1")expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()expect(mockGetBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "b1", "u1")expect(mockPersistUploadedBotAvatar).toHaveBeenCalledWith(expect.anything(),expect.anything(),- { botId: "b1", ownerId: "u1" },+ { botId: "b1", ownerId: "u1", objectKey: "bot-avatar/b1/objects/object-2" },)expect(mockAuthUpdateUser).not.toHaveBeenCalled()})@@ -206,7 +268,7 @@ describe("POST /api/community/users/me/avatar", () => {mockHandleBotAvatarUpload.mockResolvedValue({ok: true,id: "b1",- key: "bot-avatar/b1",+ key: "bot-avatar/b1/objects/object-2",url: "/api/community/bots/b1/avatar",filename: "bot.png",contentType: "image/png",@@ -223,7 +285,7 @@ describe("POST /api/community/users/me/avatar", () => {mockHandleBotAvatarUpload.mockResolvedValue({ok: true,id: "b1",- key: "bot-avatar/b1",+ key: "bot-avatar/b1/objects/object-2",url: "/api/community/bots/b1/avatar",filename: "bot.png",contentType: "image/png",@@ -234,4 +296,109 @@ describe("POST /api/community/users/me/avatar", () => {const res = await POST(postReq(), {} as never)expect(res.status).toBe(500)})++ it("fails closed when a persisted bot avatar cannot publish its stable alias", async () => {+ actorKind = "bot"+ mockHandleBotAvatarUpload.mockResolvedValue(botUpload())+ mockEnsureAvatarAliasPresent.mockResolvedValue(false)++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(500)+ expect(mockScheduleAvatarMediaReconciliation).not.toHaveBeenCalled()+ expect(mockFanOutIdentityUpdate).not.toHaveBeenCalled()+ })++ it("recovers an ambiguous human publish when verification finds the uploaded child current", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockPublishHumanAvatar.mockRejectedValue(new Error("D1 response lost"))+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 3,+ avatarObjectKey: "user-avatar/u1/objects/object-1",+ })++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ url: "/api/community/users/u1/avatar?v=3",+ avatarVersion: 3,+ })+ expect(mockCleanupAvatarCandidate).not.toHaveBeenCalled()+ })++ it("cleans an ambiguous non-current upload and returns 500", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockPublishHumanAvatar.mockRejectedValue("D1 response lost")+ mockGetLiveHumanAvatarState.mockResolvedValue({+ avatarVersion: 3,+ avatarObjectKey: "user-avatar/u1/objects/other",+ })++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(500)+ expect(mockCleanupAvatarCandidate).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ { kind: "human", id: "u1" },+ "user-avatar/u1/objects/object-1",+ )+ })++ it("returns 500 when an ambiguous human publish cannot be verified", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockPublishHumanAvatar.mockRejectedValue(new Error("D1 response lost"))+ mockGetLiveHumanAvatarState.mockRejectedValue("verification unavailable")++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(500)+ expect(mockCleanupAvatarCandidate).not.toHaveBeenCalled()+ })++ it("cleans the uploaded child when the human row disappears during publish", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockPublishHumanAvatar.mockResolvedValue(null)++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(404)+ expect(mockCleanupAvatarCandidate).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ { kind: "human", id: "u1" },+ "user-avatar/u1/objects/object-1",+ )+ })++ it("fails closed when a published human avatar cannot publish its stable alias", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockEnsureAvatarAliasPresent.mockResolvedValue(false)++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(500)+ expect(mockScheduleAvatarMediaReconciliation).not.toHaveBeenCalled()+ expect(mockFanOutIdentityUpdate).not.toHaveBeenCalled()+ })++ it("keeps the published avatar when the session refresh throws", async () => {+ mockHandleUserAvatarUpload.mockResolvedValue(humanUpload())+ mockAuthUpdateUser.mockRejectedValue("session unavailable")++ const res = await POST(postReq(), {} as never)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({+ url: "/api/community/users/u1/avatar?v=1",+ avatarVersion: 1,+ })+ expect(mockScheduleAvatarMediaReconciliation).toHaveBeenCalledOnce()+ expect(mockFanOutIdentityUpdate).toHaveBeenCalledWith(+ "u1",+ "/api/community/users/u1/avatar?v=1",+ 1,+ )+ })})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 84de7ec5d..87c28691d 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,5 +1,5 @@import { NextRequest, NextResponse } from "next/server"-import { queries } from "@alook/shared"+import { createLogger, queries } from "@alook/shared"import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeError, writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"@@ -7,48 +7,128 @@ 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"+import {+ cleanupAvatarCandidate,+ ensureAvatarAliasPresent,+ scheduleAvatarMediaReconciliation,+} from "@/lib/community/avatar-media-reconciliation"+import { fanOutIdentityUpdate } from "@/lib/community/fanout"++const log = createLogger({ service: "community-self-avatar" })export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const userId = ctx.actor.userIdconst db = getDb(ctx.env.DB)if (ctx.actor.kind === "bot") {- const before = await queries.communityBot.getBotOwnedBy(- db,- userId,- ctx.actor.ownerUserId,- )- if (!before) return writeError("bot not found", 404)+ if (!(await queries.communityBot.getBotOwnedBy(db, userId, ctx.actor.ownerUserId))) {+ 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,+ objectKey: upload.key,})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 subject = { kind: "bot" as const, id: userId }+ if (!(await ensureAvatarAliasPresent(db, ctx.env.COMMUNITY_MEDIA, subject))) {+ log.warn("community_bot_avatar_alias_unavailable", { phase: "before_response" })+ return writeError("internal error", 500)+ }+ void scheduleAvatarMediaReconciliation(db, ctx.env.COMMUNITY_MEDIA, {+ subject,+ candidates: [persisted.previousObjectKey, persisted.avatarObjectKey],+ })+ const url = botAvatarUrl(userId, persisted.avatarVersion)+ void fanOutIdentityUpdate(userId, url, persisted.avatarVersion)+ return writeJSON({ url, avatarVersion: persisted.avatarVersion })+ }++ const upload = await handleUserAvatarUpload(req, ctx.env, userId)+ if (!upload.ok) return upload.response++ let published: Awaited<ReturnType<typeof queries.user.publishHumanAvatar>>+ try {+ published = await queries.user.publishHumanAvatar(db, userId, {+ objectKey: upload.key,+ stableUrl: userAvatarUrl(userId),+ })+ } catch (error) {+ try {+ const current = await queries.user.getLiveHumanAvatarState(db, userId)+ if (current?.avatarObjectKey === upload.key && current.avatarVersion > 0) {+ published = { previous: current, current }+ } else {+ await cleanupAvatarCandidate(+ db,+ ctx.env.COMMUNITY_MEDIA,+ { kind: "human", id: userId },+ upload.key,+ )+ log.warn("community_user_avatar_publish_failed", {+ phase: "unknown_noncurrent",+ errorCategory: error instanceof Error ? error.name : "NonError",+ })+ return writeError("internal error", 500)+ }+ } catch (verificationError) {+ log.warn("community_user_avatar_publish_verification_failed", {+ phase: "unknown_commit",+ persistErrorCategory: error instanceof Error ? error.name : "NonError",+ verificationErrorCategory:+ verificationError instanceof Error ? verificationError.name : "NonError",+ })+ return writeError("internal error", 500)+ }}- 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 = authResult.headers.getSetCookie()+ if (!published) {+ await cleanupAvatarCandidate(+ db,+ ctx.env.COMMUNITY_MEDIA,+ { kind: "human", id: userId },+ upload.key,+ )+ return writeError("user not found", 404)+ }++ const subject = { kind: "human" as const, id: userId }+ if (!(await ensureAvatarAliasPresent(db, ctx.env.COMMUNITY_MEDIA, subject))) {+ log.warn("community_user_avatar_alias_unavailable", { phase: "before_response" })+ return writeError("internal error", 500)+ }++ const avatarVersion = published.current.avatarVersion+ const url = userAvatarUrl(userId, avatarVersion)+ let authHeaders: Headers | null = null+ try {+ const auth = createAuth(ctx.env)+ const authResult = (await auth.api.updateUser({+ body: { image: userAvatarUrl(userId) },+ headers: req.headers,+ returnHeaders: true,+ })) as { headers: Headers }+ authHeaders = authResult.headers+ } catch (error) {+ log.warn("community_user_avatar_session_refresh_failed", {+ phase: "after_publish",+ errorCategory: error instanceof Error ? error.name : "NonError",+ })+ }++ void scheduleAvatarMediaReconciliation(db, ctx.env.COMMUNITY_MEDIA, {+ subject,+ candidates: [published.previous.avatarObjectKey, upload.key],+ })+ void fanOutIdentityUpdate(userId, url, avatarVersion)++ const res = writeJSON({ url, avatarVersion })+ const setCookies = authHeaders?.getSetCookie() ?? []if (setCookies.length === 0) return resconst response = new NextResponse(res.body, res)diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.tsindex d85126dfa..bbb823240 100644--- a/src/web/src/app/api/community/users/me/dms/route.ts+++ b/src/web/src/app/api/community/users/me/dms/route.ts@@ -4,6 +4,7 @@ import { writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"/*** GET /api/community/users/me/dms — the DM sidebar list, relocated from the@@ -26,7 +27,9 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {userId: r.otherUserId,name: r.otherUserName,discriminator: r.otherUserDiscriminator,- avatar: r.otherUserImage ?? avatarInitial(r.otherUserName),+ avatar: canonicalUserImage(r.otherUserId, r.otherUserImage, r.otherUserAvatarVersion)+ ?? avatarInitial(r.otherUserName),+ avatarVersion: r.otherUserAvatarVersion,status: "offline" as const,preview: "",}))diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.tsindex 28915d509..91311d448 100644--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.ts@@ -9,6 +9,7 @@ import {} from "@alook/shared"import { parseBoundedInt } from "@/lib/community/messages"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (req, ctx) => {const db = getDb(ctx.env.DB)@@ -75,7 +76,12 @@ export const GET = withAuth(async (req, ctx) => {// a blank avatar — same fix as the pins route.authorId: row.author.id,authorName: row.author.name,- authorAvatar: row.author.image ?? avatarInitial(row.author.name),+ authorAvatar: canonicalUserImage(+ row.author.id,+ row.author.image,+ row.author.avatarVersion,+ ) ?? avatarInitial(row.author.name),+ authorAvatarVersion: row.author.avatarVersion,content: row.message.content,createdAt: row.message.createdAt,},diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.tsindex fc2b6303b..70d960a5e 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts@@ -10,6 +10,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON } from "@/lib/middleware/helpers"import { parseBoundedInt } from "@/lib/community/messages"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (req, ctx) => {const db = getDb(ctx.env.DB)@@ -349,7 +350,12 @@ export const GET = withAuth(async (req, ctx) => {otherUserId: d.otherUserId,otherUserName: d.otherUserName,otherUserDiscriminator: d.otherUserDiscriminator,- otherUserAvatar: d.otherUserImage ?? avatarInitial(d.otherUserName),+ otherUserAvatar: canonicalUserImage(+ d.otherUserId,+ d.otherUserImage,+ d.otherUserAvatarVersion,+ ) ?? avatarInitial(d.otherUserName),+ otherUserAvatarVersion: d.otherUserAvatarVersion,lastMessageAt: d.lastMessageAt,})).sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))diff --git a/src/web/src/app/api/community/users/me/marks/route.ts b/src/web/src/app/api/community/users/me/marks/route.tsindex 48cc9a9d5..18eb74bc7 100644--- a/src/web/src/app/api/community/users/me/marks/route.ts+++ b/src/web/src/app/api/community/users/me/marks/route.ts@@ -10,6 +10,7 @@ import {} from "@alook/shared"import { parseBoundedInt } from "@/lib/community/messages"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"// Cross-channel Marked tab: every message the current user has marked, newest// first. Scoped to the viewer's visible channels in-query (same guard as the@@ -121,7 +122,12 @@ export const GET = withCommunityActor(async (req, ctx) => {id: row.message.id,authorId: row.author.id,authorName: row.author.name,- authorAvatar: row.author.image ?? avatarInitial(row.author.name),+ authorAvatar: canonicalUserImage(+ row.author.id,+ row.author.image,+ row.author.avatarVersion,+ ) ?? avatarInitial(row.author.name),+ authorAvatarVersion: row.author.avatarVersion,content: row.message.content,// seq is the jump key (Msg.seq) — a marked message is usually outside// the loaded window, so a seq-less scroll silently no-ops. Lives insidediff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.tsindex e94098001..cdcfbed13 100644--- a/src/web/src/app/api/community/users/me/profile/route.test.ts+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts@@ -96,8 +96,10 @@ describe("GET /api/community/users/me/profile", () => {const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)expect(res.status).toBe(200)expect(await res.json()).toEqual({+ id: "u1",aboutMe: "",avatar: "/api/community/users/u1/avatar",+ avatarVersion: 0,bannerColor: null,discriminator: "4242",name: "Jane Roe",@@ -110,8 +112,10 @@ describe("GET /api/community/users/me/profile", () => {getProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: "#aabbcc", statusEmoji: "🎧", statusText: "Vibing" })const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)expect(await res.json()).toEqual({+ id: "u1",aboutMe: "hi",avatar: "/api/community/users/u1/avatar",+ avatarVersion: 0,bannerColor: "#aabbcc",discriminator: "4242",name: "Jane Roe",@@ -125,8 +129,10 @@ describe("GET /api/community/users/me/profile", () => {getUser.mockResolvedValue(null)const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)expect(await res.json()).toEqual({+ id: "u1",aboutMe: "",avatar: "",+ avatarVersion: 0,bannerColor: null,discriminator: "0000",name: "",diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.tsindex bdb65c6a7..8cb7926fb 100644--- a/src/web/src/app/api/community/users/me/profile/route.ts+++ b/src/web/src/app/api/community/users/me/profile/route.ts@@ -14,6 +14,7 @@ import { createAuth } from "@/lib/auth"import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { fanOutStatusUpdate, fanOutToServerMembers } from "@/lib/community/fanout"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withCommunityActor(async (_req, ctx) => {const db = getDb(ctx.env.DB)@@ -29,8 +30,12 @@ export const GET = withCommunityActor(async (_req, ctx) => {),])return writeJSON({+ id: userId,aboutMe: profile?.aboutMe ?? "",- avatar: viewer?.image ?? "",+ avatar: viewer+ ? canonicalUserImage(viewer.id, viewer.image, viewer.avatarVersion) ?? ""+ : "",+ avatarVersion: viewer?.avatarVersion ?? 0,bannerColor: profile?.bannerColor ?? null,discriminator: viewer?.discriminator ?? "0000",name: viewer?.name ?? "",diff --git a/src/web/src/app/api/community/users/search/route.ts b/src/web/src/app/api/community/users/search/route.tsindex 057377237..bf4f772dc 100644--- a/src/web/src/app/api/community/users/search/route.ts+++ b/src/web/src/app/api/community/users/search/route.ts@@ -9,6 +9,7 @@ import {DEFAULT_USER_SEARCH_LIMIT,parseNameAndTag,} from "@alook/shared"+import { canonicalUserImage } from "@/lib/community/storage"export const GET = withAuth(async (req: NextRequest, ctx) => {const url = new URL(req.url)@@ -42,7 +43,8 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {users: users.map((u) => ({id: u.id,name: u.name,- image: u.image,+ image: canonicalUserImage(u.id, u.image, u.avatarVersion),+ avatarVersion: u.avatarVersion,discriminator: u.discriminator,})),})diff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.tsindex 1a45cae37..46b7d497f 100644--- a/src/web/src/app/c/community-shell.identity.test.ts+++ b/src/web/src/app/c/community-shell.identity.test.ts@@ -7,6 +7,7 @@ type TestUser = {name: stringemail: stringavatar: string+ avatarVersion?: numberaboutMe?: stringdiscriminator?: stringstatusEmoji?: string | null@@ -14,8 +15,10 @@ type TestUser = {}type ProfileResponse = {+ id?: stringaboutMe: stringavatar: string+ avatarVersion: numberdiscriminator: stringname: stringstatusEmoji: string | null@@ -31,6 +34,14 @@ const { apiFetch } = vi.hoisted(() => ({const setCurrentUser = vi.fn((updater: (user: TestUser) => TestUser) => {activeUser = updater(activeUser)})+const queryClient = {+ setQueriesData: vi.fn(),+ invalidateQueries: vi.fn(),+}++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => queryClient,+}))vi.mock("./QueryProvider", () => ({QueryProvider: ({ children, userId }: { children: React.ReactNode; userId: string | null }) => {@@ -55,6 +66,7 @@ vi.mock("@/components/community/onboarding/community-onboarding-guide", () => ({}))import { CommunityShell } from "./community-shell"+import { useCommunityWsStore } from "@/stores/community/ws"beforeEach(() => {activeUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }@@ -63,6 +75,9 @@ beforeEach(() => {apiFetch.mockReset()apiFetch.mockImplementation(() => new Promise(() => undefined))setCurrentUser.mockClear()+ queryClient.setQueriesData.mockReset()+ queryClient.invalidateQueries.mockReset()+ useCommunityWsStore.getState().reset()})describe("CommunityShell identity boundary", () => {@@ -96,6 +111,7 @@ describe("CommunityShell identity boundary", () => {apiFetch.mockResolvedValueOnce({aboutMe: "hello",avatar: "new-avatar",+ avatarVersion: 3,discriminator: "4242",name: "Jane Roe",statusEmoji: "🌱",@@ -118,6 +134,7 @@ describe("CommunityShell identity boundary", () => {name: "Jane Roe",aboutMe: "hello",avatar: "new-avatar",+ avatarVersion: 3,discriminator: "4242",statusEmoji: "🌱",statusText: "Growing",@@ -130,6 +147,7 @@ describe("CommunityShell identity boundary", () => {apiFetch.mockResolvedValueOnce({aboutMe: "hello",avatar: "",+ avatarVersion: 0,discriminator: "4242",name: "",statusEmoji: null,@@ -156,4 +174,46 @@ describe("CommunityShell identity boundary", () => {})renderer.unmount()})++ it("projects an identity discovered by HTTP across already-cached messages", async () => {+ useCommunityWsStore.getState().bindIdentityOwner("user-a")+ const cached = {+ id: "m1",+ authorId: "user-a",+ authorAvatar: "/api/community/users/user-a/avatar?v=1",+ authorAvatarVersion: 1,+ }+ let projected: unknown+ queryClient.setQueriesData.mockImplementation((_filters, updater) => {+ projected = updater(cached)+ return []+ })+ apiFetch.mockResolvedValueOnce({+ id: "user-a",+ aboutMe: "hello",+ avatar: "/api/community/users/user-a/avatar?v=6",+ avatarVersion: 6,+ discriminator: "4242",+ name: "Alice",+ statusEmoji: null,+ statusText: "",+ })++ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement("span", null, "content"),+ ))+ await Promise.resolve()+ await Promise.resolve()+ })++ expect(projected).toMatchObject({+ authorAvatar: "/api/community/users/user-a/avatar?v=6",+ authorAvatarVersion: 6,+ })+ renderer.unmount()+ })})diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 3be0668bd..9fcf4bcc7 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -1,7 +1,12 @@"use client"import { useEffect, type ReactNode } from "react"-import { apiFetch } from "@/lib/api/client"+import { useQueryClient } from "@tanstack/react-query"+import {+ apiFetchIdentity,+ projectIdentityPayload,+} from "@/lib/community/identity-projection"+import { communityKeys } from "@/lib/query-keys"import { QueryProvider } from "./QueryProvider"import {CurrentUserProvider,@@ -11,6 +16,7 @@ import {} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"import { useCommunityWsStore } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingGuide } from "@/components/community/onboarding/community-onboarding-guide"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"@@ -52,8 +58,13 @@ export function CommunityShell({* effect — needed so the "Edit profile" dialog opens with the current value.*/function CommunityBootstrap({ children }: { children: ReactNode }) {+ const queryClient = useQueryClient()const currentUser = useCurrentUser()const setCurrentUser = useSetCurrentUser()+ const currentAvatarIdentity = useCommunityWsStore(+ (state) => state.avatarIdentities.get(currentUser.id),+ )+ const avatarIdentities = useCommunityWsStore((state) => state.avatarIdentities)// Wire the WS handler once for the whole community subtree. `viewerUserId`// powers the `me` flag on incoming reactions — passing null would leave that@@ -65,14 +76,20 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {// row alongside the community profile fields.const currentUserId = currentUser.iduseEffect(() => {- apiFetch<{ aboutMe: string; avatar: string; discriminator: string; name: string; statusEmoji: string | null; statusText: string }>(+ apiFetchIdentity<{ id: string; aboutMe: string; avatar: string; avatarVersion: number; discriminator: string; name: string; statusEmoji: string | null; statusText: string }>("/api/community/users/me/profile",).then((data) => {+ const avatarVersion = Number.isSafeInteger(data.avatarVersion)+ ? data.avatarVersion+ : 0setCurrentUser((u) => ({...u,aboutMe: data.aboutMe,- avatar: data.avatar || u.avatar,+ avatar: avatarVersion >= (u.avatarVersion ?? 0) && data.avatar+ ? data.avatar+ : u.avatar,+ avatarVersion: Math.max(u.avatarVersion ?? 0, avatarVersion),discriminator: data.discriminator,name: data.name || u.name,statusEmoji: data.statusEmoji,@@ -86,6 +103,40 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {.catch(() => { })}, [setCurrentUser, currentUserId])+ useEffect(() => {+ if (!currentAvatarIdentity) return+ setCurrentUser((user) => currentAvatarIdentity.avatarVersion > (user.avatarVersion ?? 0)+ ? {+ ...user,+ avatar: currentAvatarIdentity.avatar,+ avatarVersion: currentAvatarIdentity.avatarVersion,+ }+ : user)+ }, [currentAvatarIdentity, setCurrentUser])++ // HTTP fetches can discover a newer identity without a WS frame (cold+ // persisted cache, reconnect gap, or a delayed tab). Project that shared+ // highest-version overlay across every already-cached surface and the+ // detached message stream, not only the response that discovered it.+ useEffect(() => {+ if (avatarIdentities.size === 0) return+ let conflict = false+ queryClient.setQueriesData(+ { queryKey: communityKeys.all },+ (cached) => projectIdentityPayload(cached, () => { conflict = true }),+ )+ const stream = useMessageStreamStore.getState()+ for (const [userId, identity] of avatarIdentities) {+ stream.projectAvatarIdentity(userId, identity.avatar, identity.avatarVersion)+ }+ if (conflict) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.all,+ refetchType: "active",+ })+ }+ }, [avatarIdentities, queryClient])+return (<><PerfTraceBootstrap />diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex 4f687e3cc..ed035b397 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -46,6 +46,7 @@ export default function CommunityLayout({name: session.user.name,email: session.user.email,avatar: session.user.image || avatarInitial(session.user.name),+ avatarVersion: 0,}return (diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxindex c3eb2bfbb..bdfd63b62 100644--- a/src/web/src/components/community/members/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -205,6 +205,7 @@ export function useChannelMemberViewModel({name: stringdiscriminator: stringavatar: string+ avatarVersion: numberstatusEmoji?: string | nullstatusText?: string | nullisCreator?: boolean@@ -217,6 +218,7 @@ export function useChannelMemberViewModel({name: member.name,discriminator: member.discriminator,avatar: member.avatar,+ avatarVersion: member.avatarVersion,sub: "",role: "member",status: resolveRowPresence(member, onlineUserIds, currentUser.id),diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.tsindex 75c401b11..14c4834c6 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts@@ -389,11 +389,11 @@ describe("useMessageChannelController", () => {results: [{message: { id: "m2", content: "found", authorId: "u2", createdAt: "2026-01-02" },- author: { name: "Bob", image: null },+ author: { id: "u2", name: "Bob", image: null, avatarVersion: 0 },},{message: { id: "m3", content: "image", authorId: "u3", createdAt: "2026-01-03" },- author: { name: "Carol", image: "https://example.test/carol.png" },+ author: { id: "u3", name: "Carol", image: "https://example.test/carol.png", avatarVersion: 3 },},],})@@ -409,6 +409,7 @@ describe("useMessageChannelController", () => {type: "chat",authorName: "Bob",authorAvatar: avatarInitial("Bob"),+ authorAvatarVersion: 0,content: "found",createdAt: "2026-01-02",},@@ -417,6 +418,7 @@ describe("useMessageChannelController", () => {type: "chat",authorName: "Carol",authorAvatar: "https://example.test/carol.png",+ authorAvatarVersion: 3,content: "image",createdAt: "2026-01-03",},diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.tsindex 48bbe2c14..c63c90b59 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -3,7 +3,8 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"import { usePathname, useRouter, useSearchParams } from "next/navigation"import type { MentionType } from "@alook/shared"-import { apiFetch, toastApiError } from "@/lib/api/client"+import { toastApiError } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { avatarInitial } from "@/lib/community/avatar"import type { Msg } from "@/lib/community/models/message"import type { SendAttachment } from "./composer"@@ -101,10 +102,10 @@ export function useMessageChannelController({}try {const params = new URLSearchParams({ q: query, channelId })- const data = await apiFetch<{+ const data = await apiFetchIdentity<{results: Array<{message: { id: string; content: string; authorId: string; createdAt: string }- author: { name: string; image: string | null }+ author: { id: string; name: string; image: string | null; avatarVersion: number }}>}>(`/api/community/messages/search?${params}`)setSearchResults(data.results.map((result) => ({@@ -112,6 +113,7 @@ export function useMessageChannelController({type: "chat" as const,authorName: result.author.name,authorAvatar: result.author.image ?? avatarInitial(result.author.name),+ authorAvatarVersion: result.author.avatarVersion,content: result.message.content,createdAt: result.message.createdAt,})))diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsxindex f0cc05fcb..d6215e191 100644--- a/src/web/src/components/community/messages/message-context-sheet.tsx+++ b/src/web/src/components/community/messages/message-context-sheet.tsx@@ -12,6 +12,7 @@ import { displayReplyContent } from "@/lib/community/reply-content"import { ChannelIcon } from "../channels/channel-icon"import { Skeleton } from "@/components/ui/skeleton"import { apiFetch, toastApiError } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { ApiError } from "@/lib/errors"import { formatDateLabel } from "@/lib/community/format-time"import { DateDivider } from "../dividers"@@ -22,6 +23,7 @@ import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMimport type { OpenProfile } from "@/components/community/social/profile-types"import { useHoverCapable } from "@/hooks/use-hover-capable"import { channelHref } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"export type ReplyTarget = { id: string; authorName: string; text: string }@@ -173,7 +175,7 @@ export function MessageContextSheet({const toggleMark = useToggleMark()const queryKey = useMemo(- () => ["messageContext", type, channelId, targetSeq] as const,+ () => communityKeys.messageContext(type, channelId, targetSeq),[type, channelId, targetSeq],)@@ -192,7 +194,7 @@ export function MessageContextSheet({if (e instanceof ApiError && e.status === 404) return { notFound: true }throw e}- const page = await apiFetch<MessagesPage>(+ const page = await apiFetchIdentity<MessagesPage>(anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),{ signal },)diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.test.tsindex 38f4abb49..167e90a6b 100644--- a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({id: "self",name: "Self",avatar: "S",+ avatarVersion: 0,aboutMe: "About",statusEmoji: "🙂",statusText: "Here",@@ -21,6 +22,9 @@ const mocks = vi.hoisted(() => ({setUserStatus: vi.fn(),communityReset: vi.fn(),wsReset: vi.fn(),+ observeAvatarIdentity: vi.fn(),+ avatarIdentities: new Map<string, { avatar: string; avatarVersion: number }>(),+ projectAvatarIdentity: vi.fn(),streamReset: vi.fn(),clearCache: vi.fn(),signOut: vi.fn(),@@ -48,13 +52,22 @@ vi.mock("@/stores/community", () => ({}))vi.mock("@/stores/community/ws", () => ({useOnlineUserIds: () => new Set(["self", "remote"]),- useCommunityWsStore: Object.assign(vi.fn(), {- getState: () => ({ setUserStatus: mocks.setUserStatus, reset: mocks.wsReset }),+ useCommunityWsStore: Object.assign(vi.fn((selector: (state: { avatarIdentities: typeof mocks.avatarIdentities }) => unknown) =>+ selector({ avatarIdentities: mocks.avatarIdentities })), {+ getState: () => ({+ setUserStatus: mocks.setUserStatus,+ reset: mocks.wsReset,+ observeAvatarIdentity: mocks.observeAvatarIdentity,+ avatarIdentities: mocks.avatarIdentities,+ }),}),}))vi.mock("@/stores/community/message-stream", () => ({useMessageStreamStore: Object.assign(vi.fn(), {- getState: () => ({ resetAll: mocks.streamReset }),+ getState: () => ({+ resetAll: mocks.streamReset,+ projectAvatarIdentity: mocks.projectAvatarIdentity,+ }),}),}))vi.mock("@/hooks/community/use-friends", () => ({@@ -113,22 +126,31 @@ async function renderController() {prefetch: vi.fn(),}const cancelPendingNavigation = vi.fn()- const queryClient = { fetchQuery: mocks.fetchQuery, clear: vi.fn() }+ const queryClient = { fetchQuery: mocks.fetchQuery, clear: vi.fn(), setQueriesData: vi.fn() }let current!: Resultlet renderer!: TestRenderer.ReactTestRenderer+ const render = () => createElement(Capture, {+ options: {+ router,+ queryClient,+ cancelPendingNavigation,+ view: "server",+ activeServerId: "s1",+ } as never,+ onResult: (result) => { current = result },+ })await act(async () => {- renderer = TestRenderer.create(createElement(Capture, {- options: {- router,- queryClient,- cancelPendingNavigation,- view: "server",- activeServerId: "s1",- } as never,- onResult: (result) => { current = result },- }))+ renderer = TestRenderer.create(render())})- return { get current() { return current }, renderer, router, pushed, cancelPendingNavigation, queryClient }+ return {+ get current() { return current },+ renderer,+ router,+ pushed,+ cancelPendingNavigation,+ queryClient,+ rerender: async () => act(async () => renderer.update(render())),+ }}function deferred<T>() {@@ -146,6 +168,16 @@ describe("useShellProfileController", () => {mocks.updateProfile.mockResolvedValue({})mocks.clearCache.mockResolvedValue(undefined)mocks.signOut.mockResolvedValue(undefined)+ mocks.avatarIdentities.clear()+ mocks.observeAvatarIdentity.mockImplementation((userId: string, avatar: string, avatarVersion: number) => {+ const current = mocks.avatarIdentities.get(userId)+ if (current?.avatarVersion === avatarVersion) {+ return current.avatar === avatar ? "duplicate" : "conflict"+ }+ if (current && current.avatarVersion > avatarVersion) return "stale"+ mocks.avatarIdentities.set(userId, { avatar, avatarVersion })+ return "updated"+ })})afterEach(() => {@@ -211,6 +243,65 @@ describe("useShellProfileController", () => {expect(mocks.setUserStatus).not.toHaveBeenCalled()})+ it("retains the seeded avatar when an authoritative profile has a newer version but no image", async () => {+ mocks.fetchQuery.mockResolvedValue({+ id: "remote",+ aboutMe: "hydrated",+ mutualServers: 1,+ discriminator: "1234",+ image: null,+ avatarVersion: 4,+ statusEmoji: null,+ statusText: "",+ kind: "human",+ })+ const hook = await renderController()++ await act(async () => hook.current.openProfile(+ "Remote",+ { clientX: 4, clientY: 5 } as never,+ undefined,+ "remote",+ ))++ expect(hook.current.profile?.data).toMatchObject({+ avatar: "R",+ avatarVersion: 4,+ })+ })++ it("projects a newer WS identity into an already-open profile card", async () => {+ mocks.fetchQuery.mockReturnValue(new Promise(() => {}))+ const hook = await renderController()+ await act(async () => hook.current.openProfile(+ "Remote",+ { clientX: 4, clientY: 5 } as never,+ undefined,+ "remote",+ ))+ expect(hook.current.profile?.data.avatar).toBe("R")++ mocks.avatarIdentities = new Map([+ ["remote", { avatar: "/avatar?v=7", avatarVersion: 7 }],+ ])+ await hook.rerender()++ expect(hook.current.profile?.data).toMatchObject({+ avatar: "/avatar?v=7",+ avatarVersion: 7,+ })++ mocks.avatarIdentities = new Map([+ ["remote", { avatar: "/avatar?v=6", avatarVersion: 6 }],+ ])+ await hook.rerender()++ expect(hook.current.profile?.data).toMatchObject({+ avatar: "/avatar?v=7",+ avatarVersion: 7,+ })+ })+it("does not let a slow profile response overwrite the next opened card", async () => {const first = deferred<Record<string, unknown>>()const second = deferred<Record<string, unknown>>()@@ -413,6 +504,8 @@ describe("useShellProfileController", () => {})mocks.uploadAvatar.mockImplementation(() => { order.push("upload") })const hook = await renderController()+ hook.queryClient.setQueriesData.mockImplementation((_filters: unknown, updater: (value: unknown) => unknown) =>+ updater({ id: "self", image: "/old?v=1", avatarVersion: 1 }))await act(async () => hook.current.userSettingsProps.onUploadAvatar())input!.files = [new File(["image"], "avatar.png", { type: "image/png" })]await act(async () => input!.onchange?.())@@ -425,11 +518,22 @@ describe("useShellProfileController", () => {expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1)expect(hook.current.pendingAvatarCrop).toBeNull()- vi.spyOn(Date, "now").mockReturnValue(123)const uploadOptions = mocks.uploadAvatar.mock.calls[0]![1]- await act(async () => uploadOptions.onSuccess({ url: "/avatar.png" }))+ await act(async () => uploadOptions.onSuccess({ url: "/avatar.png?v=4", avatarVersion: 4 }))+ expect(mocks.avatarIdentities.get("self")).toEqual({+ avatar: "/avatar.png?v=4",+ avatarVersion: 4,+ })+ expect(mocks.setCurrentUser).toHaveBeenCalledTimes(1)const avatarUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]- expect(avatarUpdater(mocks.currentUser).avatar).toBe("/avatar.png?t=123")+ const staleUser = { ...mocks.currentUser, avatar: "/old?v=1", avatarVersion: 1 }+ expect(avatarUpdater(staleUser)).toMatchObject({+ avatar: "/avatar.png?v=4",+ avatarVersion: 4,+ })+ const newerUser = { ...mocks.currentUser, avatar: "/avatar.png?v=9", avatarVersion: 9 }+ expect(avatarUpdater(newerUser)).toBe(newerUser)+ expect(mocks.observeAvatarIdentity).toHaveBeenCalledWith("self", "/avatar.png?v=4", 4)expect(mocks.toast).toHaveBeenLastCalledWith("Avatar updated")const uploadError = new Error("upload")diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.tsindex 5357d5144..191864e4d 100644--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts@@ -1,10 +1,11 @@"use client"-import { useCallback, useState, type ComponentProps } from "react"+import { useCallback, useEffect, useState, type ComponentProps } from "react"import { parseNameAndTag } from "@alook/shared"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"+import { projectIdentityPayload } from "@/lib/community/identity-projection"import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"import { validateIconSourceFile } from "@/lib/community/image-crop"import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"@@ -65,6 +66,7 @@ export function useShellProfileController({}: Options) {const currentUser = useCurrentUser()const setCurrentUser = useSetCurrentUser()+ const avatarIdentities = useCommunityWsStore((state) => state.avatarIdentities)const onlineUserIds = useOnlineUserIds()const { friends } = useFriends()const profileServerId = resolveProfileServerId(view, activeServerId)@@ -121,6 +123,7 @@ export function useShellProfileController({name,userId,avatar: member?.avatar ?? avatarInitial(name),+ avatarVersion: member?.avatarVersion ?? 0,contextLabel: resolveProfileContextLabel(profileServerId, member),about,mutual: 0,@@ -148,6 +151,13 @@ export function useShellProfileController({about: profileResponse.aboutMe ?? previous.data.about,mutual: profileResponse.mutualServers ?? 0,discriminator: profileResponse.discriminator ?? previous.data.discriminator,+ avatar: profileResponse.avatarVersion >= (previous.data.avatarVersion ?? 0)+ ? profileResponse.image ?? previous.data.avatar+ : previous.data.avatar,+ avatarVersion: Math.max(+ previous.data.avatarVersion ?? 0,+ profileResponse.avatarVersion,+ ),identity: profileResponse.kind === "bot"? {kind: "bot",@@ -166,6 +176,25 @@ export function useShellProfileController({}}, [currentUser, friends, members, onlineUserIds, profileServerId, queryClient])+ useEffect(() => {+ setProfile((previous) => {+ const userId = previous?.data.userId+ if (!previous || !userId) return previous+ const identity = avatarIdentities.get(userId)+ if (!identity || identity.avatarVersion <= (previous.data.avatarVersion ?? 0)) {+ return previous+ }+ return {+ ...previous,+ data: {+ ...previous.data,+ avatar: identity.avatar,+ avatarVersion: identity.avatarVersion,+ },+ }+ })+ }, [avatarIdentities])+const openProfile = useCallback((name: string,event: React.MouseEvent,@@ -323,7 +352,23 @@ export function useShellProfileController({{ file },{onSuccess: (data) => {- setCurrentUser((user) => ({ ...user, avatar: `${data.url}?t=${Date.now()}` }))+ const store = useCommunityWsStore.getState()+ store.observeAvatarIdentity(currentUser.id, data.url, data.avatarVersion)+ queryClient.setQueriesData(+ { queryKey: communityKeys.all },+ (cached) => projectIdentityPayload(cached),+ )+ useMessageStreamStore.getState().projectAvatarIdentity(+ currentUser.id,+ data.url,+ data.avatarVersion,+ )+ const identity = useCommunityWsStore.getState().avatarIdentities.get(currentUser.id)+ if (identity) {+ setCurrentUser((user) => identity.avatarVersion > (user.avatarVersion ?? 0)+ ? { ...user, avatar: identity.avatar, avatarVersion: identity.avatarVersion }+ : user)+ }toast("Avatar updated")},onError: (error) => toastApiError(error, "Failed to upload avatar"),diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsxindex 716061992..1a1071654 100644--- a/src/web/src/components/community/social/friends-page.tsx+++ b/src/web/src/components/community/social/friends-page.tsx@@ -3,7 +3,8 @@import { useState, useEffect, useMemo, useRef } from "react"import type React from "react"import { Users, MessagesSquare, ChevronLeft, Check, X, AtSign, UserMinus, Ban, UserPlus, Search } from "lucide-react"-import { apiFetch, toastApiError } from "@/lib/api/client"+import { toastApiError } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"@@ -64,7 +65,7 @@ export function FriendsPage({}, [friends, filter])const [addValue, setAddValue] = useState("")- const [searchResults, setSearchResults] = useState<{ id: string; name: string; image: string | null; discriminator: string }[]>([])+ const [searchResults, setSearchResults] = useState<{ id: string; name: string; image: string | null; avatarVersion: number; discriminator: string }[]>([])const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)// Relationship state by user id, so search results can show Friends/Pending/@@ -90,7 +91,7 @@ export function FriendsPage({if (q.length < MIN_SEARCH_LENGTH) { setSearchResults([]); return }debounceRef.current = setTimeout(async () => {try {- const data = await apiFetch<{ users: { id: string; name: string; image: string | null; discriminator: string }[] }>(`/api/community/users/search?q=${encodeURIComponent(q)}`)+ const data = await apiFetchIdentity<{ users: { id: string; name: string; image: string | null; avatarVersion: number; discriminator: string }[] }>(`/api/community/users/search?q=${encodeURIComponent(q)}`)setSearchResults(data.users)} catch (e) {setSearchResults([])diff --git a/src/web/src/components/community/social/profile-lookup.ts b/src/web/src/components/community/social/profile-lookup.tsindex e9da3bd59..aadf01396 100644--- a/src/web/src/components/community/social/profile-lookup.ts+++ b/src/web/src/components/community/social/profile-lookup.ts@@ -25,6 +25,7 @@ export function buildSelfProfile(userId: currentUser.id,discriminator: currentUser.discriminator,avatar: currentUser.avatar || avatarInitial(currentUser.name),+ avatarVersion: currentUser.avatarVersion,contextLabel,about: currentUser.aboutMe ?? "",mutual: 0,diff --git a/src/web/src/components/community/social/profile-types.ts b/src/web/src/components/community/social/profile-types.tsindex ce9d01e41..ee108c260 100644--- a/src/web/src/components/community/social/profile-types.ts+++ b/src/web/src/components/community/social/profile-types.ts@@ -14,6 +14,7 @@ export type Profile = {// in @alook/shared.discriminator?: stringavatar: string+ avatarVersion?: numbercontextLabel?: stringabout: stringmutual: numberdiff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsxindex d9d313e91..3ffd9663b 100644--- a/src/web/src/components/home/landing-shell-motion.tsx+++ b/src/web/src/components/home/landing-shell-motion.tsx@@ -186,7 +186,7 @@ const CONTINUITY_CHANNELS: Record<LandingRoom, Category[]> = {}const DMS: DM[] = [- { id: "dm-alli", userId: "alli", name: "Alli", discriminator: "8145", avatar: "avatar:beam:alli", status: "online", preview: "Available" },+ { id: "dm-alli", userId: "alli", name: "Alli", discriminator: "8145", avatar: "avatar:beam:alli", avatarVersion: 0, status: "online", preview: "Available" },]const MESSAGES: RenderMsg[] = [diff --git a/src/web/src/contexts/community/current-user.tsx b/src/web/src/contexts/community/current-user.tsxindex 1a470df93..cddafc76b 100644--- a/src/web/src/contexts/community/current-user.tsx+++ b/src/web/src/contexts/community/current-user.tsx@@ -20,6 +20,7 @@ export type CurrentUser = {name: stringemail: stringavatar: string+ avatarVersion?: numberaboutMe?: string// 4-digit discriminator (`"0042"`). Hydrated alongside `aboutMe` from// /api/community/users/me/profile — see CommunityBootstrap.diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.tsindex 571f49895..e4f29cf7f 100644--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts@@ -53,6 +53,7 @@ const message = {seq: 1,authorId: "author-1",authorName: "Alice",+ authorAvatarVersion: 0,content: "hello",type: "chat" as const,createdAt: "2026-08-21T00:00:00.000Z",diff --git a/src/web/src/hooks/community/community-ws/identity-events.test.ts b/src/web/src/hooks/community/community-ws/identity-events.test.tsnew file mode 100644index 000000000..52c01b787--- /dev/null+++ b/src/web/src/hooks/community/community-ws/identity-events.test.ts@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { useCommunityWsStore } from "@/stores/community/ws"+import type { CommunityWsHandlerContext } from "./handler-context"+import { handleIdentityUpdate } from "./identity-events"++function harness() {+ const queryClient = new QueryClient()+ const invalidate = vi.fn()+ const context = {+ queryClient,+ wsStore: useCommunityWsStore.getState(),+ projection: {+ project: (project: () => void) => project(),+ invalidate,+ },+ } as unknown as CommunityWsHandlerContext+ return { queryClient, invalidate, context }+}++beforeEach(() => {+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().bindIdentityOwner("viewer")+ useMessageStreamStore.getState().resetAll()+})++describe("handleIdentityUpdate", () => {+ it("patches all cached projections and the detached message stream", () => {+ const { queryClient, context, invalidate } = harness()+ queryClient.setQueryData(communityKeys.message("m1"), {+ id: "m1",+ authorId: "u1",+ authorAvatar: "/avatar?v=1",+ authorAvatarVersion: 1,+ })+ const projectStream = vi.spyOn(+ useMessageStreamStore.getState(),+ "projectAvatarIdentity",+ )++ handleIdentityUpdate({+ type: "community:identity.update",+ userId: "u1",+ avatar: "/avatar?v=4",+ avatarVersion: 4,+ }, context)++ expect(queryClient.getQueryData(communityKeys.message("m1"))).toMatchObject({+ authorAvatar: "/avatar?v=4",+ authorAvatarVersion: 4,+ })+ expect(projectStream).toHaveBeenCalledWith("u1", "/avatar?v=4", 4)+ expect(invalidate).not.toHaveBeenCalled()+ })++ it("drops stale/same frames and invalidates a same-version conflict", () => {+ const { context, invalidate } = harness()+ const store = useCommunityWsStore.getState()+ store.observeAvatarIdentity("u1", "/avatar?v=5", 5)++ handleIdentityUpdate({+ type: "community:identity.update",+ userId: "u1",+ avatar: "/avatar?v=4",+ avatarVersion: 4,+ }, context)+ handleIdentityUpdate({+ type: "community:identity.update",+ userId: "u1",+ avatar: "/avatar?v=5",+ avatarVersion: 5,+ }, context)+ expect(invalidate).not.toHaveBeenCalled()++ handleIdentityUpdate({+ type: "community:identity.update",+ userId: "u1",+ avatar: "/different?v=5",+ avatarVersion: 5,+ }, context)+ expect(invalidate).toHaveBeenCalledWith("identity-conflict", {+ queryKey: communityKeys.all,+ refetchType: "active",+ })+ })++ it("invalidates when a cached payload conflicts with the accepted frame version", () => {+ const { queryClient, context, invalidate } = harness()+ queryClient.setQueryData(communityKeys.message("m1"), {+ id: "m1",+ authorId: "u1",+ authorAvatar: "/cached-different?v=4",+ authorAvatarVersion: 4,+ })++ handleIdentityUpdate({+ type: "community:identity.update",+ userId: "u1",+ avatar: "/authoritative?v=4",+ avatarVersion: 4,+ }, context)++ expect(invalidate).toHaveBeenCalledWith("identity-cache-conflict", {+ queryKey: communityKeys.all,+ refetchType: "active",+ })+ })+})diff --git a/src/web/src/hooks/community/community-ws/identity-events.ts b/src/web/src/hooks/community/community-ws/identity-events.tsnew file mode 100644index 000000000..e3b2a7c17--- /dev/null+++ b/src/web/src/hooks/community/community-ws/identity-events.ts@@ -0,0 +1,47 @@+import type { CommunityIdentityUpdate } from "@alook/shared"+import { communityKeys } from "@/lib/query-keys"+import { projectIdentityPayload } from "@/lib/community/identity-projection"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { useCommunityWsStore } from "@/stores/community/ws"+import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"++export function handleIdentityUpdate(+ event: CommunityIdentityUpdate,+ { queryClient, wsStore, projection }: CommunityWsHandlerContext,+) {+ const observed = wsStore.observeAvatarIdentity(+ event.userId,+ event.avatar,+ event.avatarVersion,+ )+ if (observed === "unbound" || observed === "stale" || observed === "same") return+ if (observed === "conflict") {+ projection.invalidate("identity-conflict", {+ queryKey: communityKeys.all,+ refetchType: "active",+ })+ return+ }++ let conflict = false+ projection.project(() => {+ queryClient.setQueriesData(+ { queryKey: communityKeys.all },+ (data) => projectIdentityPayload(data, () => { conflict = true }),+ )+ const current = useCommunityWsStore.getState().avatarIdentities.get(event.userId)+ if (current) {+ useMessageStreamStore.getState().projectAvatarIdentity(+ event.userId,+ current.avatar,+ current.avatarVersion,+ )+ }+ })+ if (conflict) {+ projection.invalidate("identity-cache-conflict", {+ queryKey: communityKeys.all,+ refetchType: "active",+ })+ }+}diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex d730c02d5..362ee2a1a 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -65,6 +65,7 @@ describe("useCommunityWs — member events", () => {userId: "u_1",name: "n",discriminator: "0000",+ avatarVersion: 0,role: "member",joinedAt: "2026-07-03T00:00:00.000Z",},@@ -106,6 +107,7 @@ describe("useCommunityWs — member events", () => {userId: "u_online",name: "Online member",discriminator: "0001",+ avatarVersion: 0,role: "member",joinedAt: "2026-08-17T00:00:00.000Z",},@@ -133,6 +135,7 @@ describe("useCommunityWs — member events", () => {userId: "u_offline",name: "Offline member",discriminator: "0002",+ avatarVersion: 0,role: "member",joinedAt: "2026-08-17T00:01:00.000Z",},@@ -166,6 +169,7 @@ describe("useCommunityWs — member events", () => {userId: "u_me",name: "Me",discriminator: "0001",+ avatarVersion: 0,role: "member",joinedAt: "2026-08-14T00:00:00.000Z",},diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex 46bed4403..be4425959 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -819,7 +819,7 @@ describe("useCommunityWs — message.updated", () => {message: { id: "m_dm", seq: 4, type: "chat", content: "approval" },},)- const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null }+ const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null, avatarVersion: 0 }const approval = {friendshipId: "friendship_1",status: "approved" as const,@@ -847,7 +847,7 @@ describe("useCommunityWs — message.updated", () => {type: "wsMessage",message: { id: "m_channel", seq: 4, type: "chat", content: "approval" },})- const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null }+ const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null, avatarVersion: 0 }const approval = {friendshipId: "friendship_1",status: "approved" as const,@@ -917,6 +917,7 @@ describe("useCommunityWs — DM message.create", () => {seq: 1,authorId: "u_a",authorName: "a",+ authorAvatarVersion: 0,content: "hi",type: "chat",seq: 1,@@ -960,6 +961,7 @@ describe("useCommunityWs — DM message.create", () => {seq: 12,authorId: "u_a",authorName: "a",+ authorAvatarVersion: 0,content: "replay",type: "chat",createdAt: "2026-07-03T00:00:00.000Z",diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex b7caaed98..f2198fe00 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts@@ -1,5 +1,5 @@import type { InfiniteData, QueryClient, QueryKey } from "@tanstack/react-query"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"@@ -212,7 +212,7 @@ async function fetchCurrentWindow(pageParam: MessagesPageParam,tag: string | null,): Promise<MessagesPage> {- return apiFetch<MessagesPage>(buildMessagesUrl(scopeId, pageParam, tag))+ return apiFetchIdentity<MessagesPage>(buildMessagesUrl(scopeId, pageParam, tag))}async function fetchCatchUp(@@ -229,7 +229,7 @@ async function fetchCatchUp(for (let pageIndex = 0; pageIndex < MAX_CATCH_UP_PAGES; pageIndex += 1) {const params = new URLSearchParams({ since: nextCursor })if (tag) params.set("tag", tag)- const page = await apiFetch<MessagesPage>(+ const page = await apiFetchIdentity<MessagesPage>(`/api/community/channels/${scopeId}/messages?${params}`,)messages.push(...page.messages)diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 40a3435ab..9c5e54230 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -7,6 +7,7 @@ import {capturedQueryClient,cleanupCommunityWsHarness,flushEffects,+ getCommunityApiFetchMock,messageCreate,mountHook,resetHookMemoization,@@ -36,6 +37,60 @@ async function flushMicrotasks(iterations = 12) {}describe("useCommunityWs — resyncs machines on WS reconnect", () => {+ it("re-reads the authoritative self identity after a reconnect gap", async () => {+ const apiFetch = getCommunityApiFetchMock()+ apiFetch.mockImplementation(async (url: unknown) => {+ if (url === "/api/community/users/me/read-state") {+ return { revision: 0, readStates: [] }+ }+ if (url === "/api/community/users/me/profile") {+ return {+ id: "self",+ avatar: "/api/community/users/self/avatar?v=7",+ avatarVersion: 7,+ }+ }+ throw new Error(`unexpected API fetch: ${String(url)}`)+ })+ await mountHook({ viewerUserId: "self" })+ flushEffects()++ await capturedOnReconnect!({ reconnectDurationMs: 1_000 })++ expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/profile")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ expect(useCommunityWsStore.getState().avatarIdentities.get("self")).toEqual({+ avatar: "/api/community/users/self/avatar?v=7",+ avatarVersion: 7,+ })+ })++ it("invalidates cached identity surfaces after a reconnect gap", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ capturedQueryClient.setQueryData(communityKeys.bots(), { bots: [] })++ await reconcileCommunityWsReconnect(capturedQueryClient)++ expect(capturedQueryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)+ })++ it("reports identity reconciliation failure when an active identity invalidation rejects", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ capturedQueryClient.setQueryData(communityKeys.bots(), { bots: [] })+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {+ if (filters.predicate) return Promise.reject(new Error("identity cache unavailable"))+ return originalInvalidate(filters, options)+ })++ const summary = await reconcileCommunityWsReconnect(capturedQueryClient)++ expect(summary.failureCount).toBeGreaterThan(0)+ expect(telemetry.failure).toHaveBeenCalledWith(+ expect.objectContaining({ policy: "identity-surfaces" }),+ )+ })+it("reactivates the Inbox owner after a Strict Effects cleanup/setup replay", async () => {vi.useFakeTimers()await mountHook()@@ -400,8 +455,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)expect(summary).toMatchObject({- policyCount: 14,- successCount: 13,+ policyCount: 15,+ successCount: 14,failureCount: 1,reconnectDurationMs: 900,})@@ -431,7 +486,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)useCommunityWsStore.setState({ resetPresence: originalResetPresence })- expect(summary).toMatchObject({ policyCount: 14, successCount: 13, failureCount: 1 })+ expect(summary).toMatchObject({ policyCount: 15, successCount: 14, failureCount: 1 })expect(telemetry.failure).toHaveBeenCalledWith({policy: "presence-overlay",reason: "sync-throw",@@ -452,7 +507,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(keys).not.toContain(JSON.stringify(communityKeys.dms()))expect(keys).toContain(JSON.stringify(communityKeys.friends()))expect(keys).toContain(JSON.stringify(communityKeys.servers()))- expect(summary).toMatchObject({ policyCount: 13, successCount: 13, failureCount: 0 })+ expect(summary).toMatchObject({ policyCount: 14, successCount: 14, failureCount: 0 })})it("resets presence and status overlays before authoritative invalidation starts", async () => {diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex ad0494880..094c1eb52 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -4,6 +4,7 @@ import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sidebar-threads"import { clearAllTypingIndicators } from "@/hooks/community/community-ws/typing"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityWsReconnectPolicies } from "@/hooks/community/community-ws/registry"import { reconcileFocusedMessageQueries } from "@/hooks/community/community-ws/reconnect-messages"import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"@@ -120,7 +121,10 @@ async function reconcileCachedServer(queryClient: QueryClient, serverId: string)}}-function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcilePolicy, () => void | Promise<void>> {+function policyExecutors(+ queryClient: QueryClient,+ identityOwnerUserId?: string | null,+): Record<CommunityWsReconcilePolicy, () => void | Promise<void>> {const sub = useCommunityStore.getState().subscriptionconst queryKeys = queryClient.getQueryCache().getAll().map((query) => query.queryKey)return {@@ -206,6 +210,27 @@ function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcileP},"presence-overlay": () => useCommunityWsStore.getState().resetPresence(),"status-overlay": () => useCommunityWsStore.getState().resetUserStatuses(),+ "identity-surfaces": async () => {+ const hasIdentitySurface = queryClient.getQueryCache().getAll().some((query) => (+ query.queryKey[0] === "community"+ && ["profile", "bots", "invite-info"].includes(String(query.queryKey[1]))+ ))+ const settled = await Promise.allSettled([+ ...(identityOwnerUserId+ ? [apiFetchIdentity("/api/community/users/me/profile")]+ : []),+ ...(hasIdentitySurface+ ? [queryClient.invalidateQueries({+ predicate: (query) => query.queryKey[0] === "community"+ && ["profile", "bots", "invite-info"].includes(String(query.queryKey[1])),+ refetchType: "active",+ })]+ : []),+ ])+ if (settled.some((result) => result.status === "rejected")) {+ throw new Error("identity reconciliation failed")+ }+ },"ephemeral-typing": clearAllTypingIndicators,"machines": async () => {await queryClient.invalidateQueries({ queryKey: communityKeys.machines(), refetchType: "active" })@@ -274,6 +299,7 @@ export type CommunityWsReconcileSummary = {type CommunityWsReconnectOptions = {excludePolicies?: readonly CommunityWsReconcilePolicy[]+ identityOwnerUserId?: string | null}export async function reconcileCommunityWsReconnect(@@ -282,7 +308,7 @@ export async function reconcileCommunityWsReconnect(options: CommunityWsReconnectOptions = {},): Promise<CommunityWsReconcileSummary> {const startedAt = Date.now()- const executors = policyExecutors(queryClient)+ const executors = policyExecutors(queryClient, options.identityOwnerUserId)const excludedPolicies = new Set(options.excludePolicies ?? [])const policies = communityWsReconnectPolicies.filter((policy) => !excludedPolicies.has(policy))const resetPolicies = policies.filter((policy) => RESET_POLICIES.has(policy))diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsindex 3843dcac8..e839c58e0 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -62,6 +62,9 @@ vi.mock("./presence-machine-events", () => ({handlePresenceUpdate: handlers.handlePresenceUpdate,handleStatusUpdate: handlers.handleStatusUpdate,}))+vi.mock("./identity-events", () => ({+ handleIdentityUpdate: handlers.handleIdentityUpdate,+}))function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchContext {return {@@ -77,10 +80,10 @@ function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchCo}describe("community WebSocket registry", () => {- it("has exactly one entry for each of the 43 runtime event types", () => {+ it("has exactly one entry for each of the 44 runtime event types", () => {const eventTypes = Object.values(WS_EVENTS).sort()const registryTypes = Object.keys(communityWsRegistry).sort()- expect(eventTypes).toHaveLength(43)+ expect(eventTypes).toHaveLength(44)expect(registryTypes).toEqual(eventTypes)})@@ -92,8 +95,8 @@ describe("community WebSocket registry", () => {})it("deduplicates the complete policy set", () => {- expect(communityWsReconnectPolicies).toHaveLength(14)- expect(new Set(communityWsReconnectPolicies).size).toBe(14)+ expect(communityWsReconnectPolicies).toHaveLength(15)+ expect(new Set(communityWsReconnectPolicies).size).toBe(15)})it.each([diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 3454b4ce6..e2c9a2359 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -44,6 +44,7 @@ import {handlePresenceUpdate,handleStatusUpdate,} from "@/hooks/community/community-ws/presence-machine-events"+import { handleIdentityUpdate } from "@/hooks/community/community-ws/identity-events"type CommunityEventType = CommunityWsEvent["type"]type CommunityEventFor<T extends CommunityEventType> = Extract<CommunityWsEvent, { type: T }>@@ -92,6 +93,7 @@ export const communityWsRegistry = {"community:inbox.changed": { handler: handleInboxChanged, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },"community:presence.update": { handler: handlePresenceUpdate, reconnectPolicies: ["presence-overlay", "all-cached-servers"] },"community:status.update": { handler: (event) => handleStatusUpdate(event), reconnectPolicies: ["status-overlay"] },+ "community:identity.update": { handler: handleIdentityUpdate, reconnectPolicies: ["identity-surfaces"] },"community:machine.created": { handler: handleMachineCreated, reconnectPolicies: ["machines"] },"community:machine.status": { handler: handleMachineStatus, reconnectPolicies: ["machines"] },"community:machine.updated": { handler: handleMachineUpdated, reconnectPolicies: ["machines"] },diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.tsindex b2c53ed8f..dc5d2e2a5 100644--- a/src/web/src/hooks/community/community-ws/test-harness.ts+++ b/src/web/src/hooks/community/community-ws/test-harness.ts@@ -185,6 +185,7 @@ export function messageCreate(channelId: string, msgId = "m_1"): CommunityMessagtype: "chat",authorId: "u_author",authorName: "author",+ authorAvatarVersion: 0,content: "hi",seq: 1,createdAt: "2026-07-03T00:00:00.000Z",diff --git a/src/web/src/hooks/community/community-ws/typing-events.test.ts b/src/web/src/hooks/community/community-ws/typing-events.test.tsindex 9f63c8d92..1846e6933 100644--- a/src/web/src/hooks/community/community-ws/typing-events.test.ts+++ b/src/web/src/hooks/community/community-ws/typing-events.test.ts@@ -130,6 +130,7 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {id: "m_bot_reply",authorId: "u_bot",authorName: "bot",+ authorAvatarVersion: 0,content: "done",type: "chat",seq: 1,diff --git a/src/web/src/hooks/community/fetch-all-server-members.ts b/src/web/src/hooks/community/fetch-all-server-members.tsindex 199880bb0..d360b7212 100644--- a/src/web/src/hooks/community/fetch-all-server-members.ts+++ b/src/web/src/hooks/community/fetch-all-server-members.ts@@ -1,6 +1,6 @@import { MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"import type { Member } from "@/lib/community/models/people"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"type MembersPage = {members: Member[]@@ -14,7 +14,7 @@ export async function fetchAllServerMembers(serverId: string): Promise<Member[]>do {const params = new URLSearchParams({ limit: String(MAX_MEMBERS_PAGE_SIZE) })if (cursor) params.set("cursor", cursor)- const page = await apiFetch<MembersPage>(+ const page = await apiFetchIdentity<MembersPage>(`/api/community/servers/${encodeURIComponent(serverId)}/members?${params}`,)members.push(...page.members)diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.tsindex 17bfc06d8..741bfd7cc 100644--- a/src/web/src/hooks/community/mutations/profile.ts+++ b/src/web/src/hooks/community/mutations/profile.ts@@ -27,7 +27,7 @@ export function useUpdateProfile() {}export type UploadUserAvatarArgs = { file: File }-export type UploadUserAvatarResult = { url: string }+export type UploadUserAvatarResult = { url: string; avatarVersion: number }/*** Uploads the current user's avatar. Mirrors `useUploadServerIcon`'s rawdiff --git a/src/web/src/hooks/community/use-bots.test.ts b/src/web/src/hooks/community/use-bots.test.tsindex b0dc1f6bb..c96c0e5c2 100644--- a/src/web/src/hooks/community/use-bots.test.ts+++ b/src/web/src/hooks/community/use-bots.test.ts@@ -63,6 +63,28 @@ describe("invalidateBotSurfaces", () => {})describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {+ it("useBots fetches through the identity-aware query function", async () => {+ apiFetchMock.mockResolvedValue({ bots: [] })+ const { useBots } = await import("./use-bots")+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ function Probe() {+ const result = useBots()+ return React.createElement("span", { "data-count": result.bots.length })+ }++ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ))+ })+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots"))+ expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ act(() => renderer.unmount())+ })+it("useUpdateBot forwards explicit reasoning effort values and omission", async () => {const { useUpdateBot } = await import("./use-bots")const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })@@ -138,4 +160,61 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {// Confirms why useDeleteBot's onSuccess signature is (_data, id) rather// than reading an id off the (empty) response body.})++ it("useUploadBotAvatar projects the returned identity before invalidating bot surfaces", async () => {+ const { useUploadBotAvatar } = await import("./use-bots")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const { useMessageStreamStore } = await import("@/stores/community/message-stream")+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().bindIdentityOwner("viewer")+ const projectStream = vi.spyOn(+ useMessageStreamStore.getState(),+ "projectAvatarIdentity",+ )+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })+ queryClient.setQueryData(communityKeys.bots(), {+ bots: [{ id: "bot_1", image: "/avatar?v=1", avatarVersion: 1 }],+ })+ const setQueriesData = vi.spyOn(queryClient, "setQueriesData")+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({+ url: "/api/community/bots/bot_1/avatar?v=4",+ avatarVersion: 4,+ }), { status: 200, headers: { "Content-Type": "application/json" } })))+ let mutation!: ReturnType<typeof useUploadBotAvatar>+ function Probe() {+ mutation = useUploadBotAvatar()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ))+ })++ await act(async () => {+ await mutation.mutateAsync({+ botId: "bot_1",+ file: new File(["avatar"], "avatar.png", { type: "image/png" }),+ })+ })++ expect(useCommunityWsStore.getState().avatarIdentities.get("bot_1")).toEqual({+ avatar: "/api/community/bots/bot_1/avatar?v=4",+ avatarVersion: 4,+ })+ expect(setQueriesData).toHaveBeenCalled()+ expect(queryClient.getQueryData(communityKeys.bots())).toMatchObject({+ bots: [{ id: "bot_1", image: "/api/community/bots/bot_1/avatar?v=4", avatarVersion: 4 }],+ })+ expect(projectStream).toHaveBeenCalledWith(+ "bot_1",+ "/api/community/bots/bot_1/avatar?v=4",+ 4,+ )+ act(() => renderer.unmount())+ vi.unstubAllGlobals()+ })})diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex a7de6c152..8c9540af7 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -2,7 +2,10 @@import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tanstack/react-query"import { apiFetch, readUploadError } from "@/lib/api/client"+import { apiFetchIdentity, projectIdentityPayload } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"import type { BotActivityDay } from "@/lib/community/models/people"import type { DailyUsageMetric, ReasoningEffort } from "@alook/shared"@@ -26,6 +29,7 @@ export type BotSummary = {name: stringdescription: stringimage: string | null+ avatarVersion: numbermachineId: stringruntime: stringmodelName: string | null@@ -52,7 +56,7 @@ const EMPTY_BOTS: readonly BotSummary[] = Object.freeze([])export function useBots(): UseQueryResult<BotsResponse> & { bots: BotSummary[] } {const query = useQuery({queryKey: communityKeys.bots(),- queryFn: () => apiFetch<BotsResponse>("/api/community/bots"),+ queryFn: () => apiFetchIdentity<BotsResponse>("/api/community/bots"),})return { ...query, bots: query.data?.bots ?? (EMPTY_BOTS as BotSummary[]) }}@@ -115,6 +119,7 @@ export type UpdateBotResponse = {| "name"| "description"| "image"+ | "avatarVersion"| "runtime"| "modelName"| "reasoningEffort"@@ -191,7 +196,7 @@ export function useResetMachineAgents() {}export type UploadBotAvatarArgs = { botId: string; file: File }-export type UploadBotAvatarResult = { url: string }+export type UploadBotAvatarResult = { url: string; avatarVersion: number }export function useUploadBotAvatar() {const qc = useQueryClient()@@ -207,6 +212,22 @@ export function useUploadBotAvatar() {if (!res.ok) throw await readUploadError(res, "Upload failed")return (await res.json()) as UploadBotAvatarResult},- onSuccess: (_data, variables) => invalidateBotSurfaces(qc, variables.botId),+ onSuccess: (data, variables) => {+ useCommunityWsStore.getState().observeAvatarIdentity(+ variables.botId,+ data.url,+ data.avatarVersion,+ )+ qc.setQueriesData(+ { queryKey: communityKeys.all },+ (current) => projectIdentityPayload(current),+ )+ useMessageStreamStore.getState().projectAvatarIdentity(+ variables.botId,+ data.url,+ data.avatarVersion,+ )+ invalidateBotSurfaces(qc, variables.botId)+ },})}diff --git a/src/web/src/hooks/community/use-channel-members.test.ts b/src/web/src/hooks/community/use-channel-members.test.tsnew file mode 100644index 000000000..3734a3409--- /dev/null+++ b/src/web/src/hooks/community/use-channel-members.test.ts@@ -0,0 +1,42 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { beforeEach, describe, expect, it, vi } from "vitest"++const apiFetchMock = vi.fn()++vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),+}))++beforeEach(() => {+ apiFetchMock.mockReset()+})++describe("useChannelMembers", () => {+ it("fetches the roster through the identity-aware query function", async () => {+ apiFetchMock.mockResolvedValue({ members: [] })+ const { useChannelMembers } = await import("./use-channel-members")+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ function Probe() {+ const result = useChannelMembers("private/channel")+ return React.createElement("span", { "data-count": result.members.length })+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ))+ })++ await vi.waitFor(() => {+ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/private%2Fchannel/members",+ )+ })+ expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ act(() => renderer.unmount())+ })+})diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex 0cdcf9a5f..702977e2c 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -2,6 +2,7 @@import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { CommunityRole } from "@alook/shared"import type { CommunityUserCore } from "@/lib/community/models/people"@@ -31,6 +32,7 @@ export type AddableMember = {name: string | nulldiscriminator: string | nullavatar: string+ avatarVersion: number}const EMPTY_MEMBERS: readonly ChannelMember[] = Object.freeze([])@@ -39,7 +41,7 @@ const EMPTY_ADDABLE: readonly AddableMember[] = Object.freeze([])export async function addableMembersQueryFn(serverId: string, channelId: string): Promise<{ members: AddableMember[] }> {const [serverMembers, channelData] = await Promise.all([fetchAllServerMembers(serverId),- apiFetch<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`),+ apiFetchIdentity<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`),])const present = new Set(channelData.members.map((member) => member.userId))return {@@ -50,6 +52,7 @@ export async function addableMembersQueryFn(serverId: string, channelId: string)name: member.name,discriminator: member.discriminator,avatar: member.avatar,+ avatarVersion: member.avatarVersion,})),}}@@ -62,7 +65,7 @@ export function useChannelMembers(const query = useQuery({queryKey: communityKeys.channelMembers(channelId),queryFn: () =>- apiFetch<{ members: ChannelMember[] }>(+ apiFetchIdentity<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`,),enabled: enabled && !!channelId,diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.tsindex 46e71382e..c31d395b2 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -2,6 +2,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { Thread, Msg } from "@/lib/community/models/message"@@ -136,7 +137,7 @@ export function useForumTags(channelId: string | null, enabled: boolean) {export type PinsResponse = { pins: Msg[] }export const pinsQueryFn = (channelId: string) => () =>- apiFetch<PinsResponse>(`/api/community/channels/${channelId}/pins`)+ apiFetchIdentity<PinsResponse>(`/api/community/channels/${channelId}/pins`)export function usePins(channelId: string | null): UseQueryResult<PinsResponse> & {pins: Msg[]diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex ebd209741..ebc9aecc7 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -220,9 +220,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {}, [getConnectionController])const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)const hasAuthenticatedRef = useRef(false)+ const viewerUserId = options?.viewerUserId ?? null+ viewerUserIdRef.current = viewerUserIduseEffect(() => {- viewerUserIdRef.current = options?.viewerUserId ?? null- })+ useCommunityWsStore.getState().bindIdentityOwner(viewerUserId)+ return () => {+ const store = useCommunityWsStore.getState()+ if (store.identityOwnerUserId === viewerUserId) store.bindIdentityOwner(null)+ }+ }, [viewerUserId])const inboxRefreshOwner = useRef<InboxRefreshOwner | null>(null)if (inboxRefreshOwner.current === null) {@@ -473,6 +479,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {try {await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs, {excludePolicies: ["inbox-dms"],+ identityOwnerUserId: viewerUserIdRef.current,})} finally {scheduleInboxInvalidate({ inbox: true, dms: true })diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 123d35fbb..53c3fb4bb 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -1,7 +1,7 @@"use client"import { useQuery, type UseQueryResult } from "@tanstack/react-query"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { DM } from "@/lib/community/models/people"@@ -19,7 +19,7 @@ export type DmsResponse = { conversations: DM[] }const EMPTY_DMS: readonly DM[] = Object.freeze([])export const dmsQueryFn = () =>- apiFetch<DmsResponse>("/api/community/users/me/dms")+ apiFetchIdentity<DmsResponse>("/api/community/users/me/dms")export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {const query = useQuery({diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex 84ce0ebf6..77898f0df 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -3,9 +3,10 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"import type { ForumThread } from "@/lib/community/models/message"import { useForumTags } from "./use-channel-panels"@@ -30,6 +31,7 @@ type IncludedMessage = {authorId: stringauthorName: stringauthorImage: string | null+ authorAvatarVersion: number}type IncludedFirstMessage = { channelId: string; content: string }@@ -39,6 +41,7 @@ type IncludedParticipant = {userId: stringuserName: string | nulluserImage: string | null+ userAvatarVersion: numberparticipantCount?: number}@@ -102,7 +105,7 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null) {})if (tag) params.set("tag", tag)if (pageParam) params.set("cursor", pageParam)- return apiFetch<ForumFeedPage>(+ return apiFetchIdentity<ForumFeedPage>(`/api/community/channels/${channelId}/threads?${params.toString()}`,)}@@ -126,7 +129,9 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {{id: row.userId,name: row.userName ?? "",- avatar: row.userImage ?? avatarInitial(row.userName ?? ""),+ avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)+ ?? avatarInitial(row.userName ?? ""),+ avatarVersion: row.userAvatarVersion,},])participantCountByChannel.set(row.channelId, Number(row.participantCount ?? 0))@@ -147,7 +152,11 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {text: (first?.content ?? "").slice(0, 100),},authorId: opener?.authorId ?? thread.creatorId ?? "",- authorAvatar: opener?.authorImage ?? avatarInitial(opener?.authorName ?? ""),+ authorAvatar: opener+ ? canonicalUserImage(opener.authorId, opener.authorImage, opener.authorAvatarVersion)+ ?? avatarInitial(opener.authorName)+ : avatarInitial(""),+ authorAvatarVersion: opener?.authorAvatarVersion ?? 0,openerMessageId: thread.parentMessageId ?? "",...(opener?.createdAt ? { openerCreatedAt: opener.createdAt } : {}),...(opener ? { parentSeq: opener.seq } : {}),diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex 7c5d3b058..aec6cd926 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -2,6 +2,7 @@import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"@@ -46,9 +47,9 @@ export const friendsQueryFn = async (): Promise<FriendsResponse> => {// · friends/pending) and compose the same triad. Same query key / cache grain// as before, so mutations still fire one invalidation.const [acceptedData, blockedData, pendingData] = await Promise.all([- apiFetch<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted").then(throwIfStale),- apiFetch<{ blocked: BlockedUser[]; stale?: boolean }>("/api/community/friends/blocked").then(throwIfStale),- apiFetch<{ pending: PendingRequest[]; stale?: boolean }>("/api/community/friends/pending").then(throwIfStale),+ apiFetchIdentity<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted").then(throwIfStale),+ apiFetchIdentity<{ blocked: BlockedUser[]; stale?: boolean }>("/api/community/friends/blocked").then(throwIfStale),+ apiFetchIdentity<{ pending: PendingRequest[]; stale?: boolean }>("/api/community/friends/pending").then(throwIfStale),])return {friends: acceptedData.friends,diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex 7bb6b7974..bd212126b 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -118,6 +118,32 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {})})+describe("useInboxMarked", () => {+ it("fetches the identity-aware marked feed only when enabled", async () => {+ apiFetchMock.mockResolvedValue({ marked: [] })+ const { useInboxMarked } = await import("./use-inbox")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ function Harness() {+ const result = useInboxMarked(true)+ return React.createElement("span", { "data-count": result.marked.length })+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ ))+ })++ await vi.waitFor(() => {+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/marks")+ })+ expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ act(() => renderer.unmount())+ })+})+// WS reconciliation invalidates the shared `inbox()` prefix — both feeds must// pick it up, otherwise mentions or unread refreshes would silently drop.describe("communityKeys.inbox() prefix invalidation", () => {diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex ad89a41f7..d7255f22f 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,6 +3,7 @@import { useMemo } from "react"import { useQuery, useQueryClient, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { UnreadServer, UnreadDm, Mention, Marked } from "@/lib/community/models/inbox"import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"@@ -69,7 +70,7 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {export type MentionsResponse = { mentions: Mention[] }export const inboxMentionsQueryFn = () =>- apiFetch<MentionsResponse & { stale?: boolean }>("/api/community/users/me/inbox/mentions").then(throwIfStale)+ apiFetchIdentity<MentionsResponse & { stale?: boolean }>("/api/community/users/me/inbox/mentions").then(throwIfStale)export function useInboxMentions(): UseQueryResult<MentionsResponse> & {mentions: Mention[]@@ -88,7 +89,7 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {export type MarkedResponse = { marked: Marked[] }const inboxMarkedQueryFn = () =>- apiFetch<MarkedResponse & { stale?: boolean }>("/api/community/users/me/marks").then(throwIfStale)+ apiFetchIdentity<MarkedResponse & { stale?: boolean }>("/api/community/users/me/marks").then(throwIfStale)/*** The Marked feed is lazy — unlike unreads/mentions (which the shell readsdiff --git a/src/web/src/hooks/community/use-invitable-friends.ts b/src/web/src/hooks/community/use-invitable-friends.tsindex a8bb48cd6..22eb74df1 100644--- a/src/web/src/hooks/community/use-invitable-friends.ts+++ b/src/web/src/hooks/community/use-invitable-friends.ts@@ -1,7 +1,7 @@"use client"import { useQuery, type UseQueryResult } from "@tanstack/react-query"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { Friend } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"@@ -23,7 +23,7 @@ const EMPTY: readonly Friend[] = Object.freeze([])export async function invitableFriendsQueryFn(serverId: string): Promise<InvitableFriendsResponse> {const [accepted, members] = await Promise.all([- apiFetch<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted"),+ apiFetchIdentity<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted"),fetchAllServerMembers(serverId),])if (accepted.stale) throw new Error("stale D1 read")diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.tsindex 20d1598ce..fda8ae462 100644--- a/src/web/src/hooks/community/use-message.ts+++ b/src/web/src/hooks/community/use-message.ts@@ -1,7 +1,7 @@"use client"import { useQuery, type UseQueryResult } from "@tanstack/react-query"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { Msg } from "@/lib/community/models/message"@@ -23,6 +23,7 @@ export type OpenerPayload = {authorId: stringauthorName: stringauthorAvatar: string+ authorAvatarVersion: numbercontent: string// Required, exhaustive (#12) — matches `mapMessageForApi`'s new output// shape (this payload is fed by that same endpoint, `GET /api/community/messages/:id`).@@ -35,7 +36,7 @@ export type OpenerPayload = {}export const messageQueryFn = (messageId: string) => () =>- apiFetch<OpenerPayload>(`/api/community/messages/${messageId}`)+ apiFetchIdentity<OpenerPayload>(`/api/community/messages/${messageId}`)export function useMessage(messageId: string | null | undefined,diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex b40b863fa..fc56607b6 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -8,7 +8,7 @@ import {type QueryClient,} from "@tanstack/react-query"import { useCallback, useEffect, useMemo, useRef, useState } from "react"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type {MessagesPage,@@ -80,8 +80,8 @@ export const channelMessagesQueryFn =tag,)return signal- ? apiFetch<MessagesPage>(url, { signal })- : apiFetch<MessagesPage>(url)+ ? apiFetchIdentity<MessagesPage>(url, { signal })+ : apiFetchIdentity<MessagesPage>(url)}export const dmMessagesQueryFn =@@ -98,8 +98,8 @@ export const dmMessagesQueryFn =pageParam,)return signal- ? apiFetch<MessagesPage>(url, { signal })- : apiFetch<MessagesPage>(url)+ ? apiFetchIdentity<MessagesPage>(url, { signal })+ : apiFetchIdentity<MessagesPage>(url)}export function messageMatchesTag(message: Msg, tag?: string | null): boolean {diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex 82fa8d5ca..c11f5430c 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -6,7 +6,8 @@ import {useQueryClient,type InfiniteData,} from "@tanstack/react-query"-import { apiFetch, toastApiError } from "@/lib/api/client"+import { toastApiError } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"import { communityKeys } from "@/lib/query-keys"import type { Member } from "@/lib/community/models/people"import type {@@ -48,6 +49,7 @@ export function applyJoinEvent(name: event.member.name,discriminator: event.member.discriminator,avatar: event.member.avatar ?? avatarInitial(event.member.name),+ avatarVersion: event.member.avatarVersion,status: "online",sub: "",role: event.member.role as CommunityRole,@@ -121,7 +123,7 @@ export const membersPageQueryFn =const params = new URLSearchParams()if (pageParam) params.set("cursor", pageParam)const url = `/api/community/servers/${serverId}/members${params.toString() ? `?${params}` : ""}`- return apiFetch<MembersEnvelope>(url)+ return apiFetchIdentity<MembersEnvelope>(url)}// ── Cache mutation helpers (also used by the WS handler in Step 3) ──────────@@ -423,7 +425,7 @@ export function useServerMembers(serverId: string | null): UseServerMembers {try {const params = new URLSearchParams({ q })if (cursor) params.set("cursor", cursor)- const data = await apiFetch<SearchEnvelope>(+ const data = await apiFetchIdentity<SearchEnvelope>(`/api/community/servers/${serverId}/members/search?${params}`,)if (searchSeq.current !== seq) returndiff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.tsindex dc77bb8d7..da5dc035a 100644--- a/src/web/src/hooks/community/use-user-profile.ts+++ b/src/web/src/hooks/community/use-user-profile.ts@@ -1,6 +1,6 @@"use client"-import { apiFetch } from "@/lib/api/client"+import { apiFetchIdentity } from "@/lib/community/identity-projection"/*** Fetches a public user profile card (avatar, name, aboutMe, mutual-server@@ -15,6 +15,7 @@ type UserProfileBase = {name: stringdiscriminator: stringimage: string | null+ avatarVersion: numberaboutMe: stringbannerColor: string | nullmutualServers: number@@ -32,7 +33,7 @@ export type UserProfile = UserProfileBase & ()export const userProfileQueryFn = (userId: string) => () =>- apiFetch<UserProfile>(`/api/community/users/${userId}/profile`)+ apiFetchIdentity<UserProfile>(`/api/community/users/${userId}/profile`)// How long a fetched profile card is considered fresh before a re-click// triggers a background refetch (`queryClient.fetchQuery`'s `staleTime`).diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.tsindex 9610522e8..5be5d2382 100644--- a/src/web/src/lib/analytics.ts+++ b/src/web/src/lib/analytics.ts@@ -172,6 +172,7 @@ export type CommunityWsReconcilePolicy =| "friends"| "presence-overlay"| "status-overlay"+ | "identity-surfaces"| "ephemeral-typing"| "machines"| "bot-audits"diff --git a/src/web/src/lib/community/avatar-media-reconciliation.test.ts b/src/web/src/lib/community/avatar-media-reconciliation.test.tsnew file mode 100644index 000000000..d87a34d94--- /dev/null+++ b/src/web/src/lib/community/avatar-media-reconciliation.test.ts@@ -0,0 +1,256 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ getHuman: vi.fn(),+ getBot: vi.fn(),+ waitUntil: vi.fn(),+}))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ user: {+ ...actual.queries.user,+ getLiveHumanAvatarState: (...args: unknown[]) => mocks.getHuman(...args),+ },+ communityBot: {+ ...actual.queries.communityBot,+ getLiveBotAvatar: (...args: unknown[]) => mocks.getBot(...args),+ },+ },+ }+})++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: () => ({ ctx: { waitUntil: mocks.waitUntil } }),+}))++import {+ cleanupAvatarCandidate,+ ensureAvatarAliasPresent,+ scheduleAvatarMediaReconciliation,+} from "./avatar-media-reconciliation"++function object(bytes: number[], label: string) {+ return {+ arrayBuffer: vi.fn(async () => Uint8Array.from(bytes).buffer),+ httpMetadata: { contentType: "image/webp", cacheControl: `private-${label}` },+ customMetadata: { source: label },+ }+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe("avatar alias reconciliation", () => {+ it("copies buffered known-length bytes and preserves HTTP/custom metadata", async () => {+ const current = "user-avatar/u1/objects/current"+ mocks.getHuman.mockResolvedValue({ avatarVersion: 3, avatarObjectKey: current })+ const source = object([1, 2, 3, 4], "current")+ const head = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({ key: "user-avatar/u1" })+ const get = vi.fn().mockResolvedValue(source)+ const put = vi.fn().mockResolvedValue(undefined)++ await expect(ensureAvatarAliasPresent(+ {} as never,+ { head, get, put, delete: vi.fn() } as never,+ { kind: "human", id: "u1" },+ )).resolves.toBe(true)++ expect(get).toHaveBeenCalledWith(current)+ expect(put).toHaveBeenCalledOnce()+ const [key, bytes, options] = put.mock.calls[0]!+ expect(key).toBe("user-avatar/u1")+ expect(bytes).toBeInstanceOf(ArrayBuffer)+ expect((bytes as ArrayBuffer).byteLength).toBe(4)+ expect(options).toEqual({+ httpMetadata: source.httpMetadata,+ customMetadata: source.customMetadata,+ })+ })++ it("retries a reordered alias copy until the bytes match the authoritative pointer", async () => {+ const oldKey = "user-avatar/u1/objects/old"+ const newKey = "user-avatar/u1/objects/new"+ mocks.getHuman+ .mockResolvedValueOnce({ avatarVersion: 1, avatarObjectKey: oldKey })+ .mockResolvedValueOnce({ avatarVersion: 2, avatarObjectKey: newKey })+ .mockResolvedValueOnce({ avatarVersion: 2, avatarObjectKey: newKey })+ .mockResolvedValueOnce({ avatarVersion: 2, avatarObjectKey: newKey })+ const get = vi.fn(async (key: string) => key === oldKey+ ? object([1], "old")+ : object([2], "new"))+ const put = vi.fn().mockResolvedValue(undefined)+ const head = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({ key: "user-avatar/u1" })++ await expect(ensureAvatarAliasPresent(+ {} as never,+ { head, get, put, delete: vi.fn() } as never,+ { kind: "human", id: "u1" },+ )).resolves.toBe(true)++ expect(get.mock.calls.map((call) => call[0])).toEqual([oldKey, newKey])+ expect(put).toHaveBeenCalledTimes(2)+ const finalBytes = put.mock.calls[1]![1] as ArrayBuffer+ expect([...new Uint8Array(finalBytes)]).toEqual([2])+ })++ it("returns false without copying an invalid or legacy pointer", async () => {+ mocks.getHuman.mockResolvedValue({ avatarVersion: 0, avatarObjectKey: null })+ const get = vi.fn()+ const put = vi.fn()++ await expect(ensureAvatarAliasPresent(+ {} as never,+ { head: vi.fn().mockResolvedValue(null), get, put, delete: vi.fn() } as never,+ { kind: "human", id: "u1" },+ )).resolves.toBe(false)+ expect(get).not.toHaveBeenCalled()+ expect(put).not.toHaveBeenCalled()+ })++ it("recognizes an already-present bot alias", async () => {+ const head = vi.fn().mockResolvedValue({ key: "bot-avatar/b1" })++ await expect(ensureAvatarAliasPresent(+ {} as never,+ { head, get: vi.fn(), put: vi.fn(), delete: vi.fn() } as never,+ { kind: "bot", id: "b1" },+ )).resolves.toBe(true)++ expect(head).toHaveBeenCalledWith("bot-avatar/b1")+ expect(mocks.getBot).not.toHaveBeenCalled()+ })++ it("returns false after three continuously reordered alias copies", async () => {+ let read = 0+ mocks.getHuman.mockImplementation(async () => {+ read += 1+ return {+ avatarVersion: read,+ avatarObjectKey: `user-avatar/u1/objects/object-${read}`,+ }+ })+ const get = vi.fn().mockResolvedValue(object([1], "moving"))+ const put = vi.fn().mockResolvedValue(undefined)++ await expect(ensureAvatarAliasPresent(+ {} as never,+ { head: vi.fn().mockResolvedValue(null), get, put, delete: vi.fn() } as never,+ { kind: "human", id: "u1" },+ )).resolves.toBe(false)++ expect(get).toHaveBeenCalledTimes(3)+ expect(put).toHaveBeenCalledTimes(3)+ })+})++describe("avatar candidate cleanup", () => {+ it("deletes only a verified owned child that is no longer current", async () => {+ mocks.getHuman.mockResolvedValue({+ avatarVersion: 4,+ avatarObjectKey: "user-avatar/u1/objects/current",+ })+ const remove = vi.fn().mockResolvedValue(undefined)++ await expect(cleanupAvatarCandidate(+ {} as never,+ { delete: remove } as never,+ { kind: "human", id: "u1" },+ "user-avatar/u1/objects/displaced",+ )).resolves.toBe("deleted")+ expect(remove).toHaveBeenCalledWith("user-avatar/u1/objects/displaced")+ })++ it("retains current, alias, foreign, and unverified candidates", async () => {+ const current = "bot-avatar/b1/objects/current"+ mocks.getBot.mockResolvedValue({ avatarVersion: 2, avatarObjectKey: current })+ const remove = vi.fn()++ await expect(cleanupAvatarCandidate(+ {} as never,+ { delete: remove } as never,+ { kind: "bot", id: "b1" },+ current,+ )).resolves.toBe("retained_current")+ await expect(cleanupAvatarCandidate(+ {} as never,+ { delete: remove } as never,+ { kind: "bot", id: "b1" },+ "bot-avatar/b1",+ )).resolves.toBe("retained_unowned")+ await expect(cleanupAvatarCandidate(+ {} as never,+ { delete: remove } as never,+ { kind: "bot", id: "b1" },+ "bot-avatar/b2/objects/foreign",+ )).resolves.toBe("retained_unowned")++ mocks.getBot.mockRejectedValueOnce(new Error("D1 unavailable"))+ await expect(cleanupAvatarCandidate(+ {} as never,+ { delete: remove } as never,+ { kind: "bot", id: "b1" },+ "bot-avatar/b1/objects/unknown",+ )).resolves.toBe("retained_unverified")+ expect(remove).not.toHaveBeenCalled()+ })++ it("registers the same reconciliation promise with waitUntil", async () => {+ mocks.getHuman.mockResolvedValue({+ avatarVersion: 1,+ avatarObjectKey: "user-avatar/u1/objects/current",+ })+ const bucket = {+ get: vi.fn().mockResolvedValue(object([7], "current")),+ put: vi.fn().mockResolvedValue(undefined),+ head: vi.fn(),+ delete: vi.fn(),+ }++ const work = scheduleAvatarMediaReconciliation(+ {} as never,+ bucket as never,+ { subject: { kind: "human", id: "u1" }, candidates: [] },+ )++ expect(mocks.waitUntil).toHaveBeenCalledWith(work)+ await expect(work).resolves.toBeUndefined()+ })++ it("absorbs an alias-copy failure in background reconciliation", async () => {+ mocks.getHuman.mockRejectedValue(new Error("D1 unavailable"))+ const work = scheduleAvatarMediaReconciliation(+ {} as never,+ { get: vi.fn(), put: vi.fn(), head: vi.fn(), delete: vi.fn() } as never,+ { subject: { kind: "human", id: "u1" }, candidates: [] },+ )++ await expect(work).resolves.toBeUndefined()+ })++ it("continues after an incomplete alias copy and an exact child cleanup failure", async () => {+ mocks.getHuman+ .mockResolvedValueOnce({ avatarVersion: 0, avatarObjectKey: null })+ .mockResolvedValueOnce({+ avatarVersion: 2,+ avatarObjectKey: "user-avatar/u1/objects/current",+ })+ const remove = vi.fn().mockRejectedValue(new Error("R2 unavailable"))+ const work = scheduleAvatarMediaReconciliation(+ {} as never,+ { get: vi.fn(), put: vi.fn(), head: vi.fn(), delete: remove } as never,+ {+ subject: { kind: "human", id: "u1" },+ candidates: ["user-avatar/u1/objects/displaced"],+ },+ )++ await expect(work).resolves.toBeUndefined()+ expect(remove).toHaveBeenCalledWith("user-avatar/u1/objects/displaced")+ })+})diff --git a/src/web/src/lib/community/avatar-media-reconciliation.ts b/src/web/src/lib/community/avatar-media-reconciliation.tsnew file mode 100644index 000000000..2ee7574c1--- /dev/null+++ b/src/web/src/lib/community/avatar-media-reconciliation.ts@@ -0,0 +1,149 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createLogger, queries, type Database } from "@alook/shared"+import {+ communityMediaCleanupErrorCategory,+} from "./community-media-cleanup"+import {+ buildBotAvatarKey,+ buildUserAvatarKey,+ isOwnedBotAvatarObjectKey,+ isOwnedUserAvatarObjectKey,+} from "./storage"++const log = createLogger({ service: "community-avatar-media" })+const MAX_ALIAS_RECONCILIATION_ATTEMPTS = 3++export type AvatarSubject = { kind: "human" | "bot"; id: string }++type AvatarState = {+ avatarVersion: number+ avatarObjectKey: string | null+}++type AvatarBucket = Pick<R2Bucket, "delete" | "get" | "head" | "put">++function aliasKey(subject: AvatarSubject): string {+ return subject.kind === "human"+ ? buildUserAvatarKey(subject.id)+ : buildBotAvatarKey(subject.id)+}++function ownsChild(subject: AvatarSubject, key: string): boolean {+ return subject.kind === "human"+ ? isOwnedUserAvatarObjectKey(key, subject.id)+ : isOwnedBotAvatarObjectKey(key, subject.id)+}++async function readState(db: Database, subject: AvatarSubject): Promise<AvatarState | null> {+ return subject.kind === "human"+ ? queries.user.getLiveHumanAvatarState(db, subject.id)+ : queries.communityBot.getLiveBotAvatar(db, subject.id)+}++async function copyCurrentToAlias(+ db: Database,+ bucket: AvatarBucket,+ subject: AvatarSubject,+): Promise<boolean> {+ for (let attempt = 0; attempt < MAX_ALIAS_RECONCILIATION_ATTEMPTS; attempt += 1) {+ const before = await readState(db, subject)+ const objectKey = before?.avatarObjectKey+ if (!before || before.avatarVersion <= 0 || !objectKey || !ownsChild(subject, objectKey)) {+ return false+ }++ const object = await bucket.get(objectKey)+ if (!object) return false+ const bytes = await object.arrayBuffer()+ await bucket.put(aliasKey(subject), bytes, {+ httpMetadata: object.httpMetadata,+ customMetadata: object.customMetadata,+ })++ const after = await readState(db, subject)+ if (+ after?.avatarVersion === before.avatarVersion+ && after.avatarObjectKey === objectKey+ ) {+ return true+ }+ }+ return false+}++export async function ensureAvatarAliasPresent(+ db: Database,+ bucket: AvatarBucket,+ subject: AvatarSubject,+): Promise<boolean> {+ if (await bucket.head(aliasKey(subject))) return true+ if (!(await copyCurrentToAlias(db, bucket, subject))) return false+ return Boolean(await bucket.head(aliasKey(subject)))+}++export async function cleanupAvatarCandidate(+ db: Database,+ bucket: Pick<R2Bucket, "delete">,+ subject: AvatarSubject,+ candidate: string | null | undefined,+): Promise<"deleted" | "retained_current" | "retained_unowned" | "retained_unverified"> {+ if (!candidate || !ownsChild(subject, candidate)) return "retained_unowned"++ let current: AvatarState | null+ try {+ current = await readState(db, subject)+ } catch {+ return "retained_unverified"+ }+ if (current?.avatarObjectKey === candidate) return "retained_current"++ await bucket.delete(candidate)+ return "deleted"+}++async function reconcileAvatarMedia(+ db: Database,+ bucket: AvatarBucket,+ input: { subject: AvatarSubject; candidates: Array<string | null | undefined> },+): Promise<void> {+ try {+ if (!(await copyCurrentToAlias(db, bucket, input.subject))) {+ log.warn("community_avatar_alias_reconciliation_incomplete", {+ subjectKind: input.subject.kind,+ phase: "copy_current",+ })+ }+ } catch (error) {+ log.warn("community_avatar_alias_reconciliation_failed", {+ subjectKind: input.subject.kind,+ phase: "copy_current",+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ }++ for (const candidate of new Set(input.candidates)) {+ try {+ await cleanupAvatarCandidate(db, bucket, input.subject, candidate)+ } catch (error) {+ log.warn("community_avatar_child_cleanup_failed", {+ subjectKind: input.subject.kind,+ phase: "exact_candidate",+ errorCategory: communityMediaCleanupErrorCategory(error),+ })+ }+ }+}++export function scheduleAvatarMediaReconciliation(+ db: Database,+ bucket: AvatarBucket,+ input: { subject: AvatarSubject; candidates: Array<string | null | undefined> },+): Promise<void> {+ const work = reconcileAvatarMedia(db, bucket, input)+ try {+ getCloudflareContext().ctx.waitUntil(work)+ } catch {+ // Tests and non-Workers runtimes may not expose an execution context.+ }+ return work+}diff --git a/src/web/src/lib/community/bot-avatar-persistence.test.ts b/src/web/src/lib/community/bot-avatar-persistence.test.tsindex 20b094dd9..98f01bac8 100644--- a/src/web/src/lib/community/bot-avatar-persistence.test.ts+++ b/src/web/src/lib/community/bot-avatar-persistence.test.ts@@ -1,8 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest"-const mockUpdateBot = vi.fn()-const mockGetLiveBotAvatar = vi.fn()-const mockWarn = vi.fn()+const publishOwnedBotAvatar = vi.fn()+const getLiveBotAvatar = vi.fn()+const warn = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -10,7 +10,7 @@ vi.mock("@alook/shared", async () => {...actual,createLogger: () => ({info: vi.fn(),- warn: (...args: unknown[]) => mockWarn(...args),+ warn: (...args: unknown[]) => warn(...args),error: vi.fn(),debug: vi.fn(),}),@@ -18,8 +18,8 @@ vi.mock("@alook/shared", async () => {...actual.queries,communityBot: {...actual.queries.communityBot,- updateBot: (...args: unknown[]) => mockUpdateBot(...args),- getLiveBotAvatar: (...args: unknown[]) => mockGetLiveBotAvatar(...args),+ publishOwnedBotAvatar: (...args: unknown[]) => publishOwnedBotAvatar(...args),+ getLiveBotAvatar: (...args: unknown[]) => getLiveBotAvatar(...args),},},}@@ -28,140 +28,112 @@ vi.mock("@alook/shared", async () => {import { persistUploadedBotAvatar } from "./bot-avatar-persistence"const db = {} as never+const objectKey = "bot-avatar/b1/objects/new-object"-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 }, {+function persist(remove = vi.fn()) {+ return {+ remove,+ result: persistUploadedBotAvatar(db, { delete: remove }, {botId: "b1",ownerId: "u1",- })).resolves.toEqual({ kind: "persisted" })+ objectKey,+ }),+ }+}- expect(mockUpdateBot).toHaveBeenCalledWith(db, "b1", "u1", {- image: "/api/community/bots/b1/avatar",+describe("persistUploadedBotAvatar", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns the atomic publication version and displaced pointer", async () => {+ publishOwnedBotAvatar.mockResolvedValue({+ previous: { avatarVersion: 4, avatarObjectKey: "bot-avatar/b1/objects/old" },+ current: { avatarVersion: 5, avatarObjectKey: objectKey },+ })+ const { result, remove } = persist()++ await expect(result).resolves.toEqual({+ kind: "persisted",+ avatarVersion: 5,+ avatarObjectKey: objectKey,+ previousObjectKey: "bot-avatar/b1/objects/old",+ })+ expect(publishOwnedBotAvatar).toHaveBeenCalledWith(db, "b1", "u1", {+ objectKey,+ stableUrl: "/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)+ it("deletes only the uploaded owned child when publication loses to delete", async () => {+ publishOwnedBotAvatar.mockResolvedValue(null)+ getLiveBotAvatar.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()+ await expect(persist(remove).result).resolves.toEqual({ kind: "not_found" })+ expect(remove).toHaveBeenCalledWith(objectKey)})- 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"))+ it("retains a zero-row candidate when the authoritative reread fails", async () => {+ publishOwnedBotAvatar.mockResolvedValue(null)+ getLiveBotAvatar.mockRejectedValue(new TypeError("secret key"))+ const { result, remove } = persist()- 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",+ await expect(result).resolves.toEqual({ kind: "not_found" })+ expect(remove).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith("community_bot_avatar_cleanup_unverified", {+ phase: "zero_row",+ objectState: "retained_unverified",})- expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("secret")- expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("bot-avatar/b1")+ expect(JSON.stringify(warn.mock.calls)).not.toContain("secret")})- it("retains after a thrown update verifies a live canonical row", async () => {- mockUpdateBot.mockRejectedValue(new Error("ambiguous commit"))- mockGetLiveBotAvatar.mockResolvedValue({+ it("recognizes an unknown commit when D1 now points at the uploaded child", async () => {+ publishOwnedBotAvatar.mockRejectedValue(new Error("ambiguous commit"))+ getLiveBotAvatar.mockResolvedValue({id: "b1",image: "/api/community/bots/b1/avatar",+ avatarVersion: 7,+ avatarObjectKey: objectKey,})- const remove = vi.fn()+ const { result, remove } = persist()- 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",+ await expect(result).resolves.toEqual({+ kind: "persisted",+ avatarVersion: 7,+ avatarObjectKey: objectKey,+ previousObjectKey: null,})+ expect(remove).not.toHaveBeenCalled()})- 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("cleans an unknown noncurrent candidate only after a second authoritative reread", async () => {+ publishOwnedBotAvatar.mockRejectedValue(new Error("ambiguous commit"))+ getLiveBotAvatar.mockResolvedValue({+ id: "b1",+ image: "/api/community/bots/b1/avatar",+ avatarVersion: 8,+ avatarObjectKey: "bot-avatar/b1/objects/newer",})- })+ const remove = vi.fn().mockResolvedValue(undefined)- 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(persist(remove).result).resolves.toEqual({ kind: "failed" })+ expect(getLiveBotAvatar).toHaveBeenCalledTimes(2)+ expect(remove).toHaveBeenCalledWith(objectKey)+ })- await expect(persistUploadedBotAvatar(db, { delete: remove }, {- botId: "b1",- ownerId: "u1",- })).resolves.toEqual({ kind: "failed" })+ it("never deletes unverified bytes after an unknown commit", async () => {+ publishOwnedBotAvatar.mockRejectedValue(new Error("persist secret"))+ getLiveBotAvatar.mockRejectedValue(new TypeError("verify secret"))+ const { result, remove } = persist()+ await expect(result).resolves.toEqual({ kind: "failed" })expect(remove).not.toHaveBeenCalled()- expect(mockWarn).toHaveBeenCalledWith("community_bot_avatar_persist_verification_failed", {- botId: "b1",- phase: "d1_error_verification",+ expect(warn).toHaveBeenCalledWith("community_bot_avatar_persist_verification_failed", {+ phase: "unknown_commit",objectState: "retained_unverified",persistErrorCategory: "Error",verificationErrorCategory: "TypeError",})- expect(JSON.stringify(mockWarn.mock.calls)).not.toContain("secret")+ expect(JSON.stringify(warn.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.tsindex 1a8650d74..2fb160bad 100644--- a/src/web/src/lib/community/bot-avatar-persistence.ts+++ b/src/web/src/lib/community/bot-avatar-persistence.ts@@ -1,97 +1,91 @@import { createLogger, queries, type Database } from "@alook/shared"-import {- communityMediaCleanupErrorCategory,- deleteCommunityMediaObjects,-} from "./community-media-cleanup"-import { buildBotAvatarKey, botAvatarUrl } from "./storage"+import { communityMediaCleanupErrorCategory } from "./community-media-cleanup"+import { cleanupAvatarCandidate } from "./avatar-media-reconciliation"+import { botAvatarUrl } from "./storage"const log = createLogger({ service: "community-bot-avatar" })export type BotAvatarPersistenceOutcome =- | { kind: "persisted" }+ | {+ kind: "persisted"+ avatarVersion: number+ avatarObjectKey: string+ previousObjectKey: string | null+ }| { kind: "not_found" }| { kind: "failed" }-async function compensateBotAvatar(+async function compensateCandidate(+ db: Database,bucket: Pick<R2Bucket, "delete">,botId: string,- phase: "zero_row_delete_winner" | "d1_error_tombstoned",+ objectKey: string,+ phase: "zero_row" | "unknown_noncurrent",): Promise<void> {try {- await deleteCommunityMediaObjects(bucket, [buildBotAvatarKey(botId)])+ const outcome = await cleanupAvatarCandidate(+ db,+ bucket,+ { kind: "bot", id: botId },+ objectKey,+ )+ if (outcome === "retained_unverified") {+ log.warn("community_bot_avatar_cleanup_unverified", {+ phase,+ objectState: outcome,+ })+ }} 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 },+ input: { botId: string; ownerId: string; objectKey: string },): Promise<BotAvatarPersistenceOutcome> {- const url = botAvatarUrl(input.botId)-try {- const updated = await queries.communityBot.updateBot(+ const published = await queries.communityBot.publishOwnedBotAvatar(db,input.botId,input.ownerId,- { image: url },+ { objectKey: input.objectKey, stableUrl: botAvatarUrl(input.botId) },)- if (updated) return { kind: "persisted" }+ if (published) {+ return {+ kind: "persisted",+ avatarVersion: published.current.avatarVersion,+ avatarObjectKey: input.objectKey,+ previousObjectKey: published.previous.avatarObjectKey,+ }+ }} catch (error) {- let live: { id: string; image: string | null } | nulltry {- live = await queries.communityBot.getLiveBotAvatar(db, input.botId)+ const current = await queries.communityBot.getLiveBotAvatar(db, input.botId)+ if (current?.avatarObjectKey === input.objectKey && current.avatarVersion > 0) {+ return {+ kind: "persisted",+ avatarVersion: current.avatarVersion,+ avatarObjectKey: input.objectKey,+ previousObjectKey: null,+ }+ }+ await compensateCandidate(db, bucket, input.botId, input.objectKey, "unknown_noncurrent")} catch (verificationError) {log.warn("community_bot_avatar_persist_verification_failed", {- botId: input.botId,- phase: "d1_error_verification",+ phase: "unknown_commit",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")+ await compensateCandidate(db, bucket, input.botId, input.objectKey, "zero_row")return { kind: "not_found" }}diff --git a/src/web/src/lib/community/dm-cache.ts b/src/web/src/lib/community/dm-cache.tsindex 147dd437b..3e8eb3757 100644--- a/src/web/src/lib/community/dm-cache.ts+++ b/src/web/src/lib/community/dm-cache.ts@@ -10,6 +10,7 @@ export function dmSummaryFromInbox(unread: UnreadDm): DM {name: unread.otherUserName,discriminator: unread.otherUserDiscriminator,avatar: unread.otherUserAvatar,+ avatarVersion: unread.otherUserAvatarVersion,status: "offline",preview: "",unread: false,diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.tsindex de4c67249..e13bc9385 100644--- a/src/web/src/lib/community/enrich-messages.test.ts+++ b/src/web/src/lib/community/enrich-messages.test.ts@@ -5,6 +5,11 @@ const mocks = vi.hoisted(() => ({listReactions: vi.fn(),getReplies: vi.fn(),listChildren: vi.fn(),+ listForumChildren: vi.fn(),+ listTags: vi.fn(),+ getFirstMessages: vi.fn(),+ listParticipants: vi.fn(),+ hydrateApprovals: vi.fn(),getLatestSeq: vi.fn(),}))@@ -27,10 +32,24 @@ vi.mock("@alook/shared", async () => {...actual.queries.communityMessage,getMessagesByIdsInScope: (...args: unknown[]) => mocks.getReplies(...args),getLatestMessageSeq: (...args: unknown[]) => mocks.getLatestSeq(...args),+ getFirstMessageByChannelIds: (...args: unknown[]) => mocks.getFirstMessages(...args),},communityChannel: {...actual.queries.communityChannel,listChildChannels: (...args: unknown[]) => mocks.listChildren(...args),+ listChildChannelsByParentMessageIds: (...args: unknown[]) => mocks.listForumChildren(...args),+ },+ communityMessageTag: {+ ...actual.queries.communityMessageTag,+ listTagsForMessages: (...args: unknown[]) => mocks.listTags(...args),+ },+ communityThread: {+ ...actual.queries.communityThread,+ listParticipantsForChannels: (...args: unknown[]) => mocks.listParticipants(...args),+ },+ communityFriendship: {+ ...actual.queries.communityFriendship,+ hydrateApprovalsForDmMessages: (...args: unknown[]) => mocks.hydrateApprovals(...args),},},}@@ -43,6 +62,11 @@ describe("enrichMessages attachment projection", () => {vi.clearAllMocks()mocks.listReactions.mockResolvedValue([])mocks.listChildren.mockResolvedValue([])+ mocks.listForumChildren.mockResolvedValue([])+ mocks.listTags.mockResolvedValue([])+ mocks.getFirstMessages.mockResolvedValue([])+ mocks.listParticipants.mockResolvedValue([])+ mocks.hydrateApprovals.mockResolvedValue(new Map())mocks.getLatestSeq.mockResolvedValue(9)})@@ -102,4 +126,115 @@ describe("enrichMessages attachment projection", () => {}),])})++ it("projects canonical versioned avatars for forum thread participants", async () => {+ mocks.listAttachments.mockResolvedValue([])+ mocks.getReplies.mockResolvedValue([])+ mocks.listForumChildren.mockResolvedValue([{+ id: "thread-1",+ parentMessageId: "m1",+ name: "Topic",+ messageCount: 2,+ lastMessageAt: "2026-08-13T01:00:00.000Z",+ createdAt: "2026-08-13T00:00:00.000Z",+ }])+ mocks.getFirstMessages.mockResolvedValue([{+ channelId: "thread-1",+ content: "Opening preview",+ }])+ mocks.listParticipants.mockResolvedValue([{+ channelId: "thread-1",+ userId: "u2",+ userName: "Bob",+ userImage: "/api/community/users/u2/avatar",+ userAvatarVersion: 4,+ participantCount: 1,+ }])++ const result = await enrichMessages(+ {} as never,+ "u1",+ { channelId: "forum-1", isForum: true },+ [{+ id: "m1",+ seq: 9,+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ authorAvatarVersion: 0,+ content: "topic",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ createdAt: "2026-08-13T00:00:00.000Z",+ channelId: "forum-1",+ }],+ )++ expect(result.messages[0]).toMatchObject({+ thread: {+ id: "thread-1",+ participants: [{+ id: "u2",+ avatar: "/api/community/users/u2/avatar?v=4",+ avatarVersion: 4,+ }],+ participantCount: 1,+ },+ })+ })++ it("falls back to initials for forum participants without an avatar", async () => {+ mocks.listAttachments.mockResolvedValue([])+ mocks.getReplies.mockResolvedValue([])+ mocks.listForumChildren.mockResolvedValue([{+ id: "thread-1",+ parentMessageId: "m1",+ name: "Topic",+ messageCount: 1,+ lastMessageAt: null,+ createdAt: "2026-08-13T00:00:00.000Z",+ }])+ mocks.getFirstMessages.mockResolvedValue([])+ mocks.listParticipants.mockResolvedValue([{+ channelId: "thread-1",+ userId: "u2",+ userName: "Bob",+ userImage: null,+ userAvatarVersion: 0,+ participantCount: 1,+ }])++ const result = await enrichMessages(+ {} as never,+ "u1",+ { channelId: "forum-1", isForum: true },+ [{+ id: "m1",+ seq: 9,+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ authorAvatarVersion: 0,+ content: "topic",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ createdAt: "2026-08-13T00:00:00.000Z",+ channelId: "forum-1",+ }],+ )++ expect(result.messages[0]).toMatchObject({+ thread: {+ participants: [{+ id: "u2",+ avatar: "B",+ avatarVersion: 0,+ }],+ },+ })+ })})diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsindex 47ef1f91f..0211bb4ea 100644--- a/src/web/src/lib/community/enrich-messages.ts+++ b/src/web/src/lib/community/enrich-messages.ts@@ -3,6 +3,7 @@ import type { getDb } from "@/lib/db"import { groupAttachments, groupReactions } from "@/lib/community/messages"import { mapMessageForApi } from "@/lib/community/message-payload"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"// Message enrichment shared by the channel messages route, the channel// bootstrap route, and the DM messages route (previously three near-identical@@ -72,7 +73,12 @@ export async function enrichMessages(tagsByMessage.set(row.messageId, [...(tagsByMessage.get(row.messageId) ?? []), row.tag])}const firstByChannel = new Map(forumFirstMessages.map((message) => [message.channelId, message]))- const participantsByChannel = new Map<string, Array<{ id: string; name: string; avatar: string }>>()+ const participantsByChannel = new Map<string, Array<{+ id: string+ name: string+ avatar: string+ avatarVersion: number+ }>>()const participantCountByChannel = new Map<string, number>()for (const row of forumParticipants) {participantCountByChannel.set(@@ -84,7 +90,9 @@ export async function enrichMessages({id: row.userId,name: row.userName ?? "",- avatar: row.userImage ?? avatarInitial(row.userName ?? ""),+ avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)+ ?? avatarInitial(row.userName ?? ""),+ avatarVersion: row.userAvatarVersion,},])}diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 06884372f..2e67c5c24 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -43,6 +43,7 @@ vi.mock("@alook/shared", async () => {},communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),+ listDmPeerUserIds: (...a: unknown[]) => mockListDmPeerUserIds(...a),},communityFriendship: {getFriendUserIds: (...a: unknown[]) => mockGetFriendUserIds(...a),@@ -68,6 +69,7 @@ const mockGetChannel = vi.fn()const mockIsChannelPrivate = vi.fn(() => false)const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockGetDM = vi.fn()+const mockListDmPeerUserIds = vi.fn()const mockListChannelMemberUserIds = vi.fn()const mockGetCoMemberUserIds = vi.fn()const mockGetFriendUserIds = vi.fn()@@ -81,6 +83,7 @@ import {fanOutToChannel,fanOutToDM,fanOutStatusUpdate,+ fanOutIdentityUpdate,broadcastToUserSafe,} from "./fanout"import { WS_EVENTS } from "@alook/shared"@@ -283,6 +286,84 @@ describe("fanOutStatusUpdate", () => {})})+describe("fanOutIdentityUpdate", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCloudflareContext.mockImplementation(() => ({+ env: { DB: {} },+ ctx: { waitUntil: vi.fn() },+ }))+ mockBroadcastToUsers.mockResolvedValue(undefined)+ })++ it("broadcasts only to self plus the deduped co-member, friend, and DM audience", async () => {+ mockGetCoMemberUserIds.mockResolvedValue(["co-member", "shared"])+ mockGetFriendUserIds.mockResolvedValue(["friend", "shared"])+ mockListDmPeerUserIds.mockResolvedValue(["dm-peer", "friend"])++ await fanOutIdentityUpdate("self", "/api/community/users/self/avatar?v=5", 5)++ expect(mockBroadcastToUsers).toHaveBeenCalledWith(+ ["self", "co-member", "shared", "friend", "dm-peer"],+ {+ type: "community:identity.update",+ userId: "self",+ avatar: "/api/community/users/self/avatar?v=5",+ avatarVersion: 5,+ },+ )+ expect(mockBroadcastToUsers.mock.calls[0]![0]).not.toContain("stranger")+ })++ it("retains worker lifetime while recipient resolution is pending", async () => {+ const waitUntil = vi.fn()+ mockGetCloudflareContext.mockImplementation(() => ({+ env: { DB: {} },+ ctx: { waitUntil },+ }))+ let release!: (ids: string[]) => void+ mockGetCoMemberUserIds.mockReturnValue(new Promise((resolve) => { release = resolve }))+ mockGetFriendUserIds.mockResolvedValue([])+ mockListDmPeerUserIds.mockResolvedValue([])++ const work = fanOutIdentityUpdate("self", "/avatar?v=1", 1)+ expect(waitUntil).toHaveBeenCalledWith(work)+ release([])+ await work+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(+ ["self"],+ expect.objectContaining({ type: "community:identity.update" }),+ )+ })++ it("absorbs an asynchronous identity audience failure", async () => {+ mockGetCoMemberUserIds.mockRejectedValue("D1 unavailable")+ mockGetFriendUserIds.mockResolvedValue([])+ mockListDmPeerUserIds.mockResolvedValue([])++ await expect(fanOutIdentityUpdate("self", "/avatar?v=1", 1)).resolves.toBeUndefined()++ expect(mockWarn).toHaveBeenCalledWith(+ "fanout_identity_update_failed",+ { subjectId: "self", errorCategory: "NonError" },+ )+ expect(mockBroadcastToUsers).not.toHaveBeenCalled()+ })++ it("absorbs a synchronous identity fanout setup failure", async () => {+ mockGetCloudflareContext.mockImplementation(() => {+ throw new Error("no worker context")+ })++ await expect(fanOutIdentityUpdate("self", "/avatar?v=1", 1)).resolves.toBeUndefined()++ expect(mockWarn).toHaveBeenCalledWith(+ "fanout_identity_update_failed",+ { subjectId: "self", errorCategory: "Error" },+ )+ })+})+describe("fanout helpers absorb setup failures", () => {beforeEach(() => {vi.clearAllMocks()diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 1887b9814..8c53882db 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -158,6 +158,50 @@ async function getProfileAudience(db: Database, userId: string): Promise<string[return [...new Set([...coMembers, ...friends])]}+async function getIdentityAudience(db: Database, userId: string): Promise<string[]> {+ const [coMembers, friends, dmPeers] = await Promise.all([+ queries.communityMember.getCoMemberUserIds(db, userId),+ queries.communityFriendship.getFriendUserIds(db, userId),+ queries.communityDm.listDmPeerUserIds(db, userId),+ ])+ return [...new Set([userId, ...coMembers, ...friends, ...dmPeers])]+}++export function fanOutIdentityUpdate(+ userId: string,+ avatar: string,+ avatarVersion: number,+): Promise<void> {+ try {+ const { env, ctx } = getCloudflareContext()+ const db = getDb((env as Env).DB)+ const work = (async () => {+ try {+ const audience = await getIdentityAudience(db, userId)+ await broadcastToRecipients(audience, {+ type: WS_EVENTS.IDENTITY_UPDATE,+ userId,+ avatar,+ avatarVersion,+ })+ } catch (error) {+ log.warn("fanout_identity_update_failed", {+ subjectId: userId,+ errorCategory: error instanceof Error ? error.name : "NonError",+ })+ }+ })()+ try { ctx.waitUntil(work) } catch { }+ return work+ } catch (error) {+ log.warn("fanout_identity_update_failed", {+ subjectId: userId,+ errorCategory: error instanceof Error ? error.name : "NonError",+ })+ return Promise.resolve()+ }+}+/*** Fan out a status change to everyone who can currently see the user* (server co-members + friends). Self is intentionally excluded from theirdiff --git a/src/web/src/lib/community/identity-projection.test.ts b/src/web/src/lib/community/identity-projection.test.tsnew file mode 100644index 000000000..cfca30a8f--- /dev/null+++ b/src/web/src/lib/community/identity-projection.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { useCommunityWsStore } from "@/stores/community/ws"+import { projectIdentityPayload } from "./identity-projection"++beforeEach(() => {+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().bindIdentityOwner("viewer-a")+})++describe("projectIdentityPayload", () => {+ it("uses a two-pass observation so a newer row later in one payload upgrades every copy", () => {+ const untouched = { kind: "sentinel" }+ const payload = {+ rows: [+ { userId: "u1", avatar: "/avatar?v=2", avatarVersion: 2 },+ { userId: "u1", avatar: "/avatar?v=5", avatarVersion: 5 },+ ],+ untouched,+ }++ const projected = projectIdentityPayload(payload)++ expect(projected.rows).toEqual([+ { userId: "u1", avatar: "/avatar?v=5", avatarVersion: 5 },+ { userId: "u1", avatar: "/avatar?v=5", avatarVersion: 5 },+ ])+ expect(projected.untouched).toBe(untouched)+ expect(useCommunityWsStore.getState().avatarIdentities.get("u1"))+ .toEqual({ avatar: "/avatar?v=5", avatarVersion: 5 })+ })++ it("projects every supported nested identity slot without mutating the input", () => {+ useCommunityWsStore.getState().observeAvatarIdentity("author", "/author?v=7", 7)+ useCommunityWsStore.getState().observeAvatarIdentity("peer", "/peer?v=6", 6)+ useCommunityWsStore.getState().observeAvatarIdentity("creator", "/creator?v=5", 5)+ const payload = {+ message: {+ authorId: "author",+ authorAvatar: "/author?v=1",+ authorAvatarVersion: 1,+ },+ dm: {+ otherUserId: "peer",+ otherUserAvatar: "/peer?v=1",+ otherUserAvatarVersion: 1,+ },+ forum: {+ creatorId: "creator",+ creatorAvatar: "/creator?v=1",+ creatorAvatarVersion: 1,+ },+ }++ const projected = projectIdentityPayload(payload)++ expect(projected).not.toBe(payload)+ expect(projected.message).toMatchObject({ authorAvatar: "/author?v=7", authorAvatarVersion: 7 })+ expect(projected.dm).toMatchObject({ otherUserAvatar: "/peer?v=6", otherUserAvatarVersion: 6 })+ expect(projected.forum).toMatchObject({ creatorAvatar: "/creator?v=5", creatorAvatarVersion: 5 })+ expect(payload.message.authorAvatar).toBe("/author?v=1")+ })++ it("fences delayed stale HTTP and reports a same-version URL conflict", () => {+ projectIdentityPayload({ id: "u1", image: "/avatar?v=9", avatarVersion: 9 })+ const conflict = vi.fn()++ const stale = projectIdentityPayload(+ { id: "u1", image: "/avatar?v=4", avatarVersion: 4 },+ conflict,+ )+ expect(stale).toEqual({ id: "u1", image: "/avatar?v=9", avatarVersion: 9 })+ expect(conflict).not.toHaveBeenCalled()++ const divergent = projectIdentityPayload(+ { id: "u1", image: "/other?v=9", avatarVersion: 9 },+ conflict,+ )+ expect(divergent).toEqual({ id: "u1", image: "/avatar?v=9", avatarVersion: 9 })+ expect(conflict).toHaveBeenCalledWith("u1")+ })++ it("does not carry an identity fence across account changes", () => {+ projectIdentityPayload({ userId: "u1", avatar: "/avatar?v=8", avatarVersion: 8 })+ useCommunityWsStore.getState().bindIdentityOwner("viewer-b")++ const projected = projectIdentityPayload({+ userId: "u1",+ avatar: "/avatar?v=1",+ avatarVersion: 1,+ })++ expect(projected.avatar).toBe("/avatar?v=1")+ expect(useCommunityWsStore.getState().avatarIdentities.get("u1"))+ .toEqual({ avatar: "/avatar?v=1", avatarVersion: 1 })+ })+})diff --git a/src/web/src/lib/community/identity-projection.ts b/src/web/src/lib/community/identity-projection.tsnew file mode 100644index 000000000..de7e7b799--- /dev/null+++ b/src/web/src/lib/community/identity-projection.ts@@ -0,0 +1,144 @@+"use client"++import { apiFetch } from "@/lib/api/client"+import { useCommunityWsStore } from "@/stores/community/ws"++type IdentitySlot = Readonly<{+ userId: string+ avatar: string+ avatarVersion: string+}>++const EXPLICIT_IDENTITY_SLOTS: readonly IdentitySlot[] = [+ { userId: "authorId", avatar: "authorAvatar", avatarVersion: "authorAvatarVersion" },+ { userId: "otherUserId", avatar: "otherUserAvatar", avatarVersion: "otherUserAvatarVersion" },+ { userId: "creatorId", avatar: "creatorAvatar", avatarVersion: "creatorAvatarVersion" },+]++type IdentityObservation = Readonly<{+ slot: IdentitySlot+ userId: string+ avatar: string+ avatarVersion: number+}>++type IdentityConflictHandler = (userId: string) => void++function objectValue(value: unknown): Record<string, unknown> | undefined {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : undefined+}++function observationsFor(record: Record<string, unknown>): IdentityObservation[] {+ const slots = [...EXPLICIT_IDENTITY_SLOTS]+ if (typeof record.userId === "string") {+ slots.push({ userId: "userId", avatar: "avatar", avatarVersion: "avatarVersion" })+ slots.push({ userId: "userId", avatar: "image", avatarVersion: "avatarVersion" })+ } else {+ slots.push({ userId: "id", avatar: "avatar", avatarVersion: "avatarVersion" })+ slots.push({ userId: "id", avatar: "image", avatarVersion: "avatarVersion" })+ }++ return slots.flatMap((slot) => {+ const userId = record[slot.userId]+ const avatar = record[slot.avatar]+ const avatarVersion = record[slot.avatarVersion]+ return typeof userId === "string"+ && typeof avatar === "string"+ && typeof avatarVersion === "number"+ && Number.isSafeInteger(avatarVersion)+ && avatarVersion >= 0+ ? [{ slot, userId, avatar, avatarVersion }]+ : []+ })+}++function visitIdentityPayload(+ value: unknown,+ visit: (record: Record<string, unknown>, observations: IdentityObservation[]) => void,+): void {+ if (Array.isArray(value)) {+ for (const item of value) visitIdentityPayload(item, visit)+ return+ }+ const record = objectValue(value)+ if (!record) return+ const observations = observationsFor(record)+ if (observations.length > 0) visit(record, observations)+ for (const child of Object.values(record)) visitIdentityPayload(child, visit)+}++function projectValue(value: unknown, onConflict?: IdentityConflictHandler): unknown {+ if (Array.isArray(value)) {+ let changed = false+ const projected = value.map((item) => {+ const next = projectValue(item, onConflict)+ changed ||= next !== item+ return next+ })+ return changed ? projected : value+ }++ const record = objectValue(value)+ if (!record) return value+ let next: Record<string, unknown> | undefined+ const write = (key: string, fieldValue: unknown) => {+ next ??= { ...record }+ next[key] = fieldValue+ }++ for (const [key, child] of Object.entries(record)) {+ const projected = projectValue(child, onConflict)+ if (projected !== child) write(key, projected)+ }++ const identities = useCommunityWsStore.getState().avatarIdentities+ for (const observation of observationsFor(record)) {+ const current = identities.get(observation.userId)+ if (!current) continue+ if (current.avatarVersion === observation.avatarVersion) {+ if (current.avatar !== observation.avatar) onConflict?.(observation.userId)+ if (current.avatar === observation.avatar) continue+ }+ if (current.avatarVersion < observation.avatarVersion) continue+ write(observation.slot.avatar, current.avatar)+ write(observation.slot.avatarVersion, current.avatarVersion)+ }+ return next ?? value+}++/**+ * Register every identity carried by an authoritative HTTP payload, then+ * overlay the account-bound highest version over older nested projections.+ * The two-pass order prevents an old row earlier in the response from+ * overwriting a newer row later in the same response.+ */+export function projectIdentityPayload<T>(+ value: T,+ onConflict?: IdentityConflictHandler,+): T {+ const store = useCommunityWsStore.getState()+ visitIdentityPayload(value, (_record, observations) => {+ for (const observation of observations) {+ const result = store.observeAvatarIdentity(+ observation.userId,+ observation.avatar,+ observation.avatarVersion,+ )+ if (result === "conflict") onConflict?.(observation.userId)+ }+ })+ return projectValue(value, onConflict) as T+}++export async function apiFetchIdentity<T>(+ path: string,+ options?: RequestInit,+): Promise<T> {+ return projectIdentityPayload(+ options === undefined+ ? await apiFetch<T>(path)+ : await apiFetch<T>(path, options),+ )+}diff --git a/src/web/src/lib/community/member-payload.ts b/src/web/src/lib/community/member-payload.tsindex 857b49e32..db84bd364 100644--- a/src/web/src/lib/community/member-payload.ts+++ b/src/web/src/lib/community/member-payload.ts@@ -1,4 +1,5 @@import { avatarInitial } from "./avatar"+import { canonicalUserImage } from "./storage"// Canonical row shape the member-list queries produce. Bot columns// (`userIsBot`/`userOwnerUserId`) are optional — `searchMembers` doesn't select@@ -9,6 +10,7 @@ export type MemberRow = {role: string | nulluserName: string | nulluserImage: string | null+ userAvatarVersion: numberdiscriminator: string | nullstatusEmoji: string | nullstatusText: string | null@@ -22,6 +24,7 @@ export type MappedMember = {name: stringdiscriminator: string | undefinedavatar: string+ avatarVersion: numberstatus: "online" | "offline"sub: stringrole: string@@ -57,7 +60,9 @@ export function mapMemberForApi(userId: row.userId,name: display,discriminator: row.discriminator ?? undefined,- avatar: row.userImage ?? avatarInitial(display),+ avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)+ ?? avatarInitial(display),+ avatarVersion: row.userAvatarVersion,status: row.userId === viewerUserId ? "online" : "offline",sub: "",role: row.role ?? "member",diff --git a/src/web/src/lib/community/message-delivery-transport.test.ts b/src/web/src/lib/community/message-delivery-transport.test.tsindex 38d526535..6a381a228 100644--- a/src/web/src/lib/community/message-delivery-transport.test.ts+++ b/src/web/src/lib/community/message-delivery-transport.test.ts@@ -57,6 +57,7 @@ function batch(overrides: Partial<MessageDeliveryBatch> = {}): MessageDeliveryBaseq: 4,authorId: "u1",authorName: "Alice",+ authorAvatarVersion: 0,content: "hello",type: "chat",createdAt: "2026-08-18T00:00:00.000Z",diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex 7f4ab7d80..94012cbed 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -17,6 +17,7 @@import { truncateMessagePreview, type MentionType } from "@alook/shared"import type { FriendApprovalPayload } from "@alook/shared"import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"// The subset of fields on rows returned by// queries.communityMessage.{listMessages, getMessage, getMessagesByIds} that@@ -30,6 +31,7 @@ export type MessageRow = {authorId: stringauthorName: stringauthorImage: string | null+ authorAvatarVersion: numbercontent: string | nulltype: string | nullmentionType: string | null@@ -57,7 +59,7 @@ type ThreadPreview = {lastReplyAt?: stringtags?: string[]preview?: string- participants?: { id: string; name: string; avatar: string }[]+ participants?: { id: string; name: string; avatar: string; avatarVersion: number }[]participantCount?: number}@@ -67,7 +69,9 @@ function coreFields(row: MessageRow) {id: row.id,authorId: row.authorId,authorName: row.authorName,- authorAvatar: row.authorImage ?? avatarInitial(row.authorName),+ authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion)+ ?? avatarInitial(row.authorName),+ authorAvatarVersion: row.authorAvatarVersion,// `content` is nullable in the DB (empty message with attachments) but// both the API response and the WS payload treat it as string; coerce// once here so downstream consumers don't have to null-check.diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex a786b73b1..6bda8a1d4 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -77,6 +77,69 @@ function ack(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): Messa}describe("message stream monotonic visibility", () => {+ it("projects a newer avatar through live, participant, and optimistic rows without rollback", () => {+ const thread = {+ id: "thread-1",+ name: "Thread",+ messageCount: 1,+ participants: [+ { id: "u1", name: "Gus", avatar: "/avatar?v=1", avatarVersion: 1 },+ { id: "u2", name: "Peer", avatar: "/peer?v=7", avatarVersion: 7 },+ ],+ }+ let state = submit(emptyMessageOverlay(), intent("avatar", 1, {+ message: {+ ...localMessage("optimistic"),+ authorAvatar: "/avatar?v=1",+ authorAvatarVersion: 1,+ thread,+ },+ }))+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m-avatar", 20, "live-avatar", {+ authorId: "u2",+ authorAvatar: "/peer?v=7",+ authorAvatarVersion: 7,+ thread,+ }),+ }).state++ const projected = apply(state, {+ type: "identityUpdated",+ userId: "u1",+ avatar: "/avatar?v=2",+ avatarVersion: 2,+ }).state++ expect(projected.outboxByNonce.get("avatar")?.message).toMatchObject({+ authorAvatar: "/avatar?v=2",+ authorAvatarVersion: 2,+ thread: {+ participants: [+ { id: "u1", avatar: "/avatar?v=2", avatarVersion: 2 },+ { id: "u2", avatar: "/peer?v=7", avatarVersion: 7 },+ ],+ },+ })+ expect(projected.liveById.get("m-avatar")).toMatchObject({+ authorAvatar: "/peer?v=7",+ authorAvatarVersion: 7,+ })+ expect(projected.liveById.get("m-avatar")?.thread?.participants?.[0]).toMatchObject({+ id: "u1",+ avatar: "/avatar?v=2",+ avatarVersion: 2,+ })++ expect(apply(projected, {+ type: "identityUpdated",+ userId: "u1",+ avatar: "/avatar?v=1",+ avatarVersion: 1,+ }).state).toBe(projected)+ })+it("removes a canonical live row after a post-unit delete", () => {let state = apply(emptyMessageOverlay(), {type: "wsMessage",diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsindex e4412549c..375cf7739 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -73,6 +73,7 @@ export type MessageOverlayEvent =| { type: "liveRefreshed"; message: CanonicalMessage }| { type: "messageEdited"; messageId: string; content: string }| { type: "messageRemoved"; messageId: string }+ | { type: "identityUpdated"; userId: string; avatar: string; avatarVersion: number }| { type: "baseChanged"; messages: CanonicalMessage[]; latestSeq?: number }| { type: "dismissFailed"; nonce: string }| { type: "clear" }@@ -118,6 +119,38 @@ function canonicalDeltaOrder(a: CanonicalMessage, b: CanonicalMessage): number {return a.seq - b.seq}+function projectMessageAvatar<T extends Msg>(+ message: T,+ userId: string,+ avatar: string,+ avatarVersion: number,+): T {+ let next: Msg | undefined+ if (+ message.authorId === userId+ && (message.authorAvatarVersion ?? 0) < avatarVersion+ ) {+ next = { ...message, authorAvatar: avatar, authorAvatarVersion: avatarVersion }+ }+ const participants = message.thread?.participants+ if (participants?.some(+ (participant) => participant.id === userId && participant.avatarVersion < avatarVersion,+ )) {+ const current = next ?? message+ next = {+ ...current,+ thread: {+ ...current.thread!,+ participants: participants.map((participant) =>+ participant.id === userId && participant.avatarVersion < avatarVersion+ ? { ...participant, avatar, avatarVersion }+ : participant),+ },+ }+ }+ return (next ?? message) as T+}+function compoundIdentity(message: Pick<Msg, "authorId" | "clientNonce">,): string | undefined {@@ -471,6 +504,37 @@ export function reduceMessageOverlay(: unchanged(state)}+ case "identityUpdated": {+ let changed = false+ const liveById = new Map(state.liveById)+ for (const [id, message] of liveById) {+ const projected = projectMessageAvatar(+ message,+ event.userId,+ event.avatar,+ event.avatarVersion,+ )+ if (projected === message) continue+ liveById.set(id, projected)+ changed = true+ }+ const outboxByNonce = new Map(state.outboxByNonce)+ for (const [nonce, intent] of outboxByNonce) {+ const message = projectMessageAvatar(+ intent.message,+ event.userId,+ event.avatar,+ event.avatarVersion,+ )+ if (message === intent.message) continue+ outboxByNonce.set(nonce, { ...intent, message })+ changed = true+ }+ return changed+ ? { state: { liveById, outboxByNonce }, effects: [] }+ : unchanged(state)+ }+case "baseChanged": {const baseById = new Map(event.messages.map((message) => [message.id, message]))const baseByIdentity = new Map(diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.tsindex 8cf3fba6d..9a8a352e0 100644--- a/src/web/src/lib/community/message-wire.test.ts+++ b/src/web/src/lib/community/message-wire.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest"import type { CommunityMessageCreate } from "@alook/shared"-import { projectCommunityMessageCreate } from "./message-wire"+import { projectCommunityMessageCreate, projectPostedMessage } from "./message-wire"function wire(overrides: Partial<CommunityMessageCreate["message"]> = {},@@ -68,3 +68,26 @@ describe("projectCommunityMessageCreate", () => {])})})++describe("projectPostedMessage", () => {+ it("falls back to an initial when the posted author has no canonical avatar", () => {+ const projected = projectPostedMessage({+ id: "m2",+ seq: 43,+ authorId: "u2",+ authorName: "Gus",+ authorImage: null,+ authorAvatarVersion: 0,+ content: "hello",+ type: "default",+ embeds: null,+ createdAt: "2026-08-06T00:00:00.000Z",+ } as never, "nonce-2")++ expect(projected).toMatchObject({+ authorAvatar: "G",+ authorAvatarVersion: 0,+ clientNonce: "nonce-2",+ })+ })+})diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.tsindex abda4a507..0ca186522 100644--- a/src/web/src/lib/community/message-wire.ts+++ b/src/web/src/lib/community/message-wire.ts@@ -4,6 +4,7 @@ import { avatarInitial } from "@/lib/community/avatar"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"import { formatAttachmentSize } from "@/lib/community/attachment-presentation"import type { CanonicalMessage } from "@/lib/community/message-stream"+import { canonicalUserImage } from "@/lib/community/storage"type UiEmbed = NonNullable<Msg["embeds"]>[number]@@ -15,6 +16,7 @@ export type PostedMessage = {authorId: stringauthorName: stringauthorImage: string | null+ authorAvatarVersion: numbertype: string | nullembeds: unknown}@@ -126,6 +128,7 @@ export function projectCommunityMessageCreate(authorId: message.authorId,authorName: message.authorName,authorAvatar: message.authorAvatar || avatarInitial(message.authorName),+ authorAvatarVersion: message.authorAvatarVersion,content: message.content,createdAt: message.createdAt,...(message.clientNonce ? { clientNonce: message.clientNonce } : {}),@@ -157,7 +160,12 @@ export function projectPostedMessage(...type,authorId: message.authorId,authorName: message.authorName,- authorAvatar: message.authorImage || avatarInitial(message.authorName),+ authorAvatar: canonicalUserImage(+ message.authorId,+ message.authorImage,+ message.authorAvatarVersion,+ ) || avatarInitial(message.authorName),+ authorAvatarVersion: message.authorAvatarVersion,content: message.content ?? "",createdAt: message.createdAt,clientNonce,diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.tsindex bf675f8dc..139bc93db 100644--- a/src/web/src/lib/community/models/inbox.ts+++ b/src/web/src/lib/community/models/inbox.ts@@ -87,5 +87,6 @@ export type UnreadDm = {otherUserName: stringotherUserDiscriminator: stringotherUserAvatar: string+ otherUserAvatarVersion: numberlastMessageAt: string}diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex 9565fa2d8..aa53fdcc6 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -60,6 +60,7 @@ export type Msg = {seq?: number // Per-scope (channel/DM) monotonic sequence numbercreatedAt?: string // ISO 8601 timestamp — the UI formats for displayauthorAvatar?: string+ authorAvatarVersion?: numberfailed?: boolean// Idempotency nonce (mutation-idempotency plan). Stamped on optimistic rows// this client created and echoed back on the WS message-create, so a@@ -78,7 +79,7 @@ export type Msg = {lastReplyAt?: stringtags?: string[]preview?: string- participants?: { id: string; name: string; avatar: string }[]+ participants?: { id: string; name: string; avatar: string; avatarVersion: number }[]participantCount?: number}// Present only on a friend-approval DM card. Its presence (not the message@@ -115,6 +116,7 @@ export type Thread = {export type ForumThread = Thread & {authorId: stringauthorAvatar: string+ authorAvatarVersion: numberopenerMessageId: stringopenerCreatedAt?: stringtags: string[]@@ -123,7 +125,7 @@ export type ForumThread = Thread & {// spoke/was mentioned/was added. Drives the card's AvatarGroup. Always// present (empty for a post with no participant rows yet, e.g. one created// before the notify-scope change shipped).- participants: { id: string; name: string; avatar: string }[]+ participants: { id: string; name: string; avatar: string; avatarVersion: number }[]// Total participant rows before the card-preview cap is applied.participantCount: number}diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.tsindex 06e4e7327..71bec392c 100644--- a/src/web/src/lib/community/models/people.ts+++ b/src/web/src/lib/community/models/people.ts@@ -14,6 +14,7 @@ export type CommunityUserCore = {name: stringdiscriminator: stringavatar: string+ avatarVersion: number}export type Member = CommunityUserCore & {@@ -52,13 +53,20 @@ export type PendingRequest = {userId: stringname: stringavatar: string+ avatarVersion: numberkind: "incoming" | "outgoing"// The gating owner id while a bot-touched row is pending; null once// unlocked. Drives whether Approve/Reject buttons render.needsOwnerApproval?: string | null}-export type BlockedUser = { id: string; userId?: string; name: string; avatar: string }+export type BlockedUser = {+ id: string+ userId?: string+ name: string+ avatar: string+ avatarVersion: number+}// DM summary shown in the DM sidebar. Actual conversation history is loaded// into `ctx.messages` once the user opens the DM — DM summaries don't carrydiff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.tsindex 1f62e1024..c8d875292 100644--- a/src/web/src/lib/community/storage.test.ts+++ b/src/web/src/lib/community/storage.test.ts@@ -2,7 +2,9 @@ import { describe, it, expect } from "vitest"import {buildMediaKey,buildUserAvatarKey,+ buildUserAvatarObjectKey,buildBotAvatarKey,+ buildBotAvatarObjectKey,attachmentUrl,attachmentThumbnailUrl,buildAttachmentThumbnailKey,@@ -11,6 +13,9 @@ import {userAvatarUrl,botAvatarUrl,isOwnedServerIconKey,+ isOwnedUserAvatarObjectKey,+ isOwnedBotAvatarObjectKey,+ canonicalUserImage,} from "./storage"describe("buildUserAvatarKey", () => {@@ -23,6 +28,16 @@ describe("buildUserAvatarKey", () => {})})+describe("user avatar object ownership", () => {+ it("separates the fixed alias from one owned immutable child", () => {+ expect(buildUserAvatarObjectKey("u1", "v1")).toBe("user-avatar/u1/objects/v1")+ expect(isOwnedUserAvatarObjectKey("user-avatar/u1/objects/v1", "u1")).toBe(true)+ expect(isOwnedUserAvatarObjectKey(buildUserAvatarKey("u1"), "u1")).toBe(false)+ expect(isOwnedUserAvatarObjectKey("user-avatar/u2/objects/v1", "u1")).toBe(false)+ expect(isOwnedUserAvatarObjectKey("user-avatar/u1/objects/nested/v1", "u1")).toBe(false)+ })+})+describe("buildBotAvatarKey", () => {it("is deterministic (no randomness)", () => {expect(buildBotAvatarKey("b1")).toBe(buildBotAvatarKey("b1"))@@ -33,15 +48,36 @@ describe("buildBotAvatarKey", () => {})})+describe("bot avatar object ownership", () => {+ it("separates the fixed alias from one owned immutable child", () => {+ expect(buildBotAvatarObjectKey("b1", "v1")).toBe("bot-avatar/b1/objects/v1")+ expect(isOwnedBotAvatarObjectKey("bot-avatar/b1/objects/v1", "b1")).toBe(true)+ expect(isOwnedBotAvatarObjectKey(buildBotAvatarKey("b1"), "b1")).toBe(false)+ expect(isOwnedBotAvatarObjectKey("bot-avatar/b2/objects/v1", "b1")).toBe(false)+ })+})+describe("userAvatarUrl", () => {it("has the correct format", () => {expect(userAvatarUrl("u1")).toBe("/api/community/users/u1/avatar")+ expect(userAvatarUrl("u1", 2)).toBe("/api/community/users/u1/avatar?v=2")})})describe("botAvatarUrl", () => {it("has the correct format", () => {expect(botAvatarUrl("b1")).toBe("/api/community/bots/b1/avatar")+ expect(botAvatarUrl("b1", 3)).toBe("/api/community/bots/b1/avatar?v=3")+ })+})++describe("canonicalUserImage", () => {+ it("versions owned avatar routes and leaves external images unchanged", () => {+ expect(canonicalUserImage("u1", userAvatarUrl("u1"), 4)).toBe(userAvatarUrl("u1", 4))+ expect(canonicalUserImage("b1", botAvatarUrl("b1"), 5)).toBe(botAvatarUrl("b1", 5))+ expect(canonicalUserImage("u1", "https://cdn.example/avatar.png", 6)).toBe(+ "https://cdn.example/avatar.png",+ )})})diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.tsindex e70d98962..2bf4bfcfa 100644--- a/src/web/src/lib/community/storage.ts+++ b/src/web/src/lib/community/storage.ts@@ -55,23 +55,56 @@ export function isOwnedServerIconKey(key: string, serverId: string): boolean {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.+// Stable aliases remain deterministic for rollback compatibility. New avatar+// publications write immutable `/objects/<uuid>` children and D1 points at+// exactly one child; the canonical read URL carries that D1 version.export function buildUserAvatarKey(userId: string): string {return `user-avatar/${userId}`}-export function userAvatarUrl(userId: string): string {- return `/api/community/users/${userId}/avatar`+export function buildUserAvatarObjectKey(userId: string, fileId: string): string {+ return `${buildUserAvatarKey(userId)}/objects/${fileId}`+}++export function isOwnedUserAvatarObjectKey(key: string, userId: string): boolean {+ const prefix = `${buildUserAvatarKey(userId)}/objects/`+ const suffix = key.startsWith(prefix) ? key.slice(prefix.length) : ""+ return suffix.length > 0 && !suffix.includes("/")+}++export function userAvatarUrl(userId: string, avatarVersion?: number): string {+ const base = `/api/community/users/${userId}/avatar`+ return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base}export function buildBotAvatarKey(botId: string): string {return `bot-avatar/${botId}`}-export function botAvatarUrl(botId: string): string {- return `/api/community/bots/${botId}/avatar`+export function buildBotAvatarObjectKey(botId: string, fileId: string): string {+ return `${buildBotAvatarKey(botId)}/objects/${fileId}`+}++export function isOwnedBotAvatarObjectKey(key: string, botId: string): boolean {+ const prefix = `${buildBotAvatarKey(botId)}/objects/`+ const suffix = key.startsWith(prefix) ? key.slice(prefix.length) : ""+ return suffix.length > 0 && !suffix.includes("/")+}++export function botAvatarUrl(botId: string, avatarVersion?: number): string {+ const base = `/api/community/bots/${botId}/avatar`+ return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base+}++export function canonicalUserImage(+ userId: string,+ image: string | null,+ avatarVersion: number,+): string | null {+ if (!image) return null+ if (image === userAvatarUrl(userId)) return userAvatarUrl(userId, avatarVersion)+ if (image === botAvatarUrl(userId)) return botAvatarUrl(userId, avatarVersion)+ return image}/**diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex da3063833..06fb4983b 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -384,13 +384,13 @@ describe("handleServerIconUpload", () => {describe("handleUserAvatarUpload", () => {beforeEach(() => vi.clearAllMocks())- it("uploads a valid png avatar under the deterministic user-avatar/{userId} key", async () => {+ it("uploads a valid png avatar under an immutable user-avatar child key", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("me.png", "image/png", 10)const res = await handleUserAvatarUpload(reqWithFile(file), envWithR2(put), "u1")expect(res.ok).toBe(true)if (!res.ok) return- expect(res.key).toBe("user-avatar/u1")+ expect(res.key).toMatch(/^user-avatar\/u1\/objects\/[0-9a-f-]+$/)})it("returns the routable avatar route URL, not the (404-ing) media catch-all shape", async () => {@@ -402,7 +402,7 @@ describe("handleUserAvatarUpload", () => {expect(res.url).toBe("/api/community/users/u1/avatar")})- it("re-uploading the same user overwrites the same key (no fileId)", async () => {+ it("re-uploading the same user allocates a distinct immutable child", async () => {const put = vi.fn().mockResolvedValue(undefined)const first = await handleUserAvatarUpload(reqWithFile(fakeFile("a.png", "image/png", 10)),@@ -416,7 +416,9 @@ describe("handleUserAvatarUpload", () => {)expect(first.ok && second.ok).toBe(true)if (!first.ok || !second.ok) return- expect(first.key).toBe(second.key)+ expect(first.key).not.toBe(second.key)+ expect(first.key).toMatch(/^user-avatar\/u1\/objects\/[0-9a-f-]+$/)+ expect(second.key).toMatch(/^user-avatar\/u1\/objects\/[0-9a-f-]+$/)})it("rejects oversize avatars with 413", async () => {@@ -450,13 +452,13 @@ describe("handleUserAvatarUpload", () => {describe("handleBotAvatarUpload", () => {beforeEach(() => vi.clearAllMocks())- it("uploads a valid png avatar under the deterministic bot-avatar/{botId} key", async () => {+ it("uploads a valid png avatar under an immutable bot-avatar child key", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("bot.png", "image/png", 10)const res = await handleBotAvatarUpload(reqWithFile(file), envWithR2(put), "b1")expect(res.ok).toBe(true)if (!res.ok) return- expect(res.key).toBe("bot-avatar/b1")+ expect(res.key).toMatch(/^bot-avatar\/b1\/objects\/[0-9a-f-]+$/)})it("returns the routable avatar route URL, not the (404-ing) media catch-all shape", async () => {diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex 86d80c718..9f0b4e76e 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -19,8 +19,8 @@ import {buildMediaKey,buildAttachmentThumbnailKey,buildServerIconKey,- buildUserAvatarKey,- buildBotAvatarKey,+ buildUserAvatarObjectKey,+ buildBotAvatarObjectKey,serverIconUrl,userAvatarUrl,botAvatarUrl,@@ -286,13 +286,7 @@ export async function handleServerIconUpload(}}-/**- * Validate + upload a user/bot avatar to a deterministic key — unlike server- * icons, there's no `fileId`/old-key-delete dance since R2 `.put()` overwrites- * the same object in place on every re-upload. Shared by- * `handleUserAvatarUpload` and `handleBotAvatarUpload`, which only differ in- * key/URL builder.- */+/** Validate and upload one immutable user/bot avatar object. */async function handleAvatarUpload(req: NextRequest,env: Env,@@ -338,7 +332,13 @@ export function handleUserAvatarUpload(env: Env,userId: string,): Promise<UploadResult> {- return handleAvatarUpload(req, env, userId, buildUserAvatarKey(userId), userAvatarUrl(userId))+ return handleAvatarUpload(+ req,+ env,+ userId,+ buildUserAvatarObjectKey(userId, crypto.randomUUID()),+ userAvatarUrl(userId),+ )}export function handleBotAvatarUpload(@@ -346,7 +346,13 @@ export function handleBotAvatarUpload(env: Env,botId: string,): Promise<UploadResult> {- return handleAvatarUpload(req, env, botId, buildBotAvatarKey(botId), botAvatarUrl(botId))+ return handleAvatarUpload(+ req,+ env,+ botId,+ buildBotAvatarObjectKey(botId, crypto.randomUUID()),+ botAvatarUrl(botId),+ )}/**diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 137d132e8..76bae7281 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -26,6 +26,7 @@ describe("communityKeys", () => {expect(communityKeys.machines()[0]).toBe("community")expect(communityKeys.channelMessages("c1")[0]).toBe("community")expect(communityKeys.message("m1")[0]).toBe("community")+ expect(communityKeys.messageContext("channel", "c1", 7)[0]).toBe("community")})it("nests server-scoped keys under communityKeys.server(id)", () => {@@ -139,6 +140,13 @@ describe("communityKeys", () => {"message","m1",])+ expect(communityKeys.messageContext("dm", "d1", 7)).toEqual([+ "community",+ "message-context",+ "dm",+ "d1",+ 7,+ ])})it("keeps report polling specific to one report and outside the bots-list cache", () => {diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 6fd3ffe0c..21736b498 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -105,6 +105,8 @@ export const communityKeys = {// Single hydrated message (opener block, deep-link previews).message: (messageId: string) =>[...communityKeys.all, "message", messageId] as const,+ messageContext: (type: "channel" | "dm", channelId: string, targetSeq: number | null) =>+ [...communityKeys.all, "message-context", type, channelId, targetSeq] as const,// ── Inbox ───────────────────────────────────────────────────────────────inbox: () => [...communityKeys.all, "inbox"] as const,diff --git a/src/web/src/stores/community/message-stream.test.ts b/src/web/src/stores/community/message-stream.test.tsindex 549f2f1c9..222b0a203 100644--- a/src/web/src/stores/community/message-stream.test.ts+++ b/src/web/src/stores/community/message-stream.test.ts@@ -61,4 +61,42 @@ describe("message stream store", () => {expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:failed")expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1)})++ it("projects a newer avatar across every active scope and ignores stale versions", () => {+ const store = useMessageStreamStore.getState()+ store.accept(channel("c1"), {+ ...acceptedIntent("n1"),+ message: {+ type: "chat" as const,+ content: "n1",+ authorId: "u1",+ authorAvatar: "/avatar?v=1",+ authorAvatarVersion: 1,+ },+ })+ store.accept(channel("c2"), {+ ...acceptedIntent("n2"),+ message: {+ type: "chat" as const,+ content: "n2",+ authorId: "u1",+ authorAvatar: "/avatar?v=1",+ authorAvatarVersion: 1,+ },+ })++ store.projectAvatarIdentity("u1", "/avatar?v=2", 2)++ expect(getMessageOverlay(channel("c1")).outboxByNonce.get("n1")?.message).toMatchObject({+ authorAvatar: "/avatar?v=2",+ authorAvatarVersion: 2,+ })+ expect(getMessageOverlay(channel("c2")).outboxByNonce.get("n2")?.message).toMatchObject({+ authorAvatar: "/avatar?v=2",+ authorAvatarVersion: 2,+ })+ const entries = useMessageStreamStore.getState().entries+ store.projectAvatarIdentity("u1", "/avatar?v=1", 1)+ expect(useMessageStreamStore.getState().entries).toBe(entries)+ })})diff --git a/src/web/src/stores/community/message-stream.ts b/src/web/src/stores/community/message-stream.tsindex 0208096de..32ece184a 100644--- a/src/web/src/stores/community/message-stream.ts+++ b/src/web/src/stores/community/message-stream.ts@@ -19,6 +19,7 @@ type MessageStreamStoreState = {nextOrdinal: numberaccept: (scope: MessageScope, intent: Omit<NewOutboxIntent, "localOrdinal">) => booleandispatch: (scope: MessageScope, event: MessageOverlayEvent) => void+ projectAvatarIdentity: (userId: string, avatar: string, avatarVersion: number) => voidgetRetryPayload: (scope: MessageScope, nonce: string) => OutboxRetryPayload | undefinedremoveScope: (scope: MessageScope) => voidremoveServer: (serverId: string) => void@@ -68,6 +69,24 @@ export const useMessageStreamStore = create<MessageStreamStoreState>((set, get)executeEffects(transition.effects)},+ projectAvatarIdentity: (userId, avatar, avatarVersion) => {+ const current = get()+ const entries = new Map(current.entries)+ let changed = false+ for (const [key, entry] of current.entries) {+ const transition = reduceMessageOverlay(entry.state, {+ type: "identityUpdated",+ userId,+ avatar,+ avatarVersion,+ })+ if (transition.state === entry.state) continue+ entries.set(key, { ...entry, state: transition.state })+ changed = true+ }+ if (changed) set({ entries })+ },+getRetryPayload: (scope, nonce) => {const entry = get().entries.get(messageScopeKey(scope))return entry ? getOutboxRetryPayload(entry.state, nonce) : undefineddiff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.tsindex 91fa1c2d9..8dbc29e97 100644--- a/src/web/src/stores/community/ws.test.ts+++ b/src/web/src/stores/community/ws.test.ts@@ -292,6 +292,48 @@ describe("useCommunityWsStore", () => {expect(useCommunityWsStore.getState().userStatuses.size).toBe(0)})+ it("fences avatar identity by the bound account and highest observed version", () => {+ const unbound = useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=1", 1)+ expect(unbound).toBe("unbound")+ expect(useCommunityWsStore.getState().avatarIdentities.size).toBe(0)++ useCommunityWsStore.getState().bindIdentityOwner("account-a")+ expect(useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=2", 2))+ .toBe("accepted")+ const accepted = useCommunityWsStore.getState().avatarIdentities+ expect(accepted.get("u1")).toEqual({ avatar: "/a?v=2", avatarVersion: 2 })++ expect(useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=1", 1))+ .toBe("stale")+ expect(useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=2", 2))+ .toBe("same")+ expect(useCommunityWsStore.getState().observeAvatarIdentity("u1", "/other?v=2", 2))+ .toBe("conflict")+ expect(useCommunityWsStore.getState().avatarIdentities).toBe(accepted)++ expect(useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=3", 3))+ .toBe("accepted")+ expect(useCommunityWsStore.getState().avatarIdentities.get("u1"))+ .toEqual({ avatar: "/a?v=3", avatarVersion: 3 })+ })++ it("retains the fence for the same account and clears it on account switch/reset", () => {+ useCommunityWsStore.getState().bindIdentityOwner("account-a")+ useCommunityWsStore.getState().observeAvatarIdentity("u1", "/a?v=4", 4)+ const before = useCommunityWsStore.getState().avatarIdentities++ useCommunityWsStore.getState().bindIdentityOwner("account-a")+ expect(useCommunityWsStore.getState().avatarIdentities).toBe(before)++ useCommunityWsStore.getState().bindIdentityOwner("account-b")+ expect(useCommunityWsStore.getState().identityOwnerUserId).toBe("account-b")+ expect(useCommunityWsStore.getState().avatarIdentities.size).toBe(0)++ useCommunityWsStore.getState().reset()+ expect(useCommunityWsStore.getState().identityOwnerUserId).toBeNull()+ expect(useCommunityWsStore.getState().avatarIdentities.size).toBe(0)+ })+it("pushBotAuditEvent prepends newest-first, dedups on id, and bounds each per-bot ring", () => {const push = useCommunityWsStore.getState().pushBotAuditEventpush({diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex 8ab0aff39..f9cb196d8 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -55,6 +55,8 @@ export type BotAuditEventEntry = {}type UserStatus = { emoji: string | null; text: string | null }+type AvatarIdentity = { avatar: string; avatarVersion: number }+type AvatarIdentityObservation = "accepted" | "same" | "stale" | "conflict" | "unbound"export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failed"const NOOP_RECONNECT = () => undefined@@ -82,6 +84,8 @@ export type CommunityWsStoreState = {* fetched row.*/userStatuses: Map<string, UserStatus>+ identityOwnerUserId: string | null+ avatarIdentities: Map<string, AvatarIdentity>/*** Per-bot rings of recent audit events, each bounded by BOT_AUDIT_RING_MAX.* Newest first inside each bot's array. A chatty bot never evicts a quieter@@ -119,6 +123,12 @@ export type CommunityWsStoreState = {completeDeliveryOperation: (operationId: string, operationDigest: string) => booleansetUserStatus: (userId: string, emoji: string | null, text: string | null) => voidresetUserStatuses: () => void+ bindIdentityOwner: (userId: string | null) => void+ observeAvatarIdentity: (+ userId: string,+ avatar: string,+ avatarVersion: number,+ ) => AvatarIdentityObservationmarkAccessDisconnected: () => voidmarkAccessConnected: () => voidsetConnectionStatus: (status: CommunityWsConnectionStatus) => void@@ -130,6 +140,7 @@ export type CommunityWsStoreState = {const initialState = (): Pick<CommunityWsStoreState,"onlineUserIds" | "seenMessageIds" | "seenDeliveryOperations" | "userStatuses" | "botAuditEvents"+ | "identityOwnerUserId" | "avatarIdentities"| "accessEpoch" | "accessConnected"| "connectionStatus" | "reconnectNow"> => ({@@ -141,6 +152,8 @@ const initialState = (): Pick<seenMessageIds: new Set(),seenDeliveryOperations: new Map(),userStatuses: new Map(),+ identityOwnerUserId: null,+ avatarIdentities: new Map(),botAuditEvents: new Map(),})@@ -238,6 +251,26 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ userStatuses: new Map() })},+ bindIdentityOwner: (userId) => {+ if (get().identityOwnerUserId === userId) return+ set({ identityOwnerUserId: userId, avatarIdentities: new Map() })+ },++ observeAvatarIdentity: (userId, avatar, avatarVersion) => {+ if (!get().identityOwnerUserId) return "unbound"+ const current = get().avatarIdentities.get(userId)+ if (current) {+ if (avatarVersion < current.avatarVersion) return "stale"+ if (avatarVersion === current.avatarVersion) {+ return avatar === current.avatar ? "same" : "conflict"+ }+ }+ const next = new Map(get().avatarIdentities)+ next.set(userId, { avatar, avatarVersion })+ set({ avatarIdentities: next })+ return "accepted"+ },+markAccessDisconnected: () => set((state) => ({accessEpoch: state.accessEpoch + 1,accessConnected: false,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.tsindex 91ed8fff1..f40d6d1b3 100644--- 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.ts@@ -34,16 +34,24 @@ describe("bot and machine-cascade avatar cleanup C2 boundary", () => {}})- it("derives every C2 cleanup key through buildBotAvatarKey", () => {+ it("deletes only an authoritative owned child and the exact stable alias", () => {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)")+ const persistence = source("src/web/src/lib/community/bot-avatar-persistence.ts")+ expect(persistence).toContain("cleanupAvatarCandidate(")+ expect(persistence).toContain("objectKey: input.objectKey")++ for (const path of [+ "src/web/src/app/api/community/bots/[id]/route.ts",+ "src/web/src/app/api/community/machines/[id]/route.ts",+ ]) {+ const deletion = source(path)+ expect(deletion).toContain("isOwnedBotAvatarObjectKey")+ expect(deletion).toContain("before.avatarObjectKey")+ expect(deletion).toContain("buildBotAvatarKey(")+ expect(deletion).not.toContain(".list(")+ }})it("keeps the human self-avatar branch on Better Auth and user storage", () => {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.tsindex 6ee6ea0fc..ab2d59472 100644--- 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.ts@@ -51,18 +51,25 @@ async function createBot(machineId: string, name: string): Promise<string> {return body.bot.id}-async function uploadAvatar(page: import("@playwright/test").Page, botId: string): Promise<number> {+async function uploadAvatar(+ page: import("@playwright/test").Page,+ botId: string,+): Promise<{ status: number; url: string; avatarVersion: 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`, {+ const response = await fetch(`/api/community/bots/${id}/avatar`, {method: "POST",body: form,credentials: "include",- })).status+ })+ return {+ status: response.status,+ ...await response.json() as { url: string; avatarVersion: number },+ }}, { id: botId, base64: ONE_PIXEL_PNG_BASE64 })}@@ -75,12 +82,12 @@ test("real bot avatars become unreadable after single delete and authenticated mconst alice = await asUser("alice")await gotoAfterUserWsAuth(alice.page, "/c/me/bots")- const uploadStatus = await uploadAvatar(alice.page, botId)- expect(uploadStatus).toBe(200)+ const upload = await uploadAvatar(alice.page, botId)+ expect(upload.status).toBe(200)await alice.page.reload()await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()- const avatar = alice.page.locator(`img[src="${avatarPath}"]`)+ const avatar = alice.page.locator(`img[src="${upload.url}"]`)await expect(avatar).toBeVisible()await expect.poll(() => avatar.evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth)).toBe(1)expect(await alice.page.evaluate(async (path) => (@@ -101,7 +108,7 @@ test("real bot avatars become unreadable after single delete and authenticated mawait alice.page.reload()await expect(alice.page.getByText(botName, { exact: true })).toHaveCount(0)- await expect(alice.page.locator(`img[src="${avatarPath}"]`)).toHaveCount(0)+ await expect(alice.page.locator(`img[src="${upload.url}"]`)).toHaveCount(0)expect(await alice.page.evaluate(async (path) => (await fetch(`${path}?reload=${crypto.randomUUID()}`, { cache: "no-store" })).status, avatarPath)).toBe(404)@@ -116,7 +123,8 @@ test("real bot avatars become unreadable after single delete and authenticated mconst 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)+ const cascadeUpload = await uploadAvatar(alice.page, cascadeBotId)+ expect(cascadeUpload.status).toBe(200)await alice.page.reload()await expect(alice.page.getByText(cascadeBotName, { exact: true })).toBeVisible()expect(await alice.page.evaluate(async (path) => (diff --git a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.tsnew file mode 100644index 000000000..b8c59c8c3--- /dev/null+++ b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts@@ -0,0 +1,251 @@+import type { Page } from "@playwright/test"+import {+ expect,+ test,+ userId,+ userName,+} from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import {+ seedChannel,+ seedDm,+ seedDmMessage,+ seedFriendship,+ seedJoinServer,+ seedMessage,+ seedServer,+} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import {+ communityFrameEvents,+ proxyCommunityWebSockets,+ type CapturedCommunityFrame,+} from "./_fixtures/community-ws-proxy"++type AvatarUpload = {+ status: number+ url: string+ avatarVersion: number+}++const hideDevelopmentOverlays = "nextjs-portal, .tsqd-parent-container { display: none !important; }"++function deferred() {+ let resolve!: () => void+ const promise = new Promise<void>((done) => { resolve = done })+ return { promise, resolve }+}++function identityEvents(frames: CapturedCommunityFrame[], subjectId: string) {+ return frames.flatMap(communityFrameEvents).filter((event) => (+ event.type === "community:identity.update"+ && event.userId === subjectId+ ))+}++async function uploadSolidAvatar(page: Page, color: string): Promise<AvatarUpload> {+ return page.evaluate(async (fill) => {+ const canvas = document.createElement("canvas")+ canvas.width = 48+ canvas.height = 48+ const context = canvas.getContext("2d")!+ context.fillStyle = fill+ context.fillRect(0, 0, 48, 48)+ context.strokeStyle = "#ffffff"+ context.lineWidth = 6+ context.beginPath()+ context.moveTo(8, 40)+ context.lineTo(40, 8)+ context.stroke()+ const blob = await new Promise<Blob>((resolve, reject) => canvas.toBlob(+ (value) => value ? resolve(value) : reject(new Error("PNG encoding failed")),+ "image/png",+ ))+ const form = new FormData()+ form.append("file", new File([blob], "avatar.png", { type: "image/png" }))+ const response = await fetch("/api/community/users/me/avatar", {+ method: "POST",+ body: form,+ credentials: "include",+ })+ return {+ status: response.status,+ ...await response.json() as { url: string; avatarVersion: number },+ }+ }, color)+}++async function expectPhoto(locator: ReturnType<Page["locator"]>, url: string) {+ const photo = locator.locator(`img[src="${url}"]`).first()+ await expect(photo).toBeVisible({ timeout: 20_000 })+ await expect.poll(() => photo.evaluate((image: HTMLImageElement) => (+ image.complete && image.naturalWidth > 0+ )), { timeout: 20_000 }).toBe(true)+}++test("versioned avatars converge across live, stale, reconnect, cold, and concurrent clients", async ({ asUser }, testInfo) => {+ test.setTimeout(240_000)+ const stamp = Date.now()+ const aliceId = userId("alice")+ const serverId = await seedServer("alice", `Avatar identity ${stamp}`)+ const channelId = await seedChannel("alice", serverId, `avatar-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const messageId = await seedMessage("alice", channelId, `Avatar source ${stamp}`)+ const dmId = await seedDm("alice", userId("bob"))+ await seedDmMessage("alice", dmId, `Avatar DM ${stamp}`)+ await seedFriendship("alice", "bob", userId("bob"))++ const uploader = await asUser("alice")+ const sameAccount = await asUser("alice")+ const observer = await asUser("bob")+ // Dave is reserved for this final audience-isolation check. Carol already+ // shares a server with Alice after earlier serial specs, so she is an+ // authorized identity observer in a full-shard run even though this spec+ // does not create that relationship itself.+ const stranger = await asUser("dave")+ await sameAccount.page.setViewportSize({ width: 390, height: 844 })+ await observer.page.setViewportSize({ width: 1280, height: 900 })++ let holdNextAliceIdentity = false+ const uploaderWs = await proxyCommunityWebSockets(uploader.context)+ const sameAccountWs = await proxyCommunityWebSockets(sameAccount.context)+ const observerWs = await proxyCommunityWebSockets(observer.context, {+ decide: (frame) => {+ if (+ holdNextAliceIdentity+ && identityEvents([frame], aliceId).length > 0+ ) {+ holdNextAliceIdentity = false+ return "hold"+ }+ return "forward"+ },+ })+ const strangerWs = await proxyCommunityWebSockets(stranger.context)++ await gotoAfterUserWsAuth(uploader.page, "/c/me")+ await gotoAfterUserWsAuth(sameAccount.page, "/c/me")+ await gotoAfterUserWsAuth(observer.page, `/c/channels/${serverId}/${channelId}`)+ await gotoAfterUserWsAuth(stranger.page, "/c/me")+ const message = observer.page.locator(`[data-msg-id="${messageId}"]`)+ await expect(message).toBeVisible({ timeout: 20_000 })++ const profileGate = deferred()+ const profileStarted = deferred()+ const profilePattern = `**/api/community/users/${aliceId}/profile`+ await observer.page.route(profilePattern, async (route) => {+ const staleResponse = await route.fetch()+ profileStarted.resolve()+ await profileGate.promise+ await route.fulfill({ response: staleResponse })+ })+ await message.getByRole("button", { name: userName("alice"), exact: true }).click()+ await profileStarted.promise++ holdNextAliceIdentity = true+ const first = await uploadSolidAvatar(uploader.page, "#e5484d")+ expect(first.status).toBe(200)+ expect(first.url).toBe(`/api/community/users/${aliceId}/avatar?v=${first.avatarVersion}`)+ await expect.poll(() => observerWs.heldCount(), { timeout: 20_000 }).toBe(1)++ const second = await uploadSolidAvatar(uploader.page, "#3b82f6")+ expect(second.status).toBe(200)+ expect(second.avatarVersion).toBe(first.avatarVersion + 1)+ await expect.poll(() => identityEvents(observerWs.frames, aliceId).some(+ (event) => event.avatarVersion === second.avatarVersion,+ ), { timeout: 20_000 }).toBe(true)++ await expectPhoto(message, second.url)+ await expectPhoto(sameAccount.page.locator("body"), second.url)+ profileGate.resolve()+ await expectPhoto(observer.page.getByTestId(tid.profileCard), second.url)+ await observer.page.unroute(profilePattern)++ expect(observerWs.releaseHeld((frame) => identityEvents([frame], aliceId).some(+ (event) => event.avatarVersion === first.avatarVersion,+ ))).toBe(1)+ await observer.page.waitForTimeout(250)+ await expectPhoto(message, second.url)+ await expectPhoto(observer.page.getByTestId(tid.profileCard), second.url)++ await observer.page.getByTestId(tid.profileCard).press("Escape")+ await observer.page.getByRole("button", { name: /member/i }).first().click()+ await expectPhoto(observer.page.getByTestId(tid.memberRow(aliceId)), second.url)+ await observer.page.addStyleTag({ content: hideDevelopmentOverlays })+ await observer.page.screenshot({+ path: testInfo.outputPath("versioned-avatar-desktop-1280x900.png"),+ animations: "disabled",+ })++ await gotoAfterUserWsAuth(observer.page, "/c/me")+ await expectPhoto(observer.page.getByTestId(tid.dmRow(dmId)), second.url)+ await gotoAfterUserWsAuth(observer.page, "/c/me/friends")+ const friendRow = observer.page.getByText(userName("alice"), { exact: true })+ .locator("xpath=ancestor::button[1]")+ await expectPhoto(friendRow, second.url)++ await observer.context.setOffline(true)+ await observerWs.disconnect()+ const third = await uploadSolidAvatar(uploader.page, "#22c55e")+ expect(third.status).toBe(200)+ expect(third.avatarVersion).toBe(second.avatarVersion + 1)+ await observer.context.setOffline(false)+ await expectPhoto(friendRow, third.url)++ const cold = await asUser("bob")+ await cold.page.setViewportSize({ width: 1280, height: 900 })+ await gotoAfterUserWsAuth(cold.page, `/c/channels/${serverId}/${channelId}`)+ await expectPhoto(cold.page.locator(`[data-msg-id="${messageId}"]`), third.url)++ const [concurrentA, concurrentB] = await Promise.all([+ uploadSolidAvatar(uploader.page, "#f59e0b"),+ uploadSolidAvatar(sameAccount.page, "#a855f7"),+ ])+ expect(concurrentA.status).toBe(200)+ expect(concurrentB.status).toBe(200)+ const winner = concurrentA.avatarVersion > concurrentB.avatarVersion+ ? concurrentA+ : concurrentB+ expect(Math.abs(concurrentA.avatarVersion - concurrentB.avatarVersion)).toBe(1)++ await expectPhoto(uploader.page.locator("body"), winner.url)+ await expectPhoto(sameAccount.page.locator("body"), winner.url)+ await expectPhoto(cold.page.locator(`[data-msg-id="${messageId}"]`), winner.url)+ const selfProfile = await uploader.page.request.get("/api/community/users/me/profile")+ expect(selfProfile.status()).toBe(200)+ expect(await selfProfile.json()).toMatchObject({+ id: aliceId,+ avatar: winner.url,+ avatarVersion: winner.avatarVersion,+ })+ const stableRead = await uploader.page.request.get(`/api/community/users/${aliceId}/avatar`, {+ maxRedirects: 0,+ })+ expect(stableRead.status()).toBe(307)+ expect(stableRead.headers().location).toBe(winner.url)+ const immutableRead = await uploader.page.request.get(winner.url)+ expect(immutableRead.status()).toBe(200)+ expect(immutableRead.headers()["cache-control"]).toBe("private, max-age=31536000, immutable")++ await expect.poll(() => identityEvents(uploaderWs.frames, aliceId).some(+ (event) => event.avatarVersion === winner.avatarVersion,+ ), { timeout: 20_000 }).toBe(true)+ await expect.poll(() => identityEvents(sameAccountWs.frames, aliceId).some(+ (event) => event.avatarVersion === winner.avatarVersion,+ ), { timeout: 20_000 }).toBe(true)+ await expect.poll(() => identityEvents(observerWs.frames, aliceId).length, {+ timeout: 20_000,+ }).toBeGreaterThanOrEqual(3)+ expect(identityEvents(strangerWs.frames, aliceId)).toEqual([])++ await gotoAfterUserWsAuth(sameAccount.page, "/c/me")+ await expectPhoto(sameAccount.page.locator("body"), winner.url)+ await sameAccount.page.addStyleTag({ content: hideDevelopmentOverlays })+ await sameAccount.page.getByTestId(tid.userSettingsOpen).click()+ await expect(sameAccount.page.getByTestId(tid.settingsShell)).toBeVisible()+ await expectPhoto(sameAccount.page.getByTestId(tid.settingsShell), winner.url)+ await sameAccount.page.screenshot({+ path: testInfo.outputPath("versioned-avatar-mobile-390x844.png"),+ animations: "disabled",+ })+})diff --git a/src/web/src/test/e2e-ui/_setup/users.ts b/src/web/src/test/e2e-ui/_setup/users.tsindex f73c9a6a0..2d29da75f 100644--- a/src/web/src/test/e2e-ui/_setup/users.ts+++ b/src/web/src/test/e2e-ui/_setup/users.ts@@ -1,6 +1,6 @@-export type UserKey = "alice" | "bob" | "carol" | "logout"+export type UserKey = "alice" | "bob" | "carol" | "dave" | "logout"-export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "logout"]+export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "dave", "logout"]export function emailFor(key: UserKey, stamp: string): string {return `e2e-${key}-${stamp}@alook.test`diff --git a/src/web/src/test/e2e/message-delivery-retry.test.ts b/src/web/src/test/e2e/message-delivery-retry.test.tsindex a6e5457dd..0d004c965 100644--- a/src/web/src/test/e2e/message-delivery-retry.test.ts+++ b/src/web/src/test/e2e/message-delivery-retry.test.ts@@ -28,6 +28,7 @@ function batch(): MessageDeliveryBatch {seq: 3,authorId: "author",authorName: "Author",+ authorAvatarVersion: 0,content: "failed-only retry",type: "chat",createdAt: "2026-08-18T00:00:00.000Z",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.tsindex 4ca998e57..1e0dfa83c 100644--- a/src/web/test-runtime/community-bot-avatar-cleanup.runtime.test.ts+++ b/src/web/test-runtime/community-bot-avatar-cleanup.runtime.test.ts@@ -5,7 +5,11 @@ 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"+import {+ buildBotAvatarKey,+ buildBotAvatarObjectKey,+ botAvatarUrl,+} from "../src/lib/community/storage"const runtimeEnv = env as unknown as CloudflareEnvconst createdUsers: string[] = []@@ -140,6 +144,8 @@ describe("bot avatar query and winner semantics in real D1", () => {await expect(queries.communityBot.getLiveBotAvatar(db, canonicalBot)).resolves.toEqual({id: canonicalBot,image: botAvatarUrl(canonicalBot),+ avatarVersion: 0,+ avatarObjectKey: null,})await expect(queries.communityBot.getLiveBotAvatar(db, deletedBot)).resolves.toBeNull()await expect(queries.communityBot.getLiveBotAvatar(db, human)).resolves.toBeNull()@@ -157,12 +163,13 @@ describe("bot avatar query and winner semantics in real D1", () => {})describe("bot avatar D1 to R2 containment in real workerd", () => {- it("persists a live upload and deletes only the winning bot fixed key", async () => {+ it("publishes an immutable child and deletes only that winner plus its alias", 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 botObjectKey = buildBotAvatarObjectKey(bot, "upload-1")const userKey = `user-avatar/${bot}`const unrelatedBotKey = buildBotAvatarKey(unrelatedBot)const attachmentKey = `channel/runtime/${bot}/attachment.png`@@ -170,6 +177,7 @@ describe("bot avatar D1 to R2 containment in real workerd", () => {const bugKey = `bug-reports/${owner}/runtime-${bot}.ndjson.gz`for (const [key, value] of [[botKey, "bot"],+ [botObjectKey, "bot-object"],[userKey, "human"],[unrelatedBotKey, "other-bot"],[attachmentKey, "attachment"],@@ -184,15 +192,32 @@ describe("bot avatar D1 to R2 containment in real workerd", () => {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))+ objectKey: botObjectKey,+ })).resolves.toEqual({+ kind: "persisted",+ avatarVersion: 1,+ avatarObjectKey: botObjectKey,+ previousObjectKey: null,+ })+ expect(await first<{+ image: string+ avatarVersion: number+ avatarObjectKey: string | null+ }>("SELECT image, avatarVersion, avatarObjectKey FROM user WHERE id = ?", bot))+ .toEqual({+ image: botAvatarUrl(bot),+ avatarVersion: 1,+ avatarObjectKey: botObjectKey,+ })const won = await queries.communityBot.softDeleteBot(db, bot, owner)expect(won).toBe(true)- if (won) await deleteCommunityMediaObjects(runtimeEnv.COMMUNITY_MEDIA, [botKey])+ if (won) {+ await deleteCommunityMediaObjects(runtimeEnv.COMMUNITY_MEDIA, [botObjectKey, botKey])+ }expect(await runtimeEnv.COMMUNITY_MEDIA.get(botKey)).toBeNull()+ expect(await runtimeEnv.COMMUNITY_MEDIA.get(botObjectKey)).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")@@ -204,13 +229,14 @@ describe("bot avatar D1 to R2 containment in real workerd", () => {const owner = await seedOwner()const machine = await seedMachine(owner)const bot = await seedBot(owner, machine)- const botKey = buildBotAvatarKey(bot)+ const botKey = buildBotAvatarObjectKey(bot, "late-upload")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,+ objectKey: botKey,})).resolves.toEqual({ kind: "not_found" })expect(await runtimeEnv.COMMUNITY_MEDIA.get(botKey)).toBeNull()})diff --git a/src/web/test-runtime/versioned-avatar-identity.runtime.test.ts b/src/web/test-runtime/versioned-avatar-identity.runtime.test.tsnew file mode 100644index 000000000..00b4f75b9--- /dev/null+++ b/src/web/test-runtime/versioned-avatar-identity.runtime.test.ts@@ -0,0 +1,115 @@+/// <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 { cleanupAvatarCandidate } from "../src/lib/community/avatar-media-reconciliation"+import {+ buildUserAvatarObjectKey,+ userAvatarUrl,+} from "../src/lib/community/storage"++const runtimeEnv = env as unknown as CloudflareEnv+const users: string[] = []+const mediaKeys: string[] = []++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 seedHuman(image: string | null = null): Promise<string> {+ const id = `vai_user_${crypto.randomUUID().replaceAll("-", "")}`+ users.push(id)+ await runtimeEnv.DB.prepare(+ "INSERT INTO user (id, email, name, discriminator, image) VALUES (?, ?, ?, ?, ?)",+ ).bind(id, `${id}@example.com`, id, stamp4(id), image).run()+ return id+}++afterEach(async () => {+ for (const key of mediaKeys.splice(0)) await runtimeEnv.COMMUNITY_MEDIA.delete(key)+ for (const id of users.splice(0).reverse()) {+ await runtimeEnv.DB.prepare("DELETE FROM user WHERE id = ?").bind(id).run()+ }+})++describe("versioned human avatar publication in real D1/R2", () => {+ it("keeps legacy/external rows at the migration default until first publish", async () => {+ const external = "https://images.example.test/avatar.png"+ const userId = await seedHuman(external)+ const db = createDb(runtimeEnv.DB)++ await expect(queries.user.getLiveHumanAvatarState(db, userId)).resolves.toEqual({+ id: userId,+ image: external,+ avatarVersion: 0,+ avatarObjectKey: null,+ })++ const objectKey = buildUserAvatarObjectKey(userId, "first")+ await expect(queries.user.publishHumanAvatar(db, userId, {+ objectKey,+ stableUrl: userAvatarUrl(userId),+ })).resolves.toEqual({+ previous: {+ id: userId,+ image: external,+ avatarVersion: 0,+ avatarObjectKey: null,+ },+ current: {+ id: userId,+ image: userAvatarUrl(userId),+ avatarVersion: 1,+ avatarObjectKey: objectKey,+ },+ })+ })++ it("serializes concurrent publishes and deletes only the displaced child after reread", async () => {+ const userId = await seedHuman()+ const db = createDb(runtimeEnv.DB)+ const firstKey = buildUserAvatarObjectKey(userId, "concurrent-a")+ const secondKey = buildUserAvatarObjectKey(userId, "concurrent-b")+ for (const key of [firstKey, secondKey]) {+ mediaKeys.push(key)+ await runtimeEnv.COMMUNITY_MEDIA.put(key, key)+ }++ const outcomes = await Promise.all([+ queries.user.publishHumanAvatar(db, userId, {+ objectKey: firstKey,+ stableUrl: userAvatarUrl(userId),+ }),+ queries.user.publishHumanAvatar(db, userId, {+ objectKey: secondKey,+ stableUrl: userAvatarUrl(userId),+ }),+ ])+ expect(outcomes.every(Boolean)).toBe(true)+ expect(outcomes.map((outcome) => outcome!.current.avatarVersion).sort())+ .toEqual([1, 2])++ const current = await queries.user.getLiveHumanAvatarState(db, userId)+ expect(current?.avatarVersion).toBe(2)+ expect([firstKey, secondKey]).toContain(current?.avatarObjectKey)+ const displaced = current?.avatarObjectKey === firstKey ? secondKey : firstKey++ await expect(cleanupAvatarCandidate(+ db,+ runtimeEnv.COMMUNITY_MEDIA,+ { kind: "human", id: userId },+ current?.avatarObjectKey,+ )).resolves.toBe("retained_current")+ await expect(cleanupAvatarCandidate(+ db,+ runtimeEnv.COMMUNITY_MEDIA,+ { kind: "human", id: userId },+ displaced,+ )).resolves.toBe("deleted")+ expect(await runtimeEnv.COMMUNITY_MEDIA.get(displaced)).toBeNull()+ expect(await runtimeEnv.COMMUNITY_MEDIA.get(current!.avatarObjectKey!)).not.toBeNull()+ })+})diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.tsindex 456742d42..758cf7751 100644--- a/src/ws-do/src/community-browser-event-ingress.test.ts+++ b/src/ws-do/src/community-browser-event-ingress.test.ts@@ -69,9 +69,9 @@ function worstEscapingTarget(index: number) {}describe("community browser event ingress", () => {- it("normalizes all 43 current fixtures without a version field", () => {+ it("normalizes all 44 current fixtures without a contract version field", () => {const fixtures = Object.values(communityWsEventFixtures)- expect(fixtures).toHaveLength(43)+ expect(fixtures).toHaveLength(44)for (const fixture of fixtures) {const normalized = normalizeCommunityBrowserEvent(fixture)expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.tsindex b32bfb06d..7db112554 100644--- a/src/ws-do/src/routes/message-delivery.test.ts+++ b/src/ws-do/src/routes/message-delivery.test.ts@@ -22,6 +22,7 @@ const messageEvent = {seq: 4,authorId: "author",authorName: "Alice",+ authorAvatarVersion: 0,content: "hello",type: "chat" as const,createdAt: "2026-08-18T00:00:00.000Z",diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex d4c33a4ec..8aaf3b5a9 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -124,6 +124,7 @@ describe("WebSocketDurableObject", () => {seq: 1,authorId: "author",authorName: "Alice",+ authorAvatarVersion: 0,content: "hello",type: "chat",createdAt: "2026-08-18T00:00:00.000Z",