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
feat(community): profile card polish, presence dot & custom status
Gus8c55424e53d5
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 3bdaba928..9683e6d34 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -333,6 +333,13 @@ export type CommunityPresenceUpdate = {online: boolean}+export type CommunityStatusUpdate = {+ type: "community:status.update"+ userId: string+ statusEmoji: string | null+ statusText: string | null+}+// ── Machine events ────────────────────────────────────────────────────────────/**@@ -456,6 +463,7 @@ export type CommunityWsEvent =| CommunityDmNewMessage| CommunityDmTyping| CommunityPresenceUpdate+ | CommunityStatusUpdate| CommunityMentionCreate| CommunityMachineCreated| CommunityMachineStatus@@ -500,6 +508,7 @@ export const WS_EVENTS = {INVITE_CREATE: "community:invite.create",MENTION_CREATE: "community:mention.create",PRESENCE_UPDATE: "community:presence.update",+ STATUS_UPDATE: "community:status.update",MACHINE_CREATED: "community:machine.created",MACHINE_STATUS: "community:machine.status",MACHINE_UPDATED: "community:machine.updated",diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.tsindex e3afb11fb..f2a7f9eb1 100644--- a/src/shared/src/constants/community.ts+++ b/src/shared/src/constants/community.ts@@ -16,6 +16,8 @@ export const MAX_CATEGORY_NAME_LENGTH = 100export const MAX_FOLDER_NAME_LENGTH = 100export const MAX_PROFILE_NAME_LENGTH = 100export const MAX_PROFILE_ABOUT_LENGTH = 1000+// Short by design — this is a status term ("Vibing"), not a bio.+export const MAX_STATUS_TEXT_LENGTH = 60export const MAX_MESSAGE_CONTENT_LENGTH = 4000export const MAX_FORUM_TAG_LENGTH = 30export const MAX_FORUM_TAGS_PER_POST = 5diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 4924584f8..ac4096aa9 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -380,6 +380,10 @@ export const communityUserProfile = sqliteTable("community_user_profile", {.references(() => user.id, { onDelete: "cascade" }),aboutMe: text("about_me").default(""),bannerColor: text("banner_color"),+ // Custom status (emoji + short term) — e.g. "🎧" + "Vibing". Both nullable:+ // no row / null columns means "no status set". See migration 0056.+ statusEmoji: text("status_emoji"),+ statusText: text("status_text").default(""),});// 18. community_notification_settingdiff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 1bbc77566..8c3354b02 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -1,5 +1,5 @@import { eq, and, or, isNull, inArray } from "drizzle-orm";-import { communityFriendship } from "../../community-schema";+import { communityFriendship, communityUserProfile } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -250,9 +250,12 @@ export async function listFriends(db: Database, userId: string) {friendEmail: user.email,friendImage: user.image,friendDiscriminator: user.discriminator,+ statusEmoji: communityUserProfile.statusEmoji,+ statusText: communityUserProfile.statusText,}).from(communityFriendship).innerJoin(user, eq(user.id, communityFriendship.addresseeId))+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id)).where(and(eq(communityFriendship.requesterId, userId),@@ -269,9 +272,12 @@ export async function listFriends(db: Database, userId: string) {friendEmail: user.email,friendImage: user.image,friendDiscriminator: user.discriminator,+ statusEmoji: communityUserProfile.statusEmoji,+ statusText: communityUserProfile.statusText,}).from(communityFriendship).innerJoin(user, eq(user.id, communityFriendship.requesterId))+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id)).where(and(eq(communityFriendship.addresseeId, userId),@@ -292,8 +298,11 @@ export async function listFriends(db: Database, userId: string) {botEmail: user.email,botImage: user.image,botDiscriminator: user.discriminator,+ statusEmoji: communityUserProfile.statusEmoji,+ statusText: communityUserProfile.statusText,}).from(user)+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id)).where(and(eq(user.ownerUserId, userId),@@ -308,6 +317,8 @@ export async function listFriends(db: Database, userId: string) {friendEmail: b.botEmail,friendImage: b.botImage,friendDiscriminator: b.botDiscriminator,+ statusEmoji: b.statusEmoji,+ statusText: b.statusText,}));return [...asRequester, ...asAddressee, ...ownBotRows];diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex ec4e1415a..f93f7bc1d 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -1,5 +1,5 @@import { eq, and, ne, inArray, count, asc, or, gt, like, isNull, sql } from "drizzle-orm";-import { communityServerMember, communityChannel, communityDmConversation } from "../../community-schema";+import { communityServerMember, communityChannel, communityDmConversation, communityUserProfile } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";import {@@ -149,6 +149,8 @@ export async function listMembersPaginated(userIsBot: boolean;userOwnerUserId: string | null;discriminator: string | null;+ statusEmoji: string | null;+ statusText: string | null;}>;hasMore: boolean;cursor: { joinedAt: string; id: string } | undefined;@@ -188,9 +190,12 @@ export async function listMembersPaginated(userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,discriminator: user.discriminator,+ statusEmoji: communityUserProfile.statusEmoji,+ statusText: communityUserProfile.statusText,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id)).where(and(...conditions)).orderBy(asc(communityServerMember.joinedAt), asc(communityServerMember.id)).limit(limit + 1);@@ -236,9 +241,12 @@ export async function searchMembers(userEmail: user.email,userImage: user.image,discriminator: user.discriminator,+ statusEmoji: communityUserProfile.statusEmoji,+ statusText: communityUserProfile.statusText,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id)).where(and(eq(communityServerMember.serverId, serverId),diff --git a/src/shared/src/db/queries/community/user-profile.ts b/src/shared/src/db/queries/community/user-profile.tsindex 9ff20e251..d696c78ad 100644--- a/src/shared/src/db/queries/community/user-profile.ts+++ b/src/shared/src/db/queries/community/user-profile.ts@@ -13,7 +13,12 @@ export async function getProfile(db: Database, userId: string) {export async function updateProfile(db: Database,userId: string,- data: { aboutMe?: string; bannerColor?: string | null }+ data: {+ aboutMe?: string;+ bannerColor?: string | null;+ statusEmoji?: string | null;+ statusText?: string | null;+ }) {const [row] = await db.insert(communityUserProfile)@@ -21,6 +26,8 @@ export async function updateProfile(userId,aboutMe: data.aboutMe ?? "",bannerColor: data.bannerColor ?? null,+ statusEmoji: data.statusEmoji ?? null,+ statusText: data.statusText ?? "",}).onConflictDoUpdate({target: communityUserProfile.userId,@@ -29,6 +36,12 @@ export async function updateProfile(...(data.bannerColor !== undefined? { bannerColor: data.bannerColor }: {}),+ ...(data.statusEmoji !== undefined+ ? { statusEmoji: data.statusEmoji }+ : {}),+ ...(data.statusText !== undefined+ ? { statusText: data.statusText }+ : {}),},}).returning();diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 6f6ccd638..6249d3225 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -125,6 +125,7 @@ export {MAX_FOLDER_NAME_LENGTH,MAX_PROFILE_NAME_LENGTH,MAX_PROFILE_ABOUT_LENGTH,+ MAX_STATUS_TEXT_LENGTH,MAX_MESSAGE_CONTENT_LENGTH,MAX_FORUM_TAG_LENGTH,MAX_FORUM_TAGS_PER_POST,diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.tsindex 984d8d123..0b75f668a 100644--- a/src/shared/test/queries/community-friendship.test.ts+++ b/src/shared/test/queries/community-friendship.test.ts@@ -158,3 +158,81 @@ describe("getFriendUserIds", () => {expect(result).toEqual(["bot-1"]);});});++/**+ * `listFriends` runs three sequential sub-queries (asRequester, asAddressee,+ * ownBots) — each `leftJoin`s `communityUserProfile` to pick up+ * statusEmoji/statusText. Route each call's resolved rows in call order+ * rather than by table, since the mock chain doesn't distinguish tables.+ */+function createListFriendsDb(opts: {+ asRequesterRows?: unknown[];+ asAddresseeRows?: unknown[];+ ownBotRows?: unknown[];+} = {}) {+ const callRows = [opts.asRequesterRows ?? [], opts.asAddresseeRows ?? [], opts.ownBotRows ?? []];+ let call = 0;+ const leftJoinCalls: unknown[] = [];+ const db: any = {+ select: vi.fn(() => {+ const chain: any = {};+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn((...args: unknown[]) => {+ leftJoinCalls.push(args);+ return chain;+ });+ chain.where = vi.fn(() => Promise.resolve(callRows[call++]));+ return chain;+ }),+ };+ db.__leftJoinCalls = leftJoinCalls;+ return db;+}++describe("listFriends", () => {+ it("leftJoins communityUserProfile on all three sub-queries (asRequester, asAddressee, ownBots)", async () => {+ const db = createListFriendsDb();+ await q.listFriends(db, "u_me");+ expect(db.__leftJoinCalls).toHaveLength(3);+ });++ it("passes through statusEmoji/statusText for asRequester and asAddressee rows", async () => {+ const db = createListFriendsDb({+ asRequesterRows: [{ id: "f1", friendUserId: "u_1", statusEmoji: "🎧", statusText: "Vibing" }],+ asAddresseeRows: [{ id: "f2", friendUserId: "u_2", statusEmoji: null, statusText: null }],+ });+ const result = await q.listFriends(db, "u_me");+ expect(result).toEqual([+ { id: "f1", friendUserId: "u_1", statusEmoji: "🎧", statusText: "Vibing" },+ { id: "f2", friendUserId: "u_2", statusEmoji: null, statusText: null },+ ]);+ });++ it("defaults to null (no crash) for a friend with no communityUserProfile row via the leftJoin", async () => {+ const db = createListFriendsDb({+ asRequesterRows: [{ id: "f1", friendUserId: "u_1", statusEmoji: null, statusText: null }],+ });+ const result = await q.listFriends(db, "u_me");+ expect(result[0]).toMatchObject({ statusEmoji: null, statusText: null });+ });++ it("carries statusEmoji/statusText through the ownBots mapping onto the self-bot friendship rows", async () => {+ const db = createListFriendsDb({+ ownBotRows: [{ botUserId: "bot-1", botName: "Zoe", statusEmoji: "🎮", statusText: "Gaming" }],+ });+ const result = await q.listFriends(db, "u_me");+ expect(result).toEqual([+ {+ id: q.SELF_BOT_FRIENDSHIP_PREFIX + "bot-1",+ friendUserId: "bot-1",+ friendName: "Zoe",+ friendEmail: undefined,+ friendImage: undefined,+ friendDiscriminator: undefined,+ statusEmoji: "🎮",+ statusText: "Gaming",+ },+ ]);+ });+});diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.tsindex 2374acb59..a1e8cb236 100644--- a/src/shared/test/queries/community-member.test.ts+++ b/src/shared/test/queries/community-member.test.ts@@ -10,6 +10,7 @@ function createSelectMock(rows: any[]) {chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);chain.orderBy = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve(rows));@@ -171,6 +172,17 @@ describe("listMembersPaginated", () => {const result = await memberQueries.listMembersPaginated(db, "srv_1", { limit: 5 });expect(result.members.map((r) => r.discriminator)).toEqual(["0001", "0002"]);});++ it("leftJoins communityUserProfile and passes through statusEmoji/statusText, including a user with no profile row", async () => {+ const db = createSelectMock([+ { ...buildMember(1), statusEmoji: "🎧", statusText: "Vibing" },+ { ...buildMember(2), statusEmoji: null, statusText: null },+ ]);+ const result = await memberQueries.listMembersPaginated(db, "srv_1", { limit: 5 });+ expect(db.leftJoin).toHaveBeenCalledTimes(1);+ expect(result.members[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" });+ expect(result.members[1]).toMatchObject({ statusEmoji: null, statusText: null });+ });});describe("searchMembers", () => {@@ -179,6 +191,7 @@ describe("searchMembers", () => {chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);chain.orderBy = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve(rows));@@ -230,6 +243,15 @@ describe("searchMembers", () => {expect(db.limit).toHaveBeenCalledWith(MAX_MEMBERS_PAGE_SIZE);});+ it("leftJoins communityUserProfile and passes through statusEmoji/statusText", async () => {+ const db = createSearchMock([+ { id: "m1", userName: "Alice", statusEmoji: "🎮", statusText: "Gaming" },+ ]);+ const res = await memberQueries.searchMembers(db, "srv_1", "Ali");+ expect(db.leftJoin).toHaveBeenCalledTimes(1);+ expect(res[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" });+ });+it("escapes % and _ wildcards in the query string (LIKE escape)", async () => {// We can't observe the driver-level parameter binding here, but the// helper `escapeLikePattern` is trusted and tested elsewhere. Sanitydiff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.tsnew file mode 100644index 000000000..3e9c61ccc--- /dev/null+++ b/src/shared/test/queries/community-user-profile.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, vi } from "vitest";+import * as profileQueries from "../../src/db/queries/community/user-profile";+import { communityUserProfile } from "../../src/db/community-schema";++function createSelectMock(rows: any[]) {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(rows));+ return chain;+}++function createUpsertMock(returnRow: any) {+ const chain: any = {};+ chain.insert = vi.fn(() => chain);+ chain.values = vi.fn(() => chain);+ chain.onConflictDoUpdate = vi.fn(() => chain);+ chain.returning = vi.fn(() => Promise.resolve([returnRow]));+ return chain;+}++describe("community/user-profile exports", () => {+ it("exports getProfile + updateProfile", () => {+ expect(typeof profileQueries.getProfile).toBe("function");+ expect(typeof profileQueries.updateProfile).toBe("function");+ });+});++describe("getProfile", () => {+ it("returns the row including statusEmoji/statusText when a profile exists", async () => {+ const db = createSelectMock([+ { userId: "u_1", aboutMe: "hi", bannerColor: null, statusEmoji: "🎧", statusText: "Vibing" },+ ]);+ const result = await profileQueries.getProfile(db, "u_1");+ expect(result).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" });+ });++ it("returns null when no profile row exists", async () => {+ const db = createSelectMock([]);+ const result = await profileQueries.getProfile(db, "u_missing");+ expect(result).toBeNull();+ });+});++describe("updateProfile", () => {+ it("persists statusEmoji/statusText alongside aboutMe on insert", async () => {+ const db = createUpsertMock({+ userId: "u_1",+ aboutMe: "hi",+ bannerColor: null,+ statusEmoji: "🎧",+ statusText: "Vibing",+ });+ const result = await profileQueries.updateProfile(db, "u_1", {+ aboutMe: "hi",+ statusEmoji: "🎧",+ statusText: "Vibing",+ });+ expect(db.values).toHaveBeenCalledWith(+ expect.objectContaining({ userId: "u_1", aboutMe: "hi", statusEmoji: "🎧", statusText: "Vibing" }),+ );+ expect(result).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" });+ });++ it("an aboutMe-only update's onConflictDoUpdate.set omits statusEmoji/statusText entirely", async () => {+ const db = createUpsertMock({ userId: "u_1", aboutMe: "hi", bannerColor: null, statusEmoji: null, statusText: "" });+ await profileQueries.updateProfile(db, "u_1", { aboutMe: "hi" });+ const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];+ expect(conflictArg.set).not.toHaveProperty("statusEmoji");+ expect(conflictArg.set).not.toHaveProperty("statusText");+ expect(conflictArg.set).toMatchObject({ aboutMe: "hi" });+ expect(conflictArg.target).toBe(communityUserProfile.userId);+ });++ it("a status-only update's onConflictDoUpdate.set omits aboutMe/bannerColor entirely", async () => {+ const db = createUpsertMock({ userId: "u_1", aboutMe: "", bannerColor: null, statusEmoji: "🎮", statusText: "Gaming" });+ await profileQueries.updateProfile(db, "u_1", { statusEmoji: "🎮", statusText: "Gaming" });+ const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];+ expect(conflictArg.set).not.toHaveProperty("aboutMe");+ expect(conflictArg.set).not.toHaveProperty("bannerColor");+ expect(conflictArg.set).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" });+ });++ it("clearing statusEmoji/statusText to null writes null through to set", async () => {+ const db = createUpsertMock({ userId: "u_1", aboutMe: "", bannerColor: null, statusEmoji: null, statusText: null });+ await profileQueries.updateProfile(db, "u_1", { statusEmoji: null, statusText: null });+ const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];+ expect(conflictArg.set).toMatchObject({ statusEmoji: null, statusText: null });+ });+});diff --git a/src/web/migrations/0056_community_user_custom_status.sql b/src/web/migrations/0056_community_user_custom_status.sqlnew file mode 100644index 000000000..69f9d10bb--- /dev/null+++ b/src/web/migrations/0056_community_user_custom_status.sql@@ -0,0 +1,5 @@+-- Custom status (emoji + short term) shown on the profile card and the+-- member/friends lists. Both nullable so existing rows read as "no status+-- set" with no backfill needed.+ALTER TABLE community_user_profile ADD COLUMN status_emoji TEXT;+ALTER TABLE community_user_profile ADD COLUMN status_text TEXT DEFAULT '';diff --git a/src/web/src/app/api/community/friends/route.test.ts b/src/web/src/app/api/community/friends/route.test.tsnew file mode 100644index 000000000..dd1d31427--- /dev/null+++ b/src/web/src/app/api/community/friends/route.test.ts@@ -0,0 +1,65 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const listFriends = vi.fn()+const listBlocked = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityFriendship: {+ listFriends: (...a: unknown[]) => listFriends(...a),+ listBlocked: (...a: unknown[]) => listBlocked(...a),+ },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ }+})++import { GET } from "./route"++const req = new NextRequest("http://localhost/api/community/friends")++describe("GET /api/community/friends", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ listBlocked.mockResolvedValue([])+ })++ it("includes statusEmoji/statusText sourced from the joined profile row", async () => {+ listFriends.mockResolvedValue([+ { id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: "🎧", statusText: "Vibing" },+ ])+ const res = await GET(req, {} as never)+ expect(res.status).toBe(200)+ const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.friends[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" })+ })++ it("defaults statusEmoji/statusText for a friend with no profile row (no crash on the leftJoin)", async () => {+ listFriends.mockResolvedValue([+ { id: "f2", friendUserId: "u3", friendName: "Lindsay", friendDiscriminator: "0007", friendImage: null, statusEmoji: null, statusText: null },+ ])+ const res = await GET(req, {} as never)+ expect(res.status).toBe(200)+ const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.friends[0]).toMatchObject({ statusEmoji: null, statusText: "" })+ })+})diff --git a/src/web/src/app/api/community/friends/route.ts b/src/web/src/app/api/community/friends/route.tsindex 05e3e7abd..8ea8b1b65 100644--- a/src/web/src/app/api/community/friends/route.ts+++ b/src/web/src/app/api/community/friends/route.ts@@ -18,6 +18,8 @@ export const GET = withAuth(async (_req, ctx) => {avatar: f.friendImage ?? avatarInitial(f.friendName),status: "offline" as const,sub: "",+ statusEmoji: f.statusEmoji ?? null,+ statusText: f.statusText ?? "",}))const blocked = rawBlocked.map((b) => ({id: b.id,diff --git a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.ts b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.tsnew file mode 100644index 000000000..11197deb7--- /dev/null+++ b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.test.ts@@ -0,0 +1,80 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const listFriends = vi.fn()+const listMemberUserIds = vi.fn()+const getMember = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityFriendship: { listFriends: (...a: unknown[]) => listFriends(...a) },+ communityMember: {+ listMemberUserIds: (...a: unknown[]) => listMemberUserIds(...a),+ getMember: (...a: unknown[]) => getMember(...a),+ },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++const ctx = { params: { id: "s1" } } as any+const req = new NextRequest("http://localhost/api/community/servers/s1/invitable-friends")++describe("GET /api/community/servers/[id]/invitable-friends", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ getMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })+ listMemberUserIds.mockResolvedValue([])+ })++ it("includes statusEmoji/statusText sourced from the joined profile row, same as friends-page.tsx", async () => {+ listFriends.mockResolvedValue([+ { id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: "🎮", statusText: "Gaming" },+ ])+ const res = await GET(req, ctx)+ expect(res.status).toBe(200)+ const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.friends[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" })+ })++ it("defaults statusEmoji/statusText for a friend with no profile row", async () => {+ listFriends.mockResolvedValue([+ { id: "f2", friendUserId: "u3", friendName: "Lindsay", friendDiscriminator: "0007", friendImage: null, statusEmoji: null, statusText: null },+ ])+ const res = await GET(req, ctx)+ expect(res.status).toBe(200)+ const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.friends[0]).toMatchObject({ statusEmoji: null, statusText: "" })+ })++ it("still excludes friends who are already members of the server", async () => {+ listFriends.mockResolvedValue([+ { id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: null, statusText: null },+ ])+ listMemberUserIds.mockResolvedValue(["u2"])+ const res = await GET(req, ctx)+ const body = await res.json() as { friends: unknown[] }+ expect(body.friends).toHaveLength(0)+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.ts b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.tsindex ed85254ca..3b9374eae 100644--- a/src/web/src/app/api/community/servers/[id]/invitable-friends/route.ts+++ b/src/web/src/app/api/community/servers/[id]/invitable-friends/route.ts@@ -39,6 +39,8 @@ export const GET = withAuth(async (_req, ctx) => {avatar: f.friendImage ?? avatarInitial(f.friendName),status: "offline" as const,sub: "",+ statusEmoji: f.statusEmoji ?? null,+ statusText: f.statusText ?? "",}))return writeJSON({ friends })diff --git a/src/web/src/app/api/community/servers/[id]/members/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.test.tsindex 8681819dd..76c4a7ee2 100644--- a/src/web/src/app/api/community/servers/[id]/members/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.test.ts@@ -173,6 +173,20 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])})+ it("includes statusEmoji/statusText sourced from the joined profile row, and defaults for a user with no profile row", async () => {+ const rows = [+ { ...buildRow(1), statusEmoji: "🎧", statusText: "Vibing" },+ { ...buildRow(2), statusEmoji: null, statusText: null },+ ]+ mockListMembersPaginated.mockResolvedValue({ members: rows, hasMore: false, cursor: undefined })+ mockCountMembers.mockResolvedValue(2)++ const res = await GET(getReq(), ctx)+ const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.members[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" })+ expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })+ })+it("returns 403 for non-members (permission check ahead of the query)", async () => {mockGetMember.mockResolvedValue(null)const res = await GET(getReq(), ctx)diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.tsindex 684c0ae2e..f5d653e58 100644--- a/src/web/src/app/api/community/servers/[id]/members/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts@@ -56,6 +56,8 @@ export const GET = withAuth(async (req, ctx) => {status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",sub: "",role: r.role ?? "member",+ statusEmoji: r.statusEmoji ?? null,+ statusText: r.statusText ?? "",...(isOwnBot ? { isBot: true as const, ownerUserId: r.userOwnerUserId! } : {}),}})diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.tsindex d28a989b4..6ba944775 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts@@ -84,6 +84,17 @@ describe("GET /api/community/servers/[id]/members/search", () => {expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])})+ it("includes statusEmoji/statusText, defaulting for a user with no profile row", async () => {+ mockSearchMembers.mockResolvedValue([+ { ...buildRow(1, "Alex"), statusEmoji: "🎮", statusText: "Gaming" },+ { ...buildRow(2, "Alex"), statusEmoji: null, statusText: null },+ ])+ const res = await GET(getReq("?q=Alex"), ctx)+ const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string }> }+ expect(body.members[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" })+ expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })+ })+it("rejects empty q with 400", async () => {const res = await GET(getReq(""), ctx)expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.tsindex a97f02c35..6c01d99be 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts@@ -36,6 +36,8 @@ export const GET = withAuth(async (req, ctx) => {status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",sub: "",role: r.role ?? "member",+ statusEmoji: r.statusEmoji ?? null,+ statusText: r.statusText ?? "",}})diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts b/src/web/src/app/api/community/users/[userId]/profile/route.test.tsindex 48eb9d3eb..d64e4baf0 100644--- a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts@@ -1,13 +1,9 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))--const mockGetUser = vi.fn()-const mockGetProfile = vi.fn()-const mockListMemberServerIds = vi.fn()+const getUserPublic = vi.fn()+const getProfile = vi.fn()+const listMemberServerIds = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -16,23 +12,21 @@ vi.mock("@alook/shared", async () => {return {...actual,queries: {- user: { getUserPublic: (...a: unknown[]) => mockGetUser(...a) },- communityUserProfile: { getProfile: (...a: unknown[]) => mockGetProfile(...a) },- communityMember: {- listMemberServerIds: (...a: unknown[]) => mockListMemberServerIds(...a),- },+ user: { getUserPublic: (...a: unknown[]) => getUserPublic(...a) },+ communityUserProfile: { getProfile: (...a: unknown[]) => getProfile(...a) },+ communityMember: { listMemberServerIds: (...a: unknown[]) => listMemberServerIds(...a) },},}})vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- },+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })+ }),}))-vi.mock("@/lib/middleware/helpers", () => {+vi.mock("@/lib/middleware/helpers", async () => {const { NextResponse } = require("next/server")return {writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),@@ -42,49 +36,50 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-function req() {- return new NextRequest("http://localhost/api/community/users/u2/profile", { method: "GET" })-}--function ctx() {- return { params: Promise.resolve({ userId: "u2" }) } as any-}+const req = new NextRequest("http://localhost/api/community/users/u2/profile")describe("GET /api/community/users/[userId]/profile", () => {beforeEach(() => {vi.clearAllMocks()- mockGetUser.mockResolvedValue({- id: "u2",- name: "Bob",- email: "[email protected]",- image: "https://x/y.png",- })- mockGetProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: "#123456" })- mockListMemberServerIds.mockImplementation(async (_db: unknown, userId: string) => {+ getUserPublic.mockResolvedValue({ id: "u2", name: "Gus", discriminator: "1337", image: null })+ listMemberServerIds.mockImplementation(async (_db: unknown, userId: string) => {if (userId === "u1") return ["s1", "s2"]if (userId === "u2") return ["s2", "s3"]return []})})- it("does not include email in the response payload", async () => {- const res = await GET(req(), ctx())+ it("does not include email in the response payload and returns the exact expected shape, including statusEmoji/statusText from the joined profile row", async () => {+ getProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: null, statusEmoji: "🎧", statusText: "Vibing" })+ const res = await GET(req, { params: { userId: "u2" } } as never)expect(res.status).toBe(200)const body = await res.json() as Record<string, unknown>expect(body).not.toHaveProperty("email")expect(body).toEqual({id: "u2",- name: "Bob",- image: "https://x/y.png",+ name: "Gus",+ discriminator: "1337",+ image: null,aboutMe: "hi",- bannerColor: "#123456",+ bannerColor: null,mutualServers: 1,+ statusEmoji: "🎧",+ statusText: "Vibing",})})+ it("defaults to null/\"\" when the target has no profile row (no crash)", async () => {+ getProfile.mockResolvedValue(null)+ const res = await GET(req, { params: { userId: "u2" } } as never)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.statusEmoji).toBeNull()+ expect(body.statusText).toBe("")+ })+it("404s when the target doesn't exist or is soft-deleted — getUserPublic excludes deleted rows unconditionally", async () => {- mockGetUser.mockResolvedValue(null)- const res = await GET(req(), ctx())+ getUserPublic.mockResolvedValue(null)+ const res = await GET(req, { params: { userId: "u2" } } as never)expect(res.status).toBe(404)const body = await res.json() as Record<string, unknown>expect(body.error).toBe("user not found")diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.tsindex a1c759572..4e8da7598 100644--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts@@ -31,5 +31,7 @@ export const GET = withAuth(async (_req, ctx) => {aboutMe: profile?.aboutMe ?? "",bannerColor: profile?.bannerColor ?? null,mutualServers,+ statusEmoji: profile?.statusEmoji ?? null,+ statusText: profile?.statusText ?? "",})})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 9d431f5da..f97b8d46d 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@@ -44,6 +44,11 @@ vi.mock("@/lib/middleware/helpers", async () => {}})+const fanOutStatusUpdate = vi.fn()+vi.mock("@/lib/community/fanout", () => ({+ fanOutStatusUpdate: (...a: unknown[]) => fanOutStatusUpdate(...a),+}))+import { GET, PATCH } from "./route"function patchReq(body: unknown) {@@ -64,20 +69,38 @@ describe("GET /api/community/users/me/profile", () => {getProfile.mockResolvedValue(null)const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)expect(res.status).toBe(200)- expect(await res.json()).toEqual({ aboutMe: "", bannerColor: null, discriminator: "4242" })+ expect(await res.json()).toEqual({+ aboutMe: "",+ bannerColor: null,+ discriminator: "4242",+ statusEmoji: null,+ statusText: "",+ })})it("returns the stored profile fields when they exist", async () => {- getProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: "#aabbcc" })+ getProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: "#aabbcc", statusEmoji: "🎧", statusText: "Vibing" })const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)- expect(await res.json()).toEqual({ aboutMe: "hi", bannerColor: "#aabbcc", discriminator: "4242" })+ expect(await res.json()).toEqual({+ aboutMe: "hi",+ bannerColor: "#aabbcc",+ discriminator: "4242",+ statusEmoji: "🎧",+ statusText: "Vibing",+ })})it("falls back to \"0000\" when the user row is missing", async () => {getProfile.mockResolvedValue(null)getUser.mockResolvedValue(null)const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)- expect(await res.json()).toEqual({ aboutMe: "", bannerColor: null, discriminator: "0000" })+ expect(await res.json()).toEqual({+ aboutMe: "",+ bannerColor: null,+ discriminator: "0000",+ statusEmoji: null,+ statusText: "",+ })})})@@ -85,9 +108,12 @@ describe("PATCH /api/community/users/me/profile", () => {beforeEach(() => {vi.clearAllMocks()updateUser.mockResolvedValue(undefined)+ fanOutStatusUpdate.mockResolvedValue(undefined)updateProfile.mockImplementation(async (_db, _u, data) => ({aboutMe: data.aboutMe ?? null,bannerColor: data.bannerColor ?? null,+ statusEmoji: data.statusEmoji ?? null,+ statusText: data.statusText ?? null,}))})@@ -156,10 +182,55 @@ describe("PATCH /api/community/users/me/profile", () => {})it("returns shape consistent with GET (no userId leak)", async () => {- updateProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: "#aabbcc", userId: "u1" })+ updateProfile.mockResolvedValue({+ aboutMe: "hi",+ bannerColor: "#aabbcc",+ statusEmoji: null,+ statusText: null,+ userId: "u1",+ })const res = await PATCH(patchReq({ aboutMe: "hi" }), {} as never)const body = await res.json()- expect(body).toEqual({ aboutMe: "hi", bannerColor: "#aabbcc" })+ expect(body).toEqual({ aboutMe: "hi", bannerColor: "#aabbcc", statusEmoji: null, statusText: "" })expect(body).not.toHaveProperty("userId")})++ it("accepts a status-only PATCH (no aboutMe/bannerColor/name) — not rejected by the early-exit guard", async () => {+ const res = await PATCH(patchReq({ statusEmoji: "🎧" }), {} as never)+ expect(res.status).toBe(200)+ expect(updateProfile).toHaveBeenCalledWith({}, "u1", { statusEmoji: "🎧" })+ })++ it("accepts clearing statusEmoji/statusText to null/\"\"", async () => {+ const res = await PATCH(patchReq({ statusEmoji: null, statusText: null }), {} as never)+ expect(res.status).toBe(200)+ expect(updateProfile).toHaveBeenCalledWith({}, "u1", { statusEmoji: null, statusText: null })+ })++ it("rejects statusEmoji over MAX_EMOJI_BYTES (multi-codepoint ZWJ emoji near the boundary)", async () => {+ // Family emoji (man, woman, girl, boy joined by ZWJ) — well over 32 UTF-8+ // bytes as a single "emoji", unlike a long run of ASCII characters.+ const familyEmoji = "👨\u200d👩\u200d👧\u200d👦".repeat(2)+ const res = await PATCH(patchReq({ statusEmoji: familyEmoji }), {} as never)+ expect(res.status).toBe(400)+ expect(updateProfile).not.toHaveBeenCalled()+ })++ it("rejects statusText over MAX_STATUS_TEXT_LENGTH", async () => {+ const res = await PATCH(patchReq({ statusText: "x".repeat(61) }), {} as never)+ expect(res.status).toBe(400)+ expect(updateProfile).not.toHaveBeenCalled()+ })++ it("does not call fanOutStatusUpdate when only aboutMe changes", async () => {+ const res = await PATCH(patchReq({ aboutMe: "hi" }), {} as never)+ expect(res.status).toBe(200)+ expect(fanOutStatusUpdate).not.toHaveBeenCalled()+ })++ 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")+ })})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 47046491f..80ea49f17 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@@ -3,11 +3,14 @@ import {queries,MAX_PROFILE_NAME_LENGTH,MAX_PROFILE_ABOUT_LENGTH,+ MAX_STATUS_TEXT_LENGTH,+ MAX_EMOJI_BYTES,BANNER_COLOR_REGEX,} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { fanOutStatusUpdate } from "@/lib/community/fanout"export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)@@ -19,20 +22,34 @@ export const GET = withAuth(async (_req, ctx) => {aboutMe: profile?.aboutMe ?? "",bannerColor: profile?.bannerColor ?? null,discriminator: viewer?.discriminator ?? "0000",+ statusEmoji: profile?.statusEmoji ?? null,+ statusText: profile?.statusText ?? "",})})export const PATCH = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- let body: { name?: string; aboutMe?: string; bannerColor?: string | null }+ let body: {+ name?: string+ aboutMe?: string+ bannerColor?: string | null+ statusEmoji?: string | null+ statusText?: string | null+ }try {body = await req.json()} catch {return writeError("invalid request body", 400)}- if (body.aboutMe === undefined && body.bannerColor === undefined && body.name === undefined) {+ if (+ body.aboutMe === undefined &&+ body.bannerColor === undefined &&+ body.name === undefined &&+ body.statusEmoji === undefined &&+ body.statusText === undefined+ ) {return writeError("no changes provided", 400)}@@ -46,7 +63,12 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {await queries.user.updateUser(db, ctx.userId, { name: trimmed })}- const data: { aboutMe?: string; bannerColor?: string | null } = {}+ const data: {+ aboutMe?: string+ bannerColor?: string | null+ statusEmoji?: string | null+ statusText?: string | null+ } = {}if (body.aboutMe !== undefined) {if (typeof body.aboutMe !== "string") return writeError("aboutMe must be a string", 400)if (body.aboutMe.length > MAX_PROFILE_ABOUT_LENGTH) {@@ -66,16 +88,60 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {data.bannerColor = null}}+ if (body.statusEmoji !== undefined) {+ if (body.statusEmoji !== null) {+ if (typeof body.statusEmoji !== "string") return writeError("statusEmoji must be a string", 400)+ if (Buffer.byteLength(body.statusEmoji, "utf8") > MAX_EMOJI_BYTES) {+ return writeError(`statusEmoji must be ≤ ${MAX_EMOJI_BYTES} bytes`, 400)+ }+ data.statusEmoji = body.statusEmoji+ } else {+ data.statusEmoji = null+ }+ }+ if (body.statusText !== undefined) {+ if (body.statusText !== null) {+ if (typeof body.statusText !== "string") return writeError("statusText must be a string", 400)+ if (body.statusText.length > MAX_STATUS_TEXT_LENGTH) {+ return writeError(`statusText must be ≤ ${MAX_STATUS_TEXT_LENGTH} characters`, 400)+ }+ data.statusText = body.statusText+ } else {+ data.statusText = null+ }+ }- let updated: { aboutMe: string | null; bannerColor: string | null } | null = null- if (data.aboutMe !== undefined || data.bannerColor !== undefined) {+ let updated: {+ aboutMe: string | null+ bannerColor: string | null+ statusEmoji: string | null+ statusText: string | null+ } | null = null+ if (+ data.aboutMe !== undefined ||+ data.bannerColor !== undefined ||+ data.statusEmoji !== undefined ||+ data.statusText !== undefined+ ) {updated = await queries.communityUserProfile.updateProfile(db, ctx.userId, data)}+ // 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(+ ctx.userId,+ updated?.statusEmoji ?? null,+ updated?.statusText ?? null,+ )+ }+// Normalise the response shape — same as GET — so callers don't see// `userId` leak through on PATCH.return writeJSON({aboutMe: updated?.aboutMe ?? "",bannerColor: updated?.bannerColor ?? null,+ statusEmoji: updated?.statusEmoji ?? null,+ statusText: updated?.statusText ?? "",})})diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsxindex 154206846..2beac7cc8 100644--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx@@ -33,7 +33,7 @@ import {usePins,} from "@/hooks/community/use-channel-panels"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"import {useSendMessage,useToggleReactionApi,@@ -81,17 +81,23 @@ function ChannelView() {const { server: currentServer } = useServer(serverId)const membersHook = useServerMembers(serverId)const onlineUserIds = useOnlineUserIds()+ const userStatuses = useCommunityWsStore((s) => s.userStatuses)// Members enriched with presence — used by the message list's typingUsers// resolution and the panel roster to render the correct dot.const members = useMemo(() =>- membersHook.members.map((m) => ({- ...m,- status: m.userId === currentUser.id || onlineUserIds.has(m.userId)- ? ("online" as const)- : ("offline" as const),- })),- [membersHook.members, onlineUserIds, currentUser.id],+ membersHook.members.map((m) => {+ const liveStatus = userStatuses.get(m.userId)+ return {+ ...m,+ status: m.userId === currentUser.id || onlineUserIds.has(m.userId)+ ? ("online" as const)+ : ("offline" as const),+ statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,+ statusText: liveStatus ? liveStatus.text : m.statusText,+ }+ }),+ [membersHook.members, onlineUserIds, currentUser.id, userStatuses],)// Roster passed to the @-mention popover — filters the viewer out.// `members` (above) still includes the viewer for the roster / typing lookup;diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex ceec19f22..7f5fd8db9 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -67,15 +67,21 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const { server: currentServer } = useServer(serverId)const membersHook = useServerMembers(serverId)const onlineUserIds = useOnlineUserIds()+ const userStatuses = useCommunityWsStore((s) => s.userStatuses)const enrichedMembers = useMemo(() =>- membersHook.members.map((m) => ({- ...m,- status: (m.userId === currentUser.id || onlineUserIds.has(m.userId)- ? "online"- : "offline") as "online" | "offline",- })),- [membersHook.members, onlineUserIds, currentUser.id],+ membersHook.members.map((m) => {+ const liveStatus = userStatuses.get(m.userId)+ return {+ ...m,+ status: (m.userId === currentUser.id || onlineUserIds.has(m.userId)+ ? "online"+ : "offline") as "online" | "offline",+ statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,+ statusText: liveStatus ? liveStatus.text : m.statusText,+ }+ }),+ [membersHook.members, onlineUserIds, currentUser.id, userStatuses],)// Gate admin-only fetches on `isAdmin` so regular members don't fire// audit-log 403s and don't waste bandwidth on the invites feed they can'tdiff --git a/src/web/src/app/community/community-shell.tsx b/src/web/src/app/community/community-shell.tsxindex 073b7b5a5..219767169 100644--- a/src/web/src/app/community/community-shell.tsx+++ b/src/web/src/app/community/community-shell.tsx@@ -10,6 +10,7 @@ import {type CurrentUser,} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"+import { useCommunityWsStore } from "@/stores/community/ws"/*** Client wrapper that provides the QueryClient, CurrentUser, and the@@ -56,20 +57,31 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {// flag stuck at false for the viewer's own reactions.useCommunityWs({ viewerUserId: currentUser.id })- // Hydrate `aboutMe` — the community identity holds email/name/avatar from- // the session, but the free-text "about me" lives on the community profile- // row. Fetch it once so the settings dialog opens pre-filled.+ // Hydrate `aboutMe`/status — the community identity holds email/name/avatar+ // from the session, but the free-text "about me" and custom status live on+ // the community profile row. Fetch it once so the settings dialog and+ // UserBar/ProfileCard open pre-filled instead of blank until the next save+ // or WS event (see plans/profile-card.md).+ const currentUserId = currentUser.iduseEffect(() => {- apiFetch<{ aboutMe: string; discriminator: string }>("/api/community/users/me/profile")- .then((data) =>+ apiFetch<{ aboutMe: string; discriminator: string; statusEmoji: string | null; statusText: string }>(+ "/api/community/users/me/profile",+ )+ .then((data) => {setCurrentUser((u) => ({...u,aboutMe: data.aboutMe,discriminator: data.discriminator,- })),- )+ 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])+ }, [setCurrentUser, currentUserId])return <>{children}</>}diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsxindex fb0c81fd6..fb9174fff 100644--- a/src/web/src/app/community/me/[dmId]/page.tsx+++ b/src/web/src/app/community/me/[dmId]/page.tsx@@ -14,7 +14,7 @@ import {useCurrentChannelId,useUiHandlers,} from "@/stores/community"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"import { useDms } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"import { useDmMessages } from "@/hooks/community/use-messages"@@ -53,17 +53,23 @@ function DmView() {const { dms, isLoading: dmsLoading } = useDms()const { friends: rawFriends, blocked } = useFriends()const onlineUserIds = useOnlineUserIds()+ const userStatuses = useCommunityWsStore((s) => s.userStatuses)// 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) => ({- ...f,- status: onlineUserIds.has(f.userId ?? f.id)- ? ("online" as const)- : ("offline" as const),- })),- [rawFriends, onlineUserIds],+ rawFriends.map((f) => {+ const liveStatus = userStatuses.get(f.userId ?? f.id)+ return {+ ...f,+ status: onlineUserIds.has(f.userId ?? f.id)+ ? ("online" as const)+ : ("offline" as const),+ statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,+ statusText: liveStatus ? liveStatus.text : f.statusText,+ }+ }),+ [rawFriends, onlineUserIds, userStatuses],)// Frozen-once snapshot of the viewer's DM read pointer — the anchor for// the "New" divider AND the initial-page mode. Mirrors the channel-viewdiff --git a/src/web/src/app/community/me/page.tsx b/src/web/src/app/community/me/page.tsxindex 6dd02aad3..5c885f41f 100644--- a/src/web/src/app/community/me/page.tsx+++ b/src/web/src/app/community/me/page.tsx@@ -6,7 +6,7 @@ import { FriendsPage } from "@/components/community/friends-page"import { useMemo } from "react"import { useFriends } from "@/hooks/community/use-friends"import { useUiHandlers } from "@/stores/community"-import { useOnlineUserIds } from "@/stores/community/ws"+import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"import {useSendFriendRequest,useAcceptFriendRequest,@@ -24,15 +24,21 @@ export default function MeFriendsPage() {const { friends: rawFriends, pending, blocked, isLoading } = useFriends()const uiHandlers = useUiHandlers()const onlineUserIds = useOnlineUserIds()+ const userStatuses = useCommunityWsStore((s) => s.userStatuses)const friends = useMemo(() =>- rawFriends.map((f) => ({- ...f,- status: onlineUserIds.has(f.userId ?? f.id)- ? ("online" as const)- : ("offline" as const),- })),- [rawFriends, onlineUserIds],+ rawFriends.map((f) => {+ const liveStatus = userStatuses.get(f.userId ?? f.id)+ return {+ ...f,+ status: onlineUserIds.has(f.userId ?? f.id)+ ? ("online" as const)+ : ("offline" as const),+ statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,+ statusText: liveStatus ? liveStatus.text : f.statusText,+ }+ }),+ [rawFriends, onlineUserIds, userStatuses],)const sendFriendRequest = useSendFriendRequest()diff --git a/src/web/src/app/community/preview/_mock.ts b/src/web/src/app/community/preview/_mock.tsindex ed4b05c32..19cabcf2e 100644--- a/src/web/src/app/community/preview/_mock.ts+++ b/src/web/src/app/community/preview/_mock.ts@@ -238,20 +238,20 @@ export const FORUM_TAGS = ["All", "question", "bug", "showcase", "email", "billi// display groups (hoisted role groups, then Online/Offline) from this. Gener is the// Owner (server creator) — there is exactly one, and it can't be reassigned via the UI.export const MEMBERS: Member[] = [- { id: "m_gener", userId: "u_gener", name: "Gener", avatar: "G", status: "online", sub: "", role: "owner" },+ { id: "m_gener", userId: "u_gener", name: "Gener", avatar: "G", status: "online", sub: "", role: "owner", statusEmoji: "🎧", statusText: "Vibing" },{ id: "m_gus", userId: "u_gus", name: "Gus", avatar: "Gu", status: "online", sub: "", role: "admin" },- { id: "m_lindsay", userId: "u_lindsay", name: "Lindsay", avatar: "L", status: "online", sub: "", role: "admin" },+ { id: "m_lindsay", userId: "u_lindsay", name: "Lindsay", avatar: "L", status: "online", sub: "", role: "admin", statusEmoji: "🎮", statusText: "Gaming" },{ id: "m_tomy", userId: "u_tomy", name: "lucky tomy", avatar: "t", status: "online", sub: "AI engineer", role: "member" },- { id: "m_jgtech", userId: "u_jgtech", name: "jgtech", avatar: "j", status: "online", sub: "", role: "member" },+ { id: "m_jgtech", userId: "u_jgtech", name: "jgtech", avatar: "j", status: "online", sub: "", role: "member", statusEmoji: null, statusText: "Heads down" },{ id: "m_azzo", userId: "u_azzo", name: "Azzo", avatar: "A", status: "offline", sub: "", role: "member" },{ id: "m_distagon", userId: "u_distagon", name: "distagon", avatar: "d", status: "offline", sub: "", role: "member" },{ id: "m_reece", userId: "u_reece", name: "Reece", avatar: "R", status: "offline", sub: "", role: "member" },]export const FRIENDS: Friend[] = [- { id: "u_gus", name: "Gus", discriminator: "1337", avatar: "Gu", status: "online", sub: "Playing with agents" },+ { id: "u_gus", name: "Gus", discriminator: "1337", avatar: "Gu", status: "online", sub: "Playing with agents", statusEmoji: "🦥", statusText: "Chillin'" },{ id: "u_lindsay", name: "Lindsay", discriminator: "0007", avatar: "L", status: "online", sub: "Online" },- { id: "u_tomy", name: "lucky tomy", discriminator: "2718", avatar: "t", status: "online", sub: "AI engineer" },+ { id: "u_tomy", name: "lucky tomy", discriminator: "2718", avatar: "t", status: "online", sub: "AI engineer", statusEmoji: "🍟", statusText: "Snack break" },{ id: "u_azzo", name: "Azzo", discriminator: "4404", avatar: "A", status: "offline", sub: "Offline" },{ id: "u_reece", name: "Reece", discriminator: "8080", avatar: "R", status: "offline", sub: "Offline" },]@@ -296,9 +296,9 @@ export const DM_MESSAGES: Record<string, Msg[]> = {}export const PROFILES: Record<string, Profile> = {- Gener: { name: "Gener", discriminator: "0042", avatar: "G", role: "Owner", about: "Building Alook. Coffee, agents, and warm gray UIs.", mutual: 3, tags: ["Owner"] },- Gus: { name: "Gus", discriminator: "1337", avatar: "Gu", role: "Admin", about: "Tinkering with email-driven workflows.", mutual: 2, tags: ["Admin"] },- Lindsay: { name: "Lindsay", discriminator: "0007", avatar: "L", role: "Admin", about: "Research lead. Ask me about presets.", mutual: 2, tags: ["Admin"] },+ Gener: { name: "Gener", discriminator: "0042", avatar: "G", role: "Owner", about: "Building Alook. Coffee, agents, and warm gray UIs.", mutual: 3, statusEmoji: "🎧", statusText: "Vibing" },+ Gus: { name: "Gus", discriminator: "1337", avatar: "Gu", role: "Admin", about: "Tinkering with email-driven workflows.", mutual: 2, statusEmoji: "🦥", statusText: "Chillin'" },+ Lindsay: { name: "Lindsay", discriminator: "0007", avatar: "L", role: "Admin", about: "Research lead. Ask me about presets.", mutual: 2 },}export const INVITES: InviteRow[] = [diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex 4b92cbdaa..64694d3f1 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -90,6 +90,9 @@ export default function CommunityPreview() {return init})const [myAboutMe, setMyAboutMe] = useState("Building Alook. Coffee, agents, and warm gray UIs.")+ // In-memory-only status save for the preview scaffold — mirrors myAboutMe's+ // pattern above; no real persistence/WS fan-out here (see plans/profile-card.md).+ const [myStatus, setMyStatus] = useState<{ emoji: string | null; text: string | null }>({ emoji: "🎧", text: "Vibing" })const [editingProfile, setEditingProfile] = useState(false)// when set, the message area shows the "New Thread" creation panelconst [creatingThread, setCreatingThread] = useState(false)@@ -136,9 +139,14 @@ export default function CommunityPreview() {role: "member",about: member && "sub" in member && member.sub ? member.sub : "No bio yet.",mutual: 1,- tags: [],}- if (name === "Gener") data = { ...data, about: myAboutMe }+ // Merge presence onto the FINAL data regardless of source (curated+ // PROFILES lookup or the fallback literal above) — both mock arrays+ // already carry real mixed online/offline values, so this is what+ // makes the online/offline manual QA cases testable without two live+ // logged-in sessions (see plans/profile-card.md).+ data = { ...data, presence: member?.status, statusEmoji: member?.statusEmoji ?? data.statusEmoji, statusText: member?.statusText ?? data.statusText }+ if (name === "Gener") data = { ...data, about: myAboutMe, statusEmoji: myStatus.emoji, statusText: myStatus.text }setProfile({ data, x: e.clientX, y: e.clientY })}const profileProps = { onOpenProfile: openProfile }@@ -524,7 +532,25 @@ export default function CommunityPreview() {<NewThreadDialog channel={activeChannel} open={creatingThread} onClose={() => setCreatingThread(false)} onCreate={(name, firstMessage) => createThread(name, { firstMessage })} /><Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}><DialogContent className="flex h-[calc(100vh-4rem)] w-[calc(100vw-4rem)] sm:max-w-none flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}>- <UserSettings onClose={() => setEditingProfile(false)} userId={null} userName="Preview User" aboutMe={myAboutMe} avatar="Preview User" onSave={(data) => { if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe) }} onLogout={() => toast("Logged out")} />+ <UserSettings+ onClose={() => setEditingProfile(false)}+ userId={null}+ userName="Preview User"+ aboutMe={myAboutMe}+ avatar="Preview User"+ statusEmoji={myStatus.emoji}+ statusText={myStatus.text}+ onSave={(data) => {+ if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe)+ if (data.statusEmoji !== undefined || data.statusText !== undefined) {+ setMyStatus((s) => ({+ emoji: data.statusEmoji !== undefined ? data.statusEmoji : s.emoji,+ text: data.statusText !== undefined ? data.statusText : s.text,+ }))+ }+ }}+ onLogout={() => toast("Logged out")}+ /></DialogContent></Dialog><Dialog open={view === "settings"} onOpenChange={(o) => { if (!o) goServer() }}>@@ -564,7 +590,7 @@ export default function CommunityPreview() {{...profileProps}/>)}- {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === "Gener"} />}+ {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === "Gener"} onUpdateStatus={(emoji, text) => { setMyStatus({ emoji, text }); setProfile((p) => p ? { ...p, data: { ...p.data, statusEmoji: emoji, statusText: text } } : p) }} />}{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}{dialogs}</Shell>@@ -601,7 +627,7 @@ export default function CommunityPreview() {{...profileProps}/>)}- {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === "Gener"} />}+ {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === "Gener"} onUpdateStatus={(emoji, text) => { setMyStatus({ emoji, text }); setProfile((p) => p ? { ...p, data: { ...p.data, statusEmoji: emoji, statusText: text } } : p) }} />}{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}{dialogs}</Shell>diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex c9a0a0551..f10c35b52 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -152,6 +152,9 @@ export type Member = {status: Presencesub: stringrole: Role+ // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.+ statusEmoji?: string | null+ statusText?: string | null}export type Friend = {@@ -164,6 +167,9 @@ export type Friend = {avatar: stringstatus: Presencesub: string+ // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.+ statusEmoji?: string | null+ statusText?: string | null}export type PendingRequest = {@@ -200,7 +206,15 @@ export type Profile = {role: stringabout: stringmutual: number- tags: string[]+ // 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.+ presence?: Presence+ // Custom status (emoji + short term), e.g. "🎧 Vibing". Both undefined/null+ // means "no status set" — use `hasStatus()` from status-presets.ts, not a+ // truthiness check on either field alone.+ statusEmoji?: string | null+ statusText?: string | null}// ── Settings rows ──────────────────────────────────────────────────────────diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex 51fbb0cd0..0dc667f7b 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -12,12 +12,18 @@ function isUrl(s: string | undefined | null): boolean {return !!s && (s.startsWith("http://") || s.startsWith("https://") || s.startsWith("/"))}-export function Avatar({ label, src, size = 40, dim = false, presence }: {+export function Avatar({ label, src, size = 40, dim = false, presence, ringColor = "var(--background)" }: {label: stringsrc?: stringsize?: numberdim?: booleanpresence?: Presence+ // The cutout ring around the presence dot must match whatever surface the+ // avatar actually sits on (a card, popover, muted panel, etc.) — not+ // always the page's global background — or it reads as a visible seam+ // instead of a clean cutout. Callers on a non-default surface should pass+ // e.g. `ringColor="var(--popover)"`.+ ringColor?: string}) {const safeLabel = label || "?"const avatarConfig = parseAvatarUrl(safeLabel)@@ -61,8 +67,22 @@ export function Avatar({ label, src, size = 40, dim = false, presence }: {)}{presence === "online" && (<AvatarBadge- className="size-2.5 ring-background"- style={{ background: STATUS_COLOR.online } as React.CSSProperties}+ style={{+ background: STATUS_COLOR.online,+ // Scales with the avatar instead of a fixed 10px — on a small+ // 24-32px list avatar that's fine, but on ProfileCard's 64px+ // avatar a fixed dot reads as disproportionately tiny. Keep the+ // filled circle modest and let the cutout ring (below) carry+ // most of the size increase, or a bigger dot alone just looks+ // like an oversized blob.+ width: Math.round(size * 0.22),+ height: Math.round(size * 0.22),+ // Custom cutout ring instead of the `ring-2` default — scaled to+ // the same ratio as the avatar frame's own ring (`ring-4` on a+ // 64px avatar in profile-card.tsx, i.e. ~1/16th of the diameter)+ // so the dot's border reads as consistent with the avatar's.+ boxShadow: `0 0 0 ${Math.max(2, Math.round(size * 0.0625))}px ${ringColor}`,+ } as React.CSSProperties}/>)}</UiAvatar>diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 1b151910b..a0f94c4cc 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -546,7 +546,7 @@ function MentionRow({ item, selected, showMembersHeader, onSelect }: {}}>{item.kind === "member" ? (- <Avatar label={item.avatar} size={24} presence={item.status} />+ <Avatar label={item.avatar} size={24} presence={item.status} ringColor="var(--popover)" />) : (<span className="grid size-6 place-items-center rounded-full bg-primary/15 text-primary">{item.kind === "everyone" ? <Users className="size-3.5" /> : <AtSign className="size-3.5" />}diff --git a/src/web/src/components/community/dm-sidebar.tsx b/src/web/src/components/community/dm-sidebar.tsxindex 4d77938ef..d4e74b57d 100644--- a/src/web/src/components/community/dm-sidebar.tsx+++ b/src/web/src/components/community/dm-sidebar.tsx@@ -77,7 +77,7 @@ export const DmSidebar = memo(function DmSidebar({active ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",].join(" ")}>- <Avatar label={d.avatar} size={32} presence={isBlocked ? undefined : d.status} />+ <Avatar label={d.avatar} size={32} presence={isBlocked ? undefined : d.status} ringColor="var(--sidebar)" /><div className="min-w-0 flex-1 text-left"><div className="truncate text-sm leading-tight text-foreground">{d.name}</div><div className="truncate text-xs leading-tight text-muted-foreground">{d.preview}</div>diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsxindex 4101dd0e7..601ffbc69 100644--- a/src/web/src/components/community/edit-profile-dialog.tsx+++ b/src/web/src/components/community/edit-profile-dialog.tsx@@ -13,6 +13,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { clearPersistedCache } from "@/lib/query-persister"import { Avatar } from "./avatar"import { Field } from "./field"+import { StatusEditor, hasStatus } from "./status-editor"const THEME_OPTIONS = [{ value: "light", label: "Light", icon: Sun },@@ -109,18 +110,21 @@ function AdvancedSettings({ userId }: { userId: string | null }) {)}-export function UserSettings({ onClose, userId, userName, aboutMe, avatar, onSave, onLogout, onUploadAvatar }: {+export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statusEmoji, statusText, onSave, onLogout, onUploadAvatar }: {onClose: () => voiduserId: string | nulluserName: stringaboutMe: stringavatar: string- onSave: (data: { name?: string; aboutMe?: string }) => void+ statusEmoji?: string | null+ statusText?: string | null+ onSave: (data: { name?: string; aboutMe?: string; statusEmoji?: string | null; statusText?: string | null }) => voidonLogout?: () => voidonUploadAvatar?: () => void}) {const [name, setName] = useState(userName)const [value, setValue] = useState(aboutMe)+ const [status, setStatus] = useState({ emoji: statusEmoji ?? null, text: statusText ?? null })const [saving, setSaving] = useState(false)const [tab, setTab] = useState("profile")const timerRef = useRef<NodeJS.Timeout | null>(null)@@ -129,7 +133,7 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, onSavonSaveRef.current = onSave}, [onSave])- const debouncedSave = useCallback((data: { name?: string; aboutMe?: string }) => {+ const debouncedSave = useCallback((data: { name?: string; aboutMe?: string; statusEmoji?: string | null; statusText?: string | null }) => {if (timerRef.current) clearTimeout(timerRef.current)timerRef.current = setTimeout(() => {setSaving(true)@@ -150,6 +154,11 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, onSavdebouncedSave({ name: text.trim() })}+ const handleStatusChange = (emoji: string | null, text: string | null) => {+ setStatus({ emoji, text })+ debouncedSave({ statusEmoji: emoji, statusText: text })+ }+return (<Tabsorientation="vertical"@@ -202,6 +211,17 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, onSav<Field label="About Me"><Textarea className="h-24 resize-none" value={value} onChange={(e) => handleAboutMeChange(e.target.value)} /></Field>+ <Field label="Status">+ <StatusEditor emoji={status.emoji} text={status.text} onChange={handleStatusChange}>+ <button className="flex h-9 w-full items-center rounded-md border border-input bg-transparent px-3 text-sm hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">+ {hasStatus(status.emoji, status.text) ? (+ <span>{status.emoji} {status.text}</span>+ ) : (+ <span className="text-muted-foreground">Set a status</span>+ )}+ </button>+ </StatusEditor>+ </Field></div></TabsContent><TabsContent value="appearance">diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsxindex eca46125d..70a6afe20 100644--- a/src/web/src/components/community/friends-page.tsx+++ b/src/web/src/components/community/friends-page.tsx@@ -11,6 +11,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, Cimport { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"import { EmptyState } from "./empty-state"+import { hasStatus } from "./status-presets"import type { Friend, PendingRequest, BlockedUser, OpenProfile } from "./_types"import { isSelfBotFriendship } from "@alook/shared"@@ -107,7 +108,9 @@ export function FriendsPage({</span>)}</div>- <div className="truncate text-xs text-muted-foreground">{f.sub}</div>+ {hasStatus(f.statusEmoji, f.statusText) && (+ <div className="truncate text-xs text-muted-foreground">{f.statusEmoji} {f.statusText}</div>+ )}</div><span className="grid size-8 place-items-center rounded-full bg-secondary text-muted-foreground"><MessagesSquare className="size-4" /></span></ContextMenuTrigger>diff --git a/src/web/src/components/community/invite-dialog.tsx b/src/web/src/components/community/invite-dialog.tsxindex de128302e..f7ff56367 100644--- a/src/web/src/components/community/invite-dialog.tsx+++ b/src/web/src/components/community/invite-dialog.tsx@@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input"import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"+import { hasStatus } from "./status-presets"import { useInvitableFriends } from "@/hooks/community/use-invitable-friends"import {useResolveOrCreateInvite,@@ -183,11 +184,11 @@ export function InviteDialog({key={f.id}className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">- <Avatar label={f.avatar || f.name} size={32} presence={f.status} />+ <Avatar label={f.avatar || f.name} size={32} presence={f.status} ringColor="var(--popover)" /><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{f.name}</div>- {f.sub && (- <div className="truncate text-xs text-muted-foreground">{f.sub}</div>+ {hasStatus(f.statusEmoji, f.statusText) && (+ <div className="truncate text-xs text-muted-foreground">{f.statusEmoji} {f.statusText}</div>)}</div><Buttondiff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsxindex 945e0bf94..2f59b0f79 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/member-list.tsx@@ -11,6 +11,7 @@ import { Skeleton } from "@/components/ui/skeleton"import { Input } from "@/components/ui/input"import { Avatar } from "./avatar"import { ConfirmDialog } from "@/components/ui/confirm-dialog"+import { hasStatus } from "./status-presets"import type { Member, Role, OpenProfile } from "./_types"import { canManageServer } from "./_types"@@ -234,8 +235,8 @@ function MemberRow({<Avatar label={mem.avatar} size={32} presence={mem.status} dim={mem.status === "offline"} /><div className="min-w-0 flex-1 text-left"><div className={`truncate text-sm leading-tight ${mem.status === "offline" ? "text-muted-foreground" : ""}`}>{mem.name}</div>- {mem.sub && (- <div className="truncate text-xs leading-tight text-muted-foreground">{mem.sub}</div>+ {hasStatus(mem.statusEmoji, mem.statusText) && (+ <div className="truncate text-xs leading-tight text-muted-foreground">{mem.statusEmoji} {mem.statusText}</div>)}</div></ContextMenuTrigger>diff --git a/src/web/src/components/community/profile-card.test.ts b/src/web/src/components/community/profile-card.test.tsnew file mode 100644index 000000000..cc78aab8e--- /dev/null+++ b/src/web/src/components/community/profile-card.test.ts@@ -0,0 +1,27 @@+import { describe, it, expect } from "vitest"+import { generateGradient } from "./profile-card"++describe("generateGradient", () => {+ it("is deterministic for the same name", () => {+ expect(generateGradient("Gener")).toBe(generateGradient("Gener"))+ })++ it("stays within the documented warm band (60-80) for both hues", () => {+ const hueRegex = /oklch\(0\.\d+ 0\.\d+ (\d+(?:\.\d+)?)\)/g+ for (const name of ["Gener", "Gus", "Lindsay", "a", "some really long name here"]) {+ const css = generateGradient(name)+ const hues = [...css.matchAll(hueRegex)].map((m) => Number(m[1]))+ expect(hues).toHaveLength(2)+ for (const hue of hues) {+ expect(hue).toBeGreaterThanOrEqual(60)+ expect(hue).toBeLessThanOrEqual(80)+ }+ }+ })++ it("varies across different names", () => {+ const a = generateGradient("Gener")+ const b = generateGradient("Gus")+ expect(a).not.toBe(b)+ })+})diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsxindex 62692387c..d35e87c63 100644--- a/src/web/src/components/community/profile-card.tsx+++ b/src/web/src/components/community/profile-card.tsx@@ -4,15 +4,15 @@ import { useState } from "react"import { MessagesSquare, Shield } from "lucide-react"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Badge } from "@/components/ui/badge"-import { Separator } from "@/components/ui/separator"import { Avatar } from "./avatar"+import { StatusEditor, hasStatus } from "./status-editor"import type { Profile } from "./_types"import type { Breakpoint } from "@/hooks/use-mobile"// Deterministic, on-brand banner gradient. Hue is constrained to the warm band// (60–80 per DESIGN.md) and chroma kept low so two profiles always read as the// same family — distinct but never garish.-function generateGradient(name: string): string {+export function generateGradient(name: string): string {let hash = 0for (let i = 0; i < name.length; i++) {hash = name.charCodeAt(i) + ((hash << 5) - hash)@@ -23,7 +23,7 @@ function generateGradient(name: string): string {}// Profile card — popover anchored at the click point on desktop, bottom sheet on mobile.-export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf }: {+export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus }: {data: Profilex: numbery: number@@ -31,6 +31,9 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf }: {onClose: () => voidonMessage?: (name: string, text: string) => voidisSelf?: boolean+ // Only used when `isSelf` — the inline status row opens `StatusEditor` and+ // calls this on a preset pick / free-text commit / emoji override / clear.+ onUpdateStatus?: (emoji: string | null, text: string | null) => void}) {const [msg, setMsg] = useState("")const send = () => {@@ -47,32 +50,100 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf }: {{/* banner */}<div className="-m-2 mb-0 h-16 rounded-t-lg" style={{ background: gradient }} /><div className="px-2 pb-2">- <div className="-mt-8 mb-3 flex items-end justify-between">- <div className="rounded-full ring-4 ring-popover">- <Avatar label={data.avatar} size={64} />+ {/* `pl-4` — the card body below has its own `p-4`, so its text sits+ 16px in from this row's container; without matching padding here+ the avatar (flush left) reads as un-aligned with the name/bio+ under it. */}+ <div className="-mt-10 mb-2 flex pl-4">+ {/* `size=77` (64 * 1.2), `ring-[5px]` (round(77*0.0625), matching+ `avatar.tsx`'s own dot-ring formula so the frame keeps the+ same ratio it had at 64px), `-mt-10` (~half of 77, rounded to+ the nearest Tailwind step) keeps the same banner-overlap+ proportion the 64px avatar had at `-mt-8`. */}+ <div className="relative">+ <div className="rounded-full ring-[5px] ring-popover">+ <Avatar label={data.avatar} size={77} presence={data.presence} ringColor="var(--popover)" />+ </div>+ {/* Status sits on the same row as the presence dot, just to its+ right, instead of floating over the avatar's corner. The dot+ (`avatar.tsx`'s `AvatarBadge`) is `absolute right-0 bottom-0`+ sized to `size*0.22` — at `size=77` that's a 17px dot flush+ with the avatar's bottom-right corner, so its vertical+ center sits at `77 - 17/2 = 68.5px` from the avatar's top.+ `top-[68.5px] -translate-y-1/2` centers the pill on that+ same line; `left-full ml-2` starts it 8px past the avatar's+ (and therefore the dot's) right edge. */}+ {isSelf ? (+ <StatusEditor+ emoji={data.statusEmoji ?? null}+ text={data.statusText ?? null}+ onChange={(emoji, text) => onUpdateStatus?.(emoji, text)}+ side="bottom"+ align="start"+ >+ {/* `border-border` gives the pill a defined edge — `bg-secondary`+ alone is only ~6% lighter than the popover behind it (see+ globals.css dark-mode tokens), which read as nearly invisible.+ `shadow-(--e1)` lifts it off the banner it now overlaps.+ `max-w-32 truncate` — the pill's containing block for+ `max-w` purposes is this small avatar-sized wrapper, not+ the card, so it needs its own explicit cap rather than+ `max-w-full`. `px-2 py-0.5` (tighter than the original+ `px-2.5 py-1`) keeps the pill itself compact; emoji and+ term are split into separate spans under the row's+ `gap-2` (instead of one text node with a plain space)+ so the space between *them* can be tuned independently+ of the pill's outer padding. `whitespace-nowrap` — this+ box only sets `left` (no `right`), and its containing+ block (the 77px avatar wrapper) is narrower than `left`+ itself, so the browser's shrink-to-fit width calc has+ ~0px of "available width" to work with and falls back to+ min-content — i.e. wraps at every word — without an+ explicit no-wrap. */}+ <button className="absolute left-full top-[68.5px] ml-2 flex max-w-32 -translate-y-1/2 items-center gap-2 rounded-full border border-border bg-secondary px-2 py-0.5 text-[13px] whitespace-nowrap text-secondary-foreground shadow-(--e1) hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">+ {hasStatus(data.statusEmoji, data.statusText) ? (+ <>+ {data.statusEmoji && <span>{data.statusEmoji}</span>}+ {data.statusText && <span className="min-w-0 truncate">{data.statusText}</span>}+ </>+ ) : (+ <span className="text-muted-foreground">Set a status</span>+ )}+ </button>+ </StatusEditor>+ ) : (+ hasStatus(data.statusEmoji, data.statusText) && (+ <div className="absolute left-full top-[68.5px] ml-2 flex max-w-32 -translate-y-1/2 items-center gap-2 rounded-full border border-border bg-secondary px-2 py-0.5 text-[13px] whitespace-nowrap text-secondary-foreground shadow-(--e1)">+ {data.statusEmoji && <span>{data.statusEmoji}</span>}+ {data.statusText && <span className="min-w-0 truncate">{data.statusText}</span>}+ </div>+ )+ )}</div>- <Badge variant="secondary" className="mb-1 h-6 gap-1"><Shield className="size-3.5" /> {data.role}</Badge></div><div className="rounded-lg bg-card p-4">- <div className="text-lg font-semibold">+ <div className="text-xl font-semibold leading-tight tracking-[-0.015em]">{data.name}{data.discriminator && (- <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">+ <span className="ml-1.5 text-sm font-normal tracking-wide text-muted-foreground">#{data.discriminator}</span>)}</div>- <Separator className="my-2" />- <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">About</div>- <p className="mt-1 text-sm text-muted-foreground">{data.about || "No bio yet."}</p>- {data.mutual > 0 && (- <>- <div className="mt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Mutual servers</div>- <p className="mt-1 text-sm text-muted-foreground">{data.mutual} in common</p>- </>- )}+ {/* Bio reads directly under the name, no shouty label — it isn't+ the card's focal point, so it doesn't need a header announcing+ it. Role + mutual-server count are lower-priority context, so+ they move down here too, as one quiet caption row — `mt-6`+ (not `mt-4`) so the gap reads unambiguously as a group boundary+ (a step past DESIGN.md's 16px between-groups token) rather than+ just tighter line spacing off the bio above it. */}+ <p className="mt-2 text-[15px] text-muted-foreground">{data.about || "No bio yet."}</p>+ <div className="mt-6 flex items-center gap-2 text-xs text-muted-foreground">+ <Badge variant="secondary" className="h-5 gap-1 text-xs"><Shield className="size-3" /> {data.role}</Badge>+ {data.mutual > 0 && <span>{data.mutual} mutual server{data.mutual > 1 ? "s" : ""}</span>}+ </div>{!isSelf && (- <div className="mt-3 flex h-9 items-center gap-2 rounded-md bg-secondary px-2">+ <div className="mt-4 flex h-9 items-center gap-2 rounded-md bg-secondary px-2"><inputvalue={msg}onChange={(e) => setMsg(e.target.value)}@@ -80,10 +151,14 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf }: {if (e.key !== "Enter" || e.nativeEvent.isComposing) returnsend()}}- className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"+ className="flex-1 bg-transparent text-[15px] outline-none placeholder:text-muted-foreground"placeholder={`Message @${data.name}`}/>- <button onClick={send} className="shrink-0 text-muted-foreground hover:text-foreground" aria-label="Send message">+ <button+ onClick={send}+ className="grid size-7 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ aria-label="Send message"+ ><MessagesSquare className="size-4" /></button></div>diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsxindex 253b56ad1..b10ff9acc 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/server-settings.tsx@@ -255,7 +255,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad><div className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-2"><button onClick={(e) => onOpenProfile?.(m.name, e)} className="shrink-0">- <Avatar label={m.avatar} size={32} presence={m.status} />+ <Avatar label={m.avatar} size={32} presence={m.status} ringColor="var(--card)" /></button><div className="min-w-0 flex-1"><div className="truncate text-[15px] font-medium">{m.name}</div>diff --git a/src/web/src/components/community/shell-frame.test.ts b/src/web/src/components/community/shell-frame.test.tsnew file mode 100644index 000000000..b95cf9958--- /dev/null+++ b/src/web/src/components/community/shell-frame.test.ts@@ -0,0 +1,21 @@+import { describe, it, expect } from "vitest"+import { resolveProfilePresence } from "./shell-frame"++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()+ })+})diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 9d56ef13e..871d5a236 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -20,11 +20,11 @@ import { ProfileCard } from "./profile-card"import { ImageLightbox } from "./image-lightbox"import { ImageCropDialog } from "./image-crop-dialog"import { validateIconSourceFile } from "@/lib/community/image-crop"-import type { MobileZone, Profile, View } from "./_types"+import type { MobileZone, Presence, Profile, View } from "./_types"import { signOut } from "@/lib/auth-client"import { clearPersistedCache } from "@/lib/query-persister"import { useCommunityStore } from "@/stores/community"-import { useCommunityWsStore } from "@/stores/community/ws"+import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"import { useServers } from "@/hooks/community/use-servers"import { useFolders } from "@/hooks/community/use-folders"@@ -49,6 +49,27 @@ import {useUploadUserAvatar,} from "@/hooks/community/mutations"+/**+ * Resolves the live online/offline presence for a `ProfileCard` target.+ *+ * `member.status` / `friend.status` are NOT live presence — both API routes+ * hardcode them at fetch time (see plans/profile-card.md's "Presence+ * resolution" note). Real presence only exists by overlaying+ * `useOnlineUserIds()` on top of the raw row, same as every other call site+ * that renders a member/friend row.+ *+ * Pure function (no React) so it's 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"+}+/*** Shared community shell — ServerRail on the left, sidebar column with the* caller's own nav, main content on the right, floating UserBar, plus the@@ -87,6 +108,7 @@ export function ShellFrame({const queryClient = useQueryClient()const currentUser = useCurrentUser()const setCurrentUser = useSetCurrentUser()+ const onlineUserIds = useOnlineUserIds()// Server list + folders drive the rail. Members + friends feed the profile// popover's mutual-server count when the user opens a member card.@@ -297,7 +319,9 @@ export function ShellFrame({role: "You",about: currentUser.aboutMe ?? "",mutual: 0,- tags: [],+ presence: resolveProfilePresence(true, undefined, onlineUserIds),+ statusEmoji: currentUser.statusEmoji ?? null,+ statusText: currentUser.statusText ?? "",}setProfile({ data, x: e.clientX, y: e.clientY })return@@ -314,6 +338,10 @@ export function ShellFrame({const role: string = member && "role" in member ? (member as { role: string }).role : "member"const about: string = member && "sub" in member && (member as { sub: string }).sub ? (member as { sub: string }).sub : ""const displayRole = role.charAt(0).toUpperCase() + role.slice(1)+ // Hoisted above `data` (was previously computed after `setProfile`,+ // only for the async fetch below) so the same value can also feed+ // `resolveProfilePresence`.+ const userId = member && "userId" in member ? (member as { userId: string }).userId : member?.idconst data: Profile = {name,// discriminator is undefined until the /profile fetch below hydrates it.@@ -321,10 +349,11 @@ export function ShellFrame({role: displayRole,about,mutual: 0,- tags: role !== "member" ? [displayRole] : [],+ presence: resolveProfilePresence(false, userId, onlineUserIds),+ statusEmoji: member?.statusEmoji ?? null,+ statusText: member?.statusText ?? "",}setProfile({ data, x: e.clientX, y: e.clientY })- const userId = member && "userId" in member ? (member as { userId: string }).userId : member?.idif (userId) {// Cached under `communityKeys.profile(userId)` — a re-click on the// same person within `PROFILE_STALE_TIME_MS` resolves from memory@@ -345,6 +374,8 @@ export function ShellFrame({about: p.aboutMe ?? prev.data.about,mutual: p.mutualServers ?? 0,discriminator: p.discriminator ?? prev.data.discriminator,+ statusEmoji: p.statusEmoji ?? null,+ statusText: p.statusText ?? "",},}: prev,@@ -353,7 +384,7 @@ export function ShellFrame({.catch(() => { })}},- [currentUser, members, friends, queryClient],+ [currentUser, members, friends, queryClient, onlineUserIds],)const previewImage = useCallback((url: string) => setPreview(url), [])@@ -366,6 +397,23 @@ export function ShellFrame({})}, [previewImage, openProfile, goBackMobile])+ // Inline self-status save from the `ProfileCard` header (see status-editor.tsx).+ // Mirrors `userSettingsDialog`'s onSave status branch exactly — both save+ // paths must independently apply the same local WS-store write, since self+ // isn't in their own fan-out audience (see plans/profile-card.md).+ const updateOwnStatus = async (statusEmoji: string | null, statusText: string | null) => {+ try {+ await updateProfile.mutateAsync({ statusEmoji, statusText })+ setCurrentUser((u) => ({ ...u, statusEmoji, statusText }))+ useCommunityWsStore.getState().setUserStatus(currentUser.id, statusEmoji, statusText)+ setProfile((prev) =>+ prev ? { ...prev, data: { ...prev.data, statusEmoji, statusText } } : prev,+ )+ } catch {+ toast("Failed to update status")+ }+ }+const profileMessage = async (name: string, text: string) => {setProfile(null)const member = members.find((m) => m.name === name)@@ -466,6 +514,8 @@ export function ShellFrame({userName={currentUser.name}aboutMe={currentUser.aboutMe ?? ""}avatar={currentUser.avatar}+ statusEmoji={currentUser.statusEmoji}+ statusText={currentUser.statusText}onUploadAvatar={() => {const input = document.createElement("input")input.type = "file"@@ -489,7 +539,19 @@ export function ShellFrame({...u,...(data.name ? { name: data.name } : {}),...(data.aboutMe !== undefined ? { aboutMe: data.aboutMe } : {}),+ ...(data.statusEmoji !== undefined ? { statusEmoji: data.statusEmoji } : {}),+ ...(data.statusText !== undefined ? { statusText: data.statusText } : {}),}))+ // Self is not in their own WS fan-out audience (co-members/friends+ // means *other* people) — apply the same store write locally so+ // the viewer's own rows (member list, UserBar) update immediately.+ if (data.statusEmoji !== undefined || data.statusText !== undefined) {+ useCommunityWsStore.getState().setUserStatus(+ currentUser.id,+ data.statusEmoji ?? null,+ data.statusText ?? null,+ )+ }} catch { toast("Failed to save profile") }}}onLogout={async () => {@@ -567,7 +629,7 @@ export function ShellFrame({<UserBar user={{ name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} /></div></div>- {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} />}+ {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} onUpdateStatus={updateOwnStatus} />}{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}{userSettingsDialog}{avatarCropDialog}@@ -592,7 +654,7 @@ export function ShellFrame({{children}</div>)}- {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} />}+ {profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} onUpdateStatus={updateOwnStatus} />}{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}{userSettingsDialog}{avatarCropDialog}diff --git a/src/web/src/components/community/status-editor.tsx b/src/web/src/components/community/status-editor.tsxnew file mode 100644index 000000000..187f42af0--- /dev/null+++ b/src/web/src/components/community/status-editor.tsx@@ -0,0 +1,113 @@+"use client"++import { useState } from "react"+import type React from "react"+import { X } from "lucide-react"+import { MAX_STATUS_TEXT_LENGTH } from "@alook/shared"+import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"+import { Input } from "@/components/ui/input"+import { Separator } from "@/components/ui/separator"+import { EmojiPickerPopover } from "./emoji-picker"+import { STATUS_PRESETS, matchingPreset, hasStatus } from "./status-presets"++export { hasStatus } from "./status-presets"++/**+ * Compact status picker in a Popover, following `EmojiPickerPopover`'s+ * children-as-trigger convention — the caller supplies the trigger element+ * (a status row on `ProfileCard`, a Field-wrapped button in `UserSettings`)+ * and this component owns the popover content: 7 preset rows, a free-text+ * input, an emoji-picker trigger to override the emoji independently, and a+ * clear action.+ */+export function StatusEditor({+ emoji,+ text,+ onChange,+ children,+ side = "bottom",+ align = "start",+}: {+ emoji: string | null+ text: string | null+ onChange: (emoji: string | null, text: string | null) => void+ children: React.ReactNode+ side?: "top" | "bottom" | "left" | "right"+ align?: "start" | "center" | "end"+}) {+ const [open, setOpen] = useState(false)+ const [draftText, setDraftText] = useState(text ?? "")++ const setBoth = (o: boolean) => {+ setOpen(o)+ if (o) setDraftText(text ?? "")+ }++ const draftTextTrimmed = () => draftText.trim().slice(0, MAX_STATUS_TEXT_LENGTH)++ const commitText = () => {+ const trimmed = draftTextTrimmed()+ if (trimmed === (text ?? "")) return+ onChange(emoji, trimmed || null)+ }++ const selectedPreset = matchingPreset(emoji, text)++ return (+ <Popover open={open} onOpenChange={setBoth}>+ <PopoverTrigger render={children as React.ReactElement} />+ <PopoverContent side={side} align={align} className="w-64 space-y-2 p-2">+ <div className="space-y-0.5">+ {STATUS_PRESETS.map((preset) => (+ <button+ key={preset.text}+ onClick={() => { onChange(preset.emoji, preset.text); setBoth(false) }}+ className={[+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ selectedPreset === preset ? "bg-accent" : "",+ ].join(" ")}+ >+ <span className="text-base">{preset.emoji}</span>+ <span>{preset.text}</span>+ </button>+ ))}+ </div>+ <Separator />+ <div className="flex items-center gap-2">+ {/* Commit whatever's currently typed in the draft input alongside the+ emoji override — otherwise picking an emoji before blurring/+ pressing Enter on the text field would silently discard it. */}+ <EmojiPickerPopover side="top" align="start" onPick={(e) => onChange(e, draftTextTrimmed() || null)}>+ <button+ className="grid size-8 shrink-0 place-items-center rounded-md border border-border text-base hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ aria-label="Choose emoji"+ >+ {emoji || "🙂"}+ </button>+ </EmojiPickerPopover>+ <Input+ value={draftText}+ onChange={(e) => setDraftText(e.target.value)}+ onBlur={commitText}+ onKeyDown={(e) => {+ if (e.key !== "Enter" || e.nativeEvent.isComposing) return+ commitText()+ setBoth(false)+ }}+ placeholder="Custom status…"+ maxLength={MAX_STATUS_TEXT_LENGTH}+ className="h-8"+ />+ </div>+ {hasStatus(emoji, text) && (+ <button+ onClick={() => { onChange(null, null); setBoth(false) }}+ className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none rounded"+ >+ <X className="size-3.5" /> Clear status+ </button>+ )}+ </PopoverContent>+ </Popover>+ )+}diff --git a/src/web/src/components/community/status-presets.test.ts b/src/web/src/components/community/status-presets.test.tsnew file mode 100644index 000000000..21711ca99--- /dev/null+++ b/src/web/src/components/community/status-presets.test.ts@@ -0,0 +1,45 @@+import { describe, it, expect } from "vitest"+import { STATUS_PRESETS, hasStatus, matchingPreset } from "./status-presets"++describe("hasStatus", () => {+ it("false when both emoji and text are null/undefined/empty", () => {+ expect(hasStatus(null, null)).toBe(false)+ expect(hasStatus(undefined, undefined)).toBe(false)+ expect(hasStatus("", "")).toBe(false)+ })++ it("true when only emoji is set", () => {+ expect(hasStatus("🎧", null)).toBe(true)+ expect(hasStatus("🎧", "")).toBe(true)+ })++ it("true when only text is set", () => {+ expect(hasStatus(null, "Vibing")).toBe(true)+ expect(hasStatus("", "Vibing")).toBe(true)+ })++ it("true when both are set", () => {+ expect(hasStatus("🎧", "Vibing")).toBe(true)+ })+})++describe("matchingPreset", () => {+ it("finds the exact preset for a matching emoji+text pair", () => {+ expect(matchingPreset("🎧", "Vibing")).toEqual({ emoji: "🎧", text: "Vibing" })+ })++ it("returns undefined for a custom (non-preset) pair", () => {+ expect(matchingPreset("🍕", "Pizza time")).toBeUndefined()+ })++ it("returns undefined when the emoji is overridden away from its preset pairing", () => {+ // Same term as a preset, but a different emoji — not an exact preset match.+ expect(matchingPreset("🍕", "Vibing")).toBeUndefined()+ })++ it("every preset is internally self-consistent (round-trips through matchingPreset)", () => {+ for (const preset of STATUS_PRESETS) {+ expect(matchingPreset(preset.emoji, preset.text)).toEqual(preset)+ }+ })+})diff --git a/src/web/src/components/community/status-presets.ts b/src/web/src/components/community/status-presets.tsnew file mode 100644index 000000000..cd672bdf7--- /dev/null+++ b/src/web/src/components/community/status-presets.ts@@ -0,0 +1,36 @@+/**+ * Preset status terms (emoji + short term) offered by `StatusEditor`, plus+ * the shared "is a status set" predicate every display surface uses.+ *+ * Tone is deliberately casual/fun, not work-mode — see plans/profile-card.md.+ */+export type StatusPreset = { emoji: string; text: string }++export const STATUS_PRESETS: StatusPreset[] = [+ { emoji: "🎧", text: "Vibing" },+ { emoji: "🎮", text: "Gaming" },+ { emoji: "🦥", text: "Chillin'" },+ { emoji: "🍟", text: "Snack break" },+ { emoji: "📞", text: "On a call" },+ { emoji: "🚪", text: "Afk" },+ { emoji: "😴", text: "Do not disturb" },+]++/**+ * The emoji and term can be set semi-independently (the emoji picker can+ * override the emoji without touching the term), so "does this user have a+ * status" must check both fields — not `statusText` truthiness alone (a+ * user could have an emoji with no term, or vice versa). Every surface that+ * decides whether to render/reserve space for a status uses this.+ */+export function hasStatus(emoji: string | null | undefined, text: string | null | undefined): boolean {+ return Boolean(emoji || text)+}++/** Does this emoji+text pair match one of the known presets exactly? Used to highlight the selected preset row in `StatusEditor`. */+export function matchingPreset(+ emoji: string | null | undefined,+ text: string | null | undefined,+): StatusPreset | undefined {+ return STATUS_PRESETS.find((p) => p.emoji === emoji && p.text === text)+}diff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/user-bar.tsxindex 778b2c3e2..05790dc8b 100644--- a/src/web/src/components/community/user-bar.tsx+++ b/src/web/src/components/community/user-bar.tsx@@ -32,7 +32,7 @@ function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {return (<div className="flex flex-1 items-center gap-2"><button onClick={(e) => onOpenProfile?.(user.name, e)} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <Avatar label={user.avatar} size={28} presence="online" />+ <Avatar label={user.avatar} size={28} presence="online" ringColor="var(--muted)" /></button><button onClick={(e) => onOpenProfile?.(user.name, e)} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"><div className="truncate text-sm font-medium leading-tight">{user.name}</div>diff --git a/src/web/src/contexts/community/current-user.tsx b/src/web/src/contexts/community/current-user.tsxindex e848b6ab7..1a470df93 100644--- a/src/web/src/contexts/community/current-user.tsx+++ b/src/web/src/contexts/community/current-user.tsx@@ -24,6 +24,11 @@ export type CurrentUser = {// 4-digit discriminator (`"0042"`). Hydrated alongside `aboutMe` from// /api/community/users/me/profile — see CommunityBootstrap.discriminator?: string+ // Custom status (emoji + short term), hydrated alongside `aboutMe`/+ // `discriminator`. See `hasStatus()` in status-presets.ts for the "is a+ // status set" check — don't test either field's truthiness alone.+ statusEmoji?: string | null+ statusText?: string | null}type CurrentUserContextValue = {diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.tsindex b770bc96e..a24df53c0 100644--- a/src/web/src/hooks/community/mutations/profile.ts+++ b/src/web/src/hooks/community/mutations/profile.ts@@ -6,6 +6,8 @@ import { apiFetch } from "@/lib/api/client"export type UpdateProfileArgs = {name?: stringaboutMe?: string+ statusEmoji?: string | null+ statusText?: string | null}/**diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex 385268afd..6fb0c099c 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -15,6 +15,7 @@ import type {CommunityMachineCreated,CommunityMachineStatus,CommunityPresenceUpdate,+ CommunityStatusUpdate,CommunityMentionCreate,CommunityDmNewMessage,CommunityServerUpdate,@@ -679,6 +680,27 @@ describe("useCommunityWs — presence → Zustand store, no cache", () => {})})+describe("useCommunityWs — status.update → Zustand store, no cache", () => {+ it("status.update writes to useCommunityWsStore only", async () => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const event: CommunityStatusUpdate = {+ type: "community:status.update",+ userId: "u_status",+ statusEmoji: "🎧",+ statusText: "Vibing",+ }+ capturedOnMessage!(event)+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ expect(useCommunityWsStore.getState().userStatuses.get("u_status")).toEqual({+ emoji: "🎧",+ text: "Vibing",+ })+ // No cache touched.+ expect(spy).not.toHaveBeenCalled()+ })+})+describe("useCommunityWs — server.update patches server + list caches", () => {it("applies name change to server(id) and servers()", async () => {await mountHook()diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 432312e04..696a98b69 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -756,6 +756,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ // ── Status — no cache; write to WS store (same overlay pattern as+ // presence above, see plans/profile-card.md) ────────────────────+ case "community:status.update": {+ useCommunityWsStore.getState().setUserStatus(event.userId, event.statusEmoji, event.statusText)+ return+ }+// ── Mentions ────────────────────────────────────────────────────case "community:mention.create": {void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.tsindex dfd897cbf..8ac51cc52 100644--- a/src/web/src/hooks/community/use-user-profile.ts+++ b/src/web/src/hooks/community/use-user-profile.ts@@ -17,6 +17,8 @@ export type UserProfile = {aboutMe: stringbannerColor: string | nullmutualServers: number+ statusEmoji: string | null+ statusText: string | null}export const userProfileQueryFn = (userId: string) => () =>diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 01844c68d..36b32bb71 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -21,6 +21,7 @@ vi.mock("@alook/shared", async () => {communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),listMemberUserIds: (...a: unknown[]) => mockListMemberUserIds(...a),+ getCoMemberUserIds: (...a: unknown[]) => mockGetCoMemberUserIds(...a),},communityChannel: {getChannel: (...a: unknown[]) => mockGetChannel(...a),@@ -28,6 +29,9 @@ vi.mock("@alook/shared", async () => {communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),},+ communityFriendship: {+ getFriendUserIds: (...a: unknown[]) => mockGetFriendUserIds(...a),+ },},}})@@ -50,11 +54,14 @@ const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()const mockGetChannel = vi.fn()const mockGetDM = vi.fn()+const mockGetCoMemberUserIds = vi.fn()+const mockGetFriendUserIds = vi.fn()import {fanOutToServerMembers,fanOutToChannel,fanOutToDM,+ fanOutStatusUpdate,broadcastToUserSafe,} from "./fanout"import { WS_EVENTS } from "@alook/shared"@@ -118,6 +125,55 @@ describe("fanOutToServerMembers", () => {})})+describe("fanOutStatusUpdate", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))+ mockBroadcastToUser.mockResolvedValue(undefined)+ })++ it("broadcasts to the deduped union of co-members and friends", async () => {+ mockGetCoMemberUserIds.mockResolvedValue(["u1", "u2"])+ mockGetFriendUserIds.mockResolvedValue(["u2", "u3"])++ await fanOutStatusUpdate("self1", "🎧", "Vibing")++ expect(mockGetCoMemberUserIds).toHaveBeenCalledWith(expect.anything(), "self1")+ expect(mockGetFriendUserIds).toHaveBeenCalledWith(expect.anything(), "self1")+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)+ const targets = mockBroadcastToUser.mock.calls.map((c) => c[0]).sort()+ expect(targets).toEqual(["u1", "u2", "u3"])+ for (const call of mockBroadcastToUser.mock.calls) {+ expect(call[1]).toEqual({+ type: "community:status.update",+ userId: "self1",+ statusEmoji: "🎧",+ statusText: "Vibing",+ })+ }+ })++ it("does not broadcast when the audience is empty", async () => {+ mockGetCoMemberUserIds.mockResolvedValue([])+ mockGetFriendUserIds.mockResolvedValue([])++ await fanOutStatusUpdate("self1", null, null)++ expect(mockBroadcastToUser).not.toHaveBeenCalled()+ })++ it("never throws — absorbs a DB error and logs a warning", async () => {+ mockGetCoMemberUserIds.mockRejectedValue(new Error("db down"))++ await expect(fanOutStatusUpdate("self1", "🎧", "Vibing")).resolves.toBeUndefined()++ expect(mockWarn).toHaveBeenCalledWith(+ "fanout_status_update_failed",+ expect.objectContaining({ userId: "self1", err: expect.stringContaining("db down") }),+ )+ })+})+describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for MESSAGE_CREATE with a wakeMessageRow", () => {const wakeMessageRow = {id: "msg_1",diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 5e3f29b2a..67f4f7885 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -128,6 +128,48 @@ function maybeEnqueueWakes(}+/**+ * Resolves the audience for a self-authored profile change: co-members+ * (every server the user shares with someone) union friends. Mirrors+ * `ws-durable.ts`'s `getPresenceAudience` — that function lives in the+ * 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])]+}++/**+ * 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` /+ * `edit-profile-dialog.tsx`).+ */+export async function fanOutStatusUpdate(+ userId: string,+ statusEmoji: string | null,+ statusText: string | null,+): Promise<void> {+ try {+ const { env } = getCloudflareContext()+ const db = getDb((env as Env).DB)+ const audience = await getProfileAudience(db, userId)+ await broadcastToRecipients(audience, {+ type: WS_EVENTS.STATUS_UPDATE,+ userId,+ statusEmoji,+ statusText,+ })+ } catch (err) {+ log.warn("fanout_status_update_failed", { userId, err: String(err) })+ }+}+/*** Fan out an event to all members of a server.*/diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.tsindex 280a0ff9f..84ce75c4a 100644--- a/src/web/src/stores/community/ws.test.ts+++ b/src/web/src/stores/community/ws.test.ts@@ -119,4 +119,53 @@ describe("useCommunityWsStore", () => {expect(useCommunityWsStore.getState().onlineUserIds.size).toBe(0)expect(useCommunityWsStore.getState().seenMessageIds.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)+ })})diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex 075d6c6b7..da4d04a65 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -27,6 +27,8 @@ import { create } from "zustand"export const SEEN_MESSAGE_MAX = 500export const SEEN_MESSAGE_TRIM_TO = 400+export type UserStatus = { emoji: string | null; text: string | null }+export type CommunityWsStoreState = {/*** Everyone online right now — human or bot. The server pushes@@ -37,6 +39,14 @@ export type CommunityWsStoreState = {*/onlineUserIds: Set<string>seenMessageIds: Set<string>+ /**+ * 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>setPresence: (userId: string, online: boolean) => void/** Atomic bulk seed — one notification for N users. Use on server switch. */@@ -44,15 +54,18 @@ export type CommunityWsStoreState = {resetPresence: () => voidhasSeenMessage: (id: string) => booleanmarkSeenMessage: (id: string) => void+ setUserStatus: (userId: string, emoji: string | null, text: string | null) => void+ resetUserStatuses: () => voidreset: () => void}const initialState = (): Pick<CommunityWsStoreState,- "onlineUserIds" | "seenMessageIds"+ "onlineUserIds" | "seenMessageIds" | "userStatuses"> => ({onlineUserIds: new Set(),seenMessageIds: new Set(),+ userStatuses: new Map(),})export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => ({@@ -97,6 +110,17 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ seenMessageIds: next })},+ 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() })+ },+reset: () => set(initialState()),}))