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
refactor(web): centralize community profiles (#620)
Gustavo Yedc0aa2a81675
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 70e4315cc..1134fd275 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -48,6 +48,7 @@ const messageSchema = z.strictObject({replyToId: nullableString.optional(),replyTo: z.strictObject({id: string,+ authorId: string.optional(),authorName: string,text: string,deleted: z.boolean().optional(),@@ -404,6 +405,17 @@ const communityIdentityUpdateSchema = z.strictObject({avatarVersion: z.number().int().positive(),})+const communityProfileUpdateSchema = z.strictObject({+ type: z.literal("community:profile.update"),+ userId: string,+ name: string,+ discriminator: string,+ aboutMe: string,+ bannerColor: nullableString,+ kind: z.enum(["human", "bot"]),+ ownerUserId: nullableString,+})+const machineRuntimeSchema = CommunityMachineRuntimeSchema.strict()export const CommunityMachineSummarySchema = z.strictObject({@@ -500,6 +512,7 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [communityPresenceUpdateSchema,communityStatusUpdateSchema,communityIdentityUpdateSchema,+ communityProfileUpdateSchema,communityMachineCreatedSchema,communityMachineStatusSchema,communityMachineUpdatedSchema,@@ -567,6 +580,7 @@ export type CommunityInboxChanged = Extract<CommunityWsEvent, { type: "communityexport 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 CommunityProfileUpdate = Extract<CommunityWsEvent, { type: "community:profile.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" }>@@ -640,6 +654,7 @@ export const WS_EVENTS = {PRESENCE_UPDATE: "community:presence.update",STATUS_UPDATE: "community:status.update",IDENTITY_UPDATE: "community:identity.update",+ PROFILE_UPDATE: "community:profile.update",MACHINE_CREATED: "community:machine.created",MACHINE_STATUS: "community:machine.status",MACHINE_UPDATED: "community:machine.updated",diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 3b6bdece6..b665306a8 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -604,6 +604,7 @@ export type {CommunityPresenceUpdate,CommunityStatusUpdate,CommunityIdentityUpdate,+ CommunityProfileUpdate,CommunityMentionCreate,CommunityUnreadBump,CommunityReadStateAdvanced,diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.tsindex 7608087f2..a4d3ef03d 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 44-event union", async () => {+ it("round-trips one strict outer frame without entering the 45-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(44)+ expect(Object.values(WS_EVENTS)).toHaveLength(45)})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 405d606fc..0b20b17e1 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 44-event inventory", () => {- expect(names).toHaveLength(44)+ it("locks the exact 45-event inventory", () => {+ expect(names).toHaveLength(45)expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)})- it("decodes and canonically encodes all 44 current event fixtures", () => {+ it("decodes and canonically encodes all 45 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 b20183827..b7a6c7ea5 100644--- a/src/shared/test/community-ws-events.fixtures.ts+++ b/src/shared/test/community-ws-events.fixtures.ts@@ -256,6 +256,16 @@ export const communityWsEventFixtures = {avatar: "/api/community/users/user-1/avatar?v=2",avatarVersion: 2,},+ "community:profile.update": {+ type: "community:profile.update",+ userId: "user-1",+ name: "Alice",+ discriminator: "0042",+ aboutMe: "Hello",+ bannerColor: null,+ kind: "human",+ ownerUserId: null,+ },"community:machine.created": {type: "community:machine.created",machine,@@ -321,6 +331,7 @@ export const requiredFixturePaths = {"community:presence.update": ["online"],"community:status.update": ["statusText"],"community:identity.update": ["avatarVersion"],+ "community:profile.update": ["name"],"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 513f035c6..ce2f170d2 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(44);+ expect(Object.values(WS_EVENTS)).toHaveLength(45);for (const type of Object.values(WS_EVENTS)) {expect(isCommunityEvent({ type })).toBe(true);}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 5a159a916..4cb545751 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@@ -283,6 +283,7 @@ describe("POST /api/community/bots/[id]/avatar", () => {"b1","/api/community/bots/b1/avatar?v=2",2,+ "u1",)})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 7c9fb2037..aaa3d0dd2 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@@ -103,6 +103,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {})const url = botAvatarUrl(botId, persisted.avatarVersion)- void fanOutIdentityUpdate(botId, url, persisted.avatarVersion)+ void fanOutIdentityUpdate(botId, url, persisted.avatarVersion, ctx.userId)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 47a3d34ce..b4a4042e1 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@@ -9,6 +9,7 @@ const mockUpdateBotRuntimeConfig = vi.fn()const mockGetMachineForOwner = vi.fn()const mockIsBotOnline = vi.fn()const mockGetUserPublic = vi.fn()+const mockGetProfile = vi.fn()const mockPushBotEventToMachine = vi.fn()const mockPushAgentModelSwitchToMachine = vi.fn()const mockPushAgentProviderSwitchToMachine = vi.fn()@@ -17,6 +18,7 @@ const mockLogError = vi.fn()const mockListBotServerMemberships = vi.fn()const mockSoftDeleteBot = vi.fn()const mockFanOutToServerMembers = vi.fn()+const mockFanOutProfileUpdate = vi.fn()const mockGetCloudflareContext = vi.fn()const mockWaitUntil = vi.fn()const mockMediaDelete = vi.fn()@@ -54,6 +56,9 @@ vi.mock("@alook/shared", async () => {user: {getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),},+ communityUserProfile: {+ getProfile: (...a: unknown[]) => mockGetProfile(...a),+ },},}})@@ -69,6 +74,7 @@ vi.mock("@/lib/broadcast", () => ({}))vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),+ fanOutProfileUpdate: (...a: unknown[]) => mockFanOutProfileUpdate(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -146,6 +152,8 @@ describe("PATCH /api/community/bots/[id]", () => {id: "b1", name: "New", discriminator: "0001", description: "new desc", image: null,})mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })+ mockGetProfile.mockResolvedValue({ aboutMe: "bot bio", bannerColor: null })+ mockFanOutProfileUpdate.mockResolvedValue(undefined)mockIsBotOnline.mockResolvedValue(true)mockGetMachineForOwner.mockResolvedValue({id: "mac1",diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex 7e29ae616..5e7eec4eb 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -26,7 +26,7 @@ import {pushAgentProviderSwitchToMachine,pushAgentRuntimeConfigUpdateToMachine,} from "@/lib/community/bot-push"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { fanOutProfileUpdate, fanOutToServerMembers } from "@/lib/community/fanout"import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"const log = createLogger({ service: "community-bot-update" })@@ -122,6 +122,9 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (willPush && !owner) {return writeError("bot owner not resolvable β refusing to push a bot update with unknown ownership", 500)}+ const publicProfile = nameChanged+ ? await queries.communityUserProfile.getProfile(db, id)+ : nullconst updated = await queries.communityBot.updateBot(db, id, ctx.userId, {name: body.name,@@ -130,6 +133,20 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {})if (!updated) return writeError("bot not found", 404)+ if (nameChanged) {+ await fanOutProfileUpdate({+ id,+ name: updated.name,+ discriminator: updated.discriminator,+ aboutMe: publicProfile?.aboutMe ?? "",+ bannerColor: publicProfile?.bannerColor ?? null,+ identity: {+ kind: "bot",+ ownerProfile: { id: before.ownerUserId },+ },+ })+ }+if (willPush && owner && before.machineId) {await pushBotEventToMachine(ctx.env, before.machineId, {type: "bot:updated",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 87c28691d..9f078e9a0 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@@ -45,7 +45,12 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {candidates: [persisted.previousObjectKey, persisted.avatarObjectKey],})const url = botAvatarUrl(userId, persisted.avatarVersion)- void fanOutIdentityUpdate(userId, url, persisted.avatarVersion)+ void fanOutIdentityUpdate(+ userId,+ url,+ persisted.avatarVersion,+ ctx.actor.ownerUserId,+ )return writeJSON({ url, avatarVersion: persisted.avatarVersion })}diff --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 cdcfbed13..fc9ce270b 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@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const getProfile = vi.fn()+const getPublicProfileForViewer = vi.fn()const updateProfile = vi.fn()const getUser = vi.fn()const listMemberServerIds = vi.fn()@@ -9,6 +10,7 @@ const getMemberships = vi.fn()const authApiUpdateUser = vi.fn()const fanOutToServerMembers = vi.fn()const fanOutStatusUpdate = vi.fn()+const fanOutProfileUpdate = vi.fn()let actorKind: "human" | "bot" = "human"vi.mock("@opennextjs/cloudflare", () => ({@@ -24,8 +26,8 @@ vi.mock("@/lib/auth", () => ({}))vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => fanOutToServerMembers(...a),fanOutStatusUpdate: (...a: unknown[]) => fanOutStatusUpdate(...a),+ fanOutProfileUpdate: (...a: unknown[]) => fanOutProfileUpdate(...a),}))vi.mock("@alook/shared", async () => {@@ -35,6 +37,7 @@ vi.mock("@alook/shared", async () => {queries: {communityUserProfile: {getProfile: (...a: unknown[]) => getProfile(...a),+ getPublicProfileForViewer: (...a: unknown[]) => getPublicProfileForViewer(...a),updateProfile: (...a: unknown[]) => updateProfile(...a),},user: {@@ -131,7 +134,7 @@ describe("GET /api/community/users/me/profile", () => {expect(await res.json()).toEqual({id: "u1",aboutMe: "",- avatar: "",+ avatar: "?",avatarVersion: 0,bannerColor: null,discriminator: "0000",@@ -150,12 +153,31 @@ describe("PATCH /api/community/users/me/profile", () => {listMemberServerIds.mockResolvedValue([])getMemberships.mockResolvedValue([])fanOutStatusUpdate.mockResolvedValue(undefined)+ fanOutProfileUpdate.mockResolvedValue(undefined)updateProfile.mockImplementation(async (_db, _u, data) => ({aboutMe: data.aboutMe ?? null,bannerColor: data.bannerColor ?? null,statusEmoji: data.statusEmoji ?? null,statusText: data.statusText ?? null,}))+ getPublicProfileForViewer.mockImplementation(async (_db, id: string) => {+ const data = updateProfile.mock.calls.at(-1)?.[2] ?? {}+ const rename = authApiUpdateUser.mock.calls.at(-1)?.[0]?.body?.name+ return {+ id,+ name: rename ?? (id === "b1" ? "Bot" : "Jane Roe"),+ discriminator: "4242",+ image: null,+ avatarVersion: 0,+ aboutMe: data.aboutMe ?? "",+ bannerColor: data.bannerColor ?? null,+ statusEmoji: data.statusEmoji ?? null,+ statusText: data.statusText ?? "",+ identity: id === "b1"+ ? { kind: "bot", ownerProfile: { id: "u1" } }+ : { kind: "human" },+ }+ })})it("accepts a valid hex bannerColor", async () => {@@ -223,36 +245,18 @@ describe("PATCH /api/community/users/me/profile", () => {)})- it("rename broadcasts MEMBER_UPDATE with userId + the new nickname to every server the user belongs to", async () => {- listMemberServerIds.mockResolvedValue(["srv_a", "srv_b"])- getMemberships.mockResolvedValue([- { id: "mem_a", serverId: "srv_a", userId: "u1" },- { id: "mem_b", serverId: "srv_b", userId: "u1" },- ])-+ it("rename broadcasts the canonical profile update", async () => {const res = await PATCH(patchReq({ name: "New" }), {} as never)expect(res.status).toBe(200)- expect(fanOutToServerMembers).toHaveBeenCalledTimes(2)- expect(fanOutToServerMembers).toHaveBeenCalledWith("srv_a", expect.objectContaining({- type: "community:member.update",- serverId: "srv_a",- memberId: "mem_a",- userId: "u1",- changes: { nickname: "New" },- }))- expect(fanOutToServerMembers).toHaveBeenCalledWith("srv_b", expect.objectContaining({- type: "community:member.update",- serverId: "srv_b",- memberId: "mem_b",- userId: "u1",- changes: { nickname: "New" },- }))+ expect(fanOutProfileUpdate).toHaveBeenCalledWith(+ expect.objectContaining({ id: "u1", name: "New" }),+ )})- it("rename with no server memberships broadcasts nothing", async () => {- const res = await PATCH(patchReq({ name: "New" }), {} as never)+ it("status-only updates do not broadcast a profile frame", async () => {+ const res = await PATCH(patchReq({ statusText: "Busy" }), {} as never)expect(res.status).toBe(200)- expect(fanOutToServerMembers).not.toHaveBeenCalled()+ expect(fanOutProfileUpdate).not.toHaveBeenCalled()})it("forwards the Set-Cookie headers from auth.api.updateUser on the response", async () => {@@ -273,16 +277,31 @@ describe("PATCH /api/community/users/me/profile", () => {})it("returns shape consistent with GET (no userId leak)", async () => {- updateProfile.mockResolvedValue({+ getPublicProfileForViewer.mockResolvedValue({+ id: "u1",+ name: "Jane Roe",+ discriminator: "4242",+ image: null,+ avatarVersion: 0,aboutMe: "hi",bannerColor: "#aabbcc",statusEmoji: null,- statusText: null,- userId: "u1",+ statusText: "",+ identity: { kind: "human" },})const res = await PATCH(patchReq({ aboutMe: "hi" }), {} as never)const body = await res.json()- expect(body).toEqual({ aboutMe: "hi", bannerColor: "#aabbcc", statusEmoji: null, statusText: "" })+ expect(body).toEqual({+ id: "u1",+ name: "Jane Roe",+ discriminator: "4242",+ avatar: "J",+ avatarVersion: 0,+ aboutMe: "hi",+ bannerColor: "#aabbcc",+ statusEmoji: null,+ statusText: "",+ })expect(body).not.toHaveProperty("userId")})@@ -322,7 +341,7 @@ describe("PATCH /api/community/users/me/profile", () => {it("calls fanOutStatusUpdate when statusEmoji/statusText change", async () => {const res = await PATCH(patchReq({ statusEmoji: "π§", statusText: "Vibing" }), {} as never)expect(res.status).toBe(200)- expect(fanOutStatusUpdate).toHaveBeenCalledWith("u1", "π§", "Vibing")+ expect(fanOutStatusUpdate).toHaveBeenCalledWith("u1", "π§", "Vibing", null)})it("allows a bot to update only its own public bio", async () => {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 8cb7926fb..227599f40 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@@ -5,7 +5,6 @@ import {MAX_STATUS_TEXT_LENGTH,MAX_EMOJI_BYTES,BANNER_COLOR_REGEX,- WS_EVENTS,validateCommunityName,withD1Retry,} from "@alook/shared"@@ -13,8 +12,9 @@ import { getDb } from "@/lib/db"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 { fanOutProfileUpdate, fanOutStatusUpdate } from "@/lib/community/fanout"import { canonicalUserImage } from "@/lib/community/storage"+import { avatarInitial } from "@/lib/community/avatar"export const GET = withCommunityActor(async (_req, ctx) => {const db = getDb(ctx.env.DB)@@ -29,16 +29,17 @@ export const GET = withCommunityActor(async (_req, ctx) => {{ route: "community/profile:self-user" }),])+ const name = viewer?.name ?? ""return writeJSON({id: userId,aboutMe: profile?.aboutMe ?? "",avatar: viewer- ? canonicalUserImage(viewer.id, viewer.image, viewer.avatarVersion) ?? ""- : "",+ ? canonicalUserImage(viewer.id, viewer.image, viewer.avatarVersion) ?? avatarInitial(name)+ : avatarInitial(name),avatarVersion: viewer?.avatarVersion ?? 0,bannerColor: profile?.bannerColor ?? null,discriminator: viewer?.discriminator ?? "0000",- name: viewer?.name ?? "",+ name,statusEmoji: profile?.statusEmoji ?? null,statusText: profile?.statusText ?? "",})@@ -106,22 +107,6 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {})) as { headers: Headers }renameCookieHeaders = result.headers- // Broadcast the new name to every server the user belongs to, so open- // member lists update without a refresh (previously nothing fired- // MEMBER_UPDATE for a self-rename β only role changes did).- const serverIds = await queries.communityMember.listMemberServerIds(db, userId)- if (serverIds.length > 0) {- const memberships = await queries.communityMember.getMemberships(db, userId, serverIds)- for (const membership of memberships) {- fanOutToServerMembers(membership.serverId, {- type: WS_EVENTS.MEMBER_UPDATE,- serverId: membership.serverId,- memberId: membership.id,- userId,- changes: { nickname: trimmed },- })- }- }}const data: {@@ -172,38 +157,57 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {}}- let updated: {- aboutMe: string | null- bannerColor: string | null- statusEmoji: string | null- statusText: string | null- } | null = nullif (data.aboutMe !== undefined ||data.bannerColor !== undefined ||data.statusEmoji !== undefined ||data.statusText !== undefined) {- updated = await queries.communityUserProfile.updateProfile(db, userId, data)+ await queries.communityUserProfile.updateProfile(db, userId, data)}+ const canonical = await queries.communityUserProfile.getPublicProfileForViewer(+ db,+ userId,+ userId,+ )+ if (!canonical) return writeError("user not found", 404)+// Fan out only when a status field was actually part of this patch β a// plain aboutMe-only save must not trigger a broadcast.if (data.statusEmoji !== undefined || data.statusText !== undefined) {await fanOutStatusUpdate(userId,- updated?.statusEmoji ?? null,- updated?.statusText ?? null,+ canonical.statusEmoji,+ canonical.statusText,+ ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : null,)}+ if (+ body.name !== undefined+ || data.aboutMe !== undefined+ || data.bannerColor !== undefined+ ) {+ await fanOutProfileUpdate(canonical)+ }+// Normalise the response shape β same as GET β so callers don't see// `userId` leak through on PATCH.const res = writeJSON({- aboutMe: updated?.aboutMe ?? "",- bannerColor: updated?.bannerColor ?? null,- statusEmoji: updated?.statusEmoji ?? null,- statusText: updated?.statusText ?? "",+ id: canonical.id,+ name: canonical.name,+ discriminator: canonical.discriminator,+ avatar: canonicalUserImage(+ canonical.id,+ canonical.image,+ canonical.avatarVersion,+ ) ?? avatarInitial(canonical.name),+ avatarVersion: canonical.avatarVersion,+ aboutMe: canonical.aboutMe,+ bannerColor: canonical.bannerColor,+ statusEmoji: canonical.statusEmoji,+ statusText: canonical.statusText,})// Forward the re-signed session cookies from a rename so the browserdiff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex 74e8c24ad..cd2202955 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -12,6 +12,8 @@ import {} from "@/lib/query-persister"import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"+import { useCommunityWsStore } from "@/stores/community/ws"+import { seedPersistedMessageProfiles } from "@/lib/community/profile-seed"/*** Owns the TanStack QueryClient for the community subtree.@@ -34,6 +36,9 @@ export function QueryProvider({children: ReactNodeuserId: string | null}) {+ const profiles = useCommunityWsStore.getState()+ profiles.activateProfileAccount(userId)+ const restoreProfileSnapshot = useRef(profiles.beginProfileSnapshot()).currentconst [queryClient] = useState(() => createQueryClient())// Persister is bound to the userId at construction; on account switch the// whole community subtree unmounts and the shell re-renders with the new@@ -59,6 +64,7 @@ export function QueryProvider({return (<PersistQueryClientProviderclient={queryClient}+ onSuccess={() => seedPersistedMessageProfiles(queryClient, restoreProfileSnapshot)}persistOptions={{persister,maxAge: PERSIST_MAX_AGE_MS,diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex a9272ee05..696bcb540 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -25,7 +25,7 @@ import { ImageCropDialog } from "@/components/community/image-crop-dialog"import { validateIconSourceFile } from "@/lib/community/image-crop"import type { SettingsSection } from "@/components/community/settings/settings-types"import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"-import { resolveRowPresence } from "@/lib/community/presence"+import { readCommunityProfile } from "@/lib/community/profile-read"import {useCommunityStore,useCurrentChannelId,@@ -48,7 +48,7 @@ import {useForumSidebarThreads,type ForumSidebarThread,} from "@/hooks/community/use-forum-sidebar-threads"-import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { useCommunityWsStore } from "@/stores/community/ws"import {resolveServerNotificationDisplayLevel,useNotificationSettings,@@ -89,27 +89,29 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const currentUser = useCurrentUser()const { server: currentServer } = useServer(serverId)const membersHook = useServerMembers(serverId)- const onlineUserIds = useOnlineUserIds()- const userStatuses = useCommunityWsStore((s) => s.userStatuses)+ const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)const enrichedMembers = useMemo(() =>membersHook.members.map((m) => {- const liveStatus = userStatuses.get(m.userId)+ const profile = readCommunityProfile(profilesByUserId.get(m.userId), m.userId)return {...m,- status: resolveRowPresence(m, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,- statusText: liveStatus ? liveStatus.text : m.statusText,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: m.userId === currentUser.id ? "online" as const : profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,}}),- [membersHook.members, onlineUserIds, currentUser.id, userStatuses],+ [currentUser.id, membersHook.members, profilesByUserId],)// `myMember` comes from the raw (not enriched) members list so this stays// stable across presence ticks.const myMember = membersHook.members.find((m) => m.userId === currentUser.id)const isAdmin = canManageServer(myMember?.role)- const presence = usePresence(serverId)- const { online: initialOnline } = presence+ usePresence(serverId)const notifs = useNotificationSettings()const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])const channelNotif = notifs.channel@@ -210,23 +212,6 @@ export default function ServerLayout({ children }: { children: ReactNode }) {ejectedRef.current = false}, [serverId])- // Seed the presence set on server switch β WS `presence.update` keeps it- // fresh after this initial hydration. `hydratePresence` is an atomic- // one-shot replacement AND no-ops when the incoming list matches current- // state β critical to avoid a render loop when `initialOnline`'s reference- // shifts on re-render (loading state, cache tick) without semantic change.- //- // Guard against seeding from a non-authoritative snapshot: while the query- // is still fetching, or when the presence route degraded to `stale: true`- // (retry-exhaust on D1 β `keepPreviousData` bubbles a StaleReadError, so- // `presence.data` is `undefined` on first-load-during-outage), we must NOT- // atomically wipe the WS-populated set to an empty list.- useEffect(() => {- if (presence.isFetching) return- if (presence.data === undefined) return- useCommunityWsStore.getState().hydratePresence(initialOnline)- }, [presence.isFetching, presence.data, initialOnline])-const [serverSettingsOpen, setServerSettingsOpen] = useState(false)const [settingsSection, setSettingsSection] = useState<SettingsSection>("overview")const [invitePopoverOpen, setInvitePopoverOpen] = useState(false)diff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.tsindex 46b7d497f..b35d90a4a 100644--- a/src/web/src/app/c/community-shell.identity.test.ts+++ b/src/web/src/app/c/community-shell.identity.test.ts@@ -7,48 +7,16 @@ type TestUser = {name: stringemail: stringavatar: string- avatarVersion?: number- aboutMe?: string- discriminator?: string- statusEmoji?: string | null- statusText?: string | null-}--type ProfileResponse = {- id?: string- aboutMe: string- avatar: string- avatarVersion: number- discriminator: string- name: string- statusEmoji: string | null- statusText: string}let activeUser: TestUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }let providerInstance = 0const renderedProviders: Array<{ userId: string | null; instance: number }> = []-const { apiFetch } = vi.hoisted(() => ({- apiFetch: vi.fn<() => Promise<ProfileResponse>>(),-}))-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,-}))+const apiFetchProfiles = vi.hoisted(() => vi.fn(() => Promise.resolve({})))vi.mock("./QueryProvider", () => ({QueryProvider: ({ children, userId }: { children: React.ReactNode; userId: string | null }) => {- const [instance] = useState(() => {- providerInstance += 1- return providerInstance- })+ const [instance] = useState(() => ++providerInstance)renderedProviders.push({ userId, instance })return children},@@ -56,32 +24,31 @@ vi.mock("./QueryProvider", () => ({vi.mock("@/contexts/community/current-user", () => ({CurrentUserProvider: ({ children }: { children: React.ReactNode }) => children,useCurrentUser: () => activeUser,- useSetCurrentUser: () => setCurrentUser,}))vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))-vi.mock("@/lib/api/client", () => ({ apiFetch }))+vi.mock("@/lib/community/profile-seed", () => ({+ apiFetchProfiles: (...args: unknown[]) => apiFetchProfiles(...args),+}))vi.mock("@/components/perf/perf-trace-bootstrap", () => ({ PerfTraceBootstrap: () => null }))vi.mock("@/components/community/onboarding/community-onboarding-guide", () => ({CommunityOnboardingGuide: () => null,}))+vi.mock("@/components/community/shell/community-ws-reconnect-overlay", () => ({+ CommunityWsReconnectBoundary: ({ children }: { children: React.ReactNode }) => children,+}))import { CommunityShell } from "./community-shell"-import { useCommunityWsStore } from "@/stores/community/ws"beforeEach(() => {activeUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }providerInstance = 0renderedProviders.length = 0- apiFetch.mockReset()- apiFetch.mockImplementation(() => new Promise(() => undefined))- setCurrentUser.mockClear()- queryClient.setQueriesData.mockReset()- queryClient.invalidateQueries.mockReset()- useCommunityWsStore.getState().reset()+ apiFetchProfiles.mockReset()+ apiFetchProfiles.mockResolvedValue({})})describe("CommunityShell identity boundary", () => {- it("remounts the in-memory query client boundary when the signed-in user changes", () => {+ it("remounts the in-memory query boundary when the signed-in user changes", () => {let renderer!: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(React.createElement(@@ -90,7 +57,7 @@ describe("CommunityShell identity boundary", () => {React.createElement("span", null, "content"),))})- const userAInstance = renderedProviders.at(-1)?.instance+ expect(renderedProviders.at(-1)).toEqual({ userId: "user-a", instance: 1 })activeUser = { id: "user-b", name: "B", email: "[email protected]", avatar: "B" }act(() => {@@ -100,24 +67,11 @@ describe("CommunityShell identity boundary", () => {React.createElement("span", null, "content"),))})-expect(renderedProviders.at(-1)).toEqual({ userId: "user-b", instance: 2 })- expect(userAInstance).toBe(1)renderer.unmount()})- it("hydrates a stale session name from the canonical self profile", async () => {- activeUser = { id: "user-a", name: "Alice", email: "[email protected]", avatar: "old-avatar" }- apiFetch.mockResolvedValueOnce({- aboutMe: "hello",- avatar: "new-avatar",- avatarVersion: 3,- discriminator: "4242",- name: "Jane Roe",- statusEmoji: "π±",- statusText: "Growing",- })-+ it("loads the canonical self profile through the typed seeding boundary", async () => {let renderer!: TestRenderer.ReactTestRendererawait act(async () => {renderer = TestRenderer.create(React.createElement(@@ -128,92 +82,30 @@ describe("CommunityShell identity boundary", () => {await Promise.resolve()})- expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/profile")- expect(setCurrentUser).toHaveBeenCalledOnce()- expect(activeUser).toMatchObject({+ expect(apiFetchProfiles).toHaveBeenCalledWith(+ "/api/community/users/me/profile",+ expect.any(Function),+ )+ const mapProfile = apiFetchProfiles.mock.calls[0]![1] as (profile: Record<string, unknown>) => unknown+ expect(mapProfile({+ id: "user-a",name: "Jane Roe",+ discriminator: "4242",aboutMe: "hello",avatar: "new-avatar",avatarVersion: 3,- discriminator: "4242",- statusEmoji: "π±",- statusText: "Growing",- })- renderer.unmount()- })-- it("preserves the session name when the self profile has no canonical name", async () => {- activeUser = { id: "user-a", name: "Alice", email: "[email protected]", avatar: "old-avatar" }- apiFetch.mockResolvedValueOnce({- aboutMe: "hello",- avatar: "",- avatarVersion: 0,- discriminator: "4242",- name: "",- 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()- })-- expect(activeUser).toMatchObject({- name: "Alice",- aboutMe: "hello",- avatar: "old-avatar",- discriminator: "4242",statusEmoji: null,statusText: "",- })- 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({+ })).toEqual([{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,- })+ identityAbout: {+ name: "Jane Roe",+ discriminator: "4242",+ aboutMe: "hello",+ },+ avatar: { avatar: "new-avatar", avatarVersion: 3 },+ status: { statusEmoji: null, statusText: "" },+ }])renderer.unmount()})})diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 9fcf4bcc7..4e81f832b 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -1,22 +1,14 @@"use client"import { useEffect, type ReactNode } from "react"-import { useQueryClient } from "@tanstack/react-query"-import {- apiFetchIdentity,- projectIdentityPayload,-} from "@/lib/community/identity-projection"-import { communityKeys } from "@/lib/query-keys"+import { apiFetchProfiles } from "@/lib/community/profile-seed"import { QueryProvider } from "./QueryProvider"import {CurrentUserProvider,useCurrentUser,- useSetCurrentUser,type CurrentUser,} 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"@@ -58,13 +50,7 @@ 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@@ -76,66 +62,27 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {// row alongside the community profile fields.const currentUserId = currentUser.iduseEffect(() => {- apiFetchIdentity<{ id: string; aboutMe: string; avatar: string; avatarVersion: number; discriminator: string; name: string; statusEmoji: string | null; statusText: string }>(+ apiFetchProfiles<{ id: string; aboutMe: string; avatar: string; avatarVersion: number; discriminator: string; name: string; statusEmoji: string | null; statusText: string }>("/api/community/users/me/profile",+ (profile) => [{+ id: profile.id,+ identityAbout: {+ name: profile.name,+ discriminator: profile.discriminator,+ aboutMe: profile.aboutMe,+ },+ avatar: {+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ },+ status: {+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ },+ }],)- .then((data) => {- const avatarVersion = Number.isSafeInteger(data.avatarVersion)- ? data.avatarVersion- : 0- setCurrentUser((u) => ({- ...u,- aboutMe: data.aboutMe,- 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,- statusText: data.statusText,- }))- // Member/friend-list surfaces read status from the WS store overlay- // (see e.g. channels/layout.tsx), not from CurrentUser β seed it here- // too so the viewer's own rows in those lists match on first load.- useCommunityWsStore.getState().setUserStatus(currentUserId, data.statusEmoji, data.statusText)- }).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])+ }, [currentUserId])return (<>diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 5227e0ddc..a29c97016 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -20,9 +20,9 @@ import {useTypingUsersForScope,useTypingNamesForScope,} from "@/stores/community"-import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"+import { useCommunityWsStore } from "@/stores/community/ws"import { tid } from "@/lib/community/testids"-import { resolveRowPresence } from "@/lib/community/presence"+import { readCommunityProfile } from "@/lib/community/profile-read"import { makeUserNameResolver } from "@/lib/community/display-name"import { dmsQueryFn, type DmsResponse } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"@@ -110,22 +110,26 @@ function DmView() {const dms = dmsQuery.data?.conversations ?? EMPTY_DMSconst dmsLoading = dmsQuery.isLoadingconst { friends: rawFriends, blocked } = useFriends()- const onlineUserIds = useOnlineUserIds()- const userStatuses = useCommunityWsStore((s) => s.userStatuses)+ const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)// Enrich with presence β the Composer @-picker uses `f.status` to render// the avatar presence dot; without this enrichment every avatar shows offline.const friends = useMemo(() =>rawFriends.map((f) => {- const liveStatus = userStatuses.get(f.userId ?? f.id)+ const userId = f.userId ?? f.id+ const profile = readCommunityProfile(profilesByUserId.get(userId), userId)return {...f,- status: resolveRowPresence(f, onlineUserIds),- statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,- statusText: liveStatus ? liveStatus.text : f.statusText,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,}}),- [rawFriends, onlineUserIds, userStatuses],+ [profilesByUserId, rawFriends],)// Frozen-once snapshot of the viewer's DM read pointer β the anchor for// the "New" divider AND the initial-page mode. Mirrors the channel-view@@ -318,11 +322,19 @@ function DmView() {const dm = useMemo(() => {const raw = dms.find((d) => d.id === dmId) ?? nullif (!raw) return null+ const profile = readCommunityProfile(+ profilesByUserId.get(raw.userId),+ raw.userId,+ )return {...raw,- status: resolveRowPresence(raw, onlineUserIds),+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,}- }, [dms, dmId, onlineUserIds])+ }, [dms, dmId, profilesByUserId])const openProfile: OpenProfile = (name, e, discriminator, userId) => {uiHandlers.openProfile?.(name, e, discriminator, userId)diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsxindex 3dd3c325c..07ecc79cc 100644--- a/src/web/src/app/c/me/friends/page.tsx+++ b/src/web/src/app/c/me/friends/page.tsx@@ -5,8 +5,8 @@ import { FriendsPage } from "@/components/community/social/friends-page"import { useMemo } from "react"import { useFriends } from "@/hooks/community/use-friends"import { useUiHandlers } from "@/stores/community"-import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"-import { resolveRowPresence } from "@/lib/community/presence"+import { useCommunityWsStore } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"import {useSendFriendRequest,useAcceptFriendRequest,@@ -24,20 +24,24 @@ export default function MeFriendsPage() {const bp = useBreakpoint()const { friends: rawFriends, pending, blocked, isLoading } = useFriends()const uiHandlers = useUiHandlers()- const onlineUserIds = useOnlineUserIds()- const userStatuses = useCommunityWsStore((s) => s.userStatuses)+ const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)const friends = useMemo(() =>rawFriends.map((f) => {- const liveStatus = userStatuses.get(f.userId ?? f.id)+ const userId = f.userId ?? f.id+ const profile = readCommunityProfile(profilesByUserId.get(userId), userId)return {...f,- status: resolveRowPresence(f, onlineUserIds),- statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,- statusText: liveStatus ? liveStatus.text : f.statusText,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,}}),- [rawFriends, onlineUserIds, userStatuses],+ [profilesByUserId, rawFriends],)const sendFriendRequest = useSendFriendRequest()diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 82d70437f..fbd3204b8 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -17,8 +17,8 @@ import { useDms } from "@/hooks/community/use-dms"import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"import { communityKeys } from "@/lib/query-keys"-import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"-import { resolveRowPresence } from "@/lib/community/presence"+import { useCommunityWsStore } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"import {clearLastMeLocation,getLastMeLeaf,@@ -46,14 +46,21 @@ export default function MeLayout({ children }: { children: ReactNode }) {} = useDms()const canonicalDmsUnsettled = dmsPending || dmsFetchingconst dmRouteVerification = useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)- const onlineUserIds = useOnlineUserIds()+ const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)const dms = useMemo(() =>- rawDms.map((d) => ({- ...d,- status: resolveRowPresence(d, onlineUserIds),- })),- [rawDms, onlineUserIds],+ rawDms.map((d) => {+ const profile = readCommunityProfile(profilesByUserId.get(d.userId), d.userId)+ return {+ ...d,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ }+ }),+ [profilesByUserId, rawDms],)const { blocked } = useFriends()const currentChannelId = useCurrentChannelId()@@ -69,17 +76,9 @@ export default function MeLayout({ children }: { children: ReactNode }) {useCommunityStore.getState().setCurrentServerId(null)}, [])- // Seed the presence set for the friends/DM subtree. This fetch carries ONLY- // friends β a strict subset of the WS presence audience (co-members βͺ- // friends). It must MERGE, not replace: a destructive `hydratePresence` here- // would evict a DM peer who is a co-member-but-not-friend that the WS snapshot- // had already marked online, flipping them onlineβoffline ~1s after load (the- // DM presence flicker bug). `mergePresence` unions instead, so WS-delivered- // ids survive. It no-ops when every id is already present.- const { online: onlineFriendIds } = useFriendsPresence()- useEffect(() => {- useCommunityWsStore.getState().mergePresence(onlineFriendIds)- }, [onlineFriendIds])+ // Seed online friends into the global profile map. The endpoint is a subset+ // of the full WS audience, so it only patches the ids it explicitly returns.+ useFriendsPresence()const machinesActive = pathname === "/c/me/machines"const botsActive = pathname === "/c/me/bots"diff --git a/src/web/src/components/community/bots/bot-activity-modal.test.ts b/src/web/src/components/community/bots/bot-activity-modal.test.tsindex 03e50e579..f249f1699 100644--- a/src/web/src/components/community/bots/bot-activity-modal.test.ts+++ b/src/web/src/components/community/bots/bot-activity-modal.test.ts@@ -40,7 +40,7 @@ vi.mock("@/components/avatar", () => ({}))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => new Set(["bot-1"]),+ useCommunityProfile: () => ({ presence: "online" }),}))vi.mock("@/hooks/community/use-bot-audit-log", () => ({diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsxindex 6b56328d8..db847d3b7 100644--- a/src/web/src/components/community/bots/bot-activity-modal.tsx+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx@@ -3,7 +3,7 @@import { useLayoutEffect, useMemo, useRef, useEffect } from "react"import { AgentAvatar } from "@/components/avatar"import { CommunitySheet } from "@/components/community/shell/community-sheet"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useCommunityProfile } from "@/stores/community/ws"import {useBotAuditLog,type AuditEvent,@@ -41,7 +41,8 @@ export function BotActivityModal({// presence). A viewer with a broken WS wouldn't receive events either, but// the daemon-side signal is what determines whether new rows are actually// being produced right now.- const online = useOnlineUserIds().has(bot?.id ?? "")+ const profile = useCommunityProfile(bot?.id)+ const online = profile?.presence === "online"const {events,isLoading,diff --git a/src/web/src/components/community/bots/bot-list-card.test.ts b/src/web/src/components/community/bots/bot-list-card.test.tsindex cd94e68e2..945822512 100644--- a/src/web/src/components/community/bots/bot-list-card.test.ts+++ b/src/web/src/components/community/bots/bot-list-card.test.ts@@ -28,7 +28,7 @@ vi.mock("@/hooks/community/mutations", () => ({useCreateOrGetDm: () => ({ mutateAsync: vi.fn() }),}))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => new Set<string>(),+ useProfilesByUserId: () => new Map(),}))function passthrough(name: string) {diff --git a/src/web/src/components/community/bots/bot-list-controller.test.ts b/src/web/src/components/community/bots/bot-list-controller.test.tsindex 89cc0eaca..b6ad6403d 100644--- a/src/web/src/components/community/bots/bot-list-controller.test.ts+++ b/src/web/src/components/community/bots/bot-list-controller.test.ts@@ -83,9 +83,9 @@ vi.mock("@/hooks/community/use-machines", () => ({},}))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => {- mocks.hookOrder.push("online")- return mocks.online+ useProfilesByUserId: () => {+ mocks.hookOrder.push("profiles")+ return new Map([...mocks.online].map((id) => [id, { id, presence: "online" }]))},}))vi.mock("@/hooks/community/mutations", () => ({@@ -181,7 +181,7 @@ describe("useBotListController", () => {"searchParams","bots","machines",- "online",+ "profiles","delete","resetBot","resetMachine",@@ -198,7 +198,7 @@ describe("useBotListController", () => {"const searchParams = useSearchParams()","const botsQuery = useBots()","const { machines, isLoading: machinesLoading } = useMachines()",- "const onlineUserIds = useOnlineUserIds()",+ "const profilesByUserId = useProfilesByUserId()","const [createOpen","const [editingBot","const [editOpen",diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.tsindex 408e7b631..341bd216f 100644--- a/src/web/src/components/community/bots/bot-list-controller.ts+++ b/src/web/src/components/community/bots/bot-list-controller.ts@@ -16,7 +16,7 @@ import {type BotSummary,} from "@/hooks/community/use-bots"import { useCreateOrGetDm } from "@/hooks/community/mutations"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useProfilesByUserId } from "@/stores/community/ws"import {advanceCommunityOnboarding,readCommunityOnboardingState,@@ -33,7 +33,7 @@ export function useBotListController(): BotListController {const { bots, isLoading } = botsQueryconst botsResolved = botsQuery.data !== undefinedconst { machines, isLoading: machinesLoading } = useMachines()- const onlineUserIds = useOnlineUserIds()+ const profilesByUserId = useProfilesByUserId()const [createOpen, setCreateOpen] = useState(false)const [editingBot, setEditingBot] = useState<BotSummary | null>(null)const [editOpen, setEditOpen] = useState(false)@@ -256,7 +256,7 @@ export function useBotListController(): BotListController {isLoading,machines,machinesLoading,- onlineUserIds,+ profilesByUserId,createOpen,setCreateOpen,editingBot,diff --git a/src/web/src/components/community/bots/bot-list-machine-group.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.test.tsindex 9666ab017..4bdad8938 100644--- a/src/web/src/components/community/bots/bot-list-machine-group.test.ts+++ b/src/web/src/components/community/bots/bot-list-machine-group.test.ts@@ -73,7 +73,7 @@ const bot = (overrides: Partial<BotSummary> = {}): BotSummary => ({function controller(overrides: Partial<BotListController> = {}): BotListController {const noop = vi.fn()return {- onlineUserIds: new Set(),+ profilesByUserId: new Map(),collapsedMachines: new Set(),setCollapsedMachines: noop,setConfirmResetMachine: noop,@@ -160,7 +160,7 @@ describe("renderBotMachineGroup", () => {act(() => {renderer = TestRenderer.create(renderBotMachineGroup(group({ machine: { id: "mac1", displayName: "My Mac", status: "online" } as BotMachineGroup["machine"] }),- controller({ onlineUserIds: new Set(), setConfirmResetMachine }),+ controller({ profilesByUserId: new Map(), setConfirmResetMachine }),))})expect(renderer.root.findAll((node) =>@@ -175,7 +175,7 @@ describe("renderBotMachineGroup", () => {act(() => {renderer.update(renderBotMachineGroup(group({ machine: { id: "mac1", displayName: "My Mac", status: "offline" } as BotMachineGroup["machine"] }),- controller({ onlineUserIds: new Set(), setConfirmResetMachine }),+ controller({ profilesByUserId: new Map(), setConfirmResetMachine }),))})expect(renderer.root.findAll((node) =>@@ -262,7 +262,7 @@ describe("renderBotMachineGroup", () => {act(() => {renderer = TestRenderer.create(renderBotMachineGroup(group(),- controller({ onlineUserIds: new Set(["b1"]) }),+ controller({ profilesByUserId: new Map([["b1", { id: "b1", presence: "online" }]]) }),))})expect(renderer.root.findAll((node) => node.children.includes("Online"))).not.toHaveLength(0)@@ -392,12 +392,15 @@ describe("renderBotMachineGroup", () => {expect(setConfirmDelete).toHaveBeenCalledWith(item)})- it("uses onlineUserIds for bot status and omits reconnect for unknown machines", () => {+ it("uses the global profile for bot status and omits reconnect for unknown machines", () => {let renderer!: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(renderBotMachineGroup(group({ machine: null }),- controller({ onlineUserIds: new Set(["b1"]), machineName: () => "Unknown machine" }),+ controller({+ profilesByUserId: new Map([["b1", { id: "b1", presence: "online" }]]),+ machineName: () => "Unknown machine",+ }),))})expect(renderer.root.findAll((node) => node.children.includes("Online"))).not.toHaveLength(0)diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsxindex 5ca9953c2..3a923d78f 100644--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx@@ -85,7 +85,7 @@ export function renderBotMachineGroup(</div><div className="flex flex-col gap-3" hidden={collapsed}>{bots.map((bot) => {- const online = controller.onlineUserIds.has(bot.id)+ const online = controller.profilesByUserId.get(bot.id)?.presence === "online"return (<Card key={bot.id} className="flex flex-col gap-3 p-4"><div className="flex items-start justify-between gap-3">diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.tsindex c8db1c9b8..261629b55 100644--- a/src/web/src/components/community/bots/bot-list-types.ts+++ b/src/web/src/components/community/bots/bot-list-types.ts@@ -1,6 +1,7 @@import type { Dispatch, SetStateAction } from "react"import type { BotSummary } from "@/hooks/community/use-bots"import type { MachineSummary } from "@/hooks/community/use-machines"+import type { CommunityProfile } from "@/lib/community/models/people"export type BotListProps = {onBack?: () => void@@ -17,7 +18,7 @@ export type BotListController = {isLoading: booleanmachines: MachineSummary[]machinesLoading: boolean- onlineUserIds: ReadonlySet<string>+ profilesByUserId: ReadonlyMap<string, CommunityProfile>createOpen: booleansetCreateOpen: Dispatch<SetStateAction<boolean>>editingBot: BotSummary | nulldiff --git a/src/web/src/components/community/bots/bot-list-view.test.ts b/src/web/src/components/community/bots/bot-list-view.test.tsindex e6d053b5b..6b2d1f18f 100644--- a/src/web/src/components/community/bots/bot-list-view.test.ts+++ b/src/web/src/components/community/bots/bot-list-view.test.ts@@ -49,7 +49,7 @@ function controller(overrides: Partial<BotListController> = {}): BotListControllisLoading: false,machines: [],machinesLoading: false,- onlineUserIds: new Set(),+ profilesByUserId: new Map(),createOpen: false,setCreateOpen: noop,editingBot: null,diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.tsindex c94cf8130..1223b7b9a 100644--- a/src/web/src/components/community/channels/forum-view.test.ts+++ b/src/web/src/components/community/channels/forum-view.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from "vitest"+import { describe, it, expect, vi } from "vitest"import { readFileSync } from "node:fs"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"@@ -11,6 +11,11 @@ import {import { tid } from "@/lib/community/testids"import type { ForumThread } from "@/lib/community/models/message"+const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unknown>>() }))+vi.mock("@/stores/community/ws", () => ({+ useProfilesByUserId: () => profileState.map,+}))+const LAST_AT = "2020-01-01T00:00:00.000Z"function makePost(over: Partial<ForumThread> = {}): ForumThread {@@ -32,6 +37,22 @@ function makePost(over: Partial<ForumThread> = {}): ForumThread {}function render(posts: ForumThread[]): string {+ profileState.map = new Map(posts.flatMap((post) => [+ ...(post.authorId && post.parent.authorName+ ? [[post.authorId, {+ id: post.authorId,+ name: post.parent.authorName,+ avatar: post.authorAvatar ?? post.parent.authorName,+ avatarVersion: 0,+ }] as const]+ : []),+ ...(post.participants ?? []).map((participant) => [participant.id, {+ id: participant.id,+ name: participant.name,+ avatar: participant.avatar,+ avatarVersion: participant.avatarVersion ?? 0,+ }] as const),+ ]))return renderToStaticMarkup(createElement(ForumView, {forumChannelId: "cha_forum",@@ -147,9 +168,9 @@ describe("ForumView post card header", () => {expect(html.indexOf('aria-hidden="true">Β·</span>')).toBeLessThan(html.indexOf(groupTid))})- it("falls back to \"Unknown\" when the creator name is empty (deleted creator)", () => {+ it("uses canonical participant identity when the opener snapshot name is empty", () => {const html = render([makePost({ parent: { authorName: "", text: "root" } })])- expect(html).toContain(">Unknown<")+ expect(html).toContain(">Alice<")})it("renders the time separator for both a solo post and a post with others", () => {diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsxindex 3f6e39e7b..cd4e1bcdb 100644--- a/src/web/src/components/community/channels/forum-view.tsx+++ b/src/web/src/components/community/channels/forum-view.tsx@@ -23,6 +23,8 @@ import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-simport { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"import { cn } from "@/lib/utils"import { FORUM_ARCHIVE_TAG } from "@alook/shared"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"const MAX_AVATARS = 5const MAX_VISIBLE_TAGS = 2@@ -221,6 +223,7 @@ export function ForumView({deletingPost?: string | nullonScrollRoot?: (node: HTMLDivElement | null) => void}) {+ const profilesByUserId = useProfilesByUserId()const [composing, setComposing] = useState(false)const [deletingFor, setDeletingFor] = useState<ForumThread | null>(null)const [tagFades, setTagFades] = useState({ left: false, right: false })@@ -419,6 +422,10 @@ export function ForumView({renderItem={(p, index) => {const canEdit = !!onEditPostTags && (canEditPostTags?.(p) ?? false)const canDelete = !!onDeletePost && (canDeletePost?.(p) ?? false)+ const author = readCommunityProfile(+ profilesByUserId.get(p.authorId),+ p.authorId,+ )const others = p.participants.filter((m) => m.id !== p.authorId)const shown = others.slice(0, MAX_AVATARS)const participantTotal = p.participantCount ?? others.length + 1@@ -490,8 +497,8 @@ export function ForumView({</div><p className="mb-2.25 mt-0.75 line-clamp-2 text-[13.5px] text-muted-foreground">{p.preview}</p><div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 text-xs text-muted-foreground">- <Avatar label={p.authorAvatar} seed={p.authorId} size={20} />- <span className="shrink-0 font-medium text-foreground" suppressHydrationWarning>{p.parent.authorName || "Unknown"}</span>+ <Avatar label={author.avatar} seed={p.authorId} size={20} />+ <span className="shrink-0 font-medium text-foreground" suppressHydrationWarning>{author.name}</span><span className="shrink-0" aria-hidden>Β·</span><span className="shrink-0" suppressHydrationWarning>{formatRelativeTime(p.lastMessageAt)}</span>{p.tags.length > 0 && <span className="shrink-0 max-sm:hidden" aria-hidden>Β·</span>}@@ -499,9 +506,15 @@ export function ForumView({<span className="ml-auto flex shrink-0 items-center gap-2">{others.length > 0 && (<AvatarGroup className="-space-x-1.25" data-testid={tid.forumThreadAvatars(p.id)}>- {shown.map((member) => (- <Avatar key={member.id} label={member.avatar} seed={member.id} size={19} ringColor="var(--background)" />- ))}+ {shown.map((member) => {+ const profile = readCommunityProfile(+ profilesByUserId.get(member.id),+ member.id,+ )+ return (+ <Avatar key={member.id} label={profile.avatar} seed={member.id} size={19} ringColor="var(--background)" />+ )+ })}{overflow > 0 && <AvatarGroupCount className="size-4.75 text-[10px]">+{overflow}</AvatarGroupCount>}</AvatarGroup>)}diff --git a/src/web/src/components/community/members/channel-member-view-model.test.ts b/src/web/src/components/community/members/channel-member-view-model.test.tsindex 608a3e690..f153092f7 100644--- a/src/web/src/components/community/members/channel-member-view-model.test.ts+++ b/src/web/src/components/community/members/channel-member-view-model.test.ts@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({addableRefetch: vi.fn(),onlineUserIds: new Set<string>(),userStatuses: new Map<string, { emoji: string | null; text: string }>(),+ profileAboutMe: new Map<string, string>(),serverSearch: vi.fn(),loadMore: vi.fn(),addChannelMember: vi.fn(),@@ -92,9 +93,30 @@ vi.mock("@/hooks/community/mutations", () => ({useKickMember: () => ({ mutateAsync: mocks.kickMember }),}))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => mocks.onlineUserIds,- useCommunityWsStore: (selector: (state: { userStatuses: typeof mocks.userStatuses }) => unknown) =>- selector({ userStatuses: mocks.userStatuses }),+ useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) => {+ const rows = [+ ...mocks.serverMembers,+ ...[...mocks.channelMembers.values()].flat(),+ ...mocks.addableMembers,+ ]+ const profilesByUserId = new Map(rows.flatMap((row) => {+ const userId = row.userId as string | undefined+ if (!userId) return []+ const status = mocks.userStatuses.get(userId)+ return [[userId, {+ id: userId,+ name: row.name,+ discriminator: row.discriminator,+ avatar: row.avatar,+ avatarVersion: row.avatarVersion ?? 0,+ aboutMe: mocks.profileAboutMe.get(userId) ?? "",+ presence: mocks.onlineUserIds.has(userId) ? "online" : "offline",+ statusEmoji: status?.emoji,+ statusText: status?.text,+ }]]+ }))+ return selector({ profilesByUserId })+ },}))vi.mock("@/components/community/members/add-members-dialog", () => ({AddMembersDialog: vi.fn(() => null),@@ -178,6 +200,7 @@ describe("useChannelMemberViewModel", () => {mocks.addableRefetch.mockResolvedValue({})mocks.onlineUserIds = new Set()mocks.userStatuses = new Map()+ mocks.profileAboutMe = new Map()mocks.addChannelMember.mockResolvedValue({})mocks.removeChannelMember.mockResolvedValue({})mocks.addThreadParticipant.mockResolvedValue({})@@ -220,6 +243,11 @@ describe("useChannelMemberViewModel", () => {})it("uses the public server roster, excludes self, and keeps the raw-roster resolver stable across presence ticks", () => {+ mocks.serverMembers = [+ member("viewer_1", "Viewer", { role: "admin" }),+ member("alice_1", "Alice", { sub: "raw presentation" }),+ ]+ mocks.profileAboutMe = new Map([["alice_1", "private profile about"]])const modelProps = props()let renderer: TestRenderer.ReactTestRendereract(() => {@@ -227,6 +255,8 @@ describe("useChannelMemberViewModel", () => {})expect(latestModel().memberPanelProps.members.map((row) => row.userId)).toEqual(["viewer_1", "alice_1"])+ expect(latestModel().memberPanelProps.members.find((row) => row.userId === "alice_1")?.sub)+ .toBe("raw presentation")expect(latestModel().composerMembers.map((row) => row.userId)).toEqual(["alice_1"])expect(latestModel().memberPanelProps.onSearchMembers).toBe(mocks.serverSearch)expect(latestModel().memberPanelProps.onAddMember).toBeUndefined()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 bdfd63b62..31a0a6f15 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@@ -9,7 +9,7 @@ import type { Member } from "@/lib/community/models/people"import type { ComposerProps } from "@/components/community/messages/composer"import { toastApiError } from "@/lib/api/client"import { makeUserNameResolver } from "@/lib/community/display-name"-import { resolveRowPresence } from "@/lib/community/presence"+import { readCommunityProfile } from "@/lib/community/profile-read"import {useAddableMembers,useAddChannelMember,@@ -22,7 +22,7 @@ import {useRemoveThreadParticipant,} from "@/hooks/community/use-thread-participants"import { useKickMember, useSetMemberRole } from "@/hooks/community/mutations"-import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { useCommunityWsStore } from "@/stores/community/ws"type MentionCandidateSource = NonNullable<ComposerProps["mentionCandidates"]>@@ -89,8 +89,7 @@ export function useChannelMemberViewModel({myRole: Role | undefined} {const membersHook = useServerMembers(serverId)- const onlineUserIds = useOnlineUserIds()- const userStatuses = useCommunityWsStore((state) => state.userStatuses)+ const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)const [memberUi, setMemberUi] = useState({ channelId, query: "", dialogOpen: false })const memberQuery = memberUi.channelId === channelId ? memberUi.query : ""const manageMembersOpen = memberUi.channelId === channelId && memberUi.dialogOpen@@ -105,15 +104,22 @@ export function useChannelMemberViewModel({const members = useMemo(() => membersHook.members.map((member) => {- const liveStatus = userStatuses.get(member.userId)+ const profile = readCommunityProfile(+ profilesByUserId.get(member.userId),+ member.userId,+ )return {...member,- status: resolveRowPresence(member, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : member.statusEmoji,- statusText: liveStatus ? liveStatus.text : member.statusText,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: member.userId === currentUser.id ? "online" as const : profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,}}),- [currentUser.id, membersHook.members, onlineUserIds, userStatuses],+ [currentUser.id, membersHook.members, profilesByUserId],)const currentChannelPrivate = useMemo(() => {@@ -202,28 +208,26 @@ export function useChannelMemberViewModel({!query || name.toLowerCase().includes(query) || (discriminator ?? "").toLowerCase().includes(query)const withPresence = (member: {userId: string- name: string- discriminator: string- avatar: string- avatarVersion: number- statusEmoji?: string | null- statusText?: string | null+ sub: stringisCreator?: booleansource?: "explicit" | "inherited" | "admin"}): Member => {- const liveStatus = userStatuses.get(member.userId)+ const profile = readCommunityProfile(+ profilesByUserId.get(member.userId),+ member.userId,+ )return {id: member.userId,userId: member.userId,- name: member.name,- discriminator: member.discriminator,- avatar: member.avatar,- avatarVersion: member.avatarVersion,- sub: "",+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ sub: member.sub,role: "member",- status: resolveRowPresence(member, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : (member.statusEmoji ?? null),- statusText: liveStatus ? liveStatus.text : (member.statusText ?? ""),+ status: member.userId === currentUser.id ? "online" : profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,isCreator: member.isCreator,source: member.source,}@@ -231,13 +235,13 @@ export function useChannelMemberViewModel({if (isNotifyUnit) {return channelMembersHook.members- .filter((member) => matches(member.name, member.discriminator)).map((member) => withPresence({ ...member, source: undefined }))+ .filter((member) => matches(member.name, member.discriminator))}if (!currentChannelPrivate) return membersreturn channelMembersHook.members- .filter((member) => matches(member.name, member.discriminator)).map(withPresence)+ .filter((member) => matches(member.name, member.discriminator))}, [channelMembersHook.members,currentChannelPrivate,@@ -245,8 +249,7 @@ export function useChannelMemberViewModel({isNotifyUnit,memberQuery,members,- onlineUserIds,- userStatuses,+ profilesByUserId,])const composerMembers = useMemo(() => {@@ -257,12 +260,19 @@ export function useChannelMemberViewModel({return roster.filter((member) => member.userId !== currentUser.id).map((member) => {- const liveStatus = userStatuses.get(member.userId)+ const profile = readCommunityProfile(+ profilesByUserId.get(member.userId),+ member.userId,+ )return {...member,- status: resolveRowPresence(member, onlineUserIds, currentUser.id),- statusEmoji: liveStatus ? liveStatus.emoji : member.statusEmoji,- statusText: liveStatus ? liveStatus.text : member.statusText,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,}})}, [@@ -271,9 +281,8 @@ export function useChannelMemberViewModel({currentUser.id,isNotifyUnit,members,- onlineUserIds,parentChannelMembersHook.members,- userStatuses,+ profilesByUserId,])const composerMentionCandidates = useMemo<MentionCandidateSource | undefined>(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 14c4834c6..c6628310e 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@@ -407,6 +407,7 @@ describe("useMessageChannelController", () => {{id: "m2",type: "chat",+ authorId: "u2",authorName: "Bob",authorAvatar: avatarInitial("Bob"),authorAvatarVersion: 0,@@ -416,6 +417,7 @@ describe("useMessageChannelController", () => {{id: "m3",type: "chat",+ authorId: "u3",authorName: "Carol",authorAvatar: "https://example.test/carol.png",authorAvatarVersion: 3,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 c63c90b59..c5f73c147 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@@ -4,7 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } frimport { usePathname, useRouter, useSearchParams } from "next/navigation"import type { MentionType } from "@alook/shared"import { toastApiError } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles } from "@/lib/community/profile-seed"import { avatarInitial } from "@/lib/community/avatar"import type { Msg } from "@/lib/community/models/message"import type { SendAttachment } from "./composer"@@ -102,15 +102,26 @@ export function useMessageChannelController({}try {const params = new URLSearchParams({ q: query, channelId })- const data = await apiFetchIdentity<{+ const data = await apiFetchProfiles<{results: Array<{message: { id: string; content: string; authorId: string; createdAt: string }author: { id: string; name: string; image: string | null; avatarVersion: number }}>- }>(`/api/community/messages/search?${params}`)+ }>(+ `/api/community/messages/search?${params}`,+ (response) => response.results.map((result) => ({+ id: result.author.id,+ identityAbout: { name: result.author.name },+ avatar: {+ avatar: result.author.image ?? avatarInitial(result.author.name),+ avatarVersion: result.author.avatarVersion,+ },+ })),+ )setSearchResults(data.results.map((result) => ({id: result.message.id,type: "chat" as const,+ authorId: result.author.id,authorName: result.author.name,authorAvatar: result.author.image ?? avatarInitial(result.author.name),authorAvatarVersion: result.author.avatarVersion,diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsxindex d6215e191..a42aa972c 100644--- a/src/web/src/components/community/messages/message-context-sheet.tsx+++ b/src/web/src/components/community/messages/message-context-sheet.tsx@@ -12,7 +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 { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { ApiError } from "@/lib/errors"import { formatDateLabel } from "@/lib/community/format-time"import { DateDivider } from "../dividers"@@ -194,8 +194,9 @@ export function MessageContextSheet({if (e instanceof ApiError && e.status === 404) return { notFound: true }throw e}- const page = await apiFetchIdentity<MessagesPage>(+ const page = await apiFetchProfiles<MessagesPage>(anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),+ (response) => messageProfilePatches(response.messages),{ signal },)const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))diff --git a/src/web/src/components/community/messages/message-list-controller.test.ts b/src/web/src/components/community/messages/message-list-controller.test.tsindex 28a04fcd1..3819d7c28 100644--- a/src/web/src/components/community/messages/message-list-controller.test.ts+++ b/src/web/src/components/community/messages/message-list-controller.test.ts@@ -493,6 +493,56 @@ describe("useMessageListController", () => {.toEqual([["ordinary", false], ["reply", false]])})+ it("regroups selected messages by stable author id despite stale raw names", () => {+ const first = { ...baseMessage, id: "first", authorName: "Old Alice" }+ const second = {+ ...baseMessage,+ id: "second",+ authorName: "New Alice",+ createdAt: new Date(1000).toISOString(),+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props({ messages: [first, second] }) }),+ { createNodeMock },+ )+ })+ act(() => {+ latest.onEnterSelectId("first")+ latest.onToggleSelectId("second")+ })++ expect(latest.selectedMessages.map((message) => [message.id, message.grouped]))+ .toEqual([["first", false], ["second", true]])+ act(() => renderer.unmount())+ })++ it("falls back to author name when selected legacy messages have no author id", () => {+ const first = { ...baseMessage, id: "first", authorId: undefined }+ const second = {+ ...baseMessage,+ id: "second",+ authorId: undefined,+ createdAt: new Date(1000).toISOString(),+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props({ messages: [first, second] }) }),+ { createNodeMock },+ )+ })+ act(() => {+ latest.onEnterSelectId("first")+ latest.onToggleSelectId("second")+ })++ expect(latest.selectedMessages.map((message) => [message.id, message.grouped]))+ .toEqual([["first", false], ["second", true]])+ act(() => renderer.unmount())+ })+it("minimally scrolls a selected row above the active accessory rail", () => {selectionRailTop = 692selectedRowBottom = 747.5diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 128f988b2..4a156a40e 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -71,7 +71,9 @@ export function useMessageListController({const grouped = !!(prev&& !message.replyTo- && prev.authorName === message.authorName+ && (prev.authorId && message.authorId+ ? prev.authorId === message.authorId+ : prev.authorName === message.authorName)&& prev.createdAt&& message.createdAt&& new Date(message.createdAt).getTime() - new Date(prev.createdAt).getTime() < 7 * 60 * 1000diff --git a/src/web/src/components/community/messages/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.tsindex 814deecd0..4bc14549a 100644--- a/src/web/src/components/community/messages/message-share-dialog.test.ts+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts@@ -8,6 +8,11 @@ import {} from "./message-share-dialog"import type { RenderMsg } from "@/lib/community/models/message"+const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unknown>>() }))+vi.mock("@/stores/community/ws", () => ({+ useProfilesByUserId: () => profileState.map,+}))+vi.mock("html-to-image", () => ({ toBlob: vi.fn() }))vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }))vi.mock("next/image", () => ({ default: "img" }))@@ -41,6 +46,15 @@ function message(overrides: Partial<RenderMsg> = {}): RenderMsg {}function renderMessage(m: RenderMsg) {+ profileState.map = new Map()+ if (m.authorId) {+ profileState.map.set(m.authorId, {+ id: m.authorId,+ name: m.authorName,+ ...(m.authorAvatar ? { avatar: m.authorAvatar } : {}),+ avatarVersion: m.authorAvatarVersion ?? 0,+ })+ }let renderer: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(React.createElement(MessageShareDialog, {diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsxindex 7fcc0681e..1e373060e 100644--- a/src/web/src/components/community/messages/message-share-dialog.tsx+++ b/src/web/src/components/community/messages/message-share-dialog.tsx@@ -15,6 +15,8 @@ import { tid } from "@/lib/community/testids"import { applyHighlightToRange, clearHighlights, hasHighlights } from "@/lib/community/highlight-range"import type { RenderMsg } from "@/lib/community/models/message"import { displayReplyContent } from "@/lib/community/reply-content"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"const SHARE_IMAGE_READY_TIMEOUT_MS = 5_000@@ -112,6 +114,7 @@ export function MessageShareDialog({ m, open, onClose }: {onClose: () => void}) {const messages = useMemo(() => (Array.isArray(m) ? m : [m]), [m])+ const profilesByUserId = useProfilesByUserId()const cardRef = useRef<HTMLDivElement>(null)// One body wrapper per message β highlight operations are scoped to the body// the drag happened in, so a drag never wraps the avatar/name/footer OR bleeds@@ -212,7 +215,11 @@ export function MessageShareDialog({ m, open, onClose }: {const url = URL.createObjectURL(blob)const a = document.createElement("a")a.href = url- a.download = `alook-message-${messages[0]?.authorName ?? "share"}.png`+ const firstAuthorId = messages[0]?.authorId+ const firstAuthor = firstAuthorId+ ? readCommunityProfile(profilesByUserId.get(firstAuthorId), firstAuthorId)+ : null+ a.download = `alook-message-${firstAuthor?.name ?? "share"}.png`a.click()URL.revokeObjectURL(url)} catch {@@ -252,6 +259,15 @@ export function MessageShareDialog({ m, open, onClose }: {className="rounded-xl bg-card p-5 shadow-(--e1)">{messages.map((msg) => {+ const author = msg.authorId+ ? readCommunityProfile(profilesByUserId.get(msg.authorId), msg.authorId)+ : null+ const replyAuthor = msg.replyTo?.authorId+ ? readCommunityProfile(+ profilesByUserId.get(msg.replyTo.authorId),+ msg.replyTo.authorId,+ )+ : nullconst visibleContent = displayReplyContent(msg.content ?? "", msg.replyTo)return (<div key={msg.id} className={msg.grouped ? "mt-0.5" : "mt-3 first:mt-0"}>@@ -265,7 +281,7 @@ export function MessageShareDialog({ m, open, onClose }: {<span className="italic">Original message was deleted</span>) : (<>- <span className="shrink-0 font-medium text-foreground/80">@{msg.replyTo.authorName}</span>+ <span className="shrink-0 font-medium text-foreground/80">@{replyAuthor?.name ?? msg.replyTo.authorName}</span><span className="min-w-0 truncate">{stripInlineMarkup(msg.replyTo.text)}</span></>)}@@ -274,14 +290,21 @@ export function MessageShareDialog({ m, open, onClose }: {<div className="flex gap-3">{msg.grouped? <div className="w-10 shrink-0" aria-hidden />- : <Avatar label={msg.authorName ?? "Unknown"} src={msg.authorAvatar} seed={msg.authorId} size={40} />}+ : (+ <Avatar+ label={author?.name ?? msg.authorName ?? "Unknown"}+ src={author?.avatar}+ seed={msg.authorId}+ size={40}+ />+ )}<div className="min-w-0 flex-1">{!msg.grouped && (<divclassName="mb-0.5 text-[15px] font-semibold"style={{ color: msg.color ?? "var(--foreground)" }}>- {msg.authorName}+ {author?.name ?? msg.authorName}</div>)}{/* Each body: clamp at 32 lines (Alli #137 β one number fordiff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.tsindex a5078c4e9..ee247db71 100644--- a/src/web/src/components/community/messages/message.render.test.ts+++ b/src/web/src/components/community/messages/message.render.test.ts@@ -13,6 +13,7 @@ import {} from "./message"import { EmojiPickerPopover } from "./emoji-picker"import type { RenderMsg } from "@/lib/community/models/message"+import { useCommunityWsStore } from "@/stores/community/ws"vi.mock("./emoji-picker", async () => {const ReactModule = await import("react")@@ -164,6 +165,13 @@ function textContent(node: TestRenderer.ReactTestInstance): string {beforeEach(() => {renderCount = 0+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+ const profiles = useCommunityWsStore.getState()+ profiles.seedProfiles(profiles.beginProfileSnapshot(), [{+ id: "u1",+ identityAbout: { name: "Alice" },+ }])const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }g.ResizeObserver = class { observe() {} disconnect() {} unobserve() {} }g.IntersectionObserver = class { observe() {} disconnect() {} unobserve() {} }diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex 0ef82f842..7a5ebf602 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -34,6 +34,7 @@ import {type MobileReplyGesture,} from "./mobile-message-gesture"import { useMobileAvatarMention } from "./use-mobile-avatar-mention"+import { useCommunityProfile } from "@/stores/community/ws"// Whether the "Share as Image" action is offered for a message. Share is// computed inside `Message` from the message alone (no handler is threaded in),@@ -160,6 +161,17 @@ function MessageImpl({// default without subscribing at all.hoverCapable?: boolean}) {+ const authorProfile = useCommunityProfile(m.authorId)+ const replyAuthorProfile = useCommunityProfile(m.replyTo?.authorId)+ const authorName = m.authorId+ ? (authorProfile?.name ?? "Unknown")+ : (m.authorName ?? "Unknown")+ const authorAvatar = m.authorId+ ? (authorProfile?.avatar ?? avatarInitial(authorName))+ : (m.authorAvatar ?? avatarInitial(authorName))+ const replyAuthorName = m.replyTo?.authorId+ ? (replyAuthorProfile?.name ?? "Unknown")+ : (m.replyTo?.authorName ?? "Unknown")const visibleContent = displayReplyContent(m.content ?? "", m.replyTo)// keep the hover toolbar pinned open while its β― dropdown is openconst [toolbarOpen, setToolbarOpen] = useState(false)@@ -177,7 +189,7 @@ function MessageImpl({const avatarMention = useMobileAvatarMention({onMention: onMentionAuthor,onProfileClick: (event) => {- onOpenProfile?.(m.authorName ?? "", event, undefined, m.authorId)+ onOpenProfile?.(authorName, event, undefined, m.authorId)},})// The Mark/Unmark label needs to know if THIS message is already in the@@ -450,7 +462,7 @@ function MessageImpl({<span className="italic text-muted-foreground">Original message was deleted</span>) : (<>- <span className="shrink-0 font-medium text-foreground/80">@{m.replyTo.authorName}</span>+ <span className="shrink-0 font-medium text-foreground/80">@{replyAuthorName}</span><span className="min-w-0 truncate">{stripInlineMarkup(m.replyTo.text)}</span></>)}@@ -465,21 +477,21 @@ function MessageImpl({{...avatarMention}className="shrink-0 self-start"aria-label={onMentionAuthor- ? `Open ${m.authorName ?? "member"} profile; long press to mention`+ ? `Open ${authorName} profile; long press to mention`: undefined}>- <Avatar label={m.authorAvatar ?? "?"} seed={m.authorId} size={40} />+ <Avatar label={authorAvatar} seed={m.authorId} size={40} /></button>)}<div className="min-w-0 flex-1">{!m.grouped && (<div className="flex items-baseline gap-2"><button- onClick={(e) => onOpenProfile?.(m.authorName ?? "", e, undefined, m.authorId)}+ onClick={(e) => onOpenProfile?.(authorName, e, undefined, m.authorId)}className="min-w-0 max-w-full truncate text-[15px] font-semibold hover:underline"style={{ color: m.color ?? "var(--foreground)" }}>- {m.authorName}+ {authorName}</button><span className="shrink-0 text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span></div>@@ -759,8 +771,6 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {a.grouped !== b.grouped ||a.failed !== b.failed ||a.authorId !== b.authorId ||- a.authorName !== b.authorName ||- a.authorAvatar !== b.authorAvatar ||a.color !== b.color ||a.createdAt !== b.createdAt ||a.reactions !== b.reactions ||diff --git a/src/web/src/components/community/messages/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.tsindex 75e650025..d2e257535 100644--- a/src/web/src/components/community/messages/thread-opener.test.ts+++ b/src/web/src/components/community/messages/thread-opener.test.ts@@ -6,6 +6,11 @@ const useMessageMock = vi.fn()vi.mock("@/hooks/community/use-message", () => ({useMessage: (...args: unknown[]) => useMessageMock(...args),}))+vi.mock("@/stores/community/ws", () => ({+ useCommunityProfile: (userId?: string) => userId+ ? { id: userId, name: "Alice", avatar: "A" }+ : undefined,+}))import { ThreadOpener } from "./thread-opener"@@ -35,7 +40,7 @@ describe("ThreadOpener image attachment layout", () => {id: "opener_1",type: "chat",authorId: "user_1",- authorName: "Alice",+ authorName: "Stale Alice",content: "@Bob Smith\n**visible** body",replyTo: { id: "prior", authorName: "Bob Smith", text: "original" },createdAt: "2026-08-08T00:00:00.000Z",diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex b2e224fb7..fcdc71baa 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -15,6 +15,7 @@ import type { OpenProfile } from "@/components/community/social/profile-types"import { AttachmentCard } from "./attachment-card"import { displayReplyContent } from "@/lib/community/reply-content"import { useMobileAvatarMention } from "./use-mobile-avatar-mention"+import { useCommunityProfile } from "@/stores/community/ws"// Thread opener β the parent message the thread was created from, pinned at// the top of the thread's message list. Deliberately styled like a REGULAR@@ -54,13 +55,19 @@ export function ThreadOpener({onJump?: () => void}) {const { message: msg, isLoading, isError } = useMessage(parentMessageId)+ const authorProfile = useCommunityProfile(msg?.authorId)const mentionText = msg ? resolveAuthorMentionText?.(msg.authorId) ?? null : nullconst avatarMention = useMobileAvatarMention({onMention: mentionText && onInsertMentionText? () => onInsertMentionText(mentionText): undefined,onProfileClick: (event) => {- if (msg) onOpenProfile?.(msg.authorName, event, undefined, msg.authorId)+ if (msg) {+ const name = msg.authorId+ ? (authorProfile?.name ?? "Unknown")+ : (msg.authorName ?? "Unknown")+ onOpenProfile?.(name, event, undefined, msg.authorId)+ }},})@@ -81,7 +88,12 @@ export function ThreadOpener({)}- const avatarLabel = msg.authorAvatar || avatarInitial(msg.authorName)+ const authorName = msg.authorId+ ? (authorProfile?.name ?? "Unknown")+ : (msg.authorName ?? "Unknown")+ const avatarLabel = msg.authorId+ ? (authorProfile?.avatar ?? avatarInitial(authorName))+ : (msg.authorAvatar ?? avatarInitial(authorName))const visibleContent = displayReplyContent(msg.content ?? "", msg.replyTo)return (@@ -109,7 +121,7 @@ export function ThreadOpener({{...avatarMention}className="shrink-0 self-start"aria-label={mentionText && onInsertMentionText- ? `Open ${msg.authorName} profile; long press to mention`+ ? `Open ${authorName} profile; long press to mention`: undefined}><Avatar label={avatarLabel} seed={msg.authorId} size={40} />@@ -117,10 +129,10 @@ export function ThreadOpener({<div className="min-w-0 flex-1"><div className="flex items-baseline gap-2"><button- onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}+ onClick={(e) => onOpenProfile?.(authorName, e, undefined, msg.authorId)}className="text-[15px] font-semibold hover:underline">- {msg.authorName}+ {authorName}</button><span className="text-xs text-muted-foreground" suppressHydrationWarning>{formatMessageTime(msg.createdAt)}diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex 5d4d5dede..64ca75793 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -17,6 +17,9 @@ import {type InboxRowTarget,} from "@/hooks/community/inbox-read-reservation"import { tid } from "@/lib/community/testids"+import type { CommunityProfile } from "@/lib/community/models/people"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"type UnreadChannel = UnreadServer["channels"][number]type UnreadChild = UnreadChannel["children"][number]@@ -30,7 +33,7 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected }: {+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId }: {servers: UnreadServer[]dms: UnreadDm[]loading?: boolean@@ -38,6 +41,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenonOpenThread: (server: UnreadServer, parent: UnreadChannel, child: UnreadChild) => voidonOpenDm?: (dm: UnreadDm) => voidisProjected: (target: InboxRowTarget | null) => boolean+ profilesByUserId: ReadonlyMap<string, CommunityProfile>}) {const visibleDms = dms.filter((dm) => !isProjected(inboxDmRowTarget(dm)))const visibleServers = servers.map((server) => ({@@ -59,18 +63,24 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen{visibleDms.length > 0 && (<div className="mb-3"><div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>- {visibleDms.map((d) => (+ {visibleDms.map((d) => {+ const profile = readCommunityProfile(+ profilesByUserId.get(d.otherUserId),+ d.otherUserId,+ )+ return (<buttonkey={d.channelId}data-testid={tid.inboxUnreadDm(d.channelId)}onClick={() => onOpenDm?.(d)}className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent">- <Avatar label={d.otherUserAvatar} seed={d.otherUserId} size={24} />- <span className="min-w-0 flex-1 truncate">{d.otherUserName}</span>+ <Avatar label={profile.avatar} seed={d.otherUserId} size={24} />+ <span className="min-w-0 flex-1 truncate">{profile.name}</span><ChevronRight className="size-4 shrink-0 text-muted-foreground" /></button>- ))}+ )+ })}</div>)}{visibleServers.map(({ server, channels }) => (@@ -109,12 +119,13 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen)}-function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected }: {+function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected, profilesByUserId }: {mentions: Mention[]loading?: booleanonOpenMention?: (m: Mention) => voidonDeleteMention?: (id: string) => voidisProjected: (target: InboxRowTarget | null) => boolean+ profilesByUserId: ReadonlyMap<string, CommunityProfile>}) {const visibleMentions = mentions.filter((mention) => (!isProjected(inboxMentionRowTarget(mention))@@ -123,13 +134,18 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProj<div className="h-full overflow-y-auto thin-scrollbar p-3">{loading && visibleMentions.length === 0 && <InboxRowsSkeleton />}{!loading && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}- {visibleMentions.map((mn) => (+ {visibleMentions.map((mn) => {+ const author = readCommunityProfile(+ mn.m.authorId ? profilesByUserId.get(mn.m.authorId) : undefined,+ mn.m.authorId ?? "",+ )+ return (<div key={mn.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent"><button onClick={() => onOpenMention?.(mn)} className="flex min-w-0 flex-1 items-start gap-3 text-left">- <Avatar label={mn.m.authorAvatar ?? "?"} seed={mn.m.authorId} size={36} />+ <Avatar label={author.avatar} seed={mn.m.authorId} size={36} /><div className="min-w-0 flex-1"><div className="text-sm">- <span className="font-medium">{mn.m.authorName}</span>{" "}+ <span className="font-medium">{author.name}</span>{" "}<span className="text-xs text-muted-foreground">{mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} Β· <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mn.channel}</span>@@ -151,28 +167,35 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProj</DropdownMenu>)}</div>- ))}+ )+ })}</div>)}-function MarkedTab({ marked, loading, onOpenMarked, onUnmark }: {+function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId }: {marked: Marked[]loading?: booleanonOpenMarked?: (m: Marked) => voidonUnmark?: (messageId: string) => void+ profilesByUserId: ReadonlyMap<string, CommunityProfile>}) {return (<div className="h-full overflow-y-auto thin-scrollbar p-3">{loading && marked.length === 0 && <InboxRowsSkeleton />}{!loading && marked.length === 0 && <EmptyState icon={Bookmark} label="No marked messages" />}- {marked.map((mk) => (+ {marked.map((mk) => {+ const author = readCommunityProfile(+ mk.m.authorId ? profilesByUserId.get(mk.m.authorId) : undefined,+ mk.m.authorId ?? "",+ )+ return (<div key={mk.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent"><button onClick={() => onOpenMarked?.(mk)} className="flex min-w-0 flex-1 items-start gap-3 text-left">- <Avatar label={mk.m.authorAvatar ?? "?"} seed={mk.m.authorId} size={36} />+ <Avatar label={author.avatar} seed={mk.m.authorId} size={36} /><div className="min-w-0 flex-1"><div className="text-sm">- <span className="font-medium">{mk.m.authorName}</span>{" "}+ <span className="font-medium">{author.name}</span>{" "}<span className="text-xs text-muted-foreground">in{" "}{mk.serverId@@ -198,7 +221,8 @@ function MarkedTab({ marked, loading, onOpenMarked, onUnmark }: {</DropdownMenu>)}</div>- ))}+ )+ })}</div>)}@@ -247,6 +271,7 @@ export function InboxPopover({onMarkAllRead?: () => voidisProjected?: (target: InboxRowTarget | null) => boolean}) {+ const profilesByUserId = useProfilesByUserId()const hasUnreads = unreads.length > 0 || unreadDms.length > 0const hasAnything = hasUnreads || mentions.length > 0return (@@ -292,13 +317,14 @@ export function InboxPopover({onOpenThread={onOpenThread ?? onOpenForumThread ?? (() => {})}onOpenDm={onOpenDm}isProjected={isProjected}+ profilesByUserId={profilesByUserId}/></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1">- <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} />+ <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} profilesByUserId={profilesByUserId} /></TabsContent><TabsContent value="marked" className="min-h-0 flex-1">- <MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} />+ <MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} profilesByUserId={profilesByUserId} /></TabsContent></Tabs>)diff --git a/src/web/src/components/community/shell/community-panel.tsx b/src/web/src/components/community/shell/community-panel.tsxindex bc2ed9626..6bbfad851 100644--- a/src/web/src/components/community/shell/community-panel.tsx+++ b/src/web/src/components/community/shell/community-panel.tsx@@ -17,6 +17,9 @@ import type { OpenProfile } from "@/components/community/social/profile-types"import type { RightPanel } from "@/components/community/shell/panel-types"import type { Msg, RenderMsg, Thread } from "@/lib/community/models/message"import type { Member } from "@/lib/community/models/people"+import type { CommunityProfile } from "@/lib/community/models/people"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"export type CommunityPanelProps = {open: boolean@@ -50,6 +53,7 @@ export type CommunityPanelProps = {export function CommunityPanel(props: CommunityPanelProps) {const { open, onOpenChange, kind } = propsconst { icon: Icon, label } = panelHeading(kind)+ const profilesByUserId = useProfilesByUserId()return (<CommunitySheet@@ -64,7 +68,7 @@ export function CommunityPanel(props: CommunityPanelProps) {desktopWidth={kind === "members" ? 380 : undefined}bodyClassName={kind === "members" ? "p-0 sm:p-0" : undefined}>- {renderCommunityPanelBody(props)}+ {renderCommunityPanelBody(props, profilesByUserId)}</CommunitySheet>)}@@ -93,7 +97,7 @@ function renderCommunityPanelBody({onJumpToMessage,onSearch,viewerUserId,-}: CommunityPanelProps) {+}: CommunityPanelProps, profilesByUserId: ReadonlyMap<string, CommunityProfile>) {if (kind === "members") {return (<MemberList@@ -118,18 +122,23 @@ function renderCommunityPanelBody({if (pinned.length === 0) {return <div className="py-8 text-center text-sm text-muted-foreground">No pinned messages yet.</div>}- return pinned.map((message) => (+ return pinned.map((message) => {+ const author = readCommunityProfile(+ message.authorId ? profilesByUserId.get(message.authorId) : undefined,+ message.authorId ?? "",+ )+ return (<buttonkey={message.id}onClick={() => message.seq != null && onJumpToMessage?.(message.seq)}className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left hover:bg-accent"><span className="shrink-0">- <Avatar label={message.authorAvatar ?? "?"} seed={message.authorId} size={24} />+ <Avatar label={author.avatar} seed={message.authorId} size={24} /></span><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2">- <span className="text-sm font-medium">{message.authorName}</span>+ <span className="text-sm font-medium">{author.name}</span>{message.createdAt && (<span className="text-xs text-muted-foreground">{formatRelativeTime(message.createdAt)}@@ -141,7 +150,8 @@ function renderCommunityPanelBody({</div></div></button>- ))+ )+ })}if (kind === "search") {@@ -161,7 +171,14 @@ function renderCommunityPanelBody({<><div className="mb-2 text-xs text-muted-foreground">{threads.length} threads</div><div className="space-y-1">- {threads.map((thread) => (+ {threads.map((thread) => {+ const author = thread.parent.authorId+ ? readCommunityProfile(+ profilesByUserId.get(thread.parent.authorId),+ thread.parent.authorId,+ )+ : null+ return (<buttonkey={thread.id}onClick={() => onOpenThread(thread.id)}@@ -171,7 +188,9 @@ function renderCommunityPanelBody({<div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{thread.name}</div><div className="truncate text-xs text-muted-foreground">- <span className="font-medium text-foreground/80">{thread.parent.authorName}</span>{" "}+ <span className="font-medium text-foreground/80">+ {author?.name ?? thread.parent.authorName}+ </span>{" "}{stripInlineMarkup(thread.parent.text)}</div><div className="mt-1 text-xs text-muted-foreground" suppressHydrationWarning>@@ -179,7 +198,8 @@ function renderCommunityPanelBody({</div></div></button>- ))}+ )+ })}</div></>)diff --git a/src/web/src/components/community/shell/shell-frame-overlays.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.test.tsindex 8d2a3a41c..2717b8283 100644--- a/src/web/src/components/community/shell/shell-frame-overlays.test.ts+++ b/src/web/src/components/community/shell/shell-frame-overlays.test.ts@@ -30,8 +30,6 @@ const controller = {data: { userId: "remote", name: "Remote" },x: 12,y: 34,- initialStatusEmoji: "π±",- initialStatusText: "Growing",},closeProfile: vi.fn(),profileMessage: vi.fn(),@@ -68,10 +66,6 @@ describe("ShellFrameOverlays", () => {renderer = TestRenderer.create(createElement(ShellFrameOverlays, {controller,breakpoint: "desktop",- profileStatusSeeds: {- initialStatusEmoji: "π±",- initialStatusText: "Growing",- },extraDialogs: createElement("extra-dialog"),}))})@@ -92,10 +86,8 @@ describe("ShellFrameOverlays", () => {expect(types.indexOf("crop-dialog")).toBeLessThan(types.indexOf("extra-dialog"))const profileCard = renderer.root.findByType("profile-card")- expect(profileCard.props.initialStatusEmoji).toBe("π±")- expect(profileCard.props.initialStatusText).toBe("Growing")- expect(profileCard.props.activityStatusEmoji).toBe("π±")- expect(profileCard.props.activityStatusText).toBe("Growing")+ expect("initialStatusEmoji" in profileCard.props).toBe(false)+ expect("initialStatusText" in profileCard.props).toBe(false)expect(profileCard.props.onOpenOwnerProfile).toBe(controller.openOwnerProfile)expect(profileCard.props.onOpenBotAudit).toBe(controller.openBotAudit)expect(renderer.root.findByType("crop-dialog").props.maskShape).toBe("circle")@@ -119,8 +111,8 @@ describe("ShellFrameOverlays", () => {const profileCard = renderer.root.findByType("profile-card")expect("initialStatusEmoji" in profileCard.props).toBe(false)expect("initialStatusText" in profileCard.props).toBe(false)- expect(profileCard.props.activityStatusEmoji).toBe("π±")- expect(profileCard.props.activityStatusText).toBe("Growing")+ expect("activityStatusEmoji" in profileCard.props).toBe(false)+ expect("activityStatusText" in profileCard.props).toBe(false)})it("omits nullable overlays while keeping closed sheet and settings wiring", async () => {diff --git a/src/web/src/components/community/shell/shell-frame-overlays.tsx b/src/web/src/components/community/shell/shell-frame-overlays.tsxindex dbd3cd741..1abf081cc 100644--- a/src/web/src/components/community/shell/shell-frame-overlays.tsx+++ b/src/web/src/components/community/shell/shell-frame-overlays.tsx@@ -15,15 +15,10 @@ type ProfileController = ReturnType<typeof useShellProfileController>export function ShellFrameOverlays({controller,breakpoint,- profileStatusSeeds,extraDialogs,}: {controller: ProfileControllerbreakpoint: Breakpoint- profileStatusSeeds?: {- initialStatusEmoji: string | null- initialStatusText: string | null- }extraDialogs?: ReactNode}) {const { profile, currentUser } = controller@@ -43,9 +38,6 @@ export function ShellFrameOverlays({onUpdateStatus={controller.updateOwnStatus}onOpenOwnerProfile={controller.openOwnerProfile}onOpenBotAudit={controller.openBotAudit}- activityStatusEmoji={profile.initialStatusEmoji}- activityStatusText={profile.initialStatusText}- {...profileStatusSeeds}/>)}{controller.preview && (diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.tsindex ba7194c36..34e25ef3e 100644--- a/src/web/src/components/community/shell/shell-frame-view.test.ts+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts@@ -192,10 +192,7 @@ describe("ShellFrameView", () => {expect(sidebarPanel.props).toMatchObject({ id: "sidebar", defaultSize: "24%", minSize: 160, maxSize: 360 })expect(sidebarPanel.props.className).toContain("pb-15")expect(mainPanel.props).toMatchObject({ id: "main", defaultSize: "76%" })- expect(renderer.root.findByType("shell-overlays").props.profileStatusSeeds).toEqual({- initialStatusEmoji: "π±",- initialStatusText: "Growing",- })+ expect("profileStatusSeeds" in renderer.root.findByType("shell-overlays").props).toBe(false)expect(sidebar).toHaveBeenCalledWith()expect(mocks.observe).toHaveBeenCalledTimes(1)const userBarOverlay = renderer.root.find(diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsxindex 35c02242a..057fbfb72 100644--- a/src/web/src/components/community/shell/shell-frame-view.tsx+++ b/src/web/src/components/community/shell/shell-frame-view.tsx@@ -235,12 +235,6 @@ export function ShellFrameView({<ShellFrameOverlayscontroller={profile}breakpoint={breakpoint}- {...(isDesktop && profile.profile ? {- profileStatusSeeds: {- initialStatusEmoji: profile.profile.initialStatusEmoji,- initialStatusText: profile.profile.initialStatusText,- },- } : {})}extraDialogs={extraDialogs}/>)}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 167e90a6b..a9ad07ae4 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@@ -13,18 +13,16 @@ const mocks = vi.hoisted(() => ({statusEmoji: "π",statusText: "Here",},- setCurrentUser: vi.fn(),fetchQuery: vi.fn(),createDm: vi.fn(),acceptDm: vi.fn(),updateProfile: vi.fn(),uploadAvatar: vi.fn(),- setUserStatus: vi.fn(),+ beginProfileSnapshot: vi.fn(),+ commitProfiles: vi.fn(),+ patchProfiles: 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(),@@ -43,7 +41,6 @@ vi.mock("@/hooks/community/use-user-profile", () => ({vi.mock("@/lib/community/image-crop", () => ({ validateIconSourceFile: mocks.validate }))vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => mocks.currentUser,- useSetCurrentUser: () => mocks.setCurrentUser,}))vi.mock("@/stores/community", () => ({useCommunityStore: Object.assign(vi.fn(), {@@ -51,14 +48,12 @@ vi.mock("@/stores/community", () => ({}),}))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => new Set(["self", "remote"]),- useCommunityWsStore: Object.assign(vi.fn((selector: (state: { avatarIdentities: typeof mocks.avatarIdentities }) => unknown) =>- selector({ avatarIdentities: mocks.avatarIdentities })), {+ useCommunityWsStore: Object.assign(vi.fn(), {getState: () => ({- setUserStatus: mocks.setUserStatus,reset: mocks.wsReset,- observeAvatarIdentity: mocks.observeAvatarIdentity,- avatarIdentities: mocks.avatarIdentities,+ beginProfileSnapshot: mocks.beginProfileSnapshot,+ commitProfiles: mocks.commitProfiles,+ patchProfiles: mocks.patchProfiles,}),}),}))@@ -66,7 +61,6 @@ vi.mock("@/stores/community/message-stream", () => ({useMessageStreamStore: Object.assign(vi.fn(), {getState: () => ({resetAll: mocks.streamReset,- projectAvatarIdentity: mocks.projectAvatarIdentity,}),}),}))@@ -100,8 +94,6 @@ vi.mock("@/components/community/social/profile-lookup", () => ({identity: { kind: "human" },}),}))-vi.mock("@/lib/community/presence", () => ({ resolveProfilePresence: () => "online" }))-vi.mock("@/lib/community/avatar", () => ({ avatarInitial: () => "?" }))vi.mock("@/lib/query-persister", () => ({ clearPersistedCache: mocks.clearCache }))vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({disposeAccountReadStateReconciliation: mocks.disposeReconciliation,@@ -165,19 +157,20 @@ describe("useShellProfileController", () => {if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()}mocks.validate.mockReturnValue({ ok: true })- mocks.updateProfile.mockResolvedValue({})+ mocks.updateProfile.mockResolvedValue({+ id: "self",+ name: "Self",+ discriminator: "0001",+ avatar: "S",+ avatarVersion: 0,+ aboutMe: "About",+ bannerColor: null,+ statusEmoji: "π",+ statusText: "Here",+ })+ mocks.beginProfileSnapshot.mockReturnValue({ viewerId: "self", accountEpoch: 1, revision: 0 })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(() => {@@ -203,7 +196,6 @@ describe("useShellProfileController", () => {expect(hook.current.profile?.data.name).toBe("Self")expect(hook.current.profile?.data.userId).toBeUndefined()- expect(hook.current.profile?.initialStatusEmoji).toBeNull()expect(mocks.fetchQuery).not.toHaveBeenCalled()})@@ -220,7 +212,10 @@ describe("useShellProfileController", () => {mocks.fetchQuery.mockReturnValue(response.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.about).toBe("seed")+ expect(hook.current.profile?.data).toMatchObject({+ userId: "remote",+ contextLabel: "Server member",+ })expect(mocks.fetchQuery).toHaveBeenCalledWith(expect.objectContaining({staleTime: 300_000,}))@@ -235,15 +230,12 @@ describe("useShellProfileController", () => {kind: "human",}))expect(hook.current.profile?.data).toMatchObject({- about: "hydrated",mutual: 3,- discriminator: "1234",+ identity: { kind: "human" },})- expect(hook.current.profile?.initialStatusEmoji).toBe("π±")- expect(mocks.setUserStatus).not.toHaveBeenCalled()})- it("retains the seeded avatar when an authoritative profile has a newer version but no image", async () => {+ it("keeps identity fields out of controller state after an authoritative profile fetch", async () => {mocks.fetchQuery.mockResolvedValue({id: "remote",aboutMe: "hydrated",@@ -265,12 +257,15 @@ describe("useShellProfileController", () => {))expect(hook.current.profile?.data).toMatchObject({- avatar: "R",- avatarVersion: 4,+ userId: "remote",+ mutual: 1,+ identity: { kind: "human" },})+ expect(hook.current.profile?.data).not.toHaveProperty("avatar")+ expect(hook.current.profile?.data).not.toHaveProperty("name")})- it("projects a newer WS identity into an already-open profile card", async () => {+ it("keeps open-card state limited to target and context metadata", async () => {mocks.fetchQuery.mockReturnValue(new Promise(() => {}))const hook = await renderController()await act(async () => hook.current.openProfile(@@ -279,27 +274,11 @@ describe("useShellProfileController", () => {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,+ userId: "remote",+ contextLabel: "Server member",})+ expect(hook.current.profile?.data).not.toHaveProperty("avatar")})it("does not let a slow profile response overwrite the next opened card", async () => {@@ -343,9 +322,8 @@ describe("useShellProfileController", () => {expect(hook.current.profile?.data).toMatchObject({userId: "next",- name: "Next",- about: "next hydrated",- discriminator: "9001",+ mutual: 1,+ identity: { kind: "human" },})})@@ -387,7 +365,7 @@ describe("useShellProfileController", () => {expect(hook.current.profile).toMatchObject({x: 4,y: 5,- data: { userId: "owner", name: "Owner", discriminator: "0042" },+ data: { userId: "owner" },})act(() => hook.current.openBotAudit("remote"))@@ -415,46 +393,28 @@ describe("useShellProfileController", () => {expect(hook.pushed).toEqual(["/c/me/dm1"])})- it("writes own status and UserSettings saves to current-user and WS state after mutation", async () => {- const order: string[] = []- mocks.updateProfile.mockImplementation(async () => { order.push("mutate") })- mocks.setCurrentUser.mockImplementation(() => { order.push("current-user") })- mocks.setUserStatus.mockImplementation(() => { order.push("ws") })+ it("seeds canonical mutation responses through the captured request snapshot", async () => {const hook = await renderController()await act(async () => hook.current.updateOwnStatus("π±", "Growing"))- expect(order).toEqual(["mutate", "current-user", "ws"])expect(mocks.updateProfile).toHaveBeenLastCalledWith({statusEmoji: "π±",statusText: "Growing",})- const statusUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]- expect(statusUpdater(mocks.currentUser)).toMatchObject({- statusEmoji: "π±",- statusText: "Growing",- })- expect(mocks.setUserStatus).toHaveBeenLastCalledWith("self", "π±", "Growing")+ expect(mocks.commitProfiles).toHaveBeenCalledWith(+ { viewerId: "self", accountEpoch: 1, revision: 0 },+ [expect.objectContaining({ id: "self" })],+ )- order.length = 0await act(async () => hook.current.userSettingsProps.onSave({name: "Renamed",aboutMe: "Updated",statusEmoji: "π",statusText: "Shipping",}))- expect(order).toEqual(["mutate", "current-user", "ws"])- const settingsUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]- expect(settingsUpdater(mocks.currentUser)).toMatchObject({- name: "Renamed",- aboutMe: "Updated",- statusEmoji: "π",- statusText: "Shipping",- })- expect(mocks.setUserStatus).toHaveBeenLastCalledWith("self", "π", "Shipping")-- mocks.setUserStatus.mockClear()+ expect(mocks.commitProfiles).toHaveBeenCalledTimes(2)await act(async () => hook.current.userSettingsProps.onSave({ aboutMe: "About only" }))- expect(mocks.setUserStatus).not.toHaveBeenCalled()+ expect(mocks.commitProfiles).toHaveBeenCalledTimes(3)const statusError = new Error("status")mocks.updateProfile.mockRejectedValueOnce(statusError)@@ -504,8 +464,6 @@ 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?.())@@ -520,20 +478,13 @@ describe("useShellProfileController", () => {const uploadOptions = mocks.uploadAvatar.mock.calls[0]![1]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]- 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.patchProfiles).toHaveBeenCalledWith(+ { viewerId: "self", accountEpoch: 1, revision: 0 },+ [{+ id: "self",+ avatar: { avatar: "/avatar.png?v=4", avatarVersion: 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 191864e4d..9f5623195 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,11 +1,10 @@"use client"-import { useCallback, useEffect, useState, type ComponentProps } from "react"+import { useCallback, 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"@@ -18,37 +17,34 @@ import {resolveProfileServerId,resolveProfileTarget,resolveProfileUserId,- buildSelfProfile,} from "@/components/community/social/profile-lookup"-import { resolveProfilePresence } from "@/lib/community/presence"-import { avatarInitial } from "@/lib/community/avatar"import { signOut } from "@/lib/auth-client"import { clearPersistedCache } from "@/lib/query-persister"import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"import { useCommunityStore } from "@/stores/community"-import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { useCommunityWsStore } from "@/stores/community/ws"import { useMessageStreamStore } from "@/stores/community/message-stream"-import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"+import { useCurrentUser } from "@/contexts/community/current-user"import { useFriends } from "@/hooks/community/use-friends"import { useServerMembers } from "@/hooks/community/use-server-members"import {useCreateOrGetDm,useUpdateProfile,useUploadUserAvatar,+ type UpdateProfileResult,} from "@/hooks/community/mutations"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"import type { UserSettings } from "@/components/community/settings/user-settings"import type { ImageCropDialog } from "@/components/community/image-crop-dialog"import type { QueryClient } from "@tanstack/react-query"+import type { CommunityProfileSnapshot } from "@/lib/community/models/people"import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"export type ShellProfileState = {data: Profilex: numbery: number- initialStatusEmoji: string | null- initialStatusText: string | null}type Options = Pick<ShellFrameProps, "view" | "activeServerId"> & {@@ -57,6 +53,30 @@ type Options = Pick<ShellFrameProps, "view" | "activeServerId"> & {cancelPendingNavigation: () => void}+function commitCanonicalSelfProfile(+ snapshot: CommunityProfileSnapshot,+ profile: UpdateProfileResult,+) {+ const profiles = useCommunityWsStore.getState()+ profiles.commitProfiles(snapshot, [{+ id: profile.id,+ identityAbout: {+ name: profile.name,+ discriminator: profile.discriminator,+ aboutMe: profile.aboutMe,+ bannerColor: profile.bannerColor,+ },+ avatar: {+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ },+ status: {+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ },+ }])+}+export function useShellProfileController({router,queryClient,@@ -65,9 +85,6 @@ export function useShellProfileController({activeServerId,}: Options) {const currentUser = useCurrentUser()- const setCurrentUser = useSetCurrentUser()- const avatarIdentities = useCommunityWsStore((state) => state.avatarIdentities)- const onlineUserIds = useOnlineUserIds()const { friends } = useFriends()const profileServerId = resolveProfileServerId(view, activeServerId)const { members } = useServerMembers(profileServerId)@@ -98,15 +115,14 @@ export function useShellProfileController({? members.find((member) => member.userId === currentUser.id): undefinedsetProfile({- data: buildSelfProfile(- currentUser,- onlineUserIds,- resolveProfileContextLabel(profileServerId, selfMember),- ),+ data: {+ userId: currentUser.id,+ contextLabel: resolveProfileContextLabel(profileServerId, selfMember),+ mutual: 0,+ identity: { kind: "human" },+ },x,y,- initialStatusEmoji: currentUser.statusEmoji ?? null,- initialStatusText: currentUser.statusText ?? null,})return}@@ -116,23 +132,15 @@ export function useShellProfileController({discriminator,userId: targetUserId,})- const about = member?.sub ?? ""const userId = resolveProfileUserId(member, targetUserId)setProfile({data: {- name,- userId,- avatar: member?.avatar ?? avatarInitial(name),- avatarVersion: member?.avatarVersion ?? 0,+ ...(userId ? { userId } : { name, discriminator }),contextLabel: resolveProfileContextLabel(profileServerId, member),- about,mutual: 0,- presence: resolveProfilePresence(false, userId, onlineUserIds),},x,y,- initialStatusEmoji: member?.statusEmoji ?? null,- initialStatusText: member?.statusText ?? null,})if (userId) {queryClient@@ -148,16 +156,7 @@ export function useShellProfileController({...previous,data: {...previous.data,- 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,34 +165,13 @@ export function useShellProfileController({}: { kind: "human" },},- initialStatusEmoji: profileResponse.statusEmoji,- initialStatusText: profileResponse.statusText,}: previous,)}).catch((error) => toastApiError(error, "Failed to load profile"))}- }, [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])+ }, [currentUser, friends, members, profileServerId, queryClient])const openProfile = useCallback((name: string,@@ -231,13 +209,9 @@ export function useShellProfileController({const updateOwnStatus = async (statusEmoji: string | null, statusText: string | null) => {try {- await updateProfile.mutateAsync({ statusEmoji, statusText })- setCurrentUser((user) => ({ ...user, statusEmoji, statusText }))- useCommunityWsStore.getState().setUserStatus(- currentUser.id,- statusEmoji,- statusText,- )+ const snapshot = useCommunityWsStore.getState().beginProfileSnapshot()+ const profile = await updateProfile.mutateAsync({ statusEmoji, statusText })+ commitCanonicalSelfProfile(snapshot, profile)} catch (error) {toastApiError(error, "Failed to update status")}@@ -296,21 +270,9 @@ export function useShellProfileController({const onSaveProfile: ComponentProps<typeof UserSettings>["onSave"] = async (data) => {try {- await updateProfile.mutateAsync(data)- setCurrentUser((user) => ({- ...user,- ...(data.name ? { name: data.name } : {}),- ...(data.aboutMe !== undefined ? { aboutMe: data.aboutMe } : {}),- ...(data.statusEmoji !== undefined ? { statusEmoji: data.statusEmoji } : {}),- ...(data.statusText !== undefined ? { statusText: data.statusText } : {}),- }))- if (data.statusEmoji !== undefined || data.statusText !== undefined) {- useCommunityWsStore.getState().setUserStatus(- currentUser.id,- data.statusEmoji ?? null,- data.statusText ?? null,- )- }+ const snapshot = useCommunityWsStore.getState().beginProfileSnapshot()+ const profile = await updateProfile.mutateAsync(data)+ commitCanonicalSelfProfile(snapshot, profile)} catch (error) {toastApiError(error, "Failed to save profile")}@@ -352,23 +314,11 @@ export function useShellProfileController({{ file },{onSuccess: (data) => {- 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)- }+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: currentUser.id,+ avatar: { avatar: data.url, avatarVersion: data.avatarVersion },+ }])toast("Avatar updated")},onError: (error) => toastApiError(error, "Failed to upload avatar"),diff --git a/src/web/src/components/community/shell/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsxindex 9d0e08076..71f99022d 100644--- a/src/web/src/components/community/shell/user-bar.tsx+++ b/src/web/src/components/community/shell/user-bar.tsx@@ -6,15 +6,11 @@ import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popoverimport { Avatar } from "../avatar"import { Skeleton } from "@/components/ui/skeleton"import type { OpenProfile } from "@/components/community/social/profile-types"-import { resolveProfilePresence } from "@/lib/community/presence"+import type { Presence } from "@/lib/community/models/people"import { tid } from "@/lib/community/testids"-// UserBar always renders the signed-in viewer, so presence resolves through-// the self β online branch and never consults an online set.-const EMPTY_ONLINE_SET: ReadonlySet<string> = new Set()-export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {- user: { id: string; name: string; avatar: string }+ user: { id: string; name: string; avatar: string; presence?: Presence }onOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: React.ReactNode@@ -49,7 +45,7 @@ export function UserBarSkeleton() {}function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {- user: { id: string; name: string; avatar: string }+ user: { id: string; name: string; avatar: string; presence?: Presence }onOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: React.ReactNode@@ -60,7 +56,7 @@ function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpenreturn (<div className="flex min-w-0 flex-1 items-center gap-2"><button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <Avatar label={user.avatar} seed={user.id} size={28} presence={resolveProfilePresence(true, user.id, EMPTY_ONLINE_SET)} ringColor="var(--muted)" />+ <Avatar label={user.avatar} seed={user.id} size={28} presence={user.presence} ringColor="var(--muted)" /></button><button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"><div data-testid="community-user-bar-name" className="truncate text-sm font-medium leading-tight">{user.name}</div>diff --git a/src/web/src/components/community/social/bot-approval-card.test.ts b/src/web/src/components/community/social/bot-approval-card.test.tsindex fea18507e..d66474d45 100644--- a/src/web/src/components/community/social/bot-approval-card.test.ts+++ b/src/web/src/components/community/social/bot-approval-card.test.ts@@ -1,15 +1,32 @@-import { describe, it, expect } from "vitest"+import { describe, it, expect, vi } from "vitest"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import type { FriendApprovalPayload } from "@alook/shared"import { serializeBeamSeed } from "@/lib/avatar/seed-url"import { BotApprovalCard } from "./bot-approval-card"+import { avatarInitial } from "@/lib/community/avatar"-const OTHER = { id: "u_alice", name: "Alice", discriminator: "0042", image: null }-const BOT = { id: "bot_zoe", name: "Zoe", discriminator: "0007", image: null }+const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unknown>>() }))+vi.mock("@/stores/community/ws", () => ({+ useCommunityProfile: (id?: string) => id ? profileState.map.get(id) : undefined,+}))++const OTHER = { id: "u_alice", name: "Alice", discriminator: "0042", image: null, avatarVersion: 0 }+const BOT = { id: "bot_zoe", name: "Zoe", discriminator: "0007", image: null, avatarVersion: 0 }function render(approval: FriendApprovalPayload): string {+ profileState.map = new Map([+ approval.otherProfile,+ approval.botProfile,+ approval.waitingOnProfile,+ ].flatMap((profile) => profile ? [[profile.id, {+ id: profile.id,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.image ?? avatarInitial(profile.name),+ avatarVersion: profile.avatarVersion,+ }] as const] : []))const client = new QueryClient()return renderToStaticMarkup(createElement(QueryClientProvider, { client }, createElement(BotApprovalCard, { approval })),diff --git a/src/web/src/components/community/social/bot-approval-card.tsx b/src/web/src/components/community/social/bot-approval-card.tsxindex 4fcc31738..b453b5e3c 100644--- a/src/web/src/components/community/social/bot-approval-card.tsx+++ b/src/web/src/components/community/social/bot-approval-card.tsx@@ -5,6 +5,8 @@ import type { FriendApprovalPayload } from "@alook/shared"import { useOwnerDecision } from "@/hooks/community/mutations/friends"import { Button } from "@/components/ui/button"import { ProfileAvatar } from "@/components/avatar"+import { useCommunityProfile } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"/*** Inline friend-approval card, rendered in a bot owner's DM with their bot when@@ -16,8 +18,18 @@ import { ProfileAvatar } from "@/components/avatar"export function BotApprovalCard({ approval }: { approval: FriendApprovalPayload }) {const decide = useOwnerDecision()const { status, waitingOn, otherProfile, botProfile, waitingOnProfile } = approval-- const other = otherProfile+ const other = readCommunityProfile(+ useCommunityProfile(otherProfile.id),+ otherProfile.id,+ )+ const bot = readCommunityProfile(+ useCommunityProfile(botProfile.id),+ botProfile.id,+ )+ const waiting = readCommunityProfile(+ useCommunityProfile(waitingOnProfile?.id),+ waitingOnProfile?.id ?? "",+ )const otherHandle = `${other.name}#${other.discriminator}`const onDecide = async (decision: "approve" | "deny") => {@@ -38,14 +50,14 @@ export function BotApprovalCard({ approval }: { approval: FriendApprovalPayload<ProfileAvatarlabel={other.name}seed={other.id}- src={other.image}+ src={other.avatar}size={40}data-testid="bot-approval-avatar"/><div className="min-w-0 flex-1"><div className="truncate font-medium">{otherHandle}</div><div className="text-xs text-muted-foreground">- {other.name} wants to be friends with {botProfile.name}.+ {other.name} wants to be friends with {bot.name}.</div></div></div>@@ -68,7 +80,7 @@ export function BotApprovalCard({ approval }: { approval: FriendApprovalPayload// status === "pending"if (waitingOn === "addressee" || waitingOn === "other-owner") {- const name = waitingOnProfile?.name ?? "them"+ const name = waitingOnProfile ? waiting.name : "them"return chip(`Approved β waiting on ${name}`)}diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsxindex 1a1071654..d9ceb3938 100644--- a/src/web/src/components/community/social/friends-page.tsx+++ b/src/web/src/components/community/social/friends-page.tsx@@ -4,7 +4,7 @@ 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 { toastApiError } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles } from "@/lib/community/profile-seed"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"@@ -17,6 +17,8 @@ import { hasStatus } from "./status-presets"import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"import type { OpenProfile } from "@/components/community/social/profile-types"import { isSelfBotFriendship, isPresenceOffline, MIN_SEARCH_LENGTH } from "@alook/shared"+import { useCommunityWsStore } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"function FriendSection({ title, count, emptyLabel, children }: {title: string@@ -65,7 +67,8 @@ export function FriendsPage({}, [friends, filter])const [addValue, setAddValue] = useState("")- const [searchResults, setSearchResults] = useState<{ id: string; name: string; image: string | null; avatarVersion: number; discriminator: string }[]>([])+ const [searchResults, setSearchResults] = useState<string[]>([])+ const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)// Relationship state by user id, so search results can show Friends/Pending/@@ -91,8 +94,29 @@ export function FriendsPage({if (q.length < MIN_SEARCH_LENGTH) { setSearchResults([]); return }debounceRef.current = setTimeout(async () => {try {- 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)+ const data = await apiFetchProfiles<{+ users: Array<{+ id: string+ name: string+ image: string | null+ avatarVersion: number+ discriminator: string+ }>+ }>(+ `/api/community/users/search?q=${encodeURIComponent(q)}`,+ (response) => response.users.map((user) => ({+ id: user.id,+ identityAbout: {+ name: user.name,+ discriminator: user.discriminator,+ },+ avatar: {+ avatar: user.image ?? avatarInitial(user.name),+ avatarVersion: user.avatarVersion,+ },+ })),+ )+ setSearchResults(data.users.map((user) => user.id))} catch (e) {setSearchResults([])toastApiError(e, "Search failed")@@ -258,17 +282,18 @@ export function FriendsPage({</div>{searchResults.length > 0 && (<div className="mt-1 rounded-md border border-border bg-popover p-1 shadow-(--e2)">- {searchResults.map((u) => {- const rel = relById.get(u.id)+ {searchResults.map((userId) => {+ const u = readCommunityProfile(profilesByUserId.get(userId), userId)+ const rel = relById.get(userId)const relLabel = rel === "friend" ? "Friends" : rel === "pending" ? "Pending" : rel === "blocked" ? "Blocked" : nullreturn (<button- key={u.id}+ key={userId}onClick={() => { if (!rel) sendRequest(u) }}disabled={!!rel}className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent disabled:cursor-not-allowed disabled:hover:bg-transparent">- <Avatar label={u.image ?? avatarInitial(u.name)} seed={u.id} size={28} />+ <Avatar label={u.avatar} seed={userId} size={28} /><span className={`flex-1 min-w-0 truncate text-sm font-medium ${rel ? "text-muted-foreground" : ""}`}>{u.name}<span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.tsindex ff7d0a557..af4098c93 100644--- a/src/web/src/components/community/social/invite-dialog.test.ts+++ b/src/web/src/components/community/social/invite-dialog.test.ts@@ -20,7 +20,21 @@ const mocks = vi.hoisted(() => ({vi.mock("sonner", () => ({ toast: mocks.toastSpy }))vi.mock("@/stores/community/ws", () => ({- useOnlineUserIds: () => mocks.onlineUserIds,+ useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) => {+ const profilesByUserId = new Map(mocks.friendsQuery.friends.flatMap((friend) =>+ friend.userId ? [[friend.userId, {+ id: friend.userId,+ name: friend.name,+ discriminator: friend.discriminator,+ avatar: friend.avatar,+ avatarVersion: friend.avatarVersion,+ aboutMe: friend.sub,+ presence: mocks.onlineUserIds.has(friend.userId) || mocks.onlineFriendIds.includes(friend.userId)+ ? "online"+ : "offline",+ }]] : []))+ return selector({ profilesByUserId })+ },}))vi.mock("@/hooks/community/use-friends", () => ({useFriendsPresence: () => ({ online: mocks.onlineFriendIds }),diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsxindex 7a9cf706d..b2871e56b 100644--- a/src/web/src/components/community/social/invite-dialog.tsx+++ b/src/web/src/components/community/social/invite-dialog.tsx@@ -24,8 +24,8 @@ import { useFriendsPresence } from "@/hooks/community/use-friends"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"import { useCurrentUser } from "@/contexts/community/current-user"import type { Friend } from "@/lib/community/models/people"-import { resolveRowPresence } from "@/lib/community/presence"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useCommunityWsStore } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"const INVITE_ORIGIN =typeof window !== "undefined" ? window.location.origin : ""@@ -134,8 +134,8 @@ export function InviteDialog({serverName: string}) {const currentUser = useCurrentUser()- const onlineUserIds = useOnlineUserIds()- const { online: onlineFriendIds } = useFriendsPresence(open)+ useFriendsPresence(open)+ const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)// Only friends who are NOT already members of `serverId` β server-side// filter so a stale local members cache can't leak already-joined rows.const friendsQuery = useInvitableFriends(serverId, open)@@ -151,17 +151,6 @@ export function InviteDialog({const inFlightUserIdsRef = useRef<Set<string>>(new Set())const [query, setQuery] = useState("")- // The WS store is hydrated from the current server's member-only snapshot,- // while this dialog can contain friends who are not members yet. Combine- // both authoritative scopes at read time so a later server hydration cannot- // erase a non-member friend. Exact WS deltas patch both sources (see- // presence-machine-events.ts), so an offline delta still wins immediately.- const inviteOnlineUserIds = useMemo(() => {- const next = new Set(onlineUserIds)- for (const userId of onlineFriendIds) next.add(userId)- return next- }, [onlineFriendIds, onlineUserIds])-// Resolve on open. Only depends on `open` + `token` β resolveOrCreate is a// hook that captures a fresh mutation object each render, so including it in// deps would loop. We read its latest identity via a closure at call time@@ -199,6 +188,20 @@ export function InviteDialog({const eligibleFriends = useMemo<Friend[]>(() => {const q = query.trim().toLowerCase()return friends+ .map((friend) => {+ const userId = friend.userId ?? friend.id+ const profile = readCommunityProfile(profilesByUserId.get(userId), userId)+ return {+ ...friend,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ }+ }).filter((f) => {if (!q) return truereturn (@@ -206,8 +209,7 @@ export function InviteDialog({(f.sub ?? "").toLowerCase().includes(q))})- .map((f) => ({ ...f, status: resolveRowPresence(f, inviteOnlineUserIds) }))- }, [friends, inviteOnlineUserIds, query])+ }, [friends, profilesByUserId, query])const pickerState = resolvePeoplePickerViewState({resolved: friendsQuery.data !== undefined,diff --git a/src/web/src/components/community/social/profile-card.test.ts b/src/web/src/components/community/social/profile-card.test.tsindex 364fcf681..08da3af5f 100644--- a/src/web/src/components/community/social/profile-card.test.ts+++ b/src/web/src/components/community/social/profile-card.test.ts@@ -192,7 +192,7 @@ describe("resolveProfileBackdropSeed", () => {describe("resolveCardStatus β WS overlay wins over row seed", () => {it("uses the overlay entry when one exists", () => {- const out = resolveCardStatus({ emoji: "π§", text: "Vibing" }, "π", "Reading")+ const out = resolveCardStatus({ statusEmoji: "π§", statusText: "Vibing" }, "π", "Reading")expect(out).toEqual({ emoji: "π§", text: "Vibing" })})@@ -207,9 +207,7 @@ describe("resolveCardStatus β WS overlay wins over row seed", () => {})it("lets the overlay clear a seed (emoji: null overrides seed emoji)", () => {- // When someone clears their status, the WS store's setUserStatus writes- // { emoji: null, text: null }. That must win over any lingering row seed.- const out = resolveCardStatus({ emoji: null, text: null }, "π", "Reading")+ const out = resolveCardStatus({ statusEmoji: null, statusText: null }, "π", "Reading")expect(out).toEqual({ emoji: null, text: null })})@@ -217,7 +215,7 @@ describe("resolveCardStatus β WS overlay wins over row seed", () => {// Overlay carries a text-only status (no emoji). Seed offers an emoji.// The overlay's presence β not its individual field values β is what// decides the source, so the seed's emoji does NOT leak in.- const out = resolveCardStatus({ emoji: null, text: "AFK" }, "π§", "Vibing")+ const out = resolveCardStatus({ statusEmoji: null, statusText: "AFK" }, "π§", "Vibing")expect(out).toEqual({ emoji: null, text: "AFK" })})})diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsxindex 452c25b7d..23b042ad5 100644--- a/src/web/src/components/community/social/profile-card.tsx+++ b/src/web/src/components/community/social/profile-card.tsx@@ -14,25 +14,27 @@ import type {Profile,} from "@/components/community/social/profile-types"import type { Breakpoint } from "@/hooks/use-mobile"-import { useCommunityWsStore } from "@/stores/community/ws"+import { useCommunityProfile } from "@/stores/community/ws"+import { avatarInitial } from "@/lib/community/avatar"import { tid } from "@/lib/community/testids"import { BotAuditPreview, isBotActivityActive } from "./bot-audit-preview"-// Merge rule for the card's status pill: overlay wins over seed. The overlay-// (`useCommunityWsStore.userStatuses`) is the same live source the member-// list and friend rows consume, so an entry there is always fresher than a-// row-fetched seed. When the overlay has no entry (either because that user-// hasn't emitted a `community:status.update` this session, or because the-// user is anonymous / userId is undefined), fall back to the initial-seed-// props passed by the opener. Both fields resolve independently; there is-// no "if the overlay defines emoji but not text, prefer the whole seed"-// case β the store writes both in one call.+// Live cards resolve status from the global profile map. Seed props are used+// only by static, id-less showcase cards.export function resolveCardStatus(- overlay: { emoji: string | null; text: string | null } | undefined,+ overlay: {+ statusEmoji?: string | null+ statusText?: string | null+ } | undefined,seedEmoji: string | null | undefined,seedText: string | null | undefined,): { emoji: string | null; text: string | null } {- if (overlay) return { emoji: overlay.emoji, text: overlay.text }+ if (overlay) {+ return {+ emoji: overlay.statusEmoji ?? null,+ text: overlay.statusText ?? null,+ }+ }return { emoji: seedEmoji ?? null, text: seedText ?? null }}@@ -186,11 +188,8 @@ function useAuditPreviewPosition(enabled: boolean, x: number, y: number) {}// Profile card β popover anchored at the click point on desktop, bottom sheet on mobile.-// Status (emoji + text) is read live from `useCommunityWsStore.userStatuses` β-// the same overlay the member list, friends list, and UserBar consume. The-// `initialStatusEmoji` / `initialStatusText` props are a first-paint seed for-// users the overlay has never seen a WS event for; once the overlay has an-// entry, it wins. See plans/profile-card-status-overlay.md.+// Identity, about, status, and presence are read from the global profile map+// whenever a userId is present. Static cards use their supplied display data.export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus, onOpenOwnerProfile, onOpenBotAudit, initialStatusEmoji, initialStatusText, activityStatusEmoji, activityStatusText, embedded }: {data: Profilex: number@@ -215,9 +214,23 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaconst [msg, setMsg] = useState("")const [open, setOpen] = useState(true)const mobile = bp === "mobile"- const liveStatus = useCommunityWsStore((s) => (data.userId ? s.userStatuses.get(data.userId) : undefined))+ const globalProfile = useCommunityProfile(data.userId)+ const liveStatus = data.userId+ ? {+ statusEmoji: globalProfile?.statusEmoji,+ statusText: globalProfile?.statusText,+ }+ : undefinedconst { emoji: statusEmoji, text: statusText } = resolveCardStatus(liveStatus, initialStatusEmoji, initialStatusText)const activityStatus = resolveCardStatus(liveStatus, activityStatusEmoji, activityStatusText)+ const name = data.userId ? (globalProfile?.name ?? "Unknown") : (data.name ?? "Unknown")+ const avatar = data.userId+ ? (globalProfile?.avatar ?? avatarInitial(name))+ : (data.avatar ?? avatarInitial(name))+ const discriminator = data.userId ? globalProfile?.discriminator : data.discriminator+ const about = data.userId ? globalProfile?.aboutMe : data.about+ const presence = data.userId ? (globalProfile?.presence ?? "offline") : data.presence+ const mutual = data.mutual ?? 0const botIdentity = data.identity?.kind === "bot" ? data.identity : nullconst showAuditPreview = Boolean(botIdentity?.ownedByViewer && data.userId)const { popoverRef, cardRef, previewRef, position: previewPosition } = useAuditPreviewPosition(@@ -225,7 +238,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdax,y,)- const backdropSeed = resolveProfileBackdropSeed(data.avatar, data.userId, data.name)+ const backdropSeed = resolveProfileBackdropSeed(avatar, data.userId, name)const close = () => setOpen(false)const send = () => {const text = msg.trim()@@ -253,7 +266,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaproportion the 64px avatar had at `-mt-8`. */}<div className="relative"><div className="rounded-full ring-[5px] ring-popover">- <Avatar label={data.avatar} seed={data.userId} size={77} presence={data.presence} ringColor="var(--popover)" />+ <Avatar label={avatar} seed={data.userId} size={77} presence={presence} ringColor="var(--popover)" /></div>{/* Status sits on the same row as the presence dot, just to itsright, instead of floating over the avatar's corner. The dot@@ -319,10 +332,10 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda</div><div className="rounded-lg bg-card p-4"><div className="flex min-w-0 items-baseline text-xl font-semibold leading-tight tracking-[-0.015em]">- <span className="min-w-0 truncate">{data.name}</span>- {data.discriminator && (+ <span className="min-w-0 truncate">{name}</span>+ {discriminator && (<span className="ml-1.5 shrink-0 text-sm font-normal tracking-wide text-muted-foreground">- #{data.discriminator}+ #{discriminator}</span>)}</div>@@ -333,8 +346,8 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda(not `mt-4`) so the gap reads unambiguously as a group boundary(a step past DESIGN.md's 16px between-groups token) rather thanjust tighter line spacing off the bio above it. */}- <p className="mt-2 text-[15px] text-muted-foreground">{data.about || "No bio yet."}</p>- {(botIdentity || data.contextLabel || data.mutual > 0) && (+ <p className="mt-2 text-[15px] text-muted-foreground">{about || "No bio yet."}</p>+ {(botIdentity || data.contextLabel || mutual > 0) && (<div className="mt-6 flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">{botIdentity && (<>@@ -368,7 +381,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda<Shield className="size-3" /> {data.contextLabel}</Badge>)}- {data.mutual > 0 && <span>{data.mutual} mutual server{data.mutual > 1 ? "s" : ""}</span>}+ {mutual > 0 && <span>{mutual} mutual server{mutual > 1 ? "s" : ""}</span>}</div>)}{!isSelf && (@@ -381,7 +394,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdasend()}}className="flex-1 bg-transparent text-[15px] outline-none placeholder:text-muted-foreground"- placeholder={`Message @${data.name}`}+ placeholder={`Message @${name}`}/><buttononClick={send}@@ -429,7 +442,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdashowCloseButton={false}className="data-[side=bottom]:border-t-0 bg-transparent p-3 shadow-none">- <SheetTitle className="sr-only">{data.name} profile</SheetTitle>+ <SheetTitle className="sr-only">{name} profile</SheetTitle><SheetClose className="sr-only">Close profile</SheetClose><div className="flex flex-col gap-2">{auditPreview}diff --git a/src/web/src/components/community/social/profile-lookup.test.ts b/src/web/src/components/community/social/profile-lookup.test.tsindex 2632436f3..5b358e35e 100644--- a/src/web/src/components/community/social/profile-lookup.test.ts+++ b/src/web/src/components/community/social/profile-lookup.test.ts@@ -98,13 +98,14 @@ function currentUser(overrides: Partial<CurrentUser> = {}): CurrentUser {discriminator: overrides.discriminator,statusEmoji: overrides.statusEmoji,statusText: overrides.statusText,+ presence: overrides.presence,}}describe("buildSelfProfile", () => {it("builds the viewer's own card from currentUser, independent of any member/friend list β regression for the /c/me UserBar bug where a same-named friend was shown instead of the viewer", () => {const me = currentUser({ id: "user_self", name: "Ren", discriminator: "0001", aboutMe: "hi" })- const profile = buildSelfProfile(me, new Set())+ const profile = buildSelfProfile(me)expect(profile.userId).toBe("user_self")expect(profile.name).toBe("Ren")@@ -113,18 +114,18 @@ describe("buildSelfProfile", () => {expect(profile.contextLabel).toBeUndefined()})- it("always resolves self presence to online, even when the viewer's id is absent from the online set", () => {- const profile = buildSelfProfile(currentUser({ id: "user_self" }), new Set())+ it("uses the canonical self presence supplied by currentUser", () => {+ const profile = buildSelfProfile(currentUser({ id: "user_self", presence: "online" }))expect(profile.presence).toBe("online")})it("falls back to an avatar initial when the viewer has no avatar", () => {- const profile = buildSelfProfile(currentUser({ name: "alice", avatar: "" }), new Set())+ const profile = buildSelfProfile(currentUser({ name: "alice", avatar: "" }))expect(profile.avatar).toBe("A")})it("uses the viewer's real server role when the caller provides one", () => {- const profile = buildSelfProfile(currentUser(), new Set(), "Admin")+ const profile = buildSelfProfile(currentUser(), "Admin")expect(profile.contextLabel).toBe("Admin")})diff --git a/src/web/src/components/community/social/profile-lookup.ts b/src/web/src/components/community/social/profile-lookup.tsindex aadf01396..07db3a40a 100644--- a/src/web/src/components/community/social/profile-lookup.ts+++ b/src/web/src/components/community/social/profile-lookup.ts@@ -2,7 +2,6 @@ import type { Member, Friend } from "@/lib/community/models/people"import type { Profile } from "@/components/community/social/profile-types"import type { View } from "@/components/community/shell/shell-types"import type { CurrentUser } from "@/contexts/community/current-user"-import { resolveProfilePresence } from "@/lib/community/presence"import { avatarInitial } from "@/lib/community/avatar"/**@@ -17,7 +16,6 @@ import { avatarInitial } from "@/lib/community/avatar"*/export function buildSelfProfile(currentUser: CurrentUser,- onlineUserIds: ReadonlySet<string>,contextLabel?: string,): Profile {return {@@ -29,7 +27,7 @@ export function buildSelfProfile(contextLabel,about: currentUser.aboutMe ?? "",mutual: 0,- presence: resolveProfilePresence(true, undefined, onlineUserIds),+ presence: currentUser.presence,identity: { kind: "human" },}}diff --git a/src/web/src/components/community/social/profile-types.ts b/src/web/src/components/community/social/profile-types.tsindex ee108c260..be6feb8c2 100644--- a/src/web/src/components/community/social/profile-types.ts+++ b/src/web/src/components/community/social/profile-types.ts@@ -3,7 +3,7 @@ import type { Presence } from "@/lib/community/models/people"// ββ Profile ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββexport type Profile = {- name: string+ name?: string// Stable user id of the profile's owner β the exact-match key for DM-target// resolution and self-detection (never match by non-unique display name).// Optional so mock/older Profile-constructing sites keep type-checking.@@ -13,14 +13,13 @@ export type Profile = {// flight. Shown at its true width, never re-padded. See computeDiscriminator// in @alook/shared.discriminator?: string- avatar: string+ avatar?: stringavatarVersion?: numbercontextLabel?: string- about: string- mutual: number- // Live online/offline dot on the card's avatar β undefined when no- // member/friend match could be resolved (e.g. a stale mention). See- // `resolveProfilePresence` in shell-frame.tsx.+ about?: string+ mutual?: number+ // Static-only fallback. Live cards read presence from the global profile+ // map by `userId` inside `ProfileCard`.presence?: Presence// Hydrated API identity. Seeded cards intentionally omit this so the main// profile can paint before the public profile request resolves.diff --git a/src/web/src/contexts/community/current-user.tsx b/src/web/src/contexts/community/current-user.tsxindex cddafc76b..331c5329c 100644--- a/src/web/src/contexts/community/current-user.tsx+++ b/src/web/src/contexts/community/current-user.tsx@@ -1,6 +1,17 @@"use client"-import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react"+import {+ createContext,+ useContext,+ useLayoutEffect,+ useMemo,+ type ReactNode,+} from "react"+import type { Presence } from "@/lib/community/models/people"+import {+ useCommunityProfile,+ useCommunityWsStore,+} from "@/stores/community/ws"/*** Thin context that carries the viewer's identity down the community tree.@@ -30,14 +41,10 @@ export type CurrentUser = {// status set" check β don't test either field's truthiness alone.statusEmoji?: string | nullstatusText?: string | null+ presence?: Presence}-type CurrentUserContextValue = {- currentUser: CurrentUser- setCurrentUser: (fn: (u: CurrentUser) => CurrentUser) => void-}--const CurrentUserContext = createContext<CurrentUserContextValue | null>(null)+const CurrentUserContext = createContext<CurrentUser | null>(null)export function CurrentUserProvider({initialUser,@@ -46,21 +53,25 @@ export function CurrentUserProvider({initialUser: CurrentUserchildren: ReactNode}) {- const [currentUser, setCurrentUserState] = useState<CurrentUser>(initialUser)- // `setCurrentUser` MUST keep a stable identity across renders. If it- // changes each render (e.g., inlined into `useMemo` deps on `currentUser`),- // consumers that put it in a dep array β like `CommunityShell`'s aboutMe- // hydration effect β will re-fire on every state change and can loop.- const setCurrentUser = useCallback(- (fn: (u: CurrentUser) => CurrentUser) => setCurrentUserState((u) => fn(u)),- [],- )- const value = useMemo<CurrentUserContextValue>(- () => ({ currentUser, setCurrentUser }),- [currentUser, setCurrentUser],- )+ const current = useCommunityProfile(initialUser.id)+ useLayoutEffect(() => {+ if (current?.name !== undefined && current.avatarVersion !== undefined) return+ const profiles = useCommunityWsStore.getState()+ profiles.seedProfiles(profiles.beginProfileSnapshot(), [{+ id: initialUser.id,+ ...(current?.name === undefined+ ? { identityAbout: { name: initialUser.name } }+ : {}),+ ...(current?.avatarVersion === undefined+ ? { avatar: {+ avatar: initialUser.avatar,+ avatarVersion: initialUser.avatarVersion ?? 0,+ } }+ : {}),+ }])+ }, [current?.avatarVersion, current?.name, initialUser])return (- <CurrentUserContext.Provider value={value}>+ <CurrentUserContext.Provider value={initialUser}>{children}</CurrentUserContext.Provider>)@@ -68,14 +79,19 @@ export function CurrentUserProvider({export function useCurrentUser(): CurrentUser {const ctx = useContext(CurrentUserContext)+ const profile = useCommunityProfile(ctx?.id)if (!ctx)throw new Error("useCurrentUser must be used within CurrentUserProvider")- return ctx.currentUser-}--export function useSetCurrentUser(): (fn: (u: CurrentUser) => CurrentUser) => void {- const ctx = useContext(CurrentUserContext)- if (!ctx)- throw new Error("useSetCurrentUser must be used within CurrentUserProvider")- return ctx.setCurrentUser+ return useMemo(() => ({+ id: ctx.id,+ email: ctx.email,+ name: profile?.name ?? ctx.name,+ avatar: profile?.avatar ?? ctx.avatar,+ avatarVersion: profile?.avatarVersion ?? ctx.avatarVersion,+ aboutMe: profile?.aboutMe,+ discriminator: profile?.discriminator,+ statusEmoji: profile?.statusEmoji,+ statusText: profile?.statusText,+ presence: profile?.presence,+ }), [ctx, profile])}diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.tsindex 85d1196a8..71a287580 100644--- a/src/web/src/hooks/community/community-ws/cache.test.ts+++ b/src/web/src/hooks/community/community-ws/cache.test.ts@@ -9,7 +9,6 @@ import {applyReactionToMessage,findCachedMessage,patchApprovalInCache,- patchAuthorNameInCache,patchMessageContentInCache,removeThreadFromCache,type PageCache,@@ -25,27 +24,10 @@ function pageCache(...pages: Msg[][]): PageCache {describe("community WS cache helpers", () => {it("preserves identity for undefined caches and misses", () => {const cache = pageCache([{ id: "m_1", content: "one" }])- expect(patchAuthorNameInCache(undefined, "u_1", "New")).toBeUndefined()- expect(patchAuthorNameInCache(cache, "u_missing", "New")).toBe(cache)expect(patchMessageContentInCache(cache, "m_missing", "New")).toBe(cache)expect(removeThreadFromCache(cache, "thread_missing")).toBe(cache)})- it("patches author names across pages without changing unrelated rows", () => {- const untouched = { id: "m_2", authorId: "u_2", authorName: "Other", content: "two" }- const cache = pageCache(- [{ id: "m_1", authorId: "u_1", authorName: "Old", content: "one" }, untouched],- [{ id: "m_3", authorId: "u_1", authorName: "Old", content: "three" }],- )-- const result = patchAuthorNameInCache(cache, "u_1", "New")!-- expect(result).not.toBe(cache)- expect(result.pages[0].messages[0].authorName).toBe("New")- expect(result.pages[0].messages[1]).toBe(untouched)- expect(result.pages[1].messages[0].authorName).toBe("New")- })-it("patches approval and content while preserving non-target rows", () => {const other = { id: "m_2", content: "two" }const cache = pageCache([{ id: "m_1", content: "one" }, other])diff --git a/src/web/src/hooks/community/community-ws/cache.ts b/src/web/src/hooks/community/community-ws/cache.tsindex 7375e14a3..5a97d168c 100644--- a/src/web/src/hooks/community/community-ws/cache.ts+++ b/src/web/src/hooks/community/community-ws/cache.ts@@ -7,31 +7,6 @@ import type { MessagesPage, Msg } from "@/lib/community/models/message"export type PageCache = InfiniteData<MessagesPage>-/**- * Patch every cached message authored by `userId` to the renamed- * `authorName` β `authorName` is a snapshot field written at send time- * (`communityMessage` doesn't store it; the live JOIN is `message.ts`'s- * `authorName: user.name`), so nothing else updates already-loaded message- * rows after a self-rename. Only touches rows that are actually cached in- * this client (open/previously-open channels & DMs) β a channel never- * loaded this session picks up the new name for free on its first real- * fetch, since that IS the live JOIN.- */-export function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, newName: string): PageCache | undefined {- if (!cache) return cache- let touched = false- const pages = cache.pages.map((p) => {- if (!p.messages.some((m) => m.authorId === userId)) return p- touched = true- return {- ...p,- messages: p.messages.map((m) => (m.authorId === userId ? { ...m, authorName: newName } : m)),- }- })- if (!touched) return cache- return { ...cache, pages }-}-/*** Patch the `approval` payload of a single cached message β the client-side* effect of a `MESSAGE_UPDATED` event. The card re-renders in its newdiff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.tsindex f92462b9c..5a034413b 100644--- a/src/web/src/hooks/community/community-ws/handler-context.ts+++ b/src/web/src/hooks/community/community-ws/handler-context.ts@@ -52,7 +52,7 @@ export type StructureTreeEventContext = Pick<>export type MembershipEventContext = Pick<CommunityWsHandlerContext,- "queryClient" | "viewerUserIdRef" | "projection"+ "queryClient" | "viewerUserIdRef" | "projection" | "wsStore">export type SocialEventContext = Pick<CommunityWsHandlerContext,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.tsindex 52c01b787..e98e23360 100644--- a/src/web/src/hooks/community/community-ws/identity-events.test.ts+++ b/src/web/src/hooks/community/community-ws/identity-events.test.ts@@ -1,44 +1,36 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { beforeEach, describe, expect, it } 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"+import { handleIdentityUpdate, handleProfileUpdate } from "./identity-events"function harness() {const queryClient = new QueryClient()- const invalidate = vi.fn()- const context = {+ return {queryClient,- wsStore: useCommunityWsStore.getState(),- projection: {- project: (project: () => void) => project(),- invalidate,- },- } as unknown as CommunityWsHandlerContext- return { queryClient, invalidate, context }+ context: {+ queryClient,+ wsStore: useCommunityWsStore.getState(),+ } as unknown as CommunityWsHandlerContext,+ }}beforeEach(() => {useCommunityWsStore.getState().reset()- useCommunityWsStore.getState().bindIdentityOwner("viewer")- useMessageStreamStore.getState().resetAll()+ useCommunityWsStore.getState().activateProfileAccount("viewer")})-describe("handleIdentityUpdate", () => {- it("patches all cached projections and the detached message stream", () => {- const { queryClient, context, invalidate } = harness()- queryClient.setQueryData(communityKeys.message("m1"), {+describe("profile identity events", () => {+ it("updates only the canonical avatar and leaves raw query snapshots untouched", () => {+ const { queryClient, context } = harness()+ const cached = {id: "m1",authorId: "u1",authorAvatar: "/avatar?v=1",authorAvatarVersion: 1,- })- const projectStream = vi.spyOn(- useMessageStreamStore.getState(),- "projectAvatarIdentity",- )+ }+ queryClient.setQueryData(communityKeys.message("m1"), cached)handleIdentityUpdate({type: "community:identity.update",@@ -47,64 +39,60 @@ describe("handleIdentityUpdate", () => {avatarVersion: 4,}, context)- expect(queryClient.getQueryData(communityKeys.message("m1"))).toMatchObject({- authorAvatar: "/avatar?v=4",- authorAvatarVersion: 4,+ expect(queryClient.getQueryData(communityKeys.message("m1"))).toBe(cached)+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ avatar: "/avatar?v=4",+ avatarVersion: 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)-+ it("retains the current avatar for stale and equal-version conflicting frames", () => {+ const { context } = harness()handleIdentityUpdate({type: "community:identity.update",userId: "u1",- avatar: "/avatar?v=4",- avatarVersion: 4,+ avatar: "/avatar?v=5",+ avatarVersion: 5,}, context)handleIdentityUpdate({type: "community:identity.update",userId: "u1",- avatar: "/avatar?v=5",- avatarVersion: 5,+ avatar: "/stale?v=4",+ avatarVersion: 4,}, context)- expect(invalidate).not.toHaveBeenCalled()-handleIdentityUpdate({type: "community:identity.update",userId: "u1",- avatar: "/different?v=5",+ avatar: "/conflict?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,+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ avatar: "/avatar?v=5",+ avatarVersion: 5,})+ })- handleIdentityUpdate({- type: "community:identity.update",- userId: "u1",- avatar: "/authoritative?v=4",- avatarVersion: 4,+ it("writes authoritative nullable profile fields to the canonical map", () => {+ const { context } = harness()+ handleProfileUpdate({+ type: "community:profile.update",+ userId: "bot-1",+ name: "Bot",+ discriminator: "0042",+ aboutMe: "",+ bannerColor: null,+ kind: "bot",+ ownerUserId: "owner-1",}, context)- expect(invalidate).toHaveBeenCalledWith("identity-cache-conflict", {- queryKey: communityKeys.all,- refetchType: "active",+ expect(useCommunityWsStore.getState().profilesByUserId.get("bot-1")).toMatchObject({+ name: "Bot",+ discriminator: "0042",+ aboutMe: "",+ bannerColor: null,+ kind: "bot",+ ownerUserId: "owner-1",})})})diff --git a/src/web/src/hooks/community/community-ws/identity-events.ts b/src/web/src/hooks/community/community-ws/identity-events.tsindex e3b2a7c17..9a11636fc 100644--- a/src/web/src/hooks/community/community-ws/identity-events.ts+++ b/src/web/src/hooks/community/community-ws/identity-events.ts@@ -1,47 +1,29 @@-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 { CommunityIdentityUpdate, CommunityProfileUpdate } from "@alook/shared"import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"export function handleIdentityUpdate(event: CommunityIdentityUpdate,- { queryClient, wsStore, projection }: CommunityWsHandlerContext,+ { wsStore }: 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- }+ wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{+ id: event.userId,+ avatar: { avatar: event.avatar, avatarVersion: event.avatarVersion },+ }])+}- 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",- })- }+export function handleProfileUpdate(+ event: CommunityProfileUpdate,+ { wsStore }: CommunityWsHandlerContext,+) {+ wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{+ id: event.userId,+ identityAbout: {+ name: event.name,+ discriminator: event.discriminator,+ aboutMe: event.aboutMe,+ bannerColor: event.bannerColor,+ kind: event.kind,+ ownerUserId: event.ownerUserId,+ },+ }])}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 362ee2a1a..a0ede9c19 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@@ -2,8 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryObserver } from "@tanstack/react-query"import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate } from "@alook/shared"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"-import { useCommunityWsStore } from "@/stores/community/ws"-import { resolveRowPresence } from "@/lib/community/presence"import type { PresenceResponse } from "@/hooks/community/use-server-panels"import { communityKeys } from "@/lib/query-keys"import {@@ -76,6 +74,20 @@ describe("useCommunityWs β member events", () => {}>(communityKeys.members("srv_1"))expect(cache?.pages[0].members.map((m) => m.userId)).toEqual(["u_1"])expect(cache?.pages[0].total).toBe(1)+ expect(cache?.pages[0].members[0]).toMatchObject({+ userId: "u_1",+ name: "n",+ discriminator: "0000",+ avatarVersion: 0,+ sub: "",+ })+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ expect(useCommunityWsStore.getState().profilesByUserId.get("u_1")).toMatchObject({+ name: "n",+ discriminator: "0000",+ avatar: "N",+ avatarVersion: 0,+ })})it("exact-refetches only the joined server's active presence seed", async () => {@@ -146,11 +158,6 @@ describe("useCommunityWs β member events", () => {})const refreshedSeed = capturedQueryClient.getQueryData<PresenceResponse>(affectedKey)expect(refreshedSeed).toEqual({ online: ["u_online"] })- if (!refreshedSeed) throw new Error("missing refreshed presence seed")- useCommunityWsStore.getState().hydratePresence(refreshedSeed.online)- const onlineUserIds = useCommunityWsStore.getState().onlineUserIds- expect(resolveRowPresence({ userId: "u_online" }, onlineUserIds)).toBe("online")- expect(resolveRowPresence({ userId: "u_offline" }, onlineUserIds)).toBe("offline")expect(otherQuery).toHaveBeenCalledTimes(1)expect(capturedQueryClient.getQueryData(otherKey)).toEqual({online: ["u_other"],@@ -216,7 +223,7 @@ describe("useCommunityWs β member events", () => {])})- it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {+ it("keeps message snapshots raw when member.update carries a rename", async () => {await mountHook()useMessageStreamStore.getState().dispatch({ kind: "dm", id: "dm_overlay" },@@ -233,9 +240,6 @@ describe("useCommunityWs β member events", () => {},)- // Two message caches β one channel, one DM β each with a message- // authored by the renamed user and one by someone else. Both should- // update; the other author's row must stay untouched.capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {pages: [{messages: [@@ -269,7 +273,7 @@ describe("useCommunityWs β member events", () => {pages: { messages: { id: string; authorName: string }[] }[]}>(communityKeys.channelMessages("ch_1"))expect(channelCache?.pages[0].messages).toEqual([- { id: "m_1", authorId: "u_renamed", authorName: "NewName", content: "hi" },+ { id: "m_1", authorId: "u_renamed", authorName: "OldName", content: "hi" },{ id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },])@@ -277,11 +281,11 @@ describe("useCommunityWs β member events", () => {pages: { messages: { id: string; authorName: string }[] }[]}>(communityKeys.dmMessages("dm_1"))expect(dmCache?.pages[0].messages).toEqual([- { id: "m_3", authorId: "u_renamed", authorName: "NewName", content: "sup" },+ { id: "m_3", authorId: "u_renamed", authorName: "OldName", content: "sup" },])expect(getMessageOverlay({ kind: "dm", id: "dm_overlay" }).liveById.get("m_overlay")?.authorName,- ).toBe("NewName")+ ).toBe("OldName")})it("a role-only member.update (no userId/nickname) does not touch any message cache", async () => {diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 6de0f2633..4a67f414d 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -19,9 +19,9 @@ import {grantForumSidebarChild,isKnownNonForumSidebarChannel,} from "@/hooks/community/use-forum-sidebar-threads"-import { patchAuthorNameInCache, type PageCache } from "@/hooks/community/community-ws/cache"import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"import { projectChannelScopeEviction } from "./channel-scope-projection"+import { avatarInitial } from "@/lib/community/avatar"import {invalidateChannelRefDirectory,invalidateChannelRoster,@@ -91,7 +91,18 @@ export function handleMemberJoin(event: CommunityMemberJoin,context: MembershipEventContext,) {- const { queryClient, viewerUserIdRef, projection } = context+ const { queryClient, viewerUserIdRef, projection, wsStore } = context+ wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{+ id: event.member.userId,+ identityAbout: {+ name: event.member.name,+ discriminator: event.member.discriminator,+ },+ avatar: {+ avatar: event.member.avatar ?? avatarInitial(event.member.name),+ avatarVersion: event.member.avatarVersion,+ },+ }])const key = communityKeys.members(event.serverId)queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(key,@@ -162,35 +173,5 @@ export function handleMemberUpdate(serverId: event.serverId,event,})- // A self-rename carries `userId` + `changes.nickname` β patch- // every cached message list's `authorName` snapshot for that- // author. A role-only change has no `userId`/`nickname`, so- // this is a no-op for that case.- if (event.userId && event.changes.nickname) {- const userId = event.userId- const newName = event.changes.nickname- for (const cacheEntry of queryClient.getQueryCache().findAll({- predicate: (q) =>- q.queryKey[0] === "community"- && (q.queryKey[1] === "channel" || q.queryKey[1] === "dm")- && q.queryKey[3] === "messages",- })) {- queryClient.setQueryData<PageCache | undefined>(- cacheEntry.queryKey,- (cache) => patchAuthorNameInCache(cache, userId, newName),- )- }- const streamState = useMessageStreamStore.getState()- for (const entry of streamState.entries.values()) {- if (entry.scope.kind === "channel" && entry.scope.serverId !== event.serverId) continue- for (const message of entry.state.liveById.values()) {- if (message.authorId !== userId) continue- useMessageStreamStore.getState().dispatch(entry.scope, {- type: "liveRefreshed",- message: { ...message, authorName: newName },- })- }- }- }finishMemberEvent(event, context)}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 be4425959..9d2dd51b4 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,6 +819,19 @@ describe("useCommunityWs β message.updated", () => {message: { id: "m_dm", seq: 4, type: "chat", content: "approval" },},)+ capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {+ pages: [{+ messages: [{+ id: "m_dm",+ type: "chat",+ authorId: "raw_author",+ authorName: "Raw Author",+ content: "approval",+ }],+ hasMore: false,+ }],+ pageParams: [null],+ })const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null, avatarVersion: 0 }const approval = {friendshipId: "friendship_1",@@ -826,6 +839,7 @@ describe("useCommunityWs β message.updated", () => {waitingOn: null,otherProfile: profile,botProfile: { ...profile, id: "bot_1", name: "Bot" },+ waitingOnProfile: { ...profile, id: "waiting_1", name: "Waiting" },}capturedOnMessage!({@@ -836,6 +850,21 @@ describe("useCommunityWs β message.updated", () => {})expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)+ const cache = capturedQueryClient.getQueryData<{+ pages: { messages: Array<{ authorName?: string; approval?: unknown }> }[]+ }>(communityKeys.dmMessages("dm_1"))+ expect(cache?.pages[0].messages[0]).toMatchObject({+ authorName: "Raw Author",+ approval,+ })+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ expect([...useCommunityWsStore.getState().profilesByUserId.values()]).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: "u_other", name: "Other", avatar: "O" }),+ expect.objectContaining({ id: "bot_1", name: "Bot", avatar: "B" }),+ expect.objectContaining({ id: "waiting_1", name: "Waiting", avatar: "W" }),+ ]),+ )})it("refreshes approval fields on a focused channel row that exists only in the overlay", async () => {diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex f74d9071e..2b062722c 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -22,6 +22,10 @@ import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/communitimport type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"import { armInboxReadReservationCandidate } from "@/hooks/community/inbox-read-reservation"+import {+ approvalProfilePatches,+ messageProfilePatches,+} from "@/lib/community/profile-seed"import {projectApprovalCopies,projectEditedCopies,@@ -62,6 +66,10 @@ export function handleMessageCreate(})}const projected = projectCommunityMessageCreate(event.message)+ wsStore.patchProfiles(+ wsStore.beginProfileSnapshot(),+ messageProfilePatches([projected]),+ )if (event.channelId === sub.channelId) {const serverId = useCommunityStore.getState().currentServerIdif (serverId) {@@ -176,6 +184,10 @@ export function handleMessageUpdated(event: CommunityMessageUpdated,context: MessageEventContext,) {+ context.wsStore.patchProfiles(+ context.wsStore.beginProfileSnapshot(),+ approvalProfilePatches(event.approval),+ )projectApprovalCopies(event, context)// When a card resolves (accepted/denied/superseded), the friend graph// changed β invalidate friends + pending so the owner's lists reflectdiff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.test.tsindex 0e6675ba1..4692ea99e 100644--- a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts@@ -18,7 +18,7 @@ beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)describe("useCommunityWs β presence", () => {- it("presence.update writes to the WS store and an existing friends snapshot", async () => {+ it("presence.update writes only to the canonical profile map", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {@@ -31,9 +31,9 @@ describe("useCommunityWs β presence", () => {}capturedOnMessage!(event)const { useCommunityWsStore } = await import("@/stores/community/ws")- expect(useCommunityWsStore.getState().onlineUserIds.has("u_pres")).toBe(true)+ expect(useCommunityWsStore.getState().profilesByUserId.get("u_pres")?.presence).toBe("online")expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({- online: ["friend_existing", "u_pres"],+ online: ["friend_existing"],})const patchedSnapshot = capturedQueryClient.getQueryData(communityKeys.friendsPresence())capturedOnMessage!(event)@@ -41,23 +41,18 @@ describe("useCommunityWs β presence", () => {expect(spy).not.toHaveBeenCalled()})- it("keeps reconnect snapshot scopes combined after late server hydration, then applies exact offline", async () => {+ it("applies an exact offline delta without mutating presence query snapshots", async () => {await mountHook()const { useCommunityWsStore } = await import("@/stores/community/ws")- // Reconnect reset, followed by friends refresh winning the race.- useCommunityWsStore.getState().resetPresence()capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {online: ["friend_non_member"],})-- // The later server snapshot is member-scoped and replaces only the WS- // source. The independent friends source must retain the non-member.- useCommunityWsStore.getState().hydratePresence(["server_member"])- expect(useCommunityWsStore.getState().onlineUserIds).toEqual(new Set(["server_member"]))- expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({- online: ["friend_non_member"],- })+ const store = useCommunityWsStore.getState()+ store.patchProfiles(store.beginProfileSnapshot(), [{+ id: "friend_non_member",+ presence: "online",+ }])const offline: CommunityPresenceUpdate = {type: "community:presence.update",@@ -65,8 +60,10 @@ describe("useCommunityWs β presence", () => {online: false,}capturedOnMessage!(offline)- expect(useCommunityWsStore.getState().onlineUserIds.has("friend_non_member")).toBe(false)- expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({ online: [] })+ expect(useCommunityWsStore.getState().profilesByUserId.get("friend_non_member")?.presence)+ .toBe("offline")+ expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence()))+ .toEqual({ online: ["friend_non_member"] })})it("does not create a friends presence cache from a live delta alone", async () => {@@ -93,9 +90,9 @@ describe("useCommunityWs β status.update β Zustand store, no cache", () => {}capturedOnMessage!(event)const { useCommunityWsStore } = await import("@/stores/community/ws")- expect(useCommunityWsStore.getState().userStatuses.get("u_status")).toEqual({- emoji: "π§",- text: "Vibing",+ expect(useCommunityWsStore.getState().profilesByUserId.get("u_status")).toMatchObject({+ statusEmoji: "π§",+ statusText: "Vibing",})// No cache touched.expect(spy).not.toHaveBeenCalled()diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.tsindex b5ac89480..c851eb585 100644--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts@@ -11,38 +11,29 @@ import type {import { communityKeys } from "@/lib/query-keys"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"-import type { FriendsPresenceResponse } from "@/hooks/community/use-friends"import type { MachinesResponse } from "@/hooks/community/use-machines"import type { PresenceMachineEventContext } from "@/hooks/community/community-ws/handler-context"-// The WS store carries the current server-member overlay. The friends snapshot-// is a second presence scope used by the DM shell and invite picker, so patch-// it too when it is mounted. Keeping exact deltas in both sources lets readers-// safely combine them without a stale online snapshot masking an offline event.export function handlePresenceUpdate(event: CommunityPresenceUpdate,- { queryClient }: PresenceMachineEventContext,) {- useCommunityWsStore.getState().setPresence(event.userId, event.online)- queryClient.setQueryData<FriendsPresenceResponse | undefined>(- communityKeys.friendsPresence(),- (prev) => {- if (!prev) return prev- const currentlyOnline = prev.online.includes(event.userId)- if (currentlyOnline === event.online) return prev- return {- ...prev,- online: event.online- ? [...prev.online, event.userId]- : prev.online.filter((userId) => userId !== event.userId),- }- },- )+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: event.userId,+ presence: event.online ? "online" : "offline",+ }])}// Status uses the same WS-store overlay pattern as presence.export function handleStatusUpdate(event: CommunityStatusUpdate) {- useCommunityWsStore.getState().setUserStatus(event.userId, event.statusEmoji, event.statusText)+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: event.userId,+ status: {+ statusEmoji: event.statusEmoji,+ statusText: event.statusText,+ },+ }])}// Push audit events into the bounded ring; the audit-log hook filters anddiff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex f2198fe00..3993aaf4f 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 { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"@@ -212,7 +212,10 @@ async function fetchCurrentWindow(pageParam: MessagesPageParam,tag: string | null,): Promise<MessagesPage> {- return apiFetchIdentity<MessagesPage>(buildMessagesUrl(scopeId, pageParam, tag))+ return apiFetchProfiles<MessagesPage>(+ buildMessagesUrl(scopeId, pageParam, tag),+ (page) => messageProfilePatches(page.messages),+ )}async function fetchCatchUp(@@ -229,8 +232,9 @@ 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 apiFetchIdentity<MessagesPage>(+ const page = await apiFetchProfiles<MessagesPage>(`/api/community/channels/${scopeId}/messages?${params}`,+ (response) => messageProfilePatches(response.messages),)messages.push(...page.messages)latestSeq = Math.max(latestSeq, page.latestSeq ?? 0)diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 9c5e54230..62a75b2c7 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -43,11 +43,20 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {if (url === "/api/community/users/me/read-state") {return { revision: 0, readStates: [] }}- if (url === "/api/community/users/me/profile") {+ if (url === "/api/community/users/self/profile") {return {id: "self",+ name: "Self",+ discriminator: "0001",+ image: "/api/community/users/self/avatar?v=7",avatar: "/api/community/users/self/avatar?v=7",avatarVersion: 7,+ aboutMe: "",+ bannerColor: null,+ mutualServers: 0,+ statusEmoji: null,+ statusText: null,+ kind: "human",}}throw new Error(`unexpected API fetch: ${String(url)}`)@@ -57,9 +66,9 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {await capturedOnReconnect!({ reconnectDurationMs: 1_000 })- expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/profile")+ expect(apiFetch).toHaveBeenCalledWith("/api/community/users/self/profile")const { useCommunityWsStore } = await import("@/stores/community/ws")- expect(useCommunityWsStore.getState().avatarIdentities.get("self")).toEqual({+ expect(useCommunityWsStore.getState().profilesByUserId.get("self")).toMatchObject({avatar: "/api/community/users/self/avatar?v=7",avatarVersion: 7,})@@ -74,6 +83,25 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {expect(capturedQueryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)})+ it("keeps the authenticated viewer online while resetting stale peer presence", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [+ { id: "self", presence: "online" },+ { id: "peer", presence: "online" },+ ])++ await reconcileCommunityWsReconnect(capturedQueryClient, 0, {+ viewerUserId: "self",+ })++ expect(useCommunityWsStore.getState().profilesByUserId.get("self")?.presence)+ .toBe("online")+ expect(useCommunityWsStore.getState().profilesByUserId.get("peer")?.presence)+ .toBe("offline")+ })+it("reports identity reconciliation failure when an active identity invalidation rejects", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")capturedQueryClient.setQueryData(communityKeys.bots(), { bots: [] })@@ -475,21 +503,26 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {expect(telemetry.complete).toHaveBeenCalledWith(summary)})- it("isolates a synchronous policy throw and reports only the stable policy key", async () => {+ it("isolates a policy rejection and reports only the stable policy key", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")const { useCommunityWsStore } = await import("@/stores/community/ws")- const originalResetPresence = useCommunityWsStore.getState().resetPresence+ const originalPatchProfiles = useCommunityWsStore.getState().patchProfiles+ let patchCallCount = 0useCommunityWsStore.setState({- resetPresence: () => { throw new Error("private sync detail") },+ patchProfiles: (...args) => {+ patchCallCount += 1+ if (patchCallCount === 1) throw new Error("private sync detail")+ return originalPatchProfiles(...args)+ },})const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)- useCommunityWsStore.setState({ resetPresence: originalResetPresence })+ useCommunityWsStore.setState({ patchProfiles: originalPatchProfiles })expect(summary).toMatchObject({ policyCount: 15, successCount: 14, failureCount: 1 })expect(telemetry.failure).toHaveBeenCalledWith({policy: "presence-overlay",- reason: "sync-throw",+ reason: "async-rejection",})expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private sync detail")})@@ -513,12 +546,20 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {it("resets presence and status overlays before authoritative invalidation starts", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")const { useCommunityWsStore } = await import("@/stores/community/ws")- const originalResetPresence = useCommunityWsStore.getState().resetPresence- const originalResetUserStatuses = useCommunityWsStore.getState().resetUserStatuses+ const store = useCommunityWsStore.getState()+ store.patchProfiles(store.beginProfileSnapshot(), [{+ id: "peer",+ presence: "online",+ status: { statusEmoji: "π±", statusText: "Growing" },+ }])+ const originalPatchProfiles = useCommunityWsStore.getState().patchProfilesconst order: string[] = []useCommunityWsStore.setState({- resetPresence: () => { order.push("presence-reset") },- resetUserStatuses: () => { order.push("status-reset") },+ patchProfiles: (_snapshot, patches) => {+ if (patches.some((patch) => patch.presence !== undefined)) order.push("presence-reset")+ if (patches.some((patch) => patch.status !== undefined)) order.push("status-reset")+ return true+ },})const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {@@ -532,8 +573,7 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {await reconcileCommunityWsReconnect(capturedQueryClient)useCommunityWsStore.setState({- resetPresence: originalResetPresence,- resetUserStatuses: originalResetUserStatuses,+ patchProfiles: originalPatchProfiles,})expect(order.slice(0, 2)).toEqual(["presence-reset", "status-reset"])@@ -574,6 +614,7 @@ describe("useCommunityWs β resyncs machines on WS reconnect", () => {const gates = new Map<string, { promise: Promise<void>; resolve: () => void }>()const started: string[] = []vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters) => {+ if (filters.predicate) return Promise.resolve()const key = JSON.stringify(filters.queryKey)started.push(key)let resolve!: () => voiddiff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex 094c1eb52..e1c85a073 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -4,8 +4,8 @@ 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 { userProfileQueryFn } from "@/hooks/community/use-user-profile"import { reconcileFocusedMessageQueries } from "@/hooks/community/community-ws/reconnect-messages"import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"import {@@ -123,7 +123,7 @@ async function reconcileCachedServer(queryClient: QueryClient, serverId: string)function policyExecutors(queryClient: QueryClient,- identityOwnerUserId?: string | null,+ viewerUserId?: string | null,): Record<CommunityWsReconcilePolicy, () => void | Promise<void>> {const sub = useCommunityStore.getState().subscriptionconst queryKeys = queryClient.getQueryCache().getAll().map((query) => query.queryKey)@@ -208,16 +208,35 @@ function policyExecutors("friends": async () => {await queryClient.invalidateQueries({ queryKey: communityKeys.friends(), refetchType: "active" })},- "presence-overlay": () => useCommunityWsStore.getState().resetPresence(),- "status-overlay": () => useCommunityWsStore.getState().resetUserStatuses(),+ "presence-overlay": async () => {+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(+ profiles.beginProfileSnapshot(),+ [...profiles.profilesByUserId.values()]+ .filter((profile) => (+ profile.id !== viewerUserId && profile.presence === "online"+ ))+ .map((profile) => ({ id: profile.id, presence: "offline" as const })),+ )+ },+ "status-overlay": async () => {+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(+ profiles.beginProfileSnapshot(),+ [...profiles.profilesByUserId.keys()].map((id) => ({+ id,+ status: { statusEmoji: null, statusText: null },+ })),+ )+ },"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")]+ ...(viewerUserId+ ? [userProfileQueryFn(viewerUserId)()]: []),...(hasIdentitySurface? [queryClient.invalidateQueries({@@ -299,7 +318,7 @@ export type CommunityWsReconcileSummary = {type CommunityWsReconnectOptions = {excludePolicies?: readonly CommunityWsReconcilePolicy[]- identityOwnerUserId?: string | null+ viewerUserId?: string | null}export async function reconcileCommunityWsReconnect(@@ -308,7 +327,7 @@ export async function reconcileCommunityWsReconnect(options: CommunityWsReconnectOptions = {},): Promise<CommunityWsReconcileSummary> {const startedAt = Date.now()- const executors = policyExecutors(queryClient, options.identityOwnerUserId)+ const executors = policyExecutors(queryClient, options.viewerUserId)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 e839c58e0..48f5abe1a 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -64,6 +64,7 @@ vi.mock("./presence-machine-events", () => ({}))vi.mock("./identity-events", () => ({handleIdentityUpdate: handlers.handleIdentityUpdate,+ handleProfileUpdate: handlers.handleProfileUpdate,}))function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchContext {@@ -80,10 +81,10 @@ function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchCo}describe("community WebSocket registry", () => {- it("has exactly one entry for each of the 44 runtime event types", () => {+ it("has exactly one entry for each of the 45 runtime event types", () => {const eventTypes = Object.values(WS_EVENTS).sort()const registryTypes = Object.keys(communityWsRegistry).sort()- expect(eventTypes).toHaveLength(44)+ expect(eventTypes).toHaveLength(45)expect(registryTypes).toEqual(eventTypes)})@@ -119,6 +120,7 @@ describe("community WebSocket registry", () => {["community:member.join", "handleMemberJoin"],["community:friend.accept", "handleFriendEvent"],["community:presence.update", "handlePresenceUpdate"],+ ["community:profile.update", "handleProfileUpdate"],["community:machine.created", "handleMachineCreated"],["community:bot.audit_event", "handleBotAuditEvent"],] as const)("dispatches %s through its existing handler group", (type, handlerName) => {diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex e2c9a2359..545ea33ad 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -44,7 +44,10 @@ import {handlePresenceUpdate,handleStatusUpdate,} from "@/hooks/community/community-ws/presence-machine-events"-import { handleIdentityUpdate } from "@/hooks/community/community-ws/identity-events"+import {+ handleIdentityUpdate,+ handleProfileUpdate,+} from "@/hooks/community/community-ws/identity-events"type CommunityEventType = CommunityWsEvent["type"]type CommunityEventFor<T extends CommunityEventType> = Extract<CommunityWsEvent, { type: T }>@@ -94,6 +97,7 @@ export const communityWsRegistry = {"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:profile.update": { handler: handleProfileUpdate, 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 dc5d2e2a5..0e49a5841 100644--- a/src/web/src/hooks/community/community-ws/test-harness.ts+++ b/src/web/src/hooks/community/community-ws/test-harness.ts@@ -150,6 +150,7 @@ async function resetStore() {useCommunityStore.getState().setCurrentServerId("s1")const { useCommunityWsStore } = await import("@/stores/community/ws")useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")useCommunityWsStore.getState().markAccessConnected()useMessageStreamStore.getState().resetAll()const mod = await import("../use-community-ws")diff --git a/src/web/src/hooks/community/fetch-all-server-members.ts b/src/web/src/hooks/community/fetch-all-server-members.tsindex d360b7212..e010fa283 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,9 @@import { MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"import type { Member } from "@/lib/community/models/people"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+} from "@/lib/community/profile-seed"type MembersPage = {members: Member[]@@ -14,8 +17,10 @@ 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 apiFetchIdentity<MembersPage>(+ const page = await apiFetchProfiles<MembersPage>(`/api/community/servers/${encodeURIComponent(serverId)}/members?${params}`,+ (data) => data.members.map((member) =>+ communityUserProfilePatch(member.userId, member)),)members.push(...page.members)cursor = page.hasMore ? page.cursor : undefineddiff --git a/src/web/src/hooks/community/mutations/profile.test.ts b/src/web/src/hooks/community/mutations/profile.test.tsnew file mode 100644index 000000000..f1b02bd2b--- /dev/null+++ b/src/web/src/hooks/community/mutations/profile.test.ts@@ -0,0 +1,59 @@+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),+ readUploadError: vi.fn(),+}))++beforeEach(() => apiFetchMock.mockReset())++describe("useUpdateProfile", () => {+ it("returns the authoritative PATCH response for guarded canonical commit", async () => {+ const response = {+ id: "viewer",+ name: "Renamed",+ discriminator: "0042",+ avatar: "avatar",+ avatarVersion: 3,+ aboutMe: "about",+ bannerColor: null,+ statusEmoji: "πΏ",+ statusText: "Here",+ }+ apiFetchMock.mockResolvedValue(response)+ const { useUpdateProfile } = await import("./profile")+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })+ let mutation!: ReturnType<typeof useUpdateProfile>+ function Probe() {+ mutation = useUpdateProfile()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ))+ })++ let result!: typeof response+ await act(async () => {+ result = await mutation.mutateAsync({ name: "Renamed", statusText: "Here" })+ })++ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/users/me/profile",+ {+ method: "PATCH",+ body: JSON.stringify({ name: "Renamed", statusText: "Here" }),+ },+ )+ expect(result).toBe(response)+ act(() => renderer.unmount())+ })+})diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.tsindex 741bfd7cc..3cb6bebdd 100644--- a/src/web/src/hooks/community/mutations/profile.ts+++ b/src/web/src/hooks/community/mutations/profile.ts@@ -10,19 +10,29 @@ export type UpdateProfileArgs = {statusText?: string | null}+export type UpdateProfileResult = {+ id: string+ name: string+ discriminator: string+ avatar: string+ avatarVersion: number+ aboutMe: string+ bannerColor: string | null+ statusEmoji: string | null+ statusText: string | null+}+/**- * PATCH the current user's profile card. Consumers apply the returned payload- * to their own local user state (the current-user identity lives outside the- * community query cache).+ * PATCH the current user's profile card. The shell applies the canonical+ * response to the global profile map without rewriting query data.*/export function useUpdateProfile() {- return useMutation<void, Error, UpdateProfileArgs>({- mutationFn: async (patch) => {- await apiFetch("/api/community/users/me/profile", {+ return useMutation<UpdateProfileResult, Error, UpdateProfileArgs>({+ mutationFn: (patch) =>+ apiFetch<UpdateProfileResult>("/api/community/users/me/profile", {method: "PATCH",body: JSON.stringify(patch),- })- },+ }),})}@@ -31,9 +41,8 @@ export type UploadUserAvatarResult = { url: string; avatarVersion: number }/*** Uploads the current user's avatar. Mirrors `useUploadServerIcon`'s raw- * `fetch`-with-`FormData` pattern. Consumers apply the returned URL to their- * own local `CurrentUser` state β the identity lives outside the community- * query cache (see `contexts/community/current-user.tsx`).+ * `fetch`-with-`FormData` pattern. The shell applies the versioned result to+ * the global profile map.*/export function useUploadUserAvatar() {return useMutation<UploadUserAvatarResult, Error, UploadUserAvatarArgs>({diff --git a/src/web/src/hooks/community/use-bots.test.ts b/src/web/src/hooks/community/use-bots.test.tsindex c96c0e5c2..987da7878 100644--- a/src/web/src/hooks/community/use-bots.test.ts+++ b/src/web/src/hooks/community/use-bots.test.ts@@ -3,11 +3,10 @@ import TestRenderer, { act } from "react-test-renderer"import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"-// The React harness for the hooks themselves isn't available in the repo-// (no jsdom / testing-library setup) β `invalidateBotSurfaces` is exported-// so this suite can exercise the exact invalidation logic each mutation's-// `onSuccess` calls, against a real QueryClient.+// Exercise the shared invalidation logic directly against a real QueryClient;+// hook-specific behavior is covered below with react-test-renderer.const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),@@ -15,6 +14,8 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")})function seededClient() {@@ -63,13 +64,31 @@ describe("invalidateBotSurfaces", () => {})describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {- it("useBots fetches through the identity-aware query function", async () => {- apiFetchMock.mockResolvedValue({ bots: [] })+ it("useBots fetches through the profile-seeding query function", async () => {+ apiFetchMock.mockResolvedValue({+ bots: [{+ id: "bot_1",+ name: "Seeded Bot",+ image: null,+ avatarVersion: 2,+ description: "",+ machineId: null,+ runtime: null,+ modelName: null,+ lastRefreshContextAt: null,+ dailyActivity: [],+ }],+ })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 })+ return React.createElement("span", {+ "data-count": result.bots.length,+ "data-name": result.bots[0]?.name,+ "data-avatar": result.bots[0]?.image,+ "data-version": result.bots[0]?.avatarVersion,+ })}let renderer!: TestRenderer.ReactTestRenderer@@ -81,7 +100,59 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {))})await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots"))- expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ await vi.waitFor(() => expect(renderer.root.findByType("span").props).toMatchObject({+ "data-count": 1,+ "data-name": "Seeded Bot",+ "data-avatar": "S",+ "data-version": 2,+ }))+ act(() => renderer.unmount())+ })++ it("useCreateBot commits the returned bot profile before invalidating metadata", async () => {+ const { useCreateBot } = await import("./use-bots")+ apiFetchMock.mockResolvedValue({+ bot: {+ id: "bot_created",+ name: "Created Bot",+ image: null,+ avatarVersion: 3,+ description: "",+ machineId: null,+ runtime: null,+ modelName: null,+ lastRefreshContextAt: null,+ dailyActivity: [],+ },+ })+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })+ let mutation!: ReturnType<typeof useCreateBot>+ function Probe() {+ mutation = useCreateBot()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ))+ })++ await act(async () => {+ await mutation.mutateAsync({ name: "Created Bot" })+ })++ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots", expect.objectContaining({+ method: "POST",+ }))+ expect(useCommunityWsStore.getState().profilesByUserId.get("bot_created")).toMatchObject({+ name: "Created Bot",+ kind: "bot",+ avatar: "C",+ avatarVersion: 3,+ })act(() => renderer.unmount())})@@ -103,7 +174,20 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {),)})- apiFetchMock.mockResolvedValue({ bot: { id: "bot_1" } })+ apiFetchMock.mockResolvedValue({+ bot: {+ id: "bot_1",+ name: "Bot",+ image: null,+ avatarVersion: 0,+ description: "",+ machineId: null,+ runtime: null,+ modelName: null,+ lastRefreshContextAt: null,+ dailyActivity: [],+ },+ })await act(async () => {await mutation.mutateAsync({ id: "bot_1", reasoningEffort: "xhigh" })@@ -122,10 +206,8 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {bot: { id: "bot_1", name: "Bot", description: "new description", image: null, machineId: "m_1", runtime: "node" },})const { useUpdateBot } = await import("./use-bots")- // useUpdateBot itself requires a QueryClientProvider to call useQueryClient(),- // which needs the jsdom harness this repo doesn't have. Assert the shape the- // mutationFn sends and returns instead β onSuccess's invalidateBotSurfaces(qc,- // data.bot.id) call is covered directly above.+ // Keep this low-level contract assertion focused on the mutation payload;+ // hook success behavior and shared invalidation are covered above.expect(typeof useUpdateBot).toBe("function")const result = await apiFetchMock("/api/community/bots/bot_1", {method: "PATCH",@@ -161,21 +243,15 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {// than reading an id off the (empty) response body.})- it("useUploadBotAvatar projects the returned identity before invalidating bot surfaces", async () => {+ it("useUploadBotAvatar patches the canonical avatar without rewriting raw caches", 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",- )+ useCommunityWsStore.getState().activateProfileAccount("viewer")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,@@ -201,19 +277,13 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {})})- expect(useCommunityWsStore.getState().avatarIdentities.get("bot_1")).toEqual({+ expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")).toMatchObject({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 }],+ bots: [{ id: "bot_1", image: "/avatar?v=1", avatarVersion: 1 }],})- 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 8c9540af7..5489c1fe1 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -2,12 +2,14 @@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 { apiFetchProfiles } from "@/lib/community/profile-seed"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 { BotActivityDay, CommunityProfilePatch } from "@/lib/community/models/people"+import { avatarInitial } from "@/lib/community/avatar"import type { DailyUsageMetric, ReasoningEffort } from "@alook/shared"+import { useMemo } from "react"+import { readCommunityProfile } from "@/lib/community/profile-read"export type BotUsageDay = {day: string@@ -53,12 +55,45 @@ export type BotsResponse = { bots: BotSummary[] }const EMPTY_BOTS: readonly BotSummary[] = Object.freeze([])+function botProfilePatch(bot: Pick<+ BotSummary,+ "id" | "name" | "image" | "avatarVersion"+>): CommunityProfilePatch {+ return {+ id: bot.id,+ identityAbout: {+ name: bot.name,+ kind: "bot",+ },+ avatar: {+ avatar: bot.image ?? avatarInitial(bot.name),+ avatarVersion: bot.avatarVersion,+ },+ }+}+export function useBots(): UseQueryResult<BotsResponse> & { bots: BotSummary[] } {const query = useQuery({queryKey: communityKeys.bots(),- queryFn: () => apiFetchIdentity<BotsResponse>("/api/community/bots"),+ queryFn: () => apiFetchProfiles<BotsResponse>(+ "/api/community/bots",+ (data) => data.bots.map(botProfilePatch),+ ),})- return { ...query, bots: query.data?.bots ?? (EMPTY_BOTS as BotSummary[]) }+ const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)+ const bots = useMemo(+ () => (query.data?.bots ?? EMPTY_BOTS).map((bot) => {+ const profile = readCommunityProfile(profilesByUserId.get(bot.id), bot.id)+ return {+ ...bot,+ name: profile.name,+ image: profile.avatar,+ avatarVersion: profile.avatarVersion,+ }+ }),+ [profilesByUserId, query.data?.bots],+ )+ return { ...query, bots }}export type CreateBotInput = {@@ -71,9 +106,8 @@ export type CreateBotInput = {reasoningEffort?: ReasoningEffort | null}-// Bot identity (name, image) is projected into friends() (self-bot rows) and-// dms() (DM peer avatars). Invalidate all three whenever the owner mutates-// a bot so open DM/friends pages re-render without a hard refresh.+// Bot identity (name, image) is read from the global profile map. These query+// invalidations refresh the remaining bot/friend/DM relationship metadata.//// The profile card fetches/caches a bot's aboutMe separately under// communityKeys.profile(botId) with its own 5-minute staleTime@@ -98,7 +132,11 @@ export function useCreateBot() {headers: { "Content-Type": "application/json" },body: JSON.stringify(input),}),- onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),+ onSuccess: (data) => {+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [botProfilePatch(data.bot)])+ invalidateBotSurfaces(qc, data.bot.id)+ },})}@@ -150,7 +188,11 @@ export function useUpdateBot() {: {}),}),}),- onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),+ onSuccess: (data) => {+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [botProfilePatch(data.bot)])+ invalidateBotSurfaces(qc, data.bot.id)+ },})}@@ -213,20 +255,11 @@ export function useUploadBotAvatar() {return (await res.json()) as UploadBotAvatarResult},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,- )+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: variables.botId,+ avatar: { avatar: data.url, avatarVersion: 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.tsindex 3734a3409..08c6e6246 100644--- a/src/web/src/hooks/community/use-channel-members.test.ts+++ b/src/web/src/hooks/community/use-channel-members.test.ts@@ -2,6 +2,7 @@ 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"+import { useCommunityWsStore } from "@/stores/community/ws"const apiFetchMock = vi.fn()@@ -11,11 +12,29 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")})describe("useChannelMembers", () => {it("fetches the roster through the identity-aware query function", async () => {- apiFetchMock.mockResolvedValue({ members: [] })+ apiFetchMock.mockResolvedValue({+ members: [{+ id: "membership_1",+ userId: "member_1",+ name: "Alice",+ discriminator: "0042",+ avatar: "A",+ avatarVersion: 4,+ sub: "",+ role: "member",+ status: "offline",+ statusEmoji: null,+ statusText: "",+ source: "explicit",+ isCreator: false,+ }],+ })const { useChannelMembers } = await import("./use-channel-members")const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })function Probe() {@@ -36,7 +55,15 @@ describe("useChannelMembers", () => {"/api/community/channels/private%2Fchannel/members",)})- expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ await vi.waitFor(() => {+ expect(renderer.root.findByType("span").props["data-count"]).toBe(1)+ })+ expect(useCommunityWsStore.getState().profilesByUserId.get("member_1")).toMatchObject({+ name: "Alice",+ discriminator: "0042",+ avatar: "A",+ avatarVersion: 4,+ })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 702977e2c..482edc0a2 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -2,7 +2,10 @@import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+} from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { CommunityRole } from "@alook/shared"import type { CommunityUserCore } from "@/lib/community/models/people"@@ -41,7 +44,11 @@ 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),- apiFetchIdentity<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`),+ apiFetchProfiles<{ members: ChannelMember[] }>(+ `/api/community/channels/${encodeURIComponent(channelId)}/members`,+ (data) => data.members.map((member) =>+ communityUserProfilePatch(member.userId, member)),+ ),])const present = new Set(channelData.members.map((member) => member.userId))return {@@ -65,8 +72,10 @@ export function useChannelMembers(const query = useQuery({queryKey: communityKeys.channelMembers(channelId),queryFn: () =>- apiFetchIdentity<{ members: ChannelMember[] }>(+ apiFetchProfiles<{ members: ChannelMember[] }>(`/api/community/channels/${encodeURIComponent(channelId)}/members`,+ (data) => data.members.map((member) =>+ communityUserProfilePatch(member.userId, member)),),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 c31d395b2..5170a2108 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -2,7 +2,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { Thread, Msg } from "@/lib/community/models/message"@@ -96,7 +96,11 @@ export const threadsQueryFn = (channelId: string) => async ({ signal }: { signal: thread.name,messageCount: thread.messageCount ?? 0,lastMessageAt: thread.lastMessageAt ?? thread.createdAt,- parent: { authorName: opener?.authorName ?? "", text: (opener?.content ?? first?.content ?? "").slice(0, 100) },+ parent: {+ authorId: opener?.authorId,+ authorName: opener?.authorName ?? "",+ text: (opener?.content ?? first?.content ?? "").slice(0, 100),+ },...(opener ? { parentSeq: opener.seq } : {}),...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}),}@@ -137,7 +141,10 @@ export function useForumTags(channelId: string | null, enabled: boolean) {export type PinsResponse = { pins: Msg[] }export const pinsQueryFn = (channelId: string) => () =>- apiFetchIdentity<PinsResponse>(`/api/community/channels/${channelId}/pins`)+ apiFetchProfiles<PinsResponse>(+ `/api/community/channels/${channelId}/pins`,+ (data) => messageProfilePatches(data.pins),+ )export function usePins(channelId: string | null): UseQueryResult<PinsResponse> & {pins: Msg[]diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.tsindex 0b1211a3c..2436fcc14 100644--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts@@ -12,6 +12,7 @@ import {unmountHook,} from "./community-ws/test-harness"import { useCommunityStore } from "@/stores/community"+import { useCommunityWsStore } from "@/stores/community/ws"import {registerReadSurface,releaseReadSurface,@@ -117,7 +118,12 @@ describe("community read-state lifecycle reconciliation", () => {it("schedules the first-auth owner before non-Inbox reconciliation completes", async () => {vi.useFakeTimers()- await mountHook()+ await mountHook({ viewerUserId: "viewer-1" })+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: "viewer-1",+ presence: "offline",+ }])let releaseSnapshot!: (value: unknown) => voidgetCommunityApiFetchMock().mockReturnValueOnce(new Promise((resolve) => {releaseSnapshot = resolve@@ -126,6 +132,8 @@ describe("community read-state lifecycle reconciliation", () => {const authentication = capturedUseUserWsOptions?.onAuthenticated?.()expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()+ expect(useCommunityWsStore.getState().profilesByUserId.get("viewer-1")?.presence)+ .toBe("online")await vi.advanceTimersByTimeAsync(500)expect(invalidate).toHaveBeenCalledWith({queryKey: communityKeys.inbox(),diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex ebc9aecc7..867706164 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -57,7 +57,7 @@ export type {* is driven by the reconciliation table in `plans/21-community-tech-debt-pass-2.md`.** State this hook owns *outside* the query cache:- * - `useCommunityWsStore.onlineUserIds` β presence set, WS-only.+ * - `useCommunityWsStore.profilesByUserId` β canonical user profile facts.* - `useCommunityWsStore.seenMessageIds` β dedup for `message.create`.* - `useCommunityStore.typingByScope` + `typingTimers` β typing indicator,* keyed by conversation scope with per-(scope, user) auto-expire timers.@@ -223,10 +223,20 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {const viewerUserId = options?.viewerUserId ?? nullviewerUserIdRef.current = viewerUserIduseEffect(() => {- useCommunityWsStore.getState().bindIdentityOwner(viewerUserId)+ const store = useCommunityWsStore.getState()+ const profileAccountEpoch = store.activateProfileAccount(viewerUserId)+ if (viewerUserId) {+ store.patchProfiles(store.beginProfileSnapshot(), [{+ id: viewerUserId,+ presence: "online",+ }])+ }return () => {const store = useCommunityWsStore.getState()- if (store.identityOwnerUserId === viewerUserId) store.bindIdentityOwner(null)+ if (+ store.profileViewerId === viewerUserId+ && store.profileAccountEpoch === profileAccountEpoch+ ) store.activateProfileAccount(null)}}, [viewerUserId])@@ -479,14 +489,22 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {try {await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs, {excludePolicies: ["inbox-dms"],- identityOwnerUserId: viewerUserIdRef.current,+ viewerUserId: viewerUserIdRef.current,})} finally {scheduleInboxInvalidate({ inbox: true, dms: true })}}, [queryClient, scheduleInboxInvalidate])const handleAuthenticated = useCallback(async () => {- useCommunityWsStore.getState().markAccessConnected()+ const store = useCommunityWsStore.getState()+ store.markAccessConnected()+ const viewerId = viewerUserIdRef.current+ if (viewerId) {+ store.patchProfiles(store.beginProfileSnapshot(), [{+ id: viewerId,+ presence: "online",+ }])+ }const firstAuthentication = !hasAuthenticatedRef.currenthasAuthenticatedRef.current = trueif (firstAuthentication) {diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.tsindex 1014b1743..1ecf945e7 100644--- a/src/web/src/hooks/community/use-dms.test.ts+++ b/src/web/src/hooks/community/use-dms.test.ts@@ -1,6 +1,9 @@import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient } from "@tanstack/react-query"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -9,6 +12,8 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")})describe("useDms / dmsQueryFn", () => {@@ -31,4 +36,53 @@ describe("useDms / dmsQueryFn", () => {await qc.fetchQuery({ queryKey: key, queryFn: dmsQueryFn })expect(qc.getQueryData(key)).toEqual({ conversations: [] })})++ it("projects the canonical peer profile without rewriting the raw DM cache", async () => {+ const { useDms } = await import("./use-dms")+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })+ const raw = {+ conversations: [{+ id: "dm_1",+ userId: "u_1",+ name: "Raw Alice",+ discriminator: "0001",+ avatar: "raw",+ avatarVersion: 1,+ status: "offline",+ preview: "hello",+ }],+ }+ qc.setQueryData(communityKeys.dms(), raw)+ const store = useCommunityWsStore.getState()+ store.patchProfiles(store.beginProfileSnapshot(), [{+ id: "u_1",+ identityAbout: { name: "Global Alice", discriminator: "0042" },+ avatar: { avatar: "global", avatarVersion: 7 },+ presence: "online",+ }])+ let projected!: ReturnType<typeof useDms>+ function Probe() {+ projected = useDms()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Probe),+ ))+ })++ expect(projected.dms[0]).toMatchObject({+ name: "Global Alice",+ discriminator: "0042",+ avatar: "global",+ avatarVersion: 7,+ status: "online",+ preview: "hello",+ })+ expect(qc.getQueryData(communityKeys.dms())).toBe(raw)+ act(() => renderer.unmount())+ })})diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 53c3fb4bb..866737655 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -1,9 +1,15 @@"use client"import { useQuery, type UseQueryResult } from "@tanstack/react-query"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+} from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { DM } from "@/lib/community/models/people"+import { useMemo } from "react"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"/*** Fetches the DM conversation sidebar list.@@ -19,15 +25,33 @@ export type DmsResponse = { conversations: DM[] }const EMPTY_DMS: readonly DM[] = Object.freeze([])export const dmsQueryFn = () =>- apiFetchIdentity<DmsResponse>("/api/community/users/me/dms")+ apiFetchProfiles<DmsResponse>(+ "/api/community/users/me/dms",+ (data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm)),+ )export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {const query = useQuery({queryKey: communityKeys.dms(),queryFn: dmsQueryFn,})+ const profilesByUserId = useProfilesByUserId()+ const dms = useMemo(+ () => (query.data?.conversations ?? EMPTY_DMS).map((dm) => {+ const profile = readCommunityProfile(profilesByUserId.get(dm.userId), dm.userId)+ return {+ ...dm,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ }+ }),+ [profilesByUserId, query.data?.conversations],+ )return {...query,- dms: query.data?.conversations ?? (EMPTY_DMS as DM[]),+ dms,}}diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.tsindex 0521e8e3c..9c33ee7ae 100644--- a/src/web/src/hooks/community/use-forum-feed.test.ts+++ b/src/web/src/hooks/community/use-forum-feed.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest"+import { useCommunityWsStore } from "@/stores/community/ws"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -20,7 +21,11 @@ const emptyIncluded = {}describe("forumFeedPageQueryFn", () => {- beforeEach(() => apiFetchMock.mockReset())+ beforeEach(() => {+ apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+ })it("requests the canonical created-order collection with includes, tag, and cursor", async () => {apiFetchMock.mockResolvedValue({ threads: [], included: emptyIncluded, hasMore: false })@@ -42,6 +47,49 @@ describe("forumFeedPageQueryFn", () => {const url = apiFetchMock.mock.calls[0]![0] as stringexpect(new URL(url, "http://localhost").searchParams.get("tag")).toBe("archived")})++ it("seeds opener and participant profiles while returning the raw page", async () => {+ const page = {+ threads: [],+ included: {+ parentMessages: [{+ id: "m1",+ channelId: "forum_one",+ seq: 1,+ content: "post",+ authorId: "author_1",+ authorName: "Alice",+ authorImage: null,+ authorAvatarVersion: 2,+ }],+ firstMessages: [],+ tags: [],+ participants: [+ { channelId: "thread_1", userId: "participant_1", userName: "Bob", userImage: "bob.png", userAvatarVersion: 3 },+ { channelId: "thread_1", userId: "participant_2", userName: null, userImage: null, userAvatarVersion: 0 },+ ],+ },+ hasMore: false,+ }+ apiFetchMock.mockResolvedValue(page)++ const result = await forumFeedPageQueryFn("forum_one", null)({ pageParam: null })++ expect(result).toBe(page)+ expect(useCommunityWsStore.getState().profilesByUserId.get("author_1")).toMatchObject({+ name: "Alice",+ avatar: "A",+ avatarVersion: 2,+ })+ expect(useCommunityWsStore.getState().profilesByUserId.get("participant_1")).toMatchObject({+ name: "Bob",+ avatar: "bob.png",+ avatarVersion: 3,+ })+ const anonymousParticipant = useCommunityWsStore.getState().profilesByUserId.get("participant_2")+ expect(anonymousParticipant).toMatchObject({ avatarVersion: 0 })+ expect(anonymousParticipant).not.toHaveProperty("name")+ })})describe("mapForumFeedPages", () => {diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex 77898f0df..a6b30ac7a 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -3,7 +3,7 @@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 { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import { canonicalUserImage } from "@/lib/community/storage"@@ -105,8 +105,36 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null) {})if (tag) params.set("tag", tag)if (pageParam) params.set("cursor", pageParam)- return apiFetchIdentity<ForumFeedPage>(+ return apiFetchProfiles<ForumFeedPage>(`/api/community/channels/${channelId}/threads?${params.toString()}`,+ (page) => [+ ...page.included.parentMessages.map((message) => ({+ id: message.authorId,+ identityAbout: { name: message.authorName },+ avatar: {+ avatar: canonicalUserImage(+ message.authorId,+ message.authorImage,+ message.authorAvatarVersion,+ ) ?? avatarInitial(message.authorName),+ avatarVersion: message.authorAvatarVersion,+ },+ })),+ ...page.included.participants.map((participant) => ({+ id: participant.userId,+ ...(participant.userName !== null+ ? { identityAbout: { name: participant.userName } }+ : {}),+ avatar: {+ avatar: canonicalUserImage(+ participant.userId,+ participant.userImage,+ participant.userAvatarVersion,+ ) ?? avatarInitial(participant.userName ?? "Unknown"),+ avatarVersion: participant.userAvatarVersion,+ },+ })),+ ],)}}@@ -148,6 +176,7 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {messageCount: thread.messageCount ?? 0,lastMessageAt: thread.activityAt,parent: {+ authorId: opener?.authorId,authorName: opener?.authorName ?? "",text: (first?.content ?? "").slice(0, 100),},diff --git a/src/web/src/hooks/community/use-friends.test.ts b/src/web/src/hooks/community/use-friends.test.tsindex 1928759ed..98338fd89 100644--- a/src/web/src/hooks/community/use-friends.test.ts+++ b/src/web/src/hooks/community/use-friends.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { createElement } from "react"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -10,15 +11,20 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")})describe("useFriends / friendsQueryFn", () => {it("fetches accepted + blocked + pending buckets in parallel and merges", async () => {// Legacy aggregate GET /friends retired β each bucket from its sub-resource.const byUrl: Record<string, unknown> = {- "/api/community/friends/accepted": { friends: [{ id: "f_1", name: "n", discriminator: "0000", avatar: "a", status: "offline", sub: "" }] },- "/api/community/friends/blocked": { blocked: [{ id: "b_1", name: "b", avatar: "a" }] },- "/api/community/friends/pending": { pending: [{ id: "p_1", userId: "u_1", name: "n", avatar: "a", kind: "incoming" }] },+ "/api/community/friends/accepted": { friends: [{ id: "f_1", userId: "friend_1", name: "n", discriminator: "0000", avatar: "a", avatarVersion: 1, status: "offline", sub: "" }] },+ "/api/community/friends/blocked": { blocked: [+ { id: "b_1", userId: "blocked_1", name: "b", avatar: "b", avatarVersion: 2 },+ { id: "b_legacy", name: "legacy", avatar: "l", avatarVersion: 0 },+ ] },+ "/api/community/friends/pending": { pending: [{ id: "p_1", userId: "pending_1", name: "p", avatar: "p", avatarVersion: 3, kind: "incoming" }] },}apiFetchMock.mockImplementation(async (url: string) => {if (!(url in byUrl)) throw new Error(`unexpected url ${url}`)@@ -28,8 +34,13 @@ describe("useFriends / friendsQueryFn", () => {const { friendsQueryFn } = await import("./use-friends")const data = await friendsQueryFn()expect(data.friends).toHaveLength(1)- expect(data.blocked).toHaveLength(1)+ expect(data.blocked).toHaveLength(2)expect(data.pending).toHaveLength(1)+ expect(useCommunityWsStore.getState().profilesByUserId).toMatchObject(new Map([+ ["friend_1", expect.objectContaining({ name: "n", avatarVersion: 1 })],+ ["blocked_1", expect.objectContaining({ name: "b", avatarVersion: 2 })],+ ["pending_1", expect.objectContaining({ name: "p", avatarVersion: 3 })],+ ]))expect(apiFetchMock).toHaveBeenCalledTimes(3)const urls = apiFetchMock.mock.calls.map((c) => c[0]).sort()expect(urls).toEqual([@@ -39,6 +50,55 @@ describe("useFriends / friendsQueryFn", () => {])})+ it("projects canonical profiles while preserving raw friend presentation fields", async () => {+ const { useFriends } = await import("./use-friends")+ const TestRenderer = await import("react-test-renderer")+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })+ const raw = {+ friends: [+ { id: "f1", userId: "friend_1", name: "raw friend", discriminator: "0001", avatar: "raw", avatarVersion: 1, status: "offline", statusEmoji: null, statusText: "", sub: "raw presentation" },+ { id: "legacy", name: "legacy", discriminator: "0002", avatar: "legacy", avatarVersion: 0, status: "offline", statusEmoji: null, statusText: "", sub: "legacy presentation" },+ ],+ pending: [{ id: "p1", userId: "pending_1", name: "raw pending", avatar: "raw", avatarVersion: 1, kind: "incoming" }],+ blocked: [+ { id: "b1", userId: "blocked_1", name: "raw blocked", avatar: "raw", avatarVersion: 1 },+ { id: "legacy-blocked", name: "legacy blocked", avatar: "legacy", avatarVersion: 0 },+ ],+ }+ qc.setQueryData(communityKeys.friends(), raw)+ const store = useCommunityWsStore.getState()+ store.patchProfiles(store.beginProfileSnapshot(), [+ { id: "friend_1", identityAbout: { name: "Global Friend", discriminator: "0042" }, avatar: { avatar: "friend-global", avatarVersion: 4 }, presence: "online", status: { statusEmoji: "πΏ", statusText: "Here" } },+ { id: "pending_1", identityAbout: { name: "Global Pending" }, avatar: { avatar: "pending-global", avatarVersion: 5 } },+ { id: "blocked_1", identityAbout: { name: "Global Blocked" }, avatar: { avatar: "blocked-global", avatarVersion: 6 } },+ ])+ let projected!: ReturnType<typeof useFriends>+ function Probe() {+ projected = useFriends()+ return null+ }+ let renderer!: ReturnType<typeof TestRenderer.create>+ await TestRenderer.act(async () => {+ renderer = TestRenderer.create(createElement(+ QueryClientProvider,+ { client: qc },+ createElement(Probe),+ ))+ })++ expect(projected.friends).toEqual([+ expect.objectContaining({ name: "Global Friend", discriminator: "0042", avatar: "friend-global", avatarVersion: 4, status: "online", statusEmoji: "πΏ", statusText: "Here", sub: "raw presentation" }),+ expect.objectContaining({ name: "legacy", sub: "legacy presentation" }),+ ])+ expect(projected.pending[0]).toMatchObject({ name: "Global Pending", avatar: "pending-global", avatarVersion: 5 })+ expect(projected.blocked).toEqual([+ expect.objectContaining({ name: "Global Blocked", avatar: "blocked-global", avatarVersion: 6 }),+ expect.objectContaining({ name: "legacy blocked" }),+ ])+ expect(qc.getQueryData(communityKeys.friends())).toBe(raw)+ await TestRenderer.act(async () => renderer.unmount())+ })+it("populates queryClient at communityKeys.friends() and is invalidated by prefix", async () => {apiFetchMock.mockResolvedValueOnce({ friends: [] })diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex aec6cd926..fa2def064 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -1,10 +1,17 @@"use client"import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"+import { useMemo } from "react"import { apiFetch } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+ loadAndSeedProfiles,+} from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"+import { useProfilesByUserId } from "@/stores/community/ws"+import { readCommunityProfile } from "@/lib/community/profile-read"/*** The community read routes wrap their D1 hits in `readOrStale` (see@@ -47,9 +54,44 @@ 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([- 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),+ apiFetchProfiles<{ friends: Friend[]; stale?: boolean }>(+ "/api/community/friends/accepted",+ (data) => {+ throwIfStale(data)+ return data.friends.flatMap((friend) =>+ friend.userId ? [communityUserProfilePatch(friend.userId, friend)] : [])+ },+ ),+ apiFetchProfiles<{ blocked: BlockedUser[]; stale?: boolean }>(+ "/api/community/friends/blocked",+ (data) => {+ throwIfStale(data)+ return data.blocked.flatMap((blocked) => blocked.userId+ ? [{+ id: blocked.userId,+ identityAbout: { name: blocked.name },+ avatar: {+ avatar: blocked.avatar,+ avatarVersion: blocked.avatarVersion,+ },+ }]+ : [])+ },+ ),+ apiFetchProfiles<{ pending: PendingRequest[]; stale?: boolean }>(+ "/api/community/friends/pending",+ (data) => {+ throwIfStale(data)+ return data.pending.map((pending) => ({+ id: pending.userId,+ identityAbout: { name: pending.name },+ avatar: {+ avatar: pending.avatar,+ avatarVersion: pending.avatarVersion,+ },+ }))+ },+ ),])return {friends: acceptedData.friends,@@ -68,11 +110,63 @@ export function useFriends(): UseQueryResult<FriendsResponse> & {queryFn: friendsQueryFn,placeholderData: keepPreviousData,})+ const profilesByUserId = useProfilesByUserId()+ const friends = useMemo(+ () => (query.data?.friends ?? EMPTY_FRIENDS).map((friend) => {+ if (!friend.userId) return friend+ const profile = readCommunityProfile(+ profilesByUserId.get(friend.userId),+ friend.userId,+ )+ return {+ ...friend,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ }+ }),+ [profilesByUserId, query.data?.friends],+ )+ const pending = useMemo(+ () => (query.data?.pending ?? EMPTY_PENDING).map((request) => {+ const profile = readCommunityProfile(+ profilesByUserId.get(request.userId),+ request.userId,+ )+ return {+ ...request,+ name: profile.name,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ }+ }),+ [profilesByUserId, query.data?.pending],+ )+ const blocked = useMemo(+ () => (query.data?.blocked ?? EMPTY_BLOCKED).map((entry) => {+ if (!entry.userId) return entry+ const profile = readCommunityProfile(+ profilesByUserId.get(entry.userId),+ entry.userId,+ )+ return {+ ...entry,+ name: profile.name,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ }+ }),+ [profilesByUserId, query.data?.blocked],+ )return {...query,- friends: query.data?.friends ?? (EMPTY_FRIENDS as Friend[]),- pending: query.data?.pending ?? (EMPTY_PENDING as PendingRequest[]),- blocked: query.data?.blocked ?? (EMPTY_BLOCKED as BlockedUser[]),+ friends,+ pending,+ blocked,}}@@ -81,15 +175,19 @@ export function useFriends(): UseQueryResult<FriendsResponse> & {* friends-list analogue of `usePresence(serverId)` in `use-server-panels.ts`.** Friends can be online without ever sharing a server, so the co-member-- * scoped WS presence snapshot alone never learns about them. This seeds- * `useCommunityWsStore`'s `onlineUserIds` on mount (see- * `app/c/me/layout.tsx`); WS `community:presence.update` events- * keep it fresh afterward.+ * scoped WS presence snapshot alone never learns about them. This seeds the+ * global profile map on mount; WS `community:presence.update` events keep it+ * fresh afterward.*/export type FriendsPresenceResponse = { online: string[] }export const friendsPresenceQueryFn = () =>- apiFetch<FriendsPresenceResponse & { stale?: boolean }>("/api/community/friends/presence").then(throwIfStale)+ loadAndSeedProfiles(+ () => apiFetch<FriendsPresenceResponse & { stale?: boolean }>(+ "/api/community/friends/presence",+ ).then(throwIfStale),+ (data) => data.online.map((id) => ({ id, presence: "online" })),+ )const EMPTY_ONLINE: readonly string[] = Object.freeze([])diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex d7255f22f..bc6b86dd4 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,7 +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 { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { UnreadServer, UnreadDm, Mention, Marked } from "@/lib/community/models/inbox"import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"@@ -38,10 +38,24 @@ const EMPTY_MARKED: readonly Marked[] = Object.freeze([])export type UnreadsResponse = { servers: UnreadServer[]; dms: UnreadDm[] }export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) =>- apiFetch<UnreadsResponse & { stale?: boolean }>(+ apiFetchProfiles<UnreadsResponse & { stale?: boolean }>("/api/community/users/me/inbox/unreads",+ (data) => {+ throwIfStale(data)+ return data.dms.map((dm) => ({+ id: dm.otherUserId,+ identityAbout: {+ name: dm.otherUserName,+ discriminator: dm.otherUserDiscriminator,+ },+ avatar: {+ avatar: dm.otherUserAvatar,+ avatarVersion: dm.otherUserAvatarVersion,+ },+ }))+ },{ signal },- ).then(throwIfStale)+ )export const inboxUnreadsReservedQueryFn = (queryClient: ReturnType<typeof useQueryClient>) => ({ signal }: { signal?: AbortSignal } = {},@@ -70,7 +84,13 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {export type MentionsResponse = { mentions: Mention[] }export const inboxMentionsQueryFn = () =>- apiFetchIdentity<MentionsResponse & { stale?: boolean }>("/api/community/users/me/inbox/mentions").then(throwIfStale)+ apiFetchProfiles<MentionsResponse & { stale?: boolean }>(+ "/api/community/users/me/inbox/mentions",+ (data) => {+ throwIfStale(data)+ return messageProfilePatches(data.mentions.map((mention) => mention.m))+ },+ )export function useInboxMentions(): UseQueryResult<MentionsResponse> & {mentions: Mention[]@@ -89,7 +109,13 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {export type MarkedResponse = { marked: Marked[] }const inboxMarkedQueryFn = () =>- apiFetchIdentity<MarkedResponse & { stale?: boolean }>("/api/community/users/me/marks").then(throwIfStale)+ apiFetchProfiles<MarkedResponse & { stale?: boolean }>(+ "/api/community/users/me/marks",+ (data) => {+ throwIfStale(data)+ return messageProfilePatches(data.marked.map((marked) => marked.m))+ },+ )/*** The Marked feed is lazy β unlike unreads/mentions (which the shell readsdiff --git a/src/web/src/hooks/community/use-invitable-friends.test.ts b/src/web/src/hooks/community/use-invitable-friends.test.tsnew file mode 100644index 000000000..e71842083--- /dev/null+++ b/src/web/src/hooks/community/use-invitable-friends.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { useCommunityWsStore } from "@/stores/community/ws"++const apiFetchMock = vi.fn()+const fetchAllServerMembersMock = vi.fn()+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),+}))+vi.mock("./fetch-all-server-members", () => ({+ fetchAllServerMembers: (...args: unknown[]) => fetchAllServerMembersMock(...args),+}))++beforeEach(() => {+ apiFetchMock.mockReset()+ fetchAllServerMembersMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+})++describe("invitableFriendsQueryFn", () => {+ it("seeds identified friends and preserves identifier-free rows", async () => {+ const identified = {+ id: "friendship_1",+ userId: "friend_1",+ name: "Alice",+ discriminator: "0042",+ avatar: "A",+ avatarVersion: 2,+ status: "offline",+ sub: "",+ }+ const legacy = {+ id: "legacy",+ name: "Legacy",+ discriminator: "0000",+ avatar: "L",+ avatarVersion: 0,+ status: "offline",+ sub: "",+ }+ apiFetchMock.mockResolvedValue({ friends: [identified, legacy] })+ fetchAllServerMembersMock.mockResolvedValue([{ userId: "someone_else" }])+ const { invitableFriendsQueryFn } = await import("./use-invitable-friends")++ const result = await invitableFriendsQueryFn("server_1")++ expect(result.friends).toEqual([identified, legacy])+ expect(useCommunityWsStore.getState().profilesByUserId.get("friend_1")).toMatchObject({+ name: "Alice",+ avatarVersion: 2,+ })+ })+})diff --git a/src/web/src/hooks/community/use-invitable-friends.ts b/src/web/src/hooks/community/use-invitable-friends.tsindex 22eb74df1..21a136389 100644--- a/src/web/src/hooks/community/use-invitable-friends.ts+++ b/src/web/src/hooks/community/use-invitable-friends.ts@@ -1,7 +1,10 @@"use client"import { useQuery, type UseQueryResult } from "@tanstack/react-query"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+} from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { Friend } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"@@ -23,7 +26,12 @@ const EMPTY: readonly Friend[] = Object.freeze([])export async function invitableFriendsQueryFn(serverId: string): Promise<InvitableFriendsResponse> {const [accepted, members] = await Promise.all([- apiFetchIdentity<{ friends: Friend[]; stale?: boolean }>("/api/community/friends/accepted"),+ apiFetchProfiles<{ friends: Friend[]; stale?: boolean }>(+ "/api/community/friends/accepted",+ (data) => data.friends.flatMap((friend) => friend.userId+ ? [communityUserProfilePatch(friend.userId, friend)]+ : []),+ ),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 fda8ae462..9b29509ff 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 { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { Msg } from "@/lib/community/models/message"@@ -36,7 +36,10 @@ export type OpenerPayload = {}export const messageQueryFn = (messageId: string) => () =>- apiFetchIdentity<OpenerPayload>(`/api/community/messages/${messageId}`)+ apiFetchProfiles<OpenerPayload>(+ `/api/community/messages/${messageId}`,+ (message) => messageProfilePatches([message]),+ )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 e665bbf38..a2d669227 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 { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type {MessagesPage,@@ -79,9 +79,11 @@ export const channelMessagesQueryFn =pageParam,tag,)- return signal- ? apiFetchIdentity<MessagesPage>(url, { signal })- : apiFetchIdentity<MessagesPage>(url)+ return apiFetchProfiles<MessagesPage>(+ url,+ (page) => messageProfilePatches(page.messages),+ signal ? { signal } : undefined,+ )}export const dmMessagesQueryFn =@@ -97,9 +99,11 @@ export const dmMessagesQueryFn =`/api/community/channels/${dmId}/messages`,pageParam,)- return signal- ? apiFetchIdentity<MessagesPage>(url, { signal })- : apiFetchIdentity<MessagesPage>(url)+ return apiFetchProfiles<MessagesPage>(+ url,+ (page) => messageProfilePatches(page.messages),+ signal ? { signal } : undefined,+ )}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 c11f5430c..4d4e01ad1 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -7,7 +7,10 @@ import {type InfiniteData,} from "@tanstack/react-query"import { toastApiError } from "@/lib/api/client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+} from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { Member } from "@/lib/community/models/people"import type {@@ -123,7 +126,11 @@ export const membersPageQueryFn =const params = new URLSearchParams()if (pageParam) params.set("cursor", pageParam)const url = `/api/community/servers/${serverId}/members${params.toString() ? `?${params}` : ""}`- return apiFetchIdentity<MembersEnvelope>(url)+ return apiFetchProfiles<MembersEnvelope>(+ url,+ (data) => data.members.map((member) =>+ communityUserProfilePatch(member.userId, member)),+ )}// ββ Cache mutation helpers (also used by the WS handler in Step 3) ββββββββββ@@ -425,8 +432,10 @@ export function useServerMembers(serverId: string | null): UseServerMembers {try {const params = new URLSearchParams({ q })if (cursor) params.set("cursor", cursor)- const data = await apiFetchIdentity<SearchEnvelope>(+ const data = await apiFetchProfiles<SearchEnvelope>(`/api/community/servers/${serverId}/members/search?${params}`,+ (page) => page.members.map((member) =>+ communityUserProfilePatch(member.userId, member)),)if (searchSeq.current !== seq) returnsetSearchOverlay((current) => {diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.tsindex e944d5dd3..65ebc5bcb 100644--- a/src/web/src/hooks/community/use-server-panels.ts+++ b/src/web/src/hooks/community/use-server-panels.ts@@ -2,6 +2,7 @@import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { loadAndSeedProfiles } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"import type { InviteRow } from "@/lib/community/models/people"@@ -80,13 +81,17 @@ export function useInvites(/*** Fetches the presence roster for a server β the list of online user ids* cached at `communityKeys.presence(serverId)`. WS `presence.update` events- * live-patch the `useCommunityWsStore.onlineUserIds` set (Step 3); this- * initial load seeds the same set on server switch.+ * live-patch the global profile map; this initial load seeds the same map.*/export type PresenceResponse = { online: string[]; truncated?: boolean; limit?: number }export const presenceQueryFn = (serverId: string) => () =>- apiFetch<PresenceResponse & { stale?: boolean }>(`/api/community/servers/${serverId}/presence`).then(throwIfStale)+ loadAndSeedProfiles(+ () => apiFetch<PresenceResponse & { stale?: boolean }>(+ `/api/community/servers/${serverId}/presence`,+ ).then(throwIfStale),+ (data) => data.online.map((id) => ({ id, presence: "online" })),+ )const EMPTY_ONLINE: readonly string[] = Object.freeze([])export function usePresence(diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.tsindex da5dc035a..f87038f7e 100644--- a/src/web/src/hooks/community/use-user-profile.ts+++ b/src/web/src/hooks/community/use-user-profile.ts@@ -1,6 +1,7 @@"use client"-import { apiFetchIdentity } from "@/lib/community/identity-projection"+import { apiFetchProfiles } from "@/lib/community/profile-seed"+import { avatarInitial } from "@/lib/community/avatar"/*** Fetches a public user profile card (avatar, name, aboutMe, mutual-server@@ -33,7 +34,28 @@ export type UserProfile = UserProfileBase & ()export const userProfileQueryFn = (userId: string) => () =>- apiFetchIdentity<UserProfile>(`/api/community/users/${userId}/profile`)+ apiFetchProfiles<UserProfile>(+ `/api/community/users/${userId}/profile`,+ (profile) => [{+ id: profile.id,+ identityAbout: {+ name: profile.name,+ discriminator: profile.discriminator,+ aboutMe: profile.aboutMe,+ bannerColor: profile.bannerColor,+ kind: profile.kind,+ ownerUserId: profile.kind === "bot" ? profile.ownerProfile.id : null,+ },+ avatar: {+ avatar: profile.image ?? avatarInitial(profile.name),+ avatarVersion: profile.avatarVersion,+ },+ status: {+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ },+ }],+ )// 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/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 2e67c5c24..5ca230686 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -69,7 +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 mockListDmPeerUserIds = vi.fn(() => Promise.resolve([] as string[]))const mockListChannelMemberUserIds = vi.fn()const mockGetCoMemberUserIds = vi.fn()const mockGetFriendUserIds = vi.fn()@@ -84,6 +84,7 @@ import {fanOutToDM,fanOutStatusUpdate,fanOutIdentityUpdate,+ fanOutProfileUpdate,broadcastToUserSafe,} from "./fanout"import { WS_EVENTS } from "@alook/shared"@@ -245,7 +246,7 @@ describe("fanOutStatusUpdate", () => {mockGetChannelType.mockResolvedValue("text")})- it("broadcasts to the deduped union of co-members and friends", async () => {+ it("broadcasts to self plus the deduped union of co-members and friends", async () => {mockGetCoMemberUserIds.mockResolvedValue(["u1", "u2"])mockGetFriendUserIds.mockResolvedValue(["u2", "u3"])@@ -255,7 +256,7 @@ describe("fanOutStatusUpdate", () => {expect(mockGetFriendUserIds).toHaveBeenCalledWith(expect.anything(), "self1")expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)expect(mockBroadcastToUsers).toHaveBeenCalledWith(- ["u1", "u2", "u3"],+ ["self1", "u1", "u2", "u3"],{type: "community:status.update",userId: "self1",@@ -265,13 +266,16 @@ describe("fanOutStatusUpdate", () => {)})- it("does not broadcast when the audience is empty", async () => {+ it("still broadcasts to the author's other tabs when no peer audience exists", async () => {mockGetCoMemberUserIds.mockResolvedValue([])mockGetFriendUserIds.mockResolvedValue([])await fanOutStatusUpdate("self1", null, null)- expect(mockBroadcastToUsers).not.toHaveBeenCalled()+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(+ ["self1"],+ expect.objectContaining({ type: "community:status.update" }),+ )})it("never throws β absorbs a DB error and logs a warning", async () => {@@ -364,6 +368,60 @@ describe("fanOutIdentityUpdate", () => {})})+describe("fanOutProfileUpdate", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))+ mockBroadcastToUsers.mockResolvedValue(undefined)+ mockGetCoMemberUserIds.mockResolvedValue(["co-member", "shared"])+ mockGetFriendUserIds.mockResolvedValue(["friend", "shared"])+ mockListDmPeerUserIds.mockResolvedValue(["dm-peer"])+ })++ it("broadcasts the canonical bot profile to self, peers, and its owner", async () => {+ await fanOutProfileUpdate({+ id: "bot_1",+ name: "Bot",+ discriminator: "0042",+ aboutMe: "Helper",+ bannerColor: "#123456",+ identity: { kind: "bot", ownerProfile: { id: "owner_1" } },+ })++ expect(mockBroadcastToUsers).toHaveBeenCalledWith(+ ["bot_1", "co-member", "shared", "friend", "dm-peer", "owner_1"],+ {+ type: "community:profile.update",+ userId: "bot_1",+ name: "Bot",+ discriminator: "0042",+ aboutMe: "Helper",+ bannerColor: "#123456",+ kind: "bot",+ ownerUserId: "owner_1",+ },+ )+ })++ it("uses no owner for humans and contains audience failures", async () => {+ mockGetCoMemberUserIds.mockRejectedValueOnce(new Error("db down"))++ await expect(fanOutProfileUpdate({+ id: "human_1",+ name: "Human",+ discriminator: "0001",+ aboutMe: "",+ bannerColor: null,+ identity: { kind: "human" },+ })).resolves.toBeUndefined()++ expect(mockWarn).toHaveBeenCalledWith(+ "fanout_profile_update_failed",+ expect.objectContaining({ userId: "human_1", err: expect.stringContaining("db down") }),+ )+ })+})+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 8c53882db..65b0de744 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -150,34 +150,37 @@ export function fanOutToDM(* separate `ws-do` worker and isn't reachable from `src/web`'s API routes,* but it's built from the same two shared query functions used here.*/-async function getProfileAudience(db: Database, userId: string): Promise<string[]> {- const [coMembers, friends] = await Promise.all([- queries.communityMember.getCoMemberUserIds(db, userId),- queries.communityFriendship.getFriendUserIds(db, userId),- ])- return [...new Set([...coMembers, ...friends])]-}--async function getIdentityAudience(db: Database, userId: string): Promise<string[]> {+async function getProfileAudience(+ db: Database,+ userId: string,+ ownerUserId?: string | null,+): 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])]+ return [...new Set([+ userId,+ ...coMembers,+ ...friends,+ ...dmPeers,+ ...(ownerUserId ? [ownerUserId] : []),+ ])]}export function fanOutIdentityUpdate(userId: string,avatar: string,avatarVersion: number,+ ownerUserId?: string | null,): Promise<void> {try {const { env, ctx } = getCloudflareContext()const db = getDb((env as Env).DB)const work = (async () => {try {- const audience = await getIdentityAudience(db, userId)+ const audience = await getProfileAudience(db, userId, ownerUserId)await broadcastToRecipients(audience, {type: WS_EVENTS.IDENTITY_UPDATE,userId,@@ -203,21 +206,19 @@ export function fanOutIdentityUpdate(}/**- * Fan out a status change to everyone who can currently see the user- * (server co-members + friends). Self is intentionally excluded from their- * own audience β the caller updates the local WS store directly on save- * success instead (see `setUserStatus` call sites in `shell-frame.tsx` /- * `settings/user-settings.tsx`).+ * Fan out a status change to every visible surface, including the author's+ * other tabs and devices.*/export async function fanOutStatusUpdate(userId: string,statusEmoji: string | null,statusText: string | null,+ ownerUserId?: string | null,): Promise<void> {try {const { env } = getCloudflareContext()const db = getDb((env as Env).DB)- const audience = await getProfileAudience(db, userId)+ const audience = await getProfileAudience(db, userId, ownerUserId)await broadcastToRecipients(audience, {type: WS_EVENTS.STATUS_UPDATE,userId,@@ -229,6 +230,38 @@ export async function fanOutStatusUpdate(}}+export async function fanOutProfileUpdate(profile: {+ id: string+ name: string+ discriminator: string+ aboutMe: string+ bannerColor: string | null+ identity: { kind: "human" } | {+ kind: "bot"+ ownerProfile: { id: string }+ }+}): Promise<void> {+ try {+ const { env } = getCloudflareContext()+ const db = getDb((env as Env).DB)+ const kind = profile.identity.kind+ const ownerUserId = kind === "bot" ? profile.identity.ownerProfile.id : null+ const audience = await getProfileAudience(db, profile.id, ownerUserId)+ await broadcastToRecipients(audience, {+ type: WS_EVENTS.PROFILE_UPDATE,+ userId: profile.id,+ name: profile.name,+ discriminator: profile.discriminator,+ aboutMe: profile.aboutMe,+ bannerColor: profile.bannerColor,+ kind,+ ownerUserId,+ })+ } catch (err) {+ log.warn("fanout_profile_update_failed", { userId: profile.id, err: String(err) })+ }+}+/*** Fan out an event to all members of a server.*/diff --git a/src/web/src/lib/community/identity-projection.test.ts b/src/web/src/lib/community/identity-projection.test.tsdeleted file mode 100644index cfca30a8f..000000000--- a/src/web/src/lib/community/identity-projection.test.ts+++ /dev/null@@ -1,96 +0,0 @@-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.tsdeleted file mode 100644index de7e7b799..000000000--- a/src/web/src/lib/community/identity-projection.ts+++ /dev/null@@ -1,144 +0,0 @@-"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/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.tsindex 00dd75a17..0d37d5e01 100644--- a/src/web/src/lib/community/message-dispatcher.ts+++ b/src/web/src/lib/community/message-dispatcher.ts@@ -149,10 +149,16 @@ export async function planCommittedMessage(.filter((id) => notifyContentSet.has(id) && allowed(id)),)- const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()+ const replyMap = new Map<string, {+ id: string+ authorId: string+ authorName: string+ content: string | null+ }>()if (replyTarget) {replyMap.set(replyTarget.id, {id: replyTarget.id,+ authorId: replyTarget.authorId,authorName: replyTarget.authorName,content: replyTarget.content,})diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex 94012cbed..390c76fa6 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -44,13 +44,24 @@ export type MessageRow = {friendshipId?: string | null}-type ReplyTargetRow = { id: string; authorName: string; content: string | null }+type ReplyTargetRow = {+ id: string+ authorId: string+ authorName: string+ content: string | null+}type UiAttachment = { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }type WsAttachment = { id: string; filename: string; url: string; thumbnailUrl?: string; contentType?: string; size?: number; width?: number; height?: number }type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[] }-type ReplyPreview = { id: string; authorName: string; text: string; deleted?: boolean }+type ReplyPreview = {+ id: string+ authorId?: string+ authorName: string+ text: string+ deleted?: boolean+}type ThreadPreview = {id: string@@ -97,6 +108,7 @@ function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): Rif (!target) return { id: row.replyToId, authorName: "Unknown", text: "", deleted: true }return {id: target.id,+ authorId: target.authorId,authorName: target.authorName,text: truncateMessagePreview(target.content ?? ""),}diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex 6bda8a1d4..a786b73b1 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -77,69 +77,6 @@ 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 375cf7739..e4412549c 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -73,7 +73,6 @@ 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" }@@ -119,38 +118,6 @@ 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 {@@ -504,37 +471,6 @@ 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/models/message.ts b/src/web/src/lib/community/models/message.tsindex aa53fdcc6..11617cbdf 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -71,7 +71,13 @@ export type Msg = {embeds?: Embed[]attachments?: Attachment[]reactions?: Reaction[]- replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }+ replyTo?: {+ id: string+ authorId?: string+ authorName: string+ text: string+ deleted?: boolean+ }thread?: {id: stringname: string@@ -103,7 +109,7 @@ export type Thread = {name: stringmessageCount: numberlastMessageAt: string- parent: { authorName: string; text: string }+ parent: { authorId?: string; authorName: string; text: string }// The root message's per-channel seq, when the thread was created from a// parent message (omitted only for legacy rootless threads).// Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.tsindex 71bec392c..7183fe737 100644--- a/src/web/src/lib/community/models/people.ts+++ b/src/web/src/lib/community/models/people.ts@@ -1,5 +1,37 @@export type Presence = "online" | "offline"+export type CommunityProfile = {+ id: string+ name?: string+ discriminator?: string+ avatar?: string+ avatarVersion?: number+ aboutMe?: string+ bannerColor?: string | null+ kind?: "human" | "bot"+ ownerUserId?: string | null+ statusEmoji?: string | null+ statusText?: string | null+ presence?: Presence+}++export type CommunityProfilePatch = {+ id: string+ identityAbout?: Partial<Pick<+ CommunityProfile,+ "name" | "discriminator" | "aboutMe" | "bannerColor" | "kind" | "ownerUserId"+ >>+ avatar?: { avatar: string; avatarVersion: number }+ status?: Pick<CommunityProfile, "statusEmoji" | "statusText">+ presence?: Presence+}++export type CommunityProfileSnapshot = {+ viewerId: string | null+ accountEpoch: number+ revision: number+}+// ββ Members / friends / DMs ββββββββββββββββββββββββββββββββββββββββββββββββββ// Identity fields shared by every community user view-model (member / friend /// DM). All three are required `string`: `user.name`/`user.discriminator` arediff --git a/src/web/src/lib/community/presence.test.ts b/src/web/src/lib/community/presence.test.tsdeleted file mode 100644index 5f61d1fc7..000000000--- a/src/web/src/lib/community/presence.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, it, expect } from "vitest"-import { resolveProfilePresence, resolveRowPresence } from "./presence"--describe("resolveProfilePresence", () => {- it("returns online for self regardless of onlineUserIds", () => {- expect(resolveProfilePresence(true, undefined, new Set())).toBe("online")- expect(resolveProfilePresence(true, "u1", new Set())).toBe("online")- })-- it("returns online when targetUserId is in onlineUserIds", () => {- expect(resolveProfilePresence(false, "u1", new Set(["u1", "u2"]))).toBe("online")- })-- it("returns offline when targetUserId is resolved but not online", () => {- expect(resolveProfilePresence(false, "u3", new Set(["u1", "u2"]))).toBe("offline")- })-- it("returns undefined when targetUserId is undefined (no member/friend match)", () => {- expect(resolveProfilePresence(false, undefined, new Set(["u1"]))).toBeUndefined()- })-})--describe("resolveRowPresence", () => {- it("returns online for the current user regardless of the online set", () => {- expect(resolveRowPresence({ userId: "me" }, new Set(), "me")).toBe("online")- expect(resolveRowPresence({ id: "me" }, new Set(), "me")).toBe("online")- })-- it("returns online when the resolved id is in onlineUserIds", () => {- expect(resolveRowPresence({ userId: "u1" }, new Set(["u1"]))).toBe("online")- })-- it("returns offline when the resolved id is not online", () => {- expect(resolveRowPresence({ userId: "u2" }, new Set(["u1"]))).toBe("offline")- })-- it("normalizes the key as userId ?? id", () => {- // userId wins when both present- expect(resolveRowPresence({ userId: "u1", id: "other" }, new Set(["u1"]))).toBe("online")- expect(resolveRowPresence({ userId: "u1", id: "other" }, new Set(["other"]))).toBe("offline")- // falls back to id when userId is absent/nullish- expect(resolveRowPresence({ id: "f1" }, new Set(["f1"]))).toBe("online")- expect(resolveRowPresence({ userId: null, id: "f1" }, new Set(["f1"]))).toBe("online")- })-- it("returns offline (never undefined) when no id resolves", () => {- expect(resolveRowPresence({}, new Set(["u1"]))).toBe("offline")- expect(resolveRowPresence({ userId: null, id: null }, new Set())).toBe("offline")- })-})diff --git a/src/web/src/lib/community/presence.ts b/src/web/src/lib/community/presence.tsdeleted file mode 100644index 48666645e..000000000--- a/src/web/src/lib/community/presence.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { Presence } from "@/lib/community/models/people"--/**- * The single client-side presence-overlay helper.- *- * `member.status` / `friend.status` / `dm.status` from the list routes are NOT- * live presence β the routes hardcode them at fetch time. Real presence only- * exists by overlaying `useOnlineUserIds()` (the WS-maintained set) on the raw- * row. Every call site that renders a member / friend / DM row must resolve- * presence through this one helper so self-handling and key resolution stay- * consistent instead of drifting per-site.- *- * Rules (unified across all sites):- * - self β always "online" (the signed-in viewer is present by definition).- * - a resolved id present in `onlineUserIds` β "online", else "offline".- * - no id β `undefined` (only the ProfileCard path, which tolerates it).- *- * Pure functions (no React) so they're unit-testable without a render harness.- */-export function resolveProfilePresence(- isSelf: boolean,- targetUserId: string | undefined,- onlineUserIds: ReadonlySet<string>,-): Presence | undefined {- if (isSelf) return "online"- if (!targetUserId) return undefined- return onlineUserIds.has(targetUserId) ? "online" : "offline"-}--/**- * Row-overlay variant for member / friend / DM rows. Normalizes the id key- * (`userId ?? id`) in ONE place, applies the self β online rule when- * `currentUserId` is provided, and resolves a missing id to "offline" (the- * concrete `Presence` these rows require). Delegates to- * `resolveProfilePresence` so there is a single source of presence logic.- */-export function resolveRowPresence(- row: { userId?: string | null; id?: string | null },- onlineUserIds: ReadonlySet<string>,- currentUserId?: string,-): Presence {- const id = row.userId ?? row.id ?? undefined- const isSelf = !!id && !!currentUserId && id === currentUserId- return resolveProfilePresence(isSelf, id, onlineUserIds) ?? "offline"-}diff --git a/src/web/src/lib/community/profile-read.ts b/src/web/src/lib/community/profile-read.tsnew file mode 100644index 000000000..2194493e3--- /dev/null+++ b/src/web/src/lib/community/profile-read.ts@@ -0,0 +1,20 @@+import { avatarInitial } from "@/lib/community/avatar"+import type { CommunityProfile } from "@/lib/community/models/people"++export function readCommunityProfile(+ profile: CommunityProfile | undefined,+ userId: string,+) {+ const name = profile?.name ?? "Unknown"+ return {+ id: userId,+ name,+ discriminator: profile?.discriminator ?? "",+ avatar: profile?.avatar ?? avatarInitial(name),+ avatarVersion: profile?.avatarVersion ?? 0,+ aboutMe: profile?.aboutMe ?? "",+ statusEmoji: profile?.statusEmoji,+ statusText: profile?.statusText,+ presence: profile?.presence ?? "offline" as const,+ }+}diff --git a/src/web/src/lib/community/profile-seed.test.ts b/src/web/src/lib/community/profile-seed.test.tsnew file mode 100644index 000000000..d5cd641f4--- /dev/null+++ b/src/web/src/lib/community/profile-seed.test.ts@@ -0,0 +1,200 @@+import { QueryClient } from "@tanstack/react-query"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { communityKeys } from "@/lib/query-keys"+import type { MessagesPage, Msg } from "@/lib/community/models/message"+import {+ apiFetchProfiles,+ communityUserProfilePatch,+ loadAndSeedProfiles,+ messageProfilePatches,+ seedPersistedMessageProfiles,+} from "./profile-seed"+import { useCommunityWsStore } from "@/stores/community/ws"++const apiFetch = vi.hoisted(() => vi.fn())++vi.mock("@/lib/api/client", () => ({ apiFetch }))++function activate(viewerId = "viewer") {+ useCommunityWsStore.getState().activateProfileAccount(viewerId)+ return useCommunityWsStore.getState().beginProfileSnapshot()+}++function chat(overrides: Partial<Msg> = {}): Msg {+ return {+ id: "m1",+ type: "chat",+ content: "hello",+ ...overrides,+ }+}++beforeEach(() => {+ apiFetch.mockReset()+ useCommunityWsStore.getState().reset()+})++describe("communityUserProfilePatch", () => {+ it("maps only canonical profile fields and never treats row presence or sub as profile data", () => {+ const patch = communityUserProfilePatch("u1", {+ name: "Alice",+ discriminator: "0001",+ avatar: "/alice.png",+ avatarVersion: 4,+ status: "online",+ sub: "placeholder biography",+ statusEmoji: null,+ statusText: "Heads down",+ })++ expect(patch).toEqual({+ id: "u1",+ identityAbout: { name: "Alice", discriminator: "0001" },+ avatar: { avatar: "/alice.png", avatarVersion: 4 },+ status: { statusEmoji: null, statusText: "Heads down" },+ })+ expect(patch).not.toHaveProperty("presence")+ expect(patch.identityAbout).not.toHaveProperty("aboutMe")+ })+})++describe("messageProfilePatches", () => {+ it("extracts typed author, reply, thread, and approval identities", () => {+ const patches = messageProfilePatches([chat({+ authorId: "author",+ authorName: "Author",+ authorAvatar: "/author.png",+ authorAvatarVersion: 7,+ replyTo: {+ id: "prior",+ authorId: "reply",+ authorName: "Reply",+ text: "prior text",+ },+ thread: {+ id: "thread",+ name: "Thread",+ messageCount: 1,+ participants: [{+ id: "participant",+ name: "Participant",+ avatar: "/participant.png",+ avatarVersion: 3,+ }],+ },+ approval: {+ friendshipId: "friendship",+ status: "pending",+ waitingOn: "you",+ otherProfile: {+ id: "other",+ name: "Other",+ discriminator: "0002",+ image: null,+ avatarVersion: 2,+ },+ botProfile: {+ id: "bot",+ name: "Bot",+ discriminator: "0003",+ image: "/bot.png",+ avatarVersion: 5,+ },+ waitingOnProfile: null,+ },+ })])++ expect(patches).toEqual([+ {+ id: "author",+ identityAbout: { name: "Author" },+ avatar: { avatar: "/author.png", avatarVersion: 7 },+ },+ { id: "reply", identityAbout: { name: "Reply" } },+ {+ id: "participant",+ identityAbout: { name: "Participant" },+ avatar: { avatar: "/participant.png", avatarVersion: 3 },+ },+ {+ id: "other",+ identityAbout: { name: "Other", discriminator: "0002" },+ avatar: { avatar: "O", avatarVersion: 2 },+ },+ {+ id: "bot",+ identityAbout: { name: "Bot", discriminator: "0003" },+ avatar: { avatar: "/bot.png", avatarVersion: 5 },+ },+ ])+ })+})++describe("profile seeding boundaries", () => {+ it("seeds restored persisted messages without rewriting the raw Query payload", () => {+ const snapshot = activate()+ const queryClient = new QueryClient()+ const data = {+ pages: [{+ messages: [chat({+ authorId: "u1",+ authorName: "Persisted Alice",+ authorAvatar: "/persisted.png",+ authorAvatarVersion: 8,+ })],+ hasMore: false,+ } satisfies MessagesPage],+ pageParams: [{ mode: "newest" }],+ }+ queryClient.setQueryData(communityKeys.channelMessages("channel"), data)+ const rawBefore = queryClient.getQueryData(communityKeys.channelMessages("channel"))++ seedPersistedMessageProfiles(queryClient, snapshot)++ expect(queryClient.getQueryData(communityKeys.channelMessages("channel"))).toBe(rawBefore)+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ name: "Persisted Alice",+ avatar: "/persisted.png",+ avatarVersion: 8,+ })+ })++ it("returns the raw API object while seeding its typed profile projection", async () => {+ activate()+ const raw = { member: { id: "u2", name: "API Alice" } }+ apiFetch.mockResolvedValueOnce(raw)++ const result = await apiFetchProfiles(+ "/profiles",+ (data: typeof raw) => [{+ id: data.member.id,+ identityAbout: { name: data.member.name },+ }],+ )++ expect(result).toBe(raw)+ expect(apiFetch).toHaveBeenCalledWith("/profiles")+ expect(useCommunityWsStore.getState().profilesByUserId.get("u2")?.name).toBe("API Alice")+ })++ it("does not let a late request overwrite a newer authoritative group patch", async () => {+ activate()+ let resolve!: (value: { id: string; name: string }) => void+ const pending = new Promise<{ id: string; name: string }>((done) => { resolve = done })+ const resultPromise = loadAndSeedProfiles(+ () => pending,+ (data) => [{ id: data.id, identityAbout: { name: data.name } }],+ )++ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: "u3",+ identityAbout: { name: "WS Alice" },+ }])+ const raw = { id: "u3", name: "Late API Alice" }+ resolve(raw)++ await expect(resultPromise).resolves.toBe(raw)+ expect(useCommunityWsStore.getState().profilesByUserId.get("u3")?.name).toBe("WS Alice")+ })+})diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.tsnew file mode 100644index 000000000..92b6b88d3--- /dev/null+++ b/src/web/src/lib/community/profile-seed.ts@@ -0,0 +1,132 @@+import type {+ CommunityProfilePatch,+ CommunityProfileSnapshot,+ CommunityUserCore,+} from "@/lib/community/models/people"+import type { InfiniteData, QueryClient } from "@tanstack/react-query"+import type { MessagesPage, Msg } from "@/lib/community/models/message"+import type { FriendApprovalPayload } from "@alook/shared"+import { apiFetch } from "@/lib/api/client"+import { avatarInitial } from "@/lib/community/avatar"+import { shouldPersistQueryKey } from "@/lib/query-persister"+import { useCommunityWsStore } from "@/stores/community/ws"++type CommunityUserProfileSeed = CommunityUserCore & {+ statusEmoji?: string | null+ statusText?: string | null+}++export function communityUserProfilePatch(+ userId: string,+ row: CommunityUserProfileSeed,+): CommunityProfilePatch {+ return {+ id: userId,+ identityAbout: {+ name: row.name,+ discriminator: row.discriminator,+ },+ avatar: { avatar: row.avatar, avatarVersion: row.avatarVersion },+ ...(row.statusEmoji === undefined && row.statusText === undefined+ ? {}+ : { status: {+ ...(row.statusEmoji !== undefined ? { statusEmoji: row.statusEmoji } : {}),+ ...(row.statusText !== undefined ? { statusText: row.statusText } : {}),+ } }),+ }+}++export function messageProfilePatches(messages: readonly Msg[]): CommunityProfilePatch[] {+ const patches: CommunityProfilePatch[] = []+ for (const message of messages) {+ if (message.authorId) {+ patches.push({+ id: message.authorId,+ ...(message.authorName ? { identityAbout: { name: message.authorName } } : {}),+ ...(message.authorAvatar !== undefined && message.authorAvatarVersion !== undefined+ ? { avatar: {+ avatar: message.authorAvatar,+ avatarVersion: message.authorAvatarVersion,+ } }+ : {}),+ })+ }+ if (message.replyTo?.authorId) {+ patches.push({+ id: message.replyTo.authorId,+ identityAbout: { name: message.replyTo.authorName },+ })+ }+ for (const participant of message.thread?.participants ?? []) {+ patches.push({+ id: participant.id,+ identityAbout: { name: participant.name },+ avatar: {+ avatar: participant.avatar,+ avatarVersion: participant.avatarVersion,+ },+ })+ }+ patches.push(...approvalProfilePatches(message.approval))+ }+ return patches+}++export function approvalProfilePatches(+ approval: FriendApprovalPayload | undefined,+): CommunityProfilePatch[] {+ if (!approval) return []+ return [+ approval.otherProfile,+ approval.botProfile,+ approval.waitingOnProfile,+ ].flatMap((profile) => profile ? [{+ id: profile.id,+ identityAbout: {+ name: profile.name,+ discriminator: profile.discriminator,+ },+ avatar: {+ avatar: profile.image ?? avatarInitial(profile.name),+ avatarVersion: profile.avatarVersion,+ },+ }] : [])+}++export function seedPersistedMessageProfiles(+ queryClient: QueryClient,+ snapshot: CommunityProfileSnapshot,+) {+ const patches: CommunityProfilePatch[] = []+ const cached = queryClient.getQueriesData<InfiniteData<MessagesPage>>({+ predicate: (query) => shouldPersistQueryKey(query.queryKey),+ })+ for (const [, data] of cached) {+ for (const page of data?.pages ?? []) {+ patches.push(...messageProfilePatches(page.messages))+ }+ }+ useCommunityWsStore.getState().seedProfiles(snapshot, patches)+}++export async function loadAndSeedProfiles<T>(+ load: () => Promise<T>,+ patches: (data: T) => readonly CommunityProfilePatch[],+): Promise<T> {+ const profiles = useCommunityWsStore.getState()+ const snapshot = profiles.beginProfileSnapshot()+ const data = await load()+ profiles.seedProfiles(snapshot, patches(data))+ return data+}++export function apiFetchProfiles<T>(+ path: string,+ patches: (data: T) => readonly CommunityProfilePatch[],+ options?: RequestInit,+): Promise<T> {+ return loadAndSeedProfiles(+ () => options ? apiFetch<T>(path, options) : apiFetch<T>(path),+ patches,+ )+}diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex 48239a1a3..bf3e3c6bc 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -37,8 +37,7 @@ import type { FileAttachment, ImagePreview } from "@/lib/community/models/messag* 2. Store setters should no-op on identical state.* Zustand notifies every subscriber on `set(...)` regardless of whether* the value actually changed. Guard writes with a content-equality- * check (see `subscribe` / `unsubscribe` below, and `hydratePresence` /- * `resetPresence` in `./ws.ts`). Otherwise a subscriber in the same+ * check (see `subscribe` / `unsubscribe` below). Otherwise a subscriber in the same* subtree re-renders, shifts a dep, and re-invokes the setter β loop.** 3. Selectors for "handler-shaped" state should return a module-scopeddiff --git a/src/web/src/stores/community/message-stream.test.ts b/src/web/src/stores/community/message-stream.test.tsindex 222b0a203..a2acd0312 100644--- a/src/web/src/stores/community/message-stream.test.ts+++ b/src/web/src/stores/community/message-stream.test.ts@@ -62,41 +62,4 @@ describe("message stream store", () => {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 32ece184a..0208096de 100644--- a/src/web/src/stores/community/message-stream.ts+++ b/src/web/src/stores/community/message-stream.ts@@ -19,7 +19,6 @@ 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@@ -69,24 +68,6 @@ 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 8dbc29e97..1a29251dd 100644--- a/src/web/src/stores/community/ws.test.ts+++ b/src/web/src/stores/community/ws.test.ts@@ -12,388 +12,264 @@ beforeEach(() => {useCommunityWsStore.getState().reset()})+function activate(viewerId = "viewer") {+ useCommunityWsStore.getState().activateProfileAccount(viewerId)+ return useCommunityWsStore.getState().beginProfileSnapshot()+}+describe("useCommunityWsStore", () => {it("publishes connection status, binds retry, and resets both safely", () => {const calls: string[] = []- const reconnectNow = () => calls.push("retry")- expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")-useCommunityWsStore.getState().setConnectionStatus("reconnecting")- useCommunityWsStore.getState().bindReconnectNow(reconnectNow)- expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")+ useCommunityWsStore.getState().bindReconnectNow(() => calls.push("retry"))useCommunityWsStore.getState().reconnectNow()expect(calls).toEqual(["retry"])- useCommunityWsStore.getState().setConnectionStatus("failed")useCommunityWsStore.getState().reset()expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")useCommunityWsStore.getState().reconnectNow()expect(calls).toEqual(["retry"])})- it("fails closed until the websocket is authenticated and advances epochs on disconnect", () => {- expect(useCommunityWsStore.getState()).toMatchObject({- accessConnected: false,- accessEpoch: 0,- })+ it("fails closed until websocket authentication and advances access epochs", () => {+ expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 0 })useCommunityWsStore.getState().markAccessConnected()- expect(useCommunityWsStore.getState().accessConnected).toBe(true)useCommunityWsStore.getState().markAccessDisconnected()- expect(useCommunityWsStore.getState()).toMatchObject({- accessConnected: false,- accessEpoch: 1,- })+ expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 1 })})- it("starts with empty presence + seen sets", () => {- const s = useCommunityWsStore.getState()- expect(s.onlineUserIds.size).toBe(0)- expect(s.seenMessageIds.size).toBe(0)- expect(s.seenDeliveryOperations.size).toBe(0)+ it("seeds eligible groups and preserves groups patched after request start", () => {+ const initial = activate()+ useCommunityWsStore.getState().seedProfiles(initial, [{+ id: "u1",+ identityAbout: { name: "API old", aboutMe: "api bio" },+ status: { statusEmoji: "π±", statusText: "api" },+ presence: "offline",+ }])++ const request = useCommunityWsStore.getState().beginProfileSnapshot()+ useCommunityWsStore.getState().patchProfiles(request, [{+ id: "u1",+ identityAbout: { name: "WS new", aboutMe: undefined },+ presence: "online",+ }])+ useCommunityWsStore.getState().seedProfiles(request, [{+ id: "u1",+ identityAbout: { name: "late API", aboutMe: "late bio" },+ status: { statusEmoji: "π§", statusText: "late status" },+ presence: "offline",+ }])++ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ name: "WS new",+ aboutMe: undefined,+ statusEmoji: "π§",+ statusText: "late status",+ presence: "online",+ })})- it("setPresence adds and removes user ids", () => {- useCommunityWsStore.getState().setPresence("u1", true)- useCommunityWsStore.getState().setPresence("u2", true)- expect(useCommunityWsStore.getState().onlineUserIds.has("u1")).toBe(true)- expect(useCommunityWsStore.getState().onlineUserIds.has("u2")).toBe(true)-- useCommunityWsStore.getState().setPresence("u1", false)- expect(useCommunityWsStore.getState().onlineUserIds.has("u1")).toBe(false)- // Removing an offline user is a no-op β no throw.- useCommunityWsStore.getState().setPresence("u3", false)- expect(useCommunityWsStore.getState().onlineUserIds.has("u3")).toBe(false)+ it("advances authoritative group revisions even when values are equal", () => {+ const initial = activate()+ useCommunityWsStore.getState().seedProfiles(initial, [{+ id: "u1",+ status: { statusEmoji: null, statusText: null },+ }])+ const request = useCommunityWsStore.getState().beginProfileSnapshot()+ useCommunityWsStore.getState().patchProfiles(request, [{+ id: "u1",+ status: { statusEmoji: null, statusText: null },+ }])+ const afterPatch = useCommunityWsStore.getState()+ expect(afterPatch.profileRevision).toBe(request.revision + 1)++ afterPatch.seedProfiles(request, [{+ id: "u1",+ status: { statusEmoji: "stale", statusText: "stale" },+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ statusEmoji: null,+ statusText: null,+ })})- it("setPresence swaps the Set reference so React selectors re-run", () => {- const before = useCommunityWsStore.getState().onlineUserIds- useCommunityWsStore.getState().setPresence("u1", true)- const after = useCommunityWsStore.getState().onlineUserIds- expect(after).not.toBe(before)+ it("conditionally commits a successful mutation ahead of an older API seed", () => {+ const oldGet = activate()+ const mutation = useCommunityWsStore.getState().beginProfileSnapshot()++ useCommunityWsStore.getState().commitProfiles(mutation, [{+ id: "u1",+ identityAbout: { name: "Local mutation" },+ }])+ expect(useCommunityWsStore.getState().profileRevision).toBe(1)++ useCommunityWsStore.getState().seedProfiles(oldGet, [{+ id: "u1",+ identityAbout: { name: "Old GET" },+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")?.name)+ .toBe("Local mutation")})- it("resetPresence empties online set without touching seen ids", () => {- useCommunityWsStore.getState().setPresence("u1", true)- useCommunityWsStore.getState().markSeenMessage("m1")-- useCommunityWsStore.getState().resetPresence()- expect(useCommunityWsStore.getState().onlineUserIds.size).toBe(0)- expect(useCommunityWsStore.getState().seenMessageIds.has("m1")).toBe(true)+ it("does not let a mutation response overwrite a newer WS group patch", () => {+ const mutation = activate()+ const profiles = useCommunityWsStore.getState()+ profiles.patchProfiles(profiles.beginProfileSnapshot(), [{+ id: "u1",+ identityAbout: { name: "Newer WS" },+ }])++ profiles.commitProfiles(mutation, [{+ id: "u1",+ identityAbout: { name: "Mutation response" },+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")?.name)+ .toBe("Newer WS")+ expect(useCommunityWsStore.getState().profileRevision).toBe(1)})- it("resetPresence is a no-op (no reference swap) when already empty", () => {- const before = useCommunityWsStore.getState().onlineUserIds- useCommunityWsStore.getState().resetPresence()- expect(useCommunityWsStore.getState().onlineUserIds).toBe(before)- })+ it("compares avatar versions independently without advancing group revision", () => {+ const snapshot = activate()+ const store = useCommunityWsStore.getState()+ store.patchProfiles(snapshot, [{+ id: "u1",+ avatar: { avatar: "/a?v=2", avatarVersion: 2 },+ }])+ expect(useCommunityWsStore.getState().profileRevision).toBe(0)++ store.patchProfiles(snapshot, [{+ id: "u1",+ avatar: { avatar: "/stale?v=1", avatarVersion: 1 },+ }, {+ id: "u1",+ avatar: { avatar: "/conflict?v=2", avatarVersion: 2 },+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ avatar: "/a?v=2",+ avatarVersion: 2,+ })- it("hydratePresence replaces the set atomically", () => {- useCommunityWsStore.getState().setPresence("u_stale", true)- useCommunityWsStore.getState().hydratePresence(["u1", "u2", "u3"])- const online = useCommunityWsStore.getState().onlineUserIds- expect(online.has("u_stale")).toBe(false)- expect(online.has("u1")).toBe(true)- expect(online.has("u2")).toBe(true)- expect(online.has("u3")).toBe(true)- expect(online.size).toBe(3)+ store.seedProfiles(snapshot, [{+ id: "u1",+ avatar: { avatar: "/a?v=3", avatarVersion: 3 },+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ avatar: "/a?v=3",+ avatarVersion: 3,+ })})- it("hydratePresence bails when the incoming set matches current", () => {- useCommunityWsStore.getState().hydratePresence(["u1", "u2"])- const before = useCommunityWsStore.getState().onlineUserIds- // Identical-content, different-reference input MUST NOT swap the Set β- // that's the load-bearing invariant that prevents the render loop.- useCommunityWsStore.getState().hydratePresence(["u1", "u2"])- expect(useCommunityWsStore.getState().onlineUserIds).toBe(before)- })+ it("rejects late work after viewer switch and prevents reset ABA", () => {+ const oldSnapshot = activate("viewer-a")+ useCommunityWsStore.getState().activateProfileAccount("viewer-b")+ expect(useCommunityWsStore.getState().seedProfiles(oldSnapshot, [{+ id: "u1",+ identityAbout: { name: "wrong viewer" },+ }])).toBe(false)- it("mergePresence unions instead of replacing β regression for the DM flicker", () => {- // A WS snapshot marked co-member A online; the friends-only re-seed carries- // only B. A destructive replace would evict A (the reported bug); merge must- // keep both.- useCommunityWsStore.getState().setPresence("A", true)- useCommunityWsStore.getState().mergePresence(["B"])- const online = useCommunityWsStore.getState().onlineUserIds- expect(online.has("A")).toBe(true)- expect(online.has("B")).toBe(true)- expect(online.size).toBe(2)+ const beforeReset = useCommunityWsStore.getState().beginProfileSnapshot()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer-b")+ expect(useCommunityWsStore.getState().patchProfiles(beforeReset, [{+ id: "u1",+ identityAbout: { name: "ABA" },+ }])).toBe(false)+ expect(useCommunityWsStore.getState().profilesByUserId.size).toBe(0)})- it("mergePresence bails when every incoming id is already present", () => {- useCommunityWsStore.getState().hydratePresence(["u1", "u2"])- const before = useCommunityWsStore.getState().onlineUserIds- useCommunityWsStore.getState().mergePresence(["u1"])- expect(useCommunityWsStore.getState().onlineUserIds).toBe(before)+ it("applies multiple same-user groups in one authoritative batch", () => {+ const snapshot = activate()+ useCommunityWsStore.getState().patchProfiles(snapshot, [{+ id: "u1",+ identityAbout: { name: "Alice" },+ }, {+ id: "u1",+ status: { statusEmoji: "π§", statusText: "Focus" },+ presence: "online",+ }])+ expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({+ name: "Alice",+ statusEmoji: "π§",+ statusText: "Focus",+ presence: "online",+ })+ expect(useCommunityWsStore.getState().profileRevisionsByUserId.get("u1"))+ .toEqual({ identityAbout: 1, status: 1, presence: 1 })})- it("markSeenMessage deduplicates", () => {+ it("deduplicates seen messages and trims the oldest ids", () => {useCommunityWsStore.getState().markSeenMessage("m1")const first = useCommunityWsStore.getState().seenMessageIdsuseCommunityWsStore.getState().markSeenMessage("m1")- const second = useCommunityWsStore.getState().seenMessageIds-- // Duplicate mark is a no-op β same Set reference, size still 1.- expect(second.size).toBe(1)- expect(second).toBe(first)- expect(useCommunityWsStore.getState().hasSeenMessage("m1")).toBe(true)- expect(useCommunityWsStore.getState().hasSeenMessage("m2")).toBe(false)- })-- it("marks distinct messages independently", () => {- useCommunityWsStore.getState().markSeenMessage("m1")- useCommunityWsStore.getState().markSeenMessage("m2")- expect(useCommunityWsStore.getState().seenMessageIds.size).toBe(2)- })+ expect(useCommunityWsStore.getState().seenMessageIds).toBe(first)- it("trims to the sliding-window size once the max is exceeded", () => {- // Fill up to the boundary so the next insert crosses it.- for (let i = 0; i < SEEN_MESSAGE_MAX; i++) {- useCommunityWsStore.getState().markSeenMessage(`m${i}`)+ for (let index = 2; index <= SEEN_MESSAGE_MAX + 1; index += 1) {+ useCommunityWsStore.getState().markSeenMessage(`m${index}`)}- expect(useCommunityWsStore.getState().seenMessageIds.size).toBe(- SEEN_MESSAGE_MAX,- )-- // One more triggers the trim.- useCommunityWsStore.getState().markSeenMessage(`m${SEEN_MESSAGE_MAX}`)-const after = useCommunityWsStore.getState().seenMessageIdsexpect(after.size).toBe(SEEN_MESSAGE_TRIM_TO)-- // The newest id must survive; the oldest must be evicted.- expect(after.has(`m${SEEN_MESSAGE_MAX}`)).toBe(true)- expect(after.has("m0")).toBe(false)+ expect(after.has("m1")).toBe(false)+ expect(after.has(`m${SEEN_MESSAGE_MAX + 1}`)).toBe(true)})- it("locks a delivery digest before completion and keeps same-digest failures retryable", () => {- const store = useCommunityWsStore.getState()- expect(store.observeDeliveryOperation("operation-1", "a".repeat(64))).toBe("new")- const observed = useCommunityWsStore.getState().seenDeliveryOperations- expect(observed.get("operation-1")).toEqual({- digest: "a".repeat(64),- completed: false,- })- expect(useCommunityWsStore.getState().observeDeliveryOperation("operation-1", "a".repeat(64)))- .toBe("retryable")- expect(useCommunityWsStore.getState().observeDeliveryOperation("operation-1", "b".repeat(64)))- .toBe("conflict")- expect(useCommunityWsStore.getState().seenDeliveryOperations).toBe(observed)- expect(useCommunityWsStore.getState().completeDeliveryOperation("operation-1", "b".repeat(64)))- .toBe(false)- expect(useCommunityWsStore.getState().completeDeliveryOperation("operation-1", "a".repeat(64)))- .toBe(true)- expect(useCommunityWsStore.getState().seenDeliveryOperations.get("operation-1"))- .toEqual({ digest: "a".repeat(64), completed: true })- expect(useCommunityWsStore.getState().observeDeliveryOperation("operation-1", "a".repeat(64)))- .toBe("duplicate")- expect(useCommunityWsStore.getState().observeDeliveryOperation("operation-1", "b".repeat(64)))+ it("locks delivery digests and keeps same-digest failures retryable", () => {+ const digest = "a".repeat(64)+ expect(useCommunityWsStore.getState().observeDeliveryOperation("op", digest)).toBe("new")+ expect(useCommunityWsStore.getState().observeDeliveryOperation("op", digest)).toBe("retryable")+ expect(useCommunityWsStore.getState().observeDeliveryOperation("op", "b".repeat(64))).toBe("conflict")+ expect(useCommunityWsStore.getState().completeDeliveryOperation("op", digest)).toBe(true)+ expect(useCommunityWsStore.getState().observeDeliveryOperation("op", digest)).toBe("duplicate")})- it("trims retryable/completed delivery operations together and retains them across reconnect", () => {+ it("bounds delivery operations and clears transient state on reset", () => {for (let index = 0; index <= SEEN_DELIVERY_OPERATION_MAX; index += 1) {- useCommunityWsStore.getState().observeDeliveryOperation(- `operation-${index}`,- index.toString(16).padStart(64, "0"),- )+ const digest = index.toString(16).padStart(64, "0")+ useCommunityWsStore.getState().observeDeliveryOperation(`op-${index}`, digest)if (index % 2 === 0) {- useCommunityWsStore.getState().completeDeliveryOperation(- `operation-${index}`,- index.toString(16).padStart(64, "0"),- )+ useCommunityWsStore.getState().completeDeliveryOperation(`op-${index}`, digest)}}- const operations = useCommunityWsStore.getState().seenDeliveryOperations- expect(operations.size).toBe(SEEN_DELIVERY_OPERATION_TRIM_TO)- expect(operations.has("operation-0")).toBe(false)- expect(operations.has(`operation-${SEEN_DELIVERY_OPERATION_MAX}`)).toBe(true)- expect(operations.get(`operation-${SEEN_DELIVERY_OPERATION_MAX}`)?.completed).toBe(true)- expect(operations.get(`operation-${SEEN_DELIVERY_OPERATION_MAX - 1}`)?.completed).toBe(false)-- useCommunityWsStore.getState().markAccessDisconnected()- useCommunityWsStore.getState().markAccessConnected()- expect(useCommunityWsStore.getState().seenDeliveryOperations).toBe(operations)- })-- it("reset clears both online and seen sets", () => {- useCommunityWsStore.getState().setPresence("u1", true)- useCommunityWsStore.getState().markSeenMessage("m1")- useCommunityWsStore.getState().observeDeliveryOperation(- "retryable-operation",- "a".repeat(64),- )- useCommunityWsStore.getState().observeDeliveryOperation(- "completed-operation",- "b".repeat(64),- )- useCommunityWsStore.getState().completeDeliveryOperation(- "completed-operation",- "b".repeat(64),- )-- expect(useCommunityWsStore.getState().seenDeliveryOperations.get("retryable-operation"))- .toEqual({ digest: "a".repeat(64), completed: false })- expect(useCommunityWsStore.getState().seenDeliveryOperations.get("completed-operation"))- .toEqual({ digest: "b".repeat(64), completed: true })-+ expect(useCommunityWsStore.getState().seenDeliveryOperations.size)+ .toBe(SEEN_DELIVERY_OPERATION_TRIM_TO)+ const accountEpoch = useCommunityWsStore.getState().profileAccountEpochuseCommunityWsStore.getState().reset()-- expect(useCommunityWsStore.getState().onlineUserIds.size).toBe(0)- expect(useCommunityWsStore.getState().seenMessageIds.size).toBe(0)- expect(useCommunityWsStore.getState().seenDeliveryOperations.size).toBe(0)- })-- it("starts with an empty userStatuses map", () => {- expect(useCommunityWsStore.getState().userStatuses.size).toBe(0)- })-- it("setUserStatus stores per-user and overwrites on repeat calls", () => {- useCommunityWsStore.getState().setUserStatus("u1", "π§", "Vibing")- expect(useCommunityWsStore.getState().userStatuses.get("u1")).toEqual({- emoji: "π§",- text: "Vibing",- })-- useCommunityWsStore.getState().setUserStatus("u1", null, null)- expect(useCommunityWsStore.getState().userStatuses.get("u1")).toEqual({- emoji: null,- text: null,- })- })-- it("setUserStatus swaps the Map reference so React selectors re-run", () => {- const before = useCommunityWsStore.getState().userStatuses- useCommunityWsStore.getState().setUserStatus("u1", "π§", "Vibing")- const after = useCommunityWsStore.getState().userStatuses- expect(after).not.toBe(before)- })-- it("resetUserStatuses clears the map without touching presence/seen state", () => {- useCommunityWsStore.getState().setUserStatus("u1", "π§", "Vibing")- useCommunityWsStore.getState().setPresence("u2", true)- useCommunityWsStore.getState().markSeenMessage("m1")-- useCommunityWsStore.getState().resetUserStatuses()-- expect(useCommunityWsStore.getState().userStatuses.size).toBe(0)- expect(useCommunityWsStore.getState().onlineUserIds.has("u2")).toBe(true)- expect(useCommunityWsStore.getState().seenMessageIds.has("m1")).toBe(true)- })-- it("resetUserStatuses is a no-op (no reference swap) when already empty", () => {- const before = useCommunityWsStore.getState().userStatuses- useCommunityWsStore.getState().resetUserStatuses()- expect(useCommunityWsStore.getState().userStatuses).toBe(before)- })-- it("reset also clears userStatuses", () => {- useCommunityWsStore.getState().setUserStatus("u1", "π§", "Vibing")- useCommunityWsStore.getState().reset()- 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().pushBotAuditEvent- push({- id: "e1",- botId: "b1",- kind: "tool_call",- payload: { name: "Read" },- createdAt: "2025-01-01T00:00:00.000Z",- })- push({- id: "e2",- botId: "b1",- kind: "cli_invocation",- payload: { subcommand: "send" },- createdAt: "2025-01-01T00:00:01.000Z",- })- const events = useCommunityWsStore.getState().botAuditEvents.get("b1") ?? []- expect(events[0]!.id).toBe("e2")- expect(events[1]!.id).toBe("e1")-- // Dedup on id β a second push of e2 must not duplicate.- push({- id: "e2",- botId: "b1",- kind: "cli_invocation",- payload: { subcommand: "send" },- createdAt: "2025-01-01T00:00:01.000Z",+ expect(useCommunityWsStore.getState()).toMatchObject({+ profileViewerId: null,+ profileAccountEpoch: accountEpoch + 1,})- expect((useCommunityWsStore.getState().botAuditEvents.get("b1") ?? []).length).toBe(2)+ expect(useCommunityWsStore.getState().seenDeliveryOperations.size).toBe(0)+ expect(useCommunityWsStore.getState().seenMessageIds.size).toBe(0)})- it("bounds each bot's ring independently β a chatty bot doesn't evict a quiet bot's events", () => {+ it("prepends, deduplicates, and independently bounds bot audit rings", () => {const push = useCommunityWsStore.getState().pushBotAuditEvent- // Chatty bot A: overflow the ring.- for (let i = 0; i < BOT_AUDIT_RING_MAX + 5; i++) {+ for (let index = 0; index < BOT_AUDIT_RING_MAX + 5; index += 1) {push({- id: `a${i}`,- botId: "bot_a",+ id: `a${index}`,+ botId: "bot-a",kind: "tool_call",- payload: { name: "Read" },- createdAt: `2025-01-01T00:00:${String(i).padStart(2, "0")}.000Z`,+ payload: {},+ createdAt: "2026-01-01T00:00:00.000Z",})}- // Quiet bot B: one event, way earlier in wall-clock, must survive.push({- id: "b1",- botId: "bot_b",- kind: "cli_invocation",- payload: { subcommand: "send" },- createdAt: "2020-01-01T00:00:00.000Z",+ id: "quiet",+ botId: "bot-b",+ kind: "nap",+ payload: {},+ createdAt: "2026-01-01T00:00:00.000Z",})- const aRing = useCommunityWsStore.getState().botAuditEvents.get("bot_a") ?? []- const bRing = useCommunityWsStore.getState().botAuditEvents.get("bot_b") ?? []- expect(aRing.length).toBe(BOT_AUDIT_RING_MAX)- expect(aRing[0]!.id).toBe(`a${BOT_AUDIT_RING_MAX + 4}`)- // Oldest chatty-bot events dropped.- expect(aRing.some((e) => e.id === "a0")).toBe(false)- // Quiet bot untouched.- expect(bRing).toEqual([- expect.objectContaining({ id: "b1", botId: "bot_b" }),- ])+ push({+ id: "quiet",+ botId: "bot-b",+ kind: "nap",+ payload: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ })+ expect(useCommunityWsStore.getState().botAuditEvents.get("bot-a")).toHaveLength(+ BOT_AUDIT_RING_MAX,+ )+ expect(useCommunityWsStore.getState().botAuditEvents.get("bot-b")).toHaveLength(1)})})diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex f9cb196d8..5bb523f3c 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -1,6 +1,11 @@"use client"import { create } from "zustand"+import type {+ CommunityProfile,+ CommunityProfilePatch,+ CommunityProfileSnapshot,+} from "@/lib/community/models/people"/*** Zustand store for community WS-live-patched state.@@ -12,10 +17,8 @@ import { create } from "zustand"* only cares about the current channel id.** Loop-breaker rules (short version β full rulebook lives in `./index.ts`):- * - Setters no-op on identical state (`hydratePresence` / `resetPresence`- * below). Zustand notifies every subscriber on every `set(...)`; guard- * writes with a content-equality check so a redundant seed doesn't cascade- * into every subscriber and shift a dep that re-fires the seeder.+ * - Setters no-op on identical projected values. Zustand notifies every+ * subscriber on every `set(...)`; redundant seeds keep the map reference.* - Effect writers into this store must pass reference-stable arguments β* a fresh `[]` fallback per render will trigger the seeder each pass and* without the guards above would loop.@@ -54,9 +57,8 @@ export type BotAuditEventEntry = {createdAt: string}-type UserStatus = { emoji: string | null; text: string | null }-type AvatarIdentity = { avatar: string; avatarVersion: number }-type AvatarIdentityObservation = "accepted" | "same" | "stale" | "conflict" | "unbound"+type ProfileRevisions = { identityAbout: number; status: number; presence: number }+type ProfileWriteMode = "seed" | "patch" | "commit"export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failed"const NOOP_RECONNECT = () => undefined@@ -66,26 +68,13 @@ export type CommunityWsStoreState = {accessConnected: booleanconnectionStatus: CommunityWsConnectionStatusreconnectNow: () => void- /**- * Everyone online right now β human or bot. The server pushes- * `community:presence.update` identically for both (see- * plans/community-account-debt-fixes.md Fix 3: a bot's bound-machine- * connect/disconnect fans out through the same audience-based pipeline as- * a human WS connect/disconnect), so there's a single stream to store.- */- onlineUserIds: Set<string>+ profileViewerId: string | null+ profileAccountEpoch: number+ profileRevision: number+ profilesByUserId: Map<string, CommunityProfile>+ profileRevisionsByUserId: Map<string, ProfileRevisions>seenMessageIds: Set<string>seenDeliveryOperations: Map<string, DeliveryOperationState>- /**- * Live status deltas learned via `community:status.update` after the- * initial member/friend fetch β see plans/profile-card.md's "overlay- * pattern, not cache-patching" section. Only ever holds users who changed- * status since page load; everyone else's status comes straight off the- * 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@@ -93,27 +82,20 @@ export type CommunityWsStoreState = {*/botAuditEvents: Map<string, BotAuditEventEntry[]>- setPresence: (userId: string, online: boolean) => void- /**- * Atomic bulk REPLACE β one notification for N users. Use on server switch,- * where it must PRUNE: a peer who was online in the previous server but isn't- * in the new server's snapshot has to drop to offline. The WS presence- * snapshot only emits `online:true`, so this destructive replace is the only- * thing that clears a stale-online peer on a switch.- */- hydratePresence: (userIds: readonly string[]) => void- /**- * Additive bulk MERGE β union `userIds` into the current set, one- * notification. Use for a re-seed that carries only a SUBSET of the audience- * (the friends-presence fetch), where a destructive replace would evict- * WS-delivered co-members the fetch never knew about (the DM onlineβoffline- * flicker bug). Accepted trade-off: because it never prunes and the WS- * snapshot is `online:true`-only, a peer who went offline while we were- * disconnected stays "online" until the next live `online:false` delta β the- * far rarer, less-jarring inverse of the flicker it fixes.- */- mergePresence: (userIds: readonly string[]) => void- resetPresence: () => void+ activateProfileAccount: (viewerId: string | null) => number+ beginProfileSnapshot: () => CommunityProfileSnapshot+ seedProfiles: (+ snapshot: CommunityProfileSnapshot,+ patches: readonly CommunityProfilePatch[],+ ) => boolean+ commitProfiles: (+ snapshot: CommunityProfileSnapshot,+ patches: readonly CommunityProfilePatch[],+ ) => boolean+ patchProfiles: (+ snapshot: Pick<CommunityProfileSnapshot, "viewerId" | "accountEpoch">,+ patches: readonly CommunityProfilePatch[],+ ) => booleanhasSeenMessage: (id: string) => booleanmarkSeenMessage: (id: string) => voidobserveDeliveryOperation: (@@ -121,14 +103,6 @@ export type CommunityWsStoreState = {operationDigest: string,) => DeliveryOperationObservationResultcompleteDeliveryOperation: (operationId: string, operationDigest: string) => boolean- setUserStatus: (userId: string, emoji: string | null, text: string | null) => void- resetUserStatuses: () => void- bindIdentityOwner: (userId: string | null) => void- observeAvatarIdentity: (- userId: string,- avatar: string,- avatarVersion: number,- ) => AvatarIdentityObservationmarkAccessDisconnected: () => voidmarkAccessConnected: () => voidsetConnectionStatus: (status: CommunityWsConnectionStatus) => void@@ -139,8 +113,9 @@ export type CommunityWsStoreState = {const initialState = (): Pick<CommunityWsStoreState,- "onlineUserIds" | "seenMessageIds" | "seenDeliveryOperations" | "userStatuses" | "botAuditEvents"- | "identityOwnerUserId" | "avatarIdentities"+ "profileViewerId" | "profileAccountEpoch" | "profileRevision"+ | "profilesByUserId" | "profileRevisionsByUserId"+ | "seenMessageIds" | "seenDeliveryOperations" | "botAuditEvents"| "accessEpoch" | "accessConnected"| "connectionStatus" | "reconnectNow"> => ({@@ -148,49 +123,133 @@ const initialState = (): Pick<accessConnected: false,connectionStatus: "connected",reconnectNow: NOOP_RECONNECT,- onlineUserIds: new Set(),+ profileViewerId: null,+ profileAccountEpoch: 0,+ profileRevision: 0,+ profilesByUserId: new Map(),+ profileRevisionsByUserId: new Map(),seenMessageIds: new Set(),seenDeliveryOperations: new Map(),- userStatuses: new Map(),- identityOwnerUserId: null,- avatarIdentities: new Map(),botAuditEvents: new Map(),})-export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => ({- ...initialState(),+const ZERO_REVISIONS: ProfileRevisions = { identityAbout: 0, status: 0, presence: 0 }- setPresence: (userId, online) => {- const next = new Set(get().onlineUserIds)- if (online) next.add(userId)- else next.delete(userId)- set({ onlineUserIds: next })- },+function mergeIdentityAbout(+ profile: CommunityProfile,+ patch: CommunityProfilePatch["identityAbout"],+) {+ if (!patch) return profile+ return { ...profile, ...patch }+}- hydratePresence: (userIds) => {- const current = get().onlineUserIds- // Fast-path: same members, same size β no store write, no notification.- // Prevents render loops when a caller re-runs seeding with the same list- // (e.g., an effect that re-fires because a dep re-renders identically).- if (current.size === userIds.length && userIds.every((id) => current.has(id))) {- return+function mergeAvatar(profile: CommunityProfile, patch: CommunityProfilePatch["avatar"]) {+ if (!patch || !Number.isSafeInteger(patch.avatarVersion) || patch.avatarVersion < 0) {+ return profile+ }+ if (profile.avatarVersion !== undefined && patch.avatarVersion <= profile.avatarVersion) {+ return profile+ }+ return { ...profile, ...patch }+}++function profileChanged(previous: CommunityProfile, next: CommunityProfile) {+ const keys = new Set([...Object.keys(previous), ...Object.keys(next)])+ for (const key of keys) {+ if (previous[key as keyof CommunityProfile] !== next[key as keyof CommunityProfile]) return true+ }+ return false+}++export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {+ const writeProfiles = (+ snapshot: CommunityProfileSnapshot,+ patches: readonly CommunityProfilePatch[],+ mode: ProfileWriteMode,+ ) => {+ const state = get()+ if (+ !snapshot.viewerId+ || snapshot.viewerId !== state.profileViewerId+ || snapshot.accountEpoch !== state.profileAccountEpoch+ ) return false+ const revision = state.profileRevision + 1+ const guardsRevision = mode !== "patch"+ const advancesRevisionForGroups = mode !== "seed"+ let profiles: Map<string, CommunityProfile> | null = null+ let revisions: Map<string, ProfileRevisions> | null = null+ let advancesRevision = false+ for (const patch of patches) {+ const previous = (profiles ?? state.profilesByUserId).get(patch.id) ?? { id: patch.id }+ const previousRevisions = (revisions ?? state.profileRevisionsByUserId)+ .get(patch.id) ?? ZERO_REVISIONS+ let next = previous+ const identityAbout = patch.identityAbout !== undefined+ && (!guardsRevision || previousRevisions.identityAbout <= snapshot.revision)+ const status = patch.status !== undefined+ && (!guardsRevision || previousRevisions.status <= snapshot.revision)+ const presence = patch.presence !== undefined+ && (!guardsRevision || previousRevisions.presence <= snapshot.revision)+ if (identityAbout) next = mergeIdentityAbout(next, patch.identityAbout)+ next = mergeAvatar(next, patch.avatar)+ if (status) next = { ...next, ...patch.status }+ if (presence) next = { ...next, presence: patch.presence }+ if (profileChanged(previous, next)) {+ profiles ??= new Map(state.profilesByUserId)+ profiles.set(patch.id, next)+ }+ if (advancesRevisionForGroups && (identityAbout || status || presence)) {+ advancesRevision = true+ revisions ??= new Map(state.profileRevisionsByUserId)+ revisions.set(patch.id, {+ identityAbout: identityAbout ? revision : previousRevisions.identityAbout,+ status: status ? revision : previousRevisions.status,+ presence: presence ? revision : previousRevisions.presence,+ })+ }}- set({ onlineUserIds: new Set(userIds) })- },+ if (profiles || advancesRevision) {+ set({+ ...(profiles ? { profilesByUserId: profiles } : {}),+ ...(advancesRevision ? {+ profileRevision: revision,+ profileRevisionsByUserId: revisions!,+ } : {}),+ })+ }+ return true+ }- mergePresence: (userIds) => {- const current = get().onlineUserIds- // Fast-path: every incoming id already present β no write, no notification.- if (userIds.every((id) => current.has(id))) return- const next = new Set(current)- for (const id of userIds) next.add(id)- set({ onlineUserIds: next })- },+ return {+ ...initialState(),- resetPresence: () => {- if (get().onlineUserIds.size === 0) return- set({ onlineUserIds: new Set() })- },+ activateProfileAccount: (viewerId) => {+ const state = get()+ if (state.profileViewerId === viewerId) return state.profileAccountEpoch+ const profileAccountEpoch = state.profileAccountEpoch + 1+ set({+ profileViewerId: viewerId,+ profileAccountEpoch,+ profileRevision: 0,+ profilesByUserId: new Map(),+ profileRevisionsByUserId: new Map(),+ })+ return profileAccountEpoch+ },++ beginProfileSnapshot: () => ({+ viewerId: get().profileViewerId,+ accountEpoch: get().profileAccountEpoch,+ revision: get().profileRevision,+ }),++ seedProfiles: (snapshot, patches) => writeProfiles(snapshot, patches, "seed"),+ commitProfiles: (snapshot, patches) => writeProfiles(snapshot, patches, "commit"),+ patchProfiles: (snapshot, patches) => writeProfiles(+ { ...snapshot, revision: get().profileRevision },+ patches,+ "patch",+ ),hasSeenMessage: (id) => get().seenMessageIds.has(id),@@ -240,37 +299,6 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (return true},- setUserStatus: (userId, emoji, text) => {- const next = new Map(get().userStatuses)- next.set(userId, { emoji, text })- set({ userStatuses: next })- },-- resetUserStatuses: () => {- if (get().userStatuses.size === 0) return- 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,@@ -299,19 +327,23 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ botAuditEvents: next })},- reset: () => set(initialState()),-}))+ reset: () => set({+ ...initialState(),+ profileAccountEpoch: get().profileAccountEpoch + 1,+ }),+ }+})// ββ Selectors ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-/**- * Every consumer that asks "is X online?" reads this β the server already- * pushes bot presence into the same `onlineUserIds` stream as human- * presence (see the store-level comment above), so this is a direct- * passthrough, not a union of two sources.- */-export const useOnlineUserIds = (): ReadonlySet<string> => {- return useCommunityWsStore((s) => s.onlineUserIds)+export function useCommunityProfile(userId: string | null | undefined) {+ return useCommunityWsStore((state) =>+ userId ? state.profilesByUserId.get(userId) : undefined,+ )+}++export function useProfilesByUserId(): ReadonlyMap<string, CommunityProfile> {+ return useCommunityWsStore((state) => state.profilesByUserId)}const EMPTY_AUDIT_EVENTS: BotAuditEventEntry[] = []diff --git a/src/web/src/test/e2e-ui/07-invite.spec.ts b/src/web/src/test/e2e-ui/07-invite.spec.tsindex fb8cec58b..97ca66700 100644--- a/src/web/src/test/e2e-ui/07-invite.spec.ts+++ b/src/web/src/test/e2e-ui/07-invite.spec.ts@@ -1,5 +1,103 @@-import { test, expect } from "./_fixtures/community-fixture"-import { seedServer, createInvite } from "./_fixtures/seed"+import { test, expect, userId, userName } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import {+ communityFrameEvents,+ proxyCommunityWebSockets,+} from "./_fixtures/community-ws-proxy"+import {+ seedChannel,+ seedFriendship,+ seedServer,+ createInvite,+} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++test("an offline friend comes online through reconnect and receives the invite DM", async ({ asUser }) => {+ test.setTimeout(120_000)+ const serverId = await seedServer("alice", `Friend invite ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "invite-friend")+ await seedFriendship("alice", "bob", userId("bob"))++ const alice = await asUser("alice")+ const aliceWs = await proxyCommunityWebSockets(alice.context)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ await expect(alice.page.getByRole("button", { name: "Invite to server" })).toBeVisible()+ await alice.page.getByRole("button", { name: "Invite to server" }).click()++ const dialog = alice.page.getByRole("dialog")+ const bobRow = dialog.getByText(userName("bob"), { exact: true }).locator("..").locator("..")+ await expect(bobRow.getByRole("button", { name: "Invite" })).toBeVisible({ timeout: 20_000 })+ await expect(bobRow.locator('[data-presence="offline"]')).toHaveCount(1)+ const inviteInput = dialog.locator("input[readonly]")+ await expect(inviteInput).not.toHaveValue("")+ const inviteUrl = await inviteInput.inputValue()+ expect(new URL(inviteUrl).pathname).toMatch(/^\/c\/invite\/[^/]+$/)++ const bob = await asUser("bob")+ const bobWs = await proxyCommunityWebSockets(bob.context)+ const alicePresenceStart = aliceWs.frames.length+ await gotoAfterUserWsAuth(bob.page, "/c/me")+ await expect(bob.page).toHaveURL(/\/c\/me\/friends$/)+ await expect(bobRow.locator('[data-presence="online"]')).toHaveCount(1, { timeout: 20_000 })+ await expect.poll(() => aliceWs.frames.slice(alicePresenceStart)+ .flatMap(communityFrameEvents)+ .some((frame) => frame.type === "community:presence.update"+ && frame.userId === userId("bob")+ && frame.online === true)).toBe(true)++ const connectionBaseline = bobWs.connectionCount()+ await bobWs.disconnect()+ await expect.poll(() => bobWs.connectionCount(), { timeout: 30_000 })+ .toBeGreaterThan(connectionBaseline)+ await expect.poll(() => bobWs.connectionFrames.some((frame) =>+ frame.connectionId > connectionBaseline+ && frame.direction === "server-to-client"+ && frame.type === "auth.ok",+ )).toBe(true)+ await expect(bobRow.locator('[data-presence="online"]')).toHaveCount(1, { timeout: 20_000 })++ const inviteMessagePosts: string[] = []+ alice.page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (+ request.method() !== "POST"+ || !/^\/api\/community\/channels\/[^/]+\/messages$/.test(pathname)+ ) return+ const body = request.postDataJSON() as { content?: string } | null+ if (body?.content === inviteUrl) inviteMessagePosts.push(pathname)+ })+ const dmResponsePromise = alice.page.waitForResponse((response) =>+ response.request().method() === "POST"+ && new URL(response.url()).pathname === "/api/community/channels",+ )+ const messageResponsePromise = alice.page.waitForResponse((response) =>+ response.request().method() === "POST"+ && /^\/api\/community\/channels\/[^/]+\/messages$/.test(new URL(response.url()).pathname),+ )+ await bobRow.getByRole("button", { name: "Invite" }).click()+ const [dmResponse, messageResponse] = await Promise.all([+ dmResponsePromise,+ messageResponsePromise,+ ])+ expect(dmResponse.status()).toBe(201)+ expect(messageResponse.status()).toBe(201)+ const dmPayload = await dmResponse.json() as { conversation: { id: string } }+ const messagePayload = await messageResponse.json() as { message: { id: string } }+ await expect(bobRow.getByRole("button", { name: "Invited" })).toBeDisabled()++ await expect(bob.page.getByTestId(tid.dmRow(dmPayload.conversation.id))).toBeVisible({ timeout: 20_000 })+ await bob.page.getByTestId(tid.dmRow(dmPayload.conversation.id)).click()+ await bob.page.waitForURL(new RegExp(`/c/me/${dmPayload.conversation.id}$`), {+ timeout: 20_000,+ waitUntil: "commit",+ })+ await expect(bob.page.getByTestId(tid.message(messagePayload.message.id))).toHaveCount(1)+ await expect(bob.page.getByText(inviteUrl, { exact: false }).first()).toBeVisible({ timeout: 20_000 })+ await bob.page.waitForTimeout(500)+ expect(inviteMessagePosts).toHaveLength(1)+ await expect(bob.page.locator("[data-msg-id]").filter({ hasText: inviteUrl }))+ .toHaveCount(1)+})// Journey 7 β invite accept (second identity). Alice creates a server + invite// via API, Bob accepts it through the UI, and the new server appears in Bob'sdiff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.tsindex 758cf7751..e9a75a248 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 44 current fixtures without a contract version field", () => {+ it("normalizes all 45 current fixtures without a contract version field", () => {const fixtures = Object.values(communityWsEventFixtures)- expect(fixtures).toHaveLength(44)+ expect(fixtures).toHaveLength(45)for (const fixture of fixtures) {const normalized = normalizeCommunityBrowserEvent(fixture)expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })