Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
refactor(community): consistency & fallback unification pass (#365)
Gener33c281b1a37f
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex 1c8d48323..2ade915ad 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -88,12 +88,14 @@ export type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole];// Timing constantsexport const POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS) || 3_000;export const OFFLINE_THRESHOLD_MS = Number(process.env.OFFLINE_THRESHOLD_MS) || 30_000;-// Heartbeat must be strictly less than the offline threshold — the DO alarm-// refreshes last_seen_at every HEARTBEAT_MS, and the row is only offline once-// no refresh has landed in OFFLINE_THRESHOLD_MS. A 2× ratio absorbs one missed-// beat without flapping the chip to offline.+// Invariant: heartbeat MUST be strictly less than the offline threshold — the+// DO alarm refreshes last_seen_at every HEARTBEAT_MS, and a machine is only+// flipped offline once no refresh has landed in OFFLINE_THRESHOLD_MS. Deriving+// the threshold as a multiple of the heartbeat keeps the invariant enforced in+// code (rather than two hand-tuned magic numbers that can drift apart). The 3×+// ratio absorbs two missed beats before flapping the chip to offline.export const COMMUNITY_MACHINE_HEARTBEAT_MS = 30_000;-export const COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS = 90_000;+export const COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS = 3 * COMMUNITY_MACHINE_HEARTBEAT_MS;export const COMMUNITY_MACHINE_PAIR_TOKEN_TTL_MS = 15 * 60_000;export const EVENT_POLL_INTERVAL_MS = Number(process.env.EVENT_POLL_INTERVAL_MS) || 2_000;export const AGENT_HANDLE_MIN_LENGTH = 4;diff --git a/src/shared/src/db/queries/agent.ts b/src/shared/src/db/queries/agent.tsindex e6868fd7a..9b06499a4 100644--- a/src/shared/src/db/queries/agent.ts+++ b/src/shared/src/db/queries/agent.ts@@ -1,6 +1,7 @@import { eq, and, desc, or, exists, inArray } from "drizzle-orm";import { agent, agentAccess } from "../schema";import type { Database } from "../index";+import { isPublic } from "../../utils/visibility";export async function getAgent(db: Database, id: string, workspaceId: string, userId?: string) {const rows = await db@@ -9,7 +10,7 @@ export async function getAgent(db: Database, id: string, workspaceId: string, us.where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)));const row = rows[0] ?? null;if (!row || !userId) return row;- if (row.visibility === "public" || row.ownerId === userId) return row;+ if (isPublic(row.visibility) || row.ownerId === userId) return row;const access = await db.select({ id: agentAccess.id }).from(agentAccess)diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex b8ead2481..fbfaee158 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -8,7 +8,7 @@ import {} from "../../community-schema";import type { Database } from "../../index";import { createLogger } from "../../../logger";-import { canManageServer, canSeePrivateChannel } from "../../../utils/community-roles";+import { canManageServer, canSeePrivateChannel, isForum, isForumPost } from "../../../utils/community-roles";// Module-level logger — one tag per shared query module.const log = createLogger({ service: "community-queries" });@@ -76,7 +76,7 @@ export async function createChannel(.insert(communityChannel).values({serverId: data.serverId,- categoryId: data.categoryId ?? null,+ categoryId: data.categoryId || null,name: data.name,type: data.type ?? "text",topic: data.topic ?? "",@@ -149,7 +149,7 @@ export async function getChannelForMember(db: Database, channelId: string, userI// post/channel, parent for a thread) and its creator. For a post the roster// creator is the post's own (already in `channelRow`, no extra query); the// roster member-row lookup targets `rosterAnchorId`.- const isPost = channelRow.type === "forum_post";+ const isPost = isForumPost(channelRow.type);const privacyAnchorId = channelRow.parentChannelId ?? channelRow.id;const rosterAnchorId = isPost ? channelRow.id : privacyAnchorId;@@ -173,10 +173,10 @@ export async function getChannelForMember(db: Database, channelId: string, userI// child post); everything else checks a row on the roster anchor. NOTE:// admins have NO content privilege for private units — no role short-circuit// here; an admin must be the creator or an explicit member to see it.- const isForum = channelRow.type === "forum";+ const channelIsForum = isForum(channelRow.type);const isMember = isCreator? false- : isForum+ : channelIsForum? await isMemberOfAnyChildPost(db, channelRow.id, userId): await isChannelMember(db, rosterAnchorId, userId);if (!canSeePrivateChannel({ isCreator, isChannelMember: isMember })) {@@ -676,7 +676,7 @@ export async function getPrivateChannelAudienceUserIds(// - thread → climbs to the parent channel's audience (a thread never// narrows access).// - text channel → its own explicit members ∪ its own creator.- if (type === "forum") {+ if (isForum(type)) {// Derived union = every post's own members ∪ every post's creator ∪ the// forum creator. Computed in a fixed number of queries (list posts, then one// `inArray` over their member rows) — NOT a per-post recursion (that was an@@ -700,9 +700,9 @@ export async function getPrivateChannelAudienceUserIds(// post → roster on self; thread/channel → climb to the anchor.const rosterAnchorId =- type === "forum_post" ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);+ isForumPost(type) ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);const rosterCreatorId =- type === "forum_post"+ isForumPost(type)? target[0]!.creatorId: (await db.select({ creatorId: communityChannel.creatorId })@@ -810,7 +810,7 @@ async function resolveVisibleChannelIdSet(const byId = new Map(rows.map((r) => [r.id, r]));const postsByForum = new Map<string, typeof rows>();for (const r of rows) {- if (r.type === "forum_post" && r.parentChannelId) {+ if (isForumPost(r.type) && r.parentChannelId) {const list = postsByForum.get(r.parentChannelId) ?? [];list.push(r);postsByForum.set(r.parentChannelId, list);@@ -827,7 +827,7 @@ async function resolveVisibleChannelIdSet(visible.add(r.id);continue;}- if (r.type === "forum") {+ if (isForum(r.type)) {const posts = postsByForum.get(r.id) ?? [];if (posts.some((p) => p.creatorId === userId || memberChannelIds.has(p.id))) {visible.add(r.id);@@ -842,7 +842,7 @@ async function resolveVisibleChannelIdSet(if (r.parentChannelId == null) continue;const parent = byId.get(r.parentChannelId);if (!parent) continue;- if (r.type === "forum_post") {+ if (isForumPost(r.type)) {// Public forum → post public; private forum → creator or own member row.if (!isPrivate(parent) || r.creatorId === userId || memberChannelIds.has(r.id)) {visible.add(r.id);@@ -956,7 +956,7 @@ export async function resolveChannelAccessContext(// - forum post → privacy climbs to the forum (its category), but the ROSTER// (member rows + creator) is the post's OWN id.// - thread / top-level channel → privacy anchor == roster anchor.- const isPost = channel.type === "forum_post";+ const isPost = isForumPost(channel.type);const rosterAnchorId = isPost ? channel.id : anchorId;const rosterCreatorId = isPost ? channel.creatorId : anchor.creatorId;@@ -972,10 +972,10 @@ export async function resolveChannelAccessContext(// A FORUM's access is derived from its posts (member of any child post);// everything else checks a member row on the roster anchor.- const isForum = channel.type === "forum";+ const channelIsForum = isForum(channel.type);const memberFlag =categoryPrivate === 1- ? isForum+ ? channelIsForum? await isMemberOfAnyChildPost(db, channel.id, userId): await isChannelMember(db, rosterAnchorId, userId): false;diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 8c3354b02..3318ba4a5 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -2,6 +2,7 @@ import { eq, and, or, isNull, inArray } from "drizzle-orm";import { communityFriendship, communityUserProfile } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";+import { isAccepted, isBlocked as isBlockedStatus } from "../../../utils/friendship";// Re-export from the client-safe constants module so existing// `queries.communityFriendship.isSelfBotFriendship` call-sites keep working@@ -61,10 +62,10 @@ export async function sendRequest(const existing = await findExisting(db, data.requesterId, data.addresseeId);if (existing) {- if (existing.status === "blocked") {+ if (isBlockedStatus(existing.status)) {throw new Error("blocked");}- if (existing.status === "accepted") {+ if (isAccepted(existing.status)) {throw new Error("already friends");}// status === "pending"@@ -168,7 +169,7 @@ export async function block(let removedFriendshipId: string | null = null;if (existing) {- if (existing.status === "blocked") {+ if (isBlockedStatus(existing.status)) {// Already blocked — keep it idempotent; just refresh `updatedAt` so// anyone re-issuing the block sees a current timestamp.const rows = await db@@ -186,7 +187,7 @@ export async function block(.where(eq(communityFriendship.id, existing.id));// Tell the route whether to broadcast friend.remove — only if we just// tore down a real friendship, not a pending request.- if (existing.status === "accepted") {+ if (isAccepted(existing.status)) {removedFriendshipId = existing.id;}}@@ -454,8 +455,8 @@ export async function createAcceptedFriendship(): Promise<typeof communityFriendship.$inferSelect | null> {const existing = await findExisting(db, data.requesterId, data.addresseeId);if (existing) {- if (existing.status === "accepted") return existing;- if (existing.status === "blocked") return null;+ if (isAccepted(existing.status)) return existing;+ if (isBlockedStatus(existing.status)) return null;// pending — promote to acceptedconst rows = await db.update(communityFriendship)diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex a3d0fc996..c877932bc 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -9,6 +9,7 @@ import {import { user } from "../../schema";import type { Database } from "../../index";import { listParticipatingThreadIds } from "./thread";+import { isThread } from "../../../utils/community-roles";export interface UnreadChannelRow {channelId: string;@@ -123,14 +124,14 @@ export async function listUnreadChannels(// thread surfaces in the inbox only for its participants (muted=0), NOT for// every parent-channel member who can merely read it. Posts and channels flow// through the visibility path above unchanged. Only threads are re-filtered.- const threadIds = unread.filter((r) => r.type === "thread").map((r) => r.channelId);+ const threadIds = unread.filter((r) => isThread(r.type)).map((r) => r.channelId);const participatingThreadIds =threadIds.length > 0? new Set(await listParticipatingThreadIds(db, threadIds, userId)): new Set<string>();return unread- .filter((r) => r.type !== "thread" || participatingThreadIds.has(r.channelId))+ .filter((r) => !isThread(r.type) || participatingThreadIds.has(r.channelId)).map((r) => ({channelId: r.channelId,channelName: r.channelName,diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex a7f990320..4911e35b8 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -12,6 +12,7 @@ import { communityUserProfile } from "../../community-schema";import type { Database } from "../../index";import { BOT_ACTIVITY_PRESETS, RUNNING_PRESETS } from "../../../community/bot-activity-presets";import { COMMUNITY_MACHINE_PAIR_TOKEN_TTL_MS } from "../../../constants";+import { isPresenceOnline } from "../../../utils/status";import type {CommunityMachineRuntime,CommunityMachineSummary,@@ -1009,7 +1010,7 @@ export async function isBotOnline(db: Database, botUserId: string): Promise<bool),).limit(1);- return rows.length > 0 && rows[0]!.status === "online";+ return rows.length > 0 && isPresenceOnline(rows[0]!.status);}/**diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.tsindex 971c218f3..d3872c0ac 100644--- a/src/shared/src/db/queries/community/members-resolver.ts+++ b/src/shared/src/db/queries/community/members-resolver.ts@@ -5,6 +5,7 @@ import {} from "../../community-schema";import type { Database } from "../../index";import type { CommunityRole } from "../../../utils/community-roles";+import { canManageServer, isForum, isForumPost } from "../../../utils/community-roles";import {getPrivateChannelAudienceUserIds,isChannelPrivate,@@ -111,7 +112,7 @@ export async function resolveScopeMembers(// PUBLIC unit the audience is all server members, tagged admin/inherited.const explicit = new Set<string>();if (isPrivate) {- if (type === "forum") {+ if (isForum(type)) {if (target[0]!.creatorId) explicit.add(target[0]!.creatorId);const posts = await db.select({ id: communityChannel.id, creatorId: communityChannel.creatorId })@@ -123,10 +124,10 @@ export async function resolveScopeMembers(}} else {const rosterAnchorId =- type === "forum_post" ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);+ isForumPost(type) ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);for (const id of await listChannelMemberUserIds(db, rosterAnchorId)) explicit.add(id);const rosterCreatorId =- type === "forum_post"+ isForumPost(type)? target[0]!.creatorId: (await db.select({ creatorId: communityChannel.creatorId })@@ -141,7 +142,7 @@ export async function resolveScopeMembers(const role = roleByUser.get(userId) ?? "member";let source: MemberSource;if (!isPrivate) {- source = role === "owner" || role === "admin" ? "admin" : "inherited";+ source = canManageServer(role) ? "admin" : "inherited";} else if (explicit.has(userId)) {source = "explicit";} else {diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 447424994..8e78523a4 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -511,7 +511,7 @@ export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parexport { MENTION_TOKEN_RE, stripMentionTokens } from "./utils/mention-token";export { isValidToken, isValidEmail } from "./utils/validation";export { escapeLikePattern } from "./utils/sql-like";-export { isOnline, formatStatus } from "./utils/status";+export { isOnline, formatStatus, isPresenceOnline, isPresenceOffline } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";export { generateWorkspaceSlug } from "./utils/slug";export { truncateTitle } from "./utils/title";@@ -521,11 +521,23 @@ export {canSeePrivateChannel,isAssignableRole,isChannelType,+ isForum,+ isForumPost,+ isThread,ROLES,ASSIGNABLE_ROLES,CHANNEL_TYPES,} from "./utils/community-roles";-export type { CommunityRole, ChannelType, AssignableRole } from "./utils/community-roles";+export type { CommunityRole, ChannelType, StoredChannelType, AssignableRole } from "./utils/community-roles";+export {+ isAccepted,+ isPending,+ isBlocked,+ FRIENDSHIP_STATUS,+} from "./utils/friendship";+export type { FriendshipStatus } from "./utils/friendship";+export { isPublic, isPrivate } from "./utils/visibility";+export type { AgentVisibility } from "./utils/visibility";export { extractMentionedUserIds, MENTION_TYPES, isMentionType } from "./utils/community-mentions";export type { MentionCandidate, MentionType } from "./utils/community-mentions";export { semverGte } from "./semver";diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex 36350b56c..002e61cbc 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -1,5 +1,6 @@export type CommunityRole = "owner" | "admin" | "member"export type ChannelType = "text" | "forum"+export type StoredChannelType = "text" | "forum" | "forum_post" | "thread"export const ROLES = {OWNER: "owner",@@ -50,3 +51,15 @@ export function isAssignableRole(role: unknown): role is AssignableRole {export function isChannelType(t: unknown): t is ChannelType {return typeof t === "string" && (CHANNEL_TYPES as readonly string[]).includes(t)}++export function isForum(t: string | null | undefined): boolean {+ return t === "forum"+}++export function isForumPost(t: string | null | undefined): boolean {+ return t === "forum_post"+}++export function isThread(t: string | null | undefined): boolean {+ return t === "thread"+}diff --git a/src/shared/src/utils/friendship.ts b/src/shared/src/utils/friendship.tsnew file mode 100644index 000000000..952ff231a--- /dev/null+++ b/src/shared/src/utils/friendship.ts@@ -0,0 +1,19 @@+export type FriendshipStatus = "pending" | "accepted" | "blocked"++export const FRIENDSHIP_STATUS = {+ PENDING: "pending",+ ACCEPTED: "accepted",+ BLOCKED: "blocked",+} as const++export function isAccepted(status: string | null | undefined): boolean {+ return status === FRIENDSHIP_STATUS.ACCEPTED+}++export function isPending(status: string | null | undefined): boolean {+ return status === FRIENDSHIP_STATUS.PENDING+}++export function isBlocked(status: string | null | undefined): boolean {+ return status === FRIENDSHIP_STATUS.BLOCKED+}diff --git a/src/shared/src/utils/status.ts b/src/shared/src/utils/status.tsindex 0737a0239..194540e26 100644--- a/src/shared/src/utils/status.ts+++ b/src/shared/src/utils/status.ts@@ -9,3 +9,9 @@ export function isOnline(t: string | null | undefined): boolean {return !isNaN(ms) && Date.now() - ms < OFFLINE_THRESHOLD_MS}export function formatStatus(s: RuntimeStatusType) { return s === "online" ? "Online" : "Offline" }+export function isPresenceOnline(status: string | null | undefined): boolean {+ return status === "online"+}+export function isPresenceOffline(status: string | null | undefined): boolean {+ return status === "offline"+}diff --git a/src/shared/src/utils/visibility.ts b/src/shared/src/utils/visibility.tsnew file mode 100644index 000000000..60b73b6db--- /dev/null+++ b/src/shared/src/utils/visibility.ts@@ -0,0 +1,9 @@+export type AgentVisibility = "public" | "private"++export function isPublic(visibility: string | null | undefined): boolean {+ return visibility === "public"+}++export function isPrivate(visibility: string | null | undefined): boolean {+ return visibility === "private"+}diff --git a/src/shared/test/constants.test.ts b/src/shared/test/constants.test.tsindex ba27a78cf..1fc743bee 100644--- a/src/shared/test/constants.test.ts+++ b/src/shared/test/constants.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from "vitest"import {POLL_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH,+ COMMUNITY_MACHINE_HEARTBEAT_MS, COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS,TaskStatus, TERMINAL_TASK_STATUSES, isTerminalTaskStatus,IssueStatus, ACTIVE_ISSUE_STATUSES, TERMINAL_ISSUE_STATUSES, isTerminalIssueStatus,MeetingStatus, TERMINAL_MEETING_STATUSES,@@ -10,6 +11,14 @@ describe("constants", () => {it("OFFLINE_THRESHOLD_MS is 30s", () => expect(OFFLINE_THRESHOLD_MS).toBe(30_000))it("AGENT_HANDLE_MIN_LENGTH is 4", () => expect(AGENT_HANDLE_MIN_LENGTH).toBe(4))it("EVENT_POLL < POLL_INTERVAL", () => expect(EVENT_POLL_INTERVAL_MS).toBeLessThan(POLL_INTERVAL_MS))+ // Derived-pair invariant: the DO alarm re-arms on the heartbeat cadence and+ // only flips a machine offline after the offline threshold elapses, so the+ // heartbeat MUST be strictly less than the offline threshold or machines+ // flap offline at the heartbeat boundary.+ it("machine heartbeat < machine offline threshold", () =>+ expect(COMMUNITY_MACHINE_HEARTBEAT_MS).toBeLessThan(COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS))+ it("machine offline threshold is derived as 3× heartbeat", () =>+ expect(COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS).toBe(3 * COMMUNITY_MACHINE_HEARTBEAT_MS))})describe("TaskStatus", () => {diff --git a/src/shared/test/queries/community-channel-create.test.ts b/src/shared/test/queries/community-channel-create.test.tsnew file mode 100644index 000000000..bfdd3fa3e--- /dev/null+++ b/src/shared/test/queries/community-channel-create.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect, vi } from "vitest";++vi.mock("../../src/logger", () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++import { createChannel } from "../../src/db/queries/community/channel";++function createMockDb() {+ const insertValues = vi.fn();+ const insert = vi.fn(() => ({+ values: vi.fn((v: any) => {+ insertValues(v);+ return {+ returning: vi.fn(() =>+ Promise.resolve([{ id: "c_new", ...v }])+ ),+ };+ }),+ }));+ return { insert, __insertValues: insertValues } as any;+}++describe("createChannel — categoryId coercion", () => {+ it("coerces an empty-string categoryId to null (top-level channel FK)", async () => {+ const db = createMockDb();+ await createChannel(db, { serverId: "s1", categoryId: "", name: "general" });+ expect(db.__insertValues).toHaveBeenCalledWith(+ expect.objectContaining({ categoryId: null })+ );+ });++ it("coerces undefined categoryId to null", async () => {+ const db = createMockDb();+ await createChannel(db, { serverId: "s1", name: "general" });+ expect(db.__insertValues).toHaveBeenCalledWith(+ expect.objectContaining({ categoryId: null })+ );+ });++ it("preserves a real categoryId", async () => {+ const db = createMockDb();+ await createChannel(db, { serverId: "s1", categoryId: "cat_1", name: "general" });+ expect(db.__insertValues).toHaveBeenCalledWith(+ expect.objectContaining({ categoryId: "cat_1" })+ );+ });+});diff --git a/src/shared/test/utils/predicates.test.ts b/src/shared/test/utils/predicates.test.tsnew file mode 100644index 000000000..747ab8ca7--- /dev/null+++ b/src/shared/test/utils/predicates.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect } from "vitest"+import { isForum, isForumPost, isThread, canManageServer } from "../../src/utils/community-roles"+import { isPresenceOnline, isPresenceOffline } from "../../src/utils/status"+import { isAccepted, isPending, isBlocked } from "../../src/utils/friendship"+import { isPublic, isPrivate } from "../../src/utils/visibility"++describe("channel-type predicates", () => {+ it("isForum", () => {+ expect(isForum("forum")).toBe(true)+ expect(isForum("forum_post")).toBe(false)+ expect(isForum("text")).toBe(false)+ expect(isForum(null)).toBe(false)+ expect(isForum(undefined)).toBe(false)+ })+ it("isForumPost", () => {+ expect(isForumPost("forum_post")).toBe(true)+ expect(isForumPost("forum")).toBe(false)+ expect(isForumPost(null)).toBe(false)+ })+ it("isThread", () => {+ expect(isThread("thread")).toBe(true)+ expect(isThread("text")).toBe(false)+ expect(isThread(undefined)).toBe(false)+ })+})++describe("canManageServer matches old role === owner || admin", () => {+ const roles = ["owner", "admin", "member", "guest", "", null, undefined]+ for (const role of roles) {+ it(`role=${String(role)}`, () => {+ const expected = role === "owner" || role === "admin"+ expect(canManageServer(role)).toBe(expected)+ })+ }+})++describe("presence-string predicates", () => {+ it("isPresenceOnline", () => {+ expect(isPresenceOnline("online")).toBe(true)+ expect(isPresenceOnline("offline")).toBe(false)+ expect(isPresenceOnline(null)).toBe(false)+ expect(isPresenceOnline(undefined)).toBe(false)+ })+ it("isPresenceOffline", () => {+ expect(isPresenceOffline("offline")).toBe(true)+ expect(isPresenceOffline("online")).toBe(false)+ expect(isPresenceOffline(null)).toBe(false)+ })+})++describe("friendship-status predicates", () => {+ it("isAccepted", () => {+ expect(isAccepted("accepted")).toBe(true)+ expect(isAccepted("pending")).toBe(false)+ expect(isAccepted(null)).toBe(false)+ })+ it("isPending", () => {+ expect(isPending("pending")).toBe(true)+ expect(isPending("accepted")).toBe(false)+ })+ it("isBlocked", () => {+ expect(isBlocked("blocked")).toBe(true)+ expect(isBlocked("accepted")).toBe(false)+ })+})++describe("visibility predicates", () => {+ it("isPublic", () => {+ expect(isPublic("public")).toBe(true)+ expect(isPublic("private")).toBe(false)+ expect(isPublic(null)).toBe(false)+ })+ it("isPrivate", () => {+ expect(isPrivate("private")).toBe(true)+ expect(isPrivate("public")).toBe(false)+ expect(isPrivate(undefined)).toBe(false)+ })+})diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsxindex 791379c98..4deaed786 100644--- a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx@@ -6,6 +6,8 @@ import { Badge } from "@/components/ui/badge";import { useWorkspace } from "@/contexts/workspace-context";import { ArrowUpRight } from "lucide-react";import type { WorkspaceOverview } from "@/lib/api";+import { displayName } from "@/lib/community/display-name";+import { avatarInitial } from "@/lib/community/avatar";interface TeamAccessProps {overview: WorkspaceOverview;@@ -49,12 +51,12 @@ export function TeamAccess({ overview }: TeamAccessProps) {/>) : (<div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-secondary text-xs font-medium">- {(m.name || m.email).charAt(0).toUpperCase()}+ {avatarInitial(displayName(m))}</div>)}<div className="flex-1 min-w-0"><span className="text-sm font-medium truncate block">- {m.name || m.email}+ {displayName(m)}</span>{m.name && (<span className="text-xs text-muted-foreground truncate block">diff --git a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsxindex a4ecead23..974f9c8bd 100644--- a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx@@ -19,6 +19,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import { trackTeamMemberInvited } from "@/lib/analytics";+import { displayName } from "@/lib/community/display-name";function getInviteLink(token: string) {return `${window.location.origin}/invite/${token}`;@@ -198,14 +199,12 @@ export function MembersTab() {<div className="space-y-2">{members.map((member) => {const isSelf = member.user_id === currentUserId;- const initials = member.name- ? member.name- .split(" ")- .map((n) => n[0])- .join("")- .slice(0, 2)- .toUpperCase()- : member.email.slice(0, 2).toUpperCase();+ const initials = displayName(member)+ .split(" ")+ .map((n) => n[0])+ .join("")+ .slice(0, 2)+ .toUpperCase();return (<div@@ -224,7 +223,7 @@ export function MembersTab() {{/* Name / email */}<div className="min-w-0 flex-1"><p className="text-sm font-medium truncate leading-tight">- {member.name || member.email}+ {displayName(member)}{isSelf && (<span className="ml-2 text-xs text-muted-foreground font-normal">(you)</span>)}diff --git a/src/web/src/app/api/community/agent/ack/route.ts b/src/web/src/app/api/community/agent/ack/route.tsindex 2e56b592b..d40276572 100644--- a/src/web/src/app/api/community/agent/ack/route.ts+++ b/src/web/src/app/api/community/agent/ack/route.ts@@ -3,6 +3,7 @@ import { queries, CommunityAgentAckRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"/**@@ -37,9 +38,9 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if ("error" in resolved) return resolveErrorResponse(resolved)const scopeTarget =- resolved.kind === "dm" ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }- if (resolved.kind === "dm") {+ if (isDmTarget(resolved)) {const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {diff --git a/src/web/src/app/api/community/agent/joinServer/route.ts b/src/web/src/app/api/community/agent/joinServer/route.tsindex 87ebc510e..4e95336b2 100644--- a/src/web/src/app/api/community/agent/joinServer/route.ts+++ b/src/web/src/app/api/community/agent/joinServer/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"+import { memberDisplay } from "@/lib/community/member-payload"/*** POST /api/community/agent/joinServer — `alook server join --invite <link>`.@@ -78,7 +79,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {member: {id: result.member.id,userId: result.member.userId,- name: result.member.nickname ?? result.member.userName,+ name: memberDisplay(result.member.nickname, result.member.userName),discriminator: result.member.discriminator ?? undefined,avatar: result.member.userImage ?? undefined,role: result.member.role ?? ROLES.MEMBER,diff --git a/src/web/src/app/api/community/agent/read/route.ts b/src/web/src/app/api/community/agent/read/route.tsindex 10636a988..e1d2c2be7 100644--- a/src/web/src/app/api/community/agent/read/route.ts+++ b/src/web/src/app/api/community/agent/read/route.ts@@ -3,6 +3,7 @@ import { queries, CommunityAgentReadRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"/**@@ -34,9 +35,9 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if ("error" in resolved) return resolveErrorResponse(resolved)const scopeTarget =- resolved.kind === "dm" ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }- if (resolved.kind === "dm") {+ if (isDmTarget(resolved)) {const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {diff --git a/src/web/src/app/api/community/agent/resolve/route.ts b/src/web/src/app/api/community/agent/resolve/route.tsindex 8f9f1fffc..dac3db43c 100644--- a/src/web/src/app/api/community/agent/resolve/route.ts+++ b/src/web/src/app/api/community/agent/resolve/route.ts@@ -3,6 +3,7 @@ import { queries, CommunityAgentResolveRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"/**@@ -39,9 +40,9 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if ("error" in resolved) return resolveErrorResponse(resolved)const scopeTarget =- resolved.kind === "dm" ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }- if (resolved.kind === "dm") {+ if (isDmTarget(resolved)) {const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })} else {diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex 04e23a303..47ed85d99 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -61,7 +61,8 @@ vi.mock("@alook/shared", async () => {})const mockCreateCommunityMessage = vi.fn()-vi.mock("@/lib/community/message-handler", () => ({+vi.mock("@/lib/community/message-handler", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/community/message-handler")>()),createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),}))diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsindex d3f0d4837..1ee2bc8d3 100644--- a/src/web/src/app/api/community/agent/send/route.ts+++ b/src/web/src/app/api/community/agent/send/route.ts@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"-import { createCommunityMessage, type MessageTarget } from "@/lib/community/message-handler"+import { createCommunityMessage, isDmTarget, type MessageTarget } from "@/lib/community/message-handler"/*** POST /api/community/agent/send — plan §7.@@ -43,7 +43,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {if ("error" in resolved) return resolveErrorResponse(resolved)const scopeTarget =- resolved.kind === "dm" ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }+ isDmTarget(resolved) ? { dmConversationId: resolved.dmConversationId } : { channelId: resolved.channelId }// Channel-alignment gate (plan §7, debt #2 corrected) — no bypass. The// server is the source of truth for the "seen" waterline: a client that@@ -68,7 +68,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {// channels for routing, but `createCommunityMessage` needs the full// 3-variant union to fire `CHILD_CHANNEL_UPDATE` for thread replies).let target: MessageTarget- if (resolved.kind === "dm") {+ if (isDmTarget(resolved)) {const gate = await requireDMParticipant(db, resolved.dmConversationId, ctx.botUserId)if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })target = { kind: "dm", dmId: resolved.dmConversationId, otherUserId: resolved.otherUserId }diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.tsindex f24d44c28..66dade219 100644--- a/src/web/src/app/api/community/channels/[id]/members/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, WS_EVENTS } from "@alook/shared"+import { queries, WS_EVENTS, isForum, isForumPost, isThread } from "@alook/shared"import { broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"import { requireChannelAccess } from "@/lib/community/permissions"@@ -42,7 +42,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {// roster, so both agree. Mirrors the `rosterCreatorId` split in// `resolveChannelAccessContext`.const rosterCreatorId =- access.value.channel.type === "forum_post"+ isForumPost(access.value.channel.type)? access.value.channel.creatorId: anchor.creatorId@@ -83,13 +83,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Threads are notify-only (roster lives on the participant table); a thread// has a `parentMessageId`. A forum post also has a `parentChannelId` but NO// `parentMessageId` and IS its own access unit, so it's allowed.- if (channel.type === "thread" || channel.parentMessageId) {+ if (isThread(channel.type) || channel.parentMessageId) {return writeError("threads inherit their parent channel's members", 400)}// A FORUM's membership is DERIVED from its posts (the union) — it has no roster// of its own, so a member row on the forum would never be read. Reject: add// people to individual posts, not the forum.- if (channel.type === "forum") {+ if (isForum(channel.type)) {return writeError("forum membership is derived from its posts — add members to a post", 400)}// `isPrivate` from requireChannelAccess reflects the (climbed) category — fordiff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.tsindex 147112a23..37ba47237 100644--- a/src/web/src/app/api/community/friends/request/route.ts+++ b/src/web/src/app/api/community/friends/request/route.ts@@ -1,5 +1,5 @@import { NextRequest } from "next/server"-import { queries, WS_EVENTS, isUniqueConstraintError, parseNameAndTag } from "@alook/shared"+import { queries, WS_EVENTS, isUniqueConstraintError, parseNameAndTag, isBlocked } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"@@ -162,7 +162,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON(result.friendship, 201)} catch (err: unknown) {if (err instanceof Error) {- if (err.message === "blocked") return writeError("blocked", 403)+ if (isBlocked(err.message)) return writeError("blocked", 403)if (err.message === "already friends") return writeError("already friends", 409)}if (isUniqueConstraintError(err)) {diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.tsindex b6903a236..746a4b82c 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts@@ -5,6 +5,7 @@ import { queries, ROLES, WS_EVENTS, isUniqueConstraintError } from "@alook/shareimport type { CommunityMemberJoin } from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"+import { memberDisplay } from "@/lib/community/member-payload"export const POST = withAuth(async (_req, ctx) => {const token = ctx.params?.token@@ -40,7 +41,7 @@ export const POST = withAuth(async (_req, ctx) => {member: {id: result.member.id,userId: result.member.userId,- name: result.member.nickname ?? result.member.userName,+ name: memberDisplay(result.member.nickname, result.member.userName),discriminator: result.member.discriminator ?? undefined,avatar: result.member.userImage ?? undefined,role: result.member.role ?? ROLES.MEMBER,diff --git a/src/web/src/app/api/community/media/[...key]/route.ts b/src/web/src/app/api/community/media/[...key]/route.tsindex d58ea4c2e..3092e1397 100644--- a/src/web/src/app/api/community/media/[...key]/route.ts+++ b/src/web/src/app/api/community/media/[...key]/route.ts@@ -6,6 +6,7 @@ import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"import { bindCacheKV } from "@/lib/cache"import { requireChannelMember, requireDMParticipant } from "@/lib/community/permissions"+import { isChannelTarget, isThreadTarget, isDmTarget } from "@/lib/community/message-handler"// Reject any segment that could smuggle traversal or escape the bucket.function isSafeSegment(s: string): boolean {@@ -46,11 +47,11 @@ export const GET = async (// Authorize by resource kind. Each branch loads the parent resource and// verifies membership/participation BEFORE serving any bytes.- if (kind === "channel" || kind === "thread") {+ if (isChannelTarget(kind) || isThreadTarget(kind)) {if (!id) return writeError("not found", 404)const check = await requireChannelMember(db, id, userId)if (!check.ok) return writeError(check.error, check.status)- } else if (kind === "dm") {+ } else if (isDmTarget(kind)) {if (!id) return writeError("not found", 404)// Block check is inherited from `requireDMParticipant` — do not re-inline.const check = await requireDMParticipant(db, id, userId)diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.test.tsindex 70799ad92..55f743438 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.test.ts@@ -88,6 +88,16 @@ describe("POST /servers/[id]/channels", () => {expect(mockFanOutToChannel).not.toHaveBeenCalled()})+ it("coerces an empty-string categoryId to null on a top-level create", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await POST(req({ name: "chan", categoryId: "" }), ctx)+ expect(res.status).toBe(201)+ expect(mockCreateChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ categoryId: null }),+ )+ })+it("rejects a plain member creating in a public category (403)", async () => {mockGetMember.mockResolvedValue({ id: "m1", role: "member" })mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 0 })diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex 9dd70497a..be745a101 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -74,7 +74,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {try {row = await queries.communityChannel.createChannel(db, {serverId,- categoryId: body.categoryId,+ categoryId: body.categoryId || null,name,type: body.type,topic: body.topic,diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsxindex 2fa469539..b083c873a 100644--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx@@ -15,6 +15,10 @@ import { AddMembersDialog } from "@/components/community/add-members-dialog"import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"import { canManageServer } from "@/components/community/_types"import type { MentionType } from "@alook/shared"+import { isForum as isForumType } from "@alook/shared"+import { resolveRowPresence } from "@/lib/community/presence"+import { makeUserNameResolver, displayName } from "@/lib/community/display-name"+import { avatarInitial } from "@/lib/community/avatar"import {useCommunityStore,useCurrentChannelId,@@ -102,9 +106,7 @@ function ChannelView() {const liveStatus = userStatuses.get(m.userId)return {...m,- status: m.userId === currentUser.id || onlineUserIds.has(m.userId)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(m, onlineUserIds, currentUser.id),statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,statusText: liveStatus ? liveStatus.text : m.statusText,}@@ -118,7 +120,7 @@ function ChannelView() {const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []return allChannels.find((ch) => ch.id === channelId) ?? null}, [currentServer, channelId])- const isForum = channelInServer?.type === "forum"+ const isForum = isForumType(channelInServer?.type)const isChildChannel = !channelInServer && !!currentServer?.categories// A thread is a child channel rooted on a message (`parentMessageId`). Forum// posts are child channels too but have no `parentMessageId`. Threads are the@@ -180,10 +182,7 @@ function ChannelView() {avatar: m.avatar,sub: "",role: "member" as const,- status:- m.userId === currentUser.id || onlineUserIds.has(m.userId)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(m, onlineUserIds, currentUser.id),statusEmoji: liveStatus ? liveStatus.emoji : (m.statusEmoji ?? null),statusText: liveStatus ? liveStatus.text : (m.statusText ?? ""),isCreator: m.isCreator,@@ -199,7 +198,7 @@ function ChannelView() {.filter((p) => matches(p.name ?? "", p.discriminator)).map((p) => withPresence({userId: p.userId,- name: p.name ?? "Unknown",+ name: displayName(p),discriminator: p.discriminator ?? undefined,avatar: p.avatar,// Thread rows are all real participants (removable); the thread@@ -249,7 +248,7 @@ function ChannelView() {const liveStatus = userStatuses.get(m.userId)return {...m,- status: onlineUserIds.has(m.userId) ? ("online" as const) : ("offline" as const),+ status: resolveRowPresence(m, onlineUserIds, currentUser.id),statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,statusText: liveStatus ? liveStatus.text : m.statusText,}@@ -511,7 +510,7 @@ function ChannelView() {id: r.message.id,type: "chat" as const,authorName: r.author.name,- authorAvatar: r.author.image ?? r.author.name.charAt(0).toUpperCase(),+ authorAvatar: r.author.image ?? avatarInitial(r.author.name),content: r.message.content,createdAt: r.message.createdAt,})))@@ -636,10 +635,7 @@ function ChannelView() {const threadActions = { ...messageActions, onCreateThread: undefined }- const resolveUserName = useCallback((userId: string) => {- const m = members.find((x) => x.userId === userId)- return m?.name ?? userId- }, [members])+ const resolveUserName = useMemo(() => makeUserNameResolver(members), [members])// ── Send messages ───────────────────────────────────────────────────────const sendMessage = async (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => {@@ -867,7 +863,7 @@ function ChannelView() {<><ChannelHeaderchannel={parentName}- forum={parentChannel?.type === "forum"}+ forum={isForumType(parentChannel?.type)}rightPanel={rightPanel}onToggle={togglePanel}onBack={bp === "mobile" ? () => router.back() : undefined}@@ -894,7 +890,7 @@ function ChannelView() {messages={messages}loading={messagesLoading}pinnedIds={pinnedIds}- typingUsers={typingUsers.map((id) => members.find((m) => m.userId === id)?.name ?? id)}+ typingUsers={typingUsers.map((id) => resolveUserName(id))}onOpenThread={() => { }}{...threadActions}onOpenProfile={openProfile}@@ -1015,7 +1011,7 @@ function ChannelView() {loading={messagesLoading}pinnedIds={pinnedIds}newDividerBefore={newDividerBefore}- typingUsers={typingUsers.map((id) => members.find((m) => m.userId === id)?.name ?? id)}+ typingUsers={typingUsers.map((id) => resolveUserName(id))}onOpenThread={enterThread}{...messageActions}onOpenProfile={openProfile}diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex e290c615f..e617ecd0b 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -18,6 +18,7 @@ import { ImageCropDialog } from "@/components/community/image-crop-dialog"import { validateIconSourceFile } from "@/lib/community/image-crop"import type { MobileZone, SettingsSection } from "@/components/community/_types"import { canManageServer, type ChannelType } from "@alook/shared"+import { resolveRowPresence } from "@/lib/community/presence"import {useCommunityStore,useCurrentChannelId,@@ -75,9 +76,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const liveStatus = userStatuses.get(m.userId)return {...m,- status: (m.userId === currentUser.id || onlineUserIds.has(m.userId)- ? "online"- : "offline") as "online" | "offline",+ status: resolveRowPresence(m, onlineUserIds, currentUser.id),statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,statusText: liveStatus ? liveStatus.text : m.statusText,}diff --git a/src/web/src/app/community/invite/[token]/invite-accept-client.tsx b/src/web/src/app/community/invite/[token]/invite-accept-client.tsxindex df61f9853..a77f8429e 100644--- a/src/web/src/app/community/invite/[token]/invite-accept-client.tsx+++ b/src/web/src/app/community/invite/[token]/invite-accept-client.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from "react"import { useRouter } from "next/navigation"import { toast } from "sonner"import { Button } from "@/components/ui/button"+import { avatarInitial } from "@/lib/community/avatar"import { Skeleton } from "@/components/ui/skeleton"import { useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"@@ -102,7 +103,7 @@ export function InviteAcceptClient({ token }: { token: string }) {<img src={info.serverIcon} alt={info.serverName} className="size-20 rounded-full object-cover" />) : (<span className="text-3xl font-semibold text-muted-foreground">- {info?.serverName.charAt(0).toUpperCase() ?? "?"}+ {info ? avatarInitial(info.serverName) : "?"}</span>)}</div>diff --git a/src/web/src/app/community/layout.tsx b/src/web/src/app/community/layout.tsxindex 6f28fd4e3..d61cc781c 100644--- a/src/web/src/app/community/layout.tsx+++ b/src/web/src/app/community/layout.tsx@@ -4,6 +4,7 @@ import { useEffect } from "react"import { useRouter } from "next/navigation"import { useSession } from "@/lib/auth-client"import { CommunityShell } from "./community-shell"+import { avatarInitial } from "@/lib/community/avatar"export default function CommunityLayout({children,@@ -25,7 +26,7 @@ export default function CommunityLayout({id: session.user.id,name: session.user.name,email: session.user.email,- avatar: session.user.image || session.user.name.charAt(0).toUpperCase(),+ avatar: session.user.image || avatarInitial(session.user.name),}return <CommunityShell currentUser={currentUser}>{children}</CommunityShell>diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsxindex 3d0fe8a75..8a49eca34 100644--- a/src/web/src/app/community/me/[dmId]/page.tsx+++ b/src/web/src/app/community/me/[dmId]/page.tsx@@ -16,6 +16,8 @@ import {useUiHandlers,} from "@/stores/community"import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"+import { resolveRowPresence } from "@/lib/community/presence"+import { makeUserNameResolver } from "@/lib/community/display-name"import { useDms } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"import { useDmMessages } from "@/hooks/community/use-messages"@@ -65,9 +67,7 @@ function DmView() {const liveStatus = userStatuses.get(f.userId ?? f.id)return {...f,- status: onlineUserIds.has(f.userId ?? f.id)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(f, onlineUserIds),statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,statusText: liveStatus ? liveStatus.text : f.statusText,}@@ -198,9 +198,7 @@ function DmView() {if (!raw) return nullreturn {...raw,- status: onlineUserIds.has(raw.userId)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(raw, onlineUserIds),}}, [dms, dmId, onlineUserIds])@@ -208,10 +206,7 @@ function DmView() {uiHandlers.openProfile?.(name, e, discriminator, userId)}- const resolveUserName = useCallback((userId: string) => {- const f = friends.find((x) => x.userId === userId)- return f?.name ?? userId- }, [friends])+ const resolveUserName = useMemo(() => makeUserNameResolver(friends), [friends])const messageActions = useMemo(() => ({onToggleReaction: (id: string, emoji: string) =>@@ -334,9 +329,9 @@ function DmView() {// In a DM there are only two participants — if the typing id// matches the DM's counterpart, use their DM display name.// Fall back to friends list (adds names for friend-typers in- // group DMs when we add them) and finally to the raw id.+ // group DMs when we add them) and finally to "Unknown member".if (dm && id === dm.userId) return dm.name- return friends.find((f) => f.userId === id)?.name ?? id+ return resolveUserName(id)})}onOpenThread={() => { }}onToggleReaction={dmBlocked ? undefined : messageActions.onToggleReaction}diff --git a/src/web/src/app/community/me/layout.tsx b/src/web/src/app/community/me/layout.tsxindex a515f4043..766ab471f 100644--- a/src/web/src/app/community/me/layout.tsx+++ b/src/web/src/app/community/me/layout.tsx@@ -12,6 +12,7 @@ import { useDms } from "@/hooks/community/use-dms"import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"import { communityKeys } from "@/lib/query-keys"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { resolveRowPresence } from "@/lib/community/presence"// DM-side layout. The DM subtree has no server settings, no channel sidebar,// and no `[serverId]` param — everything is scoped to the current user.@@ -26,9 +27,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {() =>rawDms.map((d) => ({...d,- status: onlineUserIds.has(d.userId)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(d, onlineUserIds),})),[rawDms, onlineUserIds],)diff --git a/src/web/src/app/community/me/page.tsx b/src/web/src/app/community/me/page.tsxindex 77a4e78de..d984340d9 100644--- a/src/web/src/app/community/me/page.tsx+++ b/src/web/src/app/community/me/page.tsx@@ -7,6 +7,7 @@ import { useMemo } from "react"import { useFriends } from "@/hooks/community/use-friends"import { useUiHandlers } from "@/stores/community"import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"+import { resolveRowPresence } from "@/lib/community/presence"import {useSendFriendRequest,useAcceptFriendRequest,@@ -32,9 +33,7 @@ export default function MeFriendsPage() {const liveStatus = userStatuses.get(f.userId ?? f.id)return {...f,- status: onlineUserIds.has(f.userId ?? f.id)- ? ("online" as const)- : ("offline" as const),+ status: resolveRowPresence(f, onlineUserIds),statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,statusText: liveStatus ? liveStatus.text : f.statusText,}diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex 659863cab..975946c73 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -18,6 +18,7 @@import { useMemo, useState } from "react"import type React from "react"import { toast } from "sonner"+import { isForum as isForumType, isServerOwner } from "@alook/shared"import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"import { Dialog, DialogContent } from "@/components/ui/dialog"@@ -31,6 +32,8 @@ import {import type { RightPanel, MobileZone, View, SettingsSection, Msg, PendingRequest, BlockedUser, ForumPost, Profile, Thread, Role, DM, Member } from "@/components/community/_types"import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelTree } from "@/components/community/use-channel-tree"+import { avatarInitial } from "@/lib/community/avatar"+import { displayName } from "@/lib/community/display-name"import { ProfileCard } from "@/components/community/profile-card"import { ImageLightbox } from "@/components/community/image-lightbox"import { UserSettings } from "@/components/community/edit-profile-dialog"@@ -139,7 +142,7 @@ export default function CommunityPreview() {let data: Profile = PROFILES[name] ?? {name,userId: member?.userId ?? member?.id,- avatar: member?.avatar ?? name.charAt(0).toUpperCase(),+ avatar: member?.avatar ?? avatarInitial(name),role: "member",about: member && "sub" in member && member.sub ? member.sub : "No bio yet.",mutual: 1,@@ -160,10 +163,10 @@ export default function CommunityPreview() {// message from profile card — find or create a DM, append the message, and navigateconst profileMessage = (userId: string, text: string) => {const source = memberList.find((m) => m.userId === userId) ?? friendList.find((f) => f.userId === userId)- const name = source?.name ?? userId+ const name = displayName(source)let target = dmList.find((d) => d.userId === userId)if (!target) {- target = { id: `dm_${userId}`, userId, name, avatar: name.charAt(0).toUpperCase(), status: "online" as const, preview: text.slice(0, 40) }+ target = { id: `dm_${userId}`, userId, name, avatar: avatarInitial(name), status: "online" as const, preview: text.slice(0, 40) }setDmList((prev) => [target!, ...prev])}const dmId = target.id@@ -193,7 +196,7 @@ export default function CommunityPreview() {// the active channel object (for forum detection) and the open thread/post.const activeChannelObj = Object.values(channelTree.order).flat().find((ch) => ch.id === activeChannel)- const isForum = activeChannelObj?.type === "forum"+ const isForum = isForumType(activeChannelObj?.type)const allThreads = [...threads, ...Object.values(forumPosts).flat()]const openThread = allThreads.find((t) => t.id === openThreadId) ?? nullconst dm = dmList.find((d) => d.id === activeDm) ?? null@@ -343,7 +346,7 @@ export default function CommunityPreview() {toast(`${name} is now ${role}`)}const kickMember = (name: string) => {- setMemberList((prev) => prev.filter((m) => m.name !== name || m.role === "owner"))+ setMemberList((prev) => prev.filter((m) => m.name !== name || isServerOwner(m.role)))toast(`${name} kicked`)}const memberActions = { onSetRole: setMemberRole, onKickMember: kickMember }@@ -354,7 +357,7 @@ export default function CommunityPreview() {onReject: (id: string) => setPending((p) => p.filter((r) => r.id !== id)),onCancelRequest: (id: string) => setPending((p) => p.filter((r) => r.id !== id)),onUnblock: (id: string) => { setBlocked((b) => b.filter((u) => u.id !== id)); toast("User unblocked") },- onSendRequest: (username: string) => { setPending((p) => [...p, { id: `pr_${username}`, userId: `u_${username}`, name: username, avatar: username.charAt(0).toUpperCase(), kind: "outgoing" }]); toast(`Friend request sent to ${username}`) },+ onSendRequest: (username: string) => { setPending((p) => [...p, { id: `pr_${username}`, userId: `u_${username}`, name: username, avatar: avatarInitial(username), kind: "outgoing" }]); toast(`Friend request sent to ${username}`) },onRemoveFriend: (id: string) => { setFriendList((p) => p.filter((f) => f.id !== id)); toast("Friend removed") },onBlock: (id: string) => { const f = friendList.find((x) => x.id === id); setFriendList((p) => p.filter((x) => x.id !== id)); if (f) setBlocked((b) => [...b, { id: f.id, name: f.name, avatar: f.avatar }]); toast("User blocked") },}diff --git a/src/web/src/components/agent-form-fields.tsx b/src/web/src/components/agent-form-fields.tsxindex 3e6b51e2d..9f8277260 100644--- a/src/web/src/components/agent-form-fields.tsx+++ b/src/web/src/components/agent-form-fields.tsx@@ -4,6 +4,7 @@ import { useState, useEffect } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { onEnterSubmit } from "@/lib/ime";import {Select,SelectTrigger,@@ -22,7 +23,7 @@ import {} from "@/components/ui/dialog";import { RuntimeSelect } from "@/components/runtime-select";import { ProviderLogo } from "@/components/provider-logo";-import { isValidHandle } from "@alook/shared";+import { isValidHandle, isPublic, isPrivate } from "@alook/shared";import type { AgentRuntime as Runtime } from "@alook/shared";import { cn } from "@/lib/utils";import { InfoIcon, XIcon, Dices, ChevronDown } from "lucide-react";@@ -435,12 +436,7 @@ export function AllowedSendersTab({ agentId }: { agentId: string }) {<Inputvalue={newEmail}onChange={(e) => setNewEmail(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- handleAdd();- }- }}+ onKeyDown={onEnterSubmit(handleAdd)}placeholder="[email protected]"type="email"className="flex-1"@@ -564,7 +560,7 @@ export function AgentAccessTab({try {await updateAgentApi(agentId, { visibility: newVisibility }, workspaceId);toast.success(- newVisibility === "public"+ isPublic(newVisibility)? "Agent is now public": "Agent is now private");@@ -651,7 +647,7 @@ export function AgentAccessTab({<div><h3 className="text-sm font-medium">Visibility</h3><p className="text-xs text-muted-foreground mt-1">- {visibility === "public"+ {isPublic(visibility)? "All workspace members can use this agent": "Only authorized members can use this agent"}</p>@@ -660,12 +656,12 @@ export function AgentAccessTab({<span className="text-xs text-muted-foreground">{savingVisibility? "Saving…"- : visibility === "public"+ : isPublic(visibility)? "Public": "Private"}</span><Switch- checked={visibility === "public"}+ checked={isPublic(visibility)}onCheckedChange={(checked) =>handleVisibilityChange(checked ? "public" : "private")}@@ -675,7 +671,7 @@ export function AgentAccessTab({</div></div>- {visibility === "private" && (+ {isPrivate(visibility) && (<div className="space-y-3"><h3 className="text-sm font-medium">Authorized Members</h3>{error && <p className="text-xs text-destructive">{error}</p>}diff --git a/src/web/src/components/channel-bar.tsx b/src/web/src/components/channel-bar.tsxindex e0a6074f5..8307e0ee8 100644--- a/src/web/src/components/channel-bar.tsx+++ b/src/web/src/components/channel-bar.tsx@@ -20,6 +20,7 @@ import {import { CSS } from "@dnd-kit/utilities";import { useChannel } from "@/contexts/channel-context";import { cn } from "@/lib/utils";+import { isImeConfirming } from "@/lib/ime";import {ContextMenu,ContextMenuContent,@@ -366,8 +367,9 @@ function CreateInput({value={value}onChange={(e) => setValue(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") handleSubmit();- if (e.key === "Escape") onCancel();+ if (isImeConfirming(e)) return;+ if (e.key === "Enter") { e.preventDefault(); handleSubmit(); }+ else if (e.key === "Escape") onCancel();}}onBlur={() => { if (!savedRef.current) onCancel(); }}disabled={loading}@@ -420,8 +422,9 @@ function RenameInput({value={value}onChange={(e) => setValue(e.target.value)}onKeyDown={(e) => {- if (e.key === "Enter") handleSubmit();- if (e.key === "Escape") onCancel();+ if (isImeConfirming(e)) return;+ if (e.key === "Enter") { e.preventDefault(); handleSubmit(); }+ else if (e.key === "Escape") onCancel();}}onBlur={() => { if (readyRef.current && !savedRef.current) onCancel(); }}disabled={loading}diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 44d9588ac..3202cec8a 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -156,7 +156,7 @@ export type ForumPost = Thread & {// ── Members / friends / DMs ──────────────────────────────────────────────────export type Role = CommunityRole-export { canManageServer } from "@alook/shared"+export { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "@alook/shared"export type Member = {id: stringdiff --git a/src/web/src/components/community/add-members-dialog.tsx b/src/web/src/components/community/add-members-dialog.tsxindex 5ba44eea7..7348746e4 100644--- a/src/web/src/components/community/add-members-dialog.tsx+++ b/src/web/src/components/community/add-members-dialog.tsx@@ -7,6 +7,7 @@ import { Dialog, DialogContent } from "@/components/ui/dialog"import { Input } from "@/components/ui/input"import { Button } from "@/components/ui/button"import { Avatar } from "./avatar"+import { displayName } from "@/lib/community/display-name"export type AddableCandidate = {userId: string@@ -80,7 +81,7 @@ export function AddMembersDialog({filtered.map((m) => (<div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40"><Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} />- <div className="min-w-0 flex-1 truncate text-sm font-medium">{m.name ?? "Unknown"}</div>+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{displayName(m)}</div><Button size="sm" disabled={addPending} onClick={() => add(m.userId)}>Add</Button>diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex 67cede8bf..0f42bb390 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -1,6 +1,7 @@import type React from "react"import { Avatar as UiAvatar, AvatarImage, AvatarFallback, AvatarBadge } from "@/components/ui/avatar"import { AvatarRenderer, parseAvatarUrl, configFromName } from "@/components/avatar"+import { avatarInitial } from "@/lib/community/avatar"import type { Presence } from "./_types"const STATUS_COLOR: Record<Presence, string> = {@@ -56,7 +57,7 @@ export function Avatar({ label, seed, src, size = 40, dim = false, presence, rin<><AvatarImage src={imageUrl} alt={safeLabel} /><AvatarFallback className="font-medium" style={{ fontSize: size * 0.4 }}>- {safeLabel.charAt(0).toUpperCase()}+ {avatarInitial(safeLabel)}</AvatarFallback></>) : avatarConfig ? (@@ -74,7 +75,7 @@ export function Avatar({ label, seed, src, size = 40, dim = false, presence, rin</span>) : (<AvatarFallback className="font-medium" style={{ fontSize: size * 0.4 }}>- {safeLabel.charAt(0).toUpperCase()}+ {avatarInitial(safeLabel)}</AvatarFallback>)}{presence && (diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsxindex b60411e24..8ab14cdcc 100644--- a/src/web/src/components/community/bots/bot-activity-modal.tsx+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx@@ -113,7 +113,7 @@ export function BotActivityModal({<Dialog open={open} onOpenChange={onOpenChange}><DialogContentshowCloseButton={false}- className="flex h-[72vh] max-h-[680px] w-full max-w-2xl flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"+ className="flex h-[72vh] max-h-170 w-full max-w-2xl flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"><header className="flex shrink-0 items-center gap-3 border-b border-border/40 px-4 py-3"><AgentAvatar name={bot?.name ?? ""} avatarUrl={bot?.image ?? null} size={32} />@@ -181,7 +181,7 @@ export function BotActivityModal({function DayDivider({ label }: { label: string }) {return (- <div className="sticky top-0 z-10 border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-[backdrop-filter]:bg-background/80">+ <div className="sticky top-0 z-10 border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-backdrop-filter:bg-background/80"><span className="font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{label}</span>diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsxindex 85b6cdb43..f8e9a74a7 100644--- a/src/web/src/components/community/bots/bot-activity-row.tsx+++ b/src/web/src/components/community/bots/bot-activity-row.tsx@@ -99,7 +99,7 @@ function RowBody({const hiddenChars = truncated ? Math.max(0, chars - countCodepoints(shownText)) : 0return (<div className="flex min-w-0 flex-col gap-1">- <div className="whitespace-pre-wrap break-words font-mono text-[12.5px] leading-relaxed text-muted-foreground">+ <div className="whitespace-pre-wrap wrap-break-word font-mono text-[12.5px] leading-relaxed text-muted-foreground">{shownText}</div>{canExpand && !expanded ? (diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 9f7663aec..40d216a56 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -5,6 +5,8 @@ import { useRouter, useSearchParams } from "next/navigation"import { ChevronLeft, Bot as BotIcon, Monitor, MoreVertical, Plus } from "lucide-react"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"+import { isPresenceOnline } from "@alook/shared"+import { machineName as resolveMachineName } from "@/lib/community/machine-name"import { Button } from "@/components/ui/button"import { Card } from "@/components/ui/card"import {@@ -78,7 +80,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {const machineName = (id: string): string => {const m = machines.find((x) => x.id === id)if (!m) return "Unknown machine"- return m.displayName?.trim() || m.hostname?.trim() || "Unnamed machine"+ return resolveMachineName(m)}// Group bots by their bound machine, ordered to match the Machines page@@ -188,7 +190,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<div className="flex flex-col gap-6">{groups.map(({ machineId, machine, bots: machineBots }) => {- const machineOnline = machine?.status === "online"+ const machineOnline = isPresenceOnline(machine?.status)return (<divkey={machineId}diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsxindex 896a6e64b..915f88da7 100644--- a/src/web/src/components/community/bots/create-bot-sheet.tsx+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx@@ -3,6 +3,8 @@import { useEffect, useMemo, useRef, useState } from "react"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"+import { isPresenceOnline } from "@alook/shared"+import { machineName } from "@/lib/community/machine-name"import {Sheet,SheetBody,@@ -43,15 +45,6 @@ function randomBotName(): string {return uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" })}-function machineLabel(m: {- displayName?: string | null- hostname?: string | null- id: string-}): string {- const name = m.displayName?.trim() || m.hostname?.trim()- return name || "Unnamed machine"-}-export function CreateBotSheet({open,onOpenChange,@@ -196,7 +189,7 @@ export function CreateBotSheet({) : (<div className="flex flex-col gap-2" role="radiogroup" aria-label="Machine">{machines.map((m) => {- const online = m.status === "online"+ const online = isPresenceOnline(m.status)const selected = machineId === m.idreturn (<label@@ -216,7 +209,7 @@ export function CreateBotSheet({onChange={() => selectMachine(m.id)}className="accent-primary size-3.5"/>- <span className="text-sm">{machineLabel(m)}</span>+ <span className="text-sm">{machineName(m)}</span><spanclassName={cn("ml-auto inline-flex items-center gap-1 text-xs",diff --git a/src/web/src/components/community/category-settings-dialog.tsx b/src/web/src/components/community/category-settings-dialog.tsxindex 7d88fd6d6..6f1aa20b8 100644--- a/src/web/src/components/community/category-settings-dialog.tsx+++ b/src/web/src/components/community/category-settings-dialog.tsx@@ -1,11 +1,12 @@"use client"import { useState } from "react"-import { Lock } from "lucide-react"import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"+import { onEnterSubmit } from "@/lib/ime"import { Field } from "./field"+import { PrivateCategoryRow } from "./private-category-row"// Category settings dialog — rename only. Privacy (public/private) is fixed at// creation and can't be changed here: flipping it would silently widen/tighten@@ -35,22 +36,12 @@ export function CategorySettingsDialog({ name, isPrivate, onClose, onSave }: {<Inputvalue={nameDraft}onChange={(e) => setNameDraft(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") save() }}+ onKeyDown={onEnterSubmit(save)}placeholder="e.g. text channels"autoFocus/></Field>- {isPrivate && (- <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">- <Lock className="size-4 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <div className="text-sm font-medium">Private category</div>- <div className="text-xs text-muted-foreground">- Members create their own channels here, visible only to invited members. Privacy can't be changed after creation.- </div>- </div>- </div>- )}+ {isPrivate && <PrivateCategoryRow isPrivate locked />}</div><DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3"><Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsxindex b768166d0..e5970be14 100644--- a/src/web/src/components/community/channel-header.tsx+++ b/src/web/src/components/community/channel-header.tsx@@ -4,7 +4,9 @@ import { useEffect, useState } from "react"import type { LucideIcon } from "lucide-react"import { Bell, BellOff, Pin, Users, MessagesSquare, ChevronLeft, Check, Pencil, MoreHorizontal } from "lucide-react"import { Button } from "@/components/ui/button"+import { avatarInitial } from "@/lib/community/avatar"import { Input } from "@/components/ui/input"+import { onEnterSubmit } from "@/lib/ime"import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"@@ -12,7 +14,7 @@ import { ChannelIcon } from "./channel-icon"import { EntityIcon } from "./entity-icon"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"-import { serverGradient } from "./server-gradient"+import { gradientFromSeed } from "@/lib/community/gradient-from-seed"import type { RightPanel } from "./_types"// Skeleton header for the loading frame between route change and channel@@ -167,12 +169,12 @@ export function ServerCrumb({ id, name, icon, size = 5, className = "" }: { id:// No icon → the same deterministic gradient fallback used by the rail// (`sortable-server.tsx`) and folder rows, so a server reads as "the// same server" everywhere it shows up, not a flat generic tile here.- style={icon ? undefined : { background: serverGradient(id) }}+ style={icon ? undefined : { background: gradientFromSeed(id) }}className={`grid shrink-0 place-items-center overflow-hidden rounded-md font-semibold ${icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]"} ${size === 7 ? "size-7 text-xs" : "size-5 text-[0.625rem]"} ${className}`}aria-label={name}title={name}>- {icon ? <img src={icon} alt="" className="size-full object-cover" /> : name.charAt(0).toUpperCase()}+ {icon ? <img src={icon} alt="" className="size-full object-cover" /> : avatarInitial(name)}</span>)}@@ -245,7 +247,7 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:<Inputvalue={draft}onChange={(e) => setDraft(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") save() }}+ onKeyDown={onEnterSubmit(save)}placeholder="thread-name"className="h-10"autoFocusdiff --git a/src/web/src/components/community/community-invite-card.tsx b/src/web/src/components/community/community-invite-card.tsxindex 5c782464d..5b38279a3 100644--- a/src/web/src/components/community/community-invite-card.tsx+++ b/src/web/src/components/community/community-invite-card.tsx@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation"import { useQuery } from "@tanstack/react-query"import { toast } from "sonner"import { apiFetch } from "@/lib/api/client"+import { avatarInitial } from "@/lib/community/avatar"import { communityKeys } from "@/lib/query-keys"import { useServers } from "@/hooks/community/use-servers"import { useJoinServer } from "@/hooks/community/mutations/servers"@@ -89,7 +90,7 @@ export function CommunityInviteCard({ token }: { token: string }) {/>) : (<div className="grid size-12 shrink-0 place-items-center rounded-lg bg-primary text-lg font-semibold text-primary-foreground">- {data.serverName.charAt(0).toUpperCase()}+ {avatarInitial(data.serverName)}</div>)}<div className="min-w-0 flex-1">diff --git a/src/web/src/components/community/create-category-dialog.tsx b/src/web/src/components/community/create-category-dialog.tsxindex d5d3c1e71..4c68775d2 100644--- a/src/web/src/components/community/create-category-dialog.tsx+++ b/src/web/src/components/community/create-category-dialog.tsx@@ -1,12 +1,12 @@"use client"import { useState } from "react"-import { Lock } from "lucide-react"import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"-import { Switch } from "@/components/ui/switch"+import { onEnterSubmit } from "@/lib/ime"import { Field } from "./field"+import { PrivateCategoryRow } from "./private-category-row"// Create Category dialog — name + private toggle (defaults to public). In a// private category any member can create a channel, but each channel is visible@@ -36,24 +36,13 @@ export function CreateCategoryDialog({ onClose, onCreate, canTogglePrivate = tru<Inputvalue={name}onChange={(e) => setName(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") submit() }}+ onKeyDown={onEnterSubmit(submit)}placeholder="e.g. text channels"autoFocus/></Field>{canTogglePrivate && (- <div className="space-y-2">- <label className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">- <Lock className="size-4 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1 text-sm font-medium">Private category</div>- <Switch checked={isPrivate} onCheckedChange={setIsPrivate} />- </label>- <p className="text-right text-xs text-muted-foreground">- {isPrivate- ? "Members create their own channels here, visible only to invited members."- : "Channels here are admin-managed and visible to everyone."}- </p>- </div>+ <PrivateCategoryRow isPrivate={isPrivate} onToggle={setIsPrivate} />)}</div><DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3">diff --git a/src/web/src/components/community/create-channel-dialog.tsx b/src/web/src/components/community/create-channel-dialog.tsxindex e42d6348c..24b5dff20 100644--- a/src/web/src/components/community/create-channel-dialog.tsx+++ b/src/web/src/components/community/create-channel-dialog.tsx@@ -5,6 +5,7 @@ import { EntityIcon } from "./entity-icon"import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"+import { onEnterSubmit } from "@/lib/ime"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"import type { ChannelType } from "@alook/shared"@@ -76,7 +77,7 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {<Inputvalue={name}onChange={(e) => setName(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") submit() }}+ onKeyDown={onEnterSubmit(submit)}placeholder="new-channel"className="h-10 pl-9"/>diff --git a/src/web/src/components/community/dividers.tsx b/src/web/src/components/community/dividers.tsxindex 9c9cf2a51..c6bf3d284 100644--- a/src/web/src/components/community/dividers.tsx+++ b/src/web/src/components/community/dividers.tsx@@ -10,15 +10,22 @@ export function DateDivider({ label }: { label: string }) {)}-export function NewDivider() {+export function NewDivider({ dateLabel }: { dateLabel?: string }) {// The row's height tracks the separator line only; the "New" pill is taken// out of flow so its taller box doesn't push messages apart.// `data-new-divider` lets `useScrollAnchor`'s mount effect center on this// element itself via `querySelector`, instead of the whole message row// (date divider + full message content) that used to be the only// `[data-msg-id]`-selectable target — see use-scroll-anchor.ts.+ // When the unread boundary lands on the first message of a new day, the+ // date label merges onto the same red line (centered) instead of rendering+ // a separate date-divider row above it.return (- <div data-new-divider className="relative my-1 flex items-center">+ <div data-new-divider className="relative my-1 flex items-center gap-2">+ <Separator className="flex-1 bg-destructive/60" />+ {dateLabel && (+ <span className="text-xs font-semibold text-destructive" suppressHydrationWarning>{dateLabel}</span>+ )}<Separator className="flex-1 bg-destructive/60" /><spanclassName="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold text-white"diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsxindex a4cff5a1f..5ba9c0a3e 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/forum-view.tsx@@ -5,6 +5,7 @@ import { MessagesSquare, ListChevronsUpDown, Plus, Tags, X, Check } from "lucideimport { Button } from "@/components/ui/button"import { formatRelativeTime } from "./format-time"import { Badge } from "@/components/ui/badge"+import { onEnterSubmit } from "@/lib/ime"import { Input } from "@/components/ui/input"import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"@@ -90,7 +91,7 @@ export function ForumView({<Inputvalue={newTag}onChange={(e) => setNewTag(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") addTag() }}+ onKeyDown={onEnterSubmit(addTag)}placeholder="new-tag"className="h-6 w-28 px-2 text-xs"/>diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsxindex a5b76c798..3d4c1dc0e 100644--- a/src/web/src/components/community/friends-page.tsx+++ b/src/web/src/components/community/friends-page.tsx@@ -4,16 +4,18 @@ import { useState, useEffect, useMemo, useRef } from "react"import type React from "react"import { Users, MessagesSquare, ChevronLeft, Check, X, AtSign, UserMinus, Ban, UserPlus, Search } from "lucide-react"import { apiFetch, toastApiError } from "@/lib/api/client"+import { isImeConfirming } from "@/lib/ime"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"+import { avatarInitial } from "@/lib/community/avatar"import { EmptyState } from "./empty-state"import { hasStatus } from "./status-presets"import type { Friend, PendingRequest, BlockedUser, OpenProfile } from "./_types"-import { isSelfBotFriendship } from "@alook/shared"+import { isSelfBotFriendship, isPresenceOffline } from "@alook/shared"function FriendSection({ title, count, emptyLabel, children }: {title: string@@ -101,9 +103,9 @@ export function FriendsPage({/>}>- <Avatar label={f.avatar} seed={f.userId} size={32} presence={f.status} dim={f.status === "offline"} />+ <Avatar label={f.avatar} seed={f.userId} size={32} presence={f.status} dim={isPresenceOffline(f.status)} /><div className="min-w-0 flex-1">- <div className={`truncate text-sm font-medium ${f.status === "offline" ? "text-muted-foreground" : ""}`}>+ <div className={`truncate text-sm font-medium ${isPresenceOffline(f.status) ? "text-muted-foreground" : ""}`}>{f.name}{f.discriminator && (<span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">@@ -202,7 +204,7 @@ export function FriendsPage({placeholder="Search by username"value={addValue}onChange={(e) => setAddValue(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter" && addValue.trim()) sendRequest(addValue.trim()) }}+ onKeyDown={(e) => { if (isImeConfirming(e)) return; if (e.key === "Enter" && addValue.trim()) sendRequest(addValue.trim()) }}/></div><Button@@ -223,7 +225,7 @@ export function FriendsPage({onClick={() => sendRequest(u.name)}className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent">- <Avatar label={u.image ?? u.name.charAt(0).toUpperCase()} seed={u.id} size={28} />+ <Avatar label={u.image ?? avatarInitial(u.name)} seed={u.id} size={28} /><span className="flex-1 min-w-0 truncate text-sm font-medium">{u.name}<span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsxindex f1f1cc859..8833d8840 100644--- a/src/web/src/components/community/machines/machine-card.tsx+++ b/src/web/src/components/community/machines/machine-card.tsx@@ -3,6 +3,7 @@import { useMemo } from "react"import { Monitor, MoreVertical } from "lucide-react"import type { CommunityMachineSummary } from "@alook/shared"+import { isPresenceOnline } from "@alook/shared"import { Card } from "@/components/ui/card"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import {@@ -12,6 +13,7 @@ import {DropdownMenuItem,} from "@/components/ui/dropdown-menu"import { timeAgo } from "@/lib/time"+import { machineName } from "@/lib/community/machine-name"import { MachineRuntimes } from "./machine-runtimes"export function MachineCard({@@ -23,7 +25,7 @@ export function MachineCard({onDelete: () => voidonReconnect: () => void}) {- const isOnline = machine.status === "online"+ const isOnline = isPresenceOnline(machine.status)const lastSeenLabel = useMemo(() => (machine.lastSeenAt ? `Last seen · ${timeAgo(machine.lastSeenAt)}` : "Never seen"),[machine.lastSeenAt]@@ -38,7 +40,7 @@ export function MachineCard({<div className="flex flex-col gap-1"><div className="flex items-center gap-2"><span className="text-[15px] font-medium text-foreground">- {machine.hostname || "Unnamed machine"}+ {machineName(machine)}</span><spanclassName={[diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex dbe7b9b09..f48045602 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -6,6 +6,7 @@ import { toast } from "sonner"import { ChevronLeft, Monitor } from "lucide-react"import { useQueryClient } from "@tanstack/react-query"import type { CommunityMachineSummary } from "@alook/shared"+import { isPresenceOnline } from "@alook/shared"import { Button } from "@/components/ui/button"import {AlertDialog,@@ -44,7 +45,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {const justConnected = machines.find((m) =>m.lastSeenAt &&- m.status === "online" &&+ isPresenceOnline(m.status) &&pendingMachineTokenId === pendingTokenId)if (justConnected && !connectedHostname) {diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsxindex 2eabe974d..3488933db 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/member-list.tsx@@ -13,7 +13,7 @@ import { Avatar } from "./avatar"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { hasStatus } from "./status-presets"import type { Member, Role, OpenProfile, MemberManageContext } from "./_types"-import { canManageServer } from "./_types"+import { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "./_types"const SETTABLE_ROLES: Role[] = ["admin", "member"]@@ -32,11 +32,11 @@ function capitalize(s: string): string {}function groupMembers(members: Member[]): { label: string; list: Member[] }[] {- const owner = members.filter((m) => m.role === "owner")- const admin = members.filter((m) => m.role === "admin")- const rest = members.filter((m) => m.role === "member")- const online = rest.filter((m) => m.status === "online")- const offline = rest.filter((m) => m.status === "offline")+ const owner = members.filter((m) => isServerOwner(m.role))+ const admin = members.filter((m) => m.role === ROLES.ADMIN)+ const rest = members.filter((m) => m.role === ROLES.MEMBER)+ const online = rest.filter((m) => isPresenceOnline(m.status))+ const offline = rest.filter((m) => isPresenceOffline(m.status))return [{ label: "Owner", list: owner },{ label: "Admin", list: admin },@@ -284,9 +284,9 @@ function MemberRow({onClick={(e) => onOpenProfile?.(mem.name, e, undefined, mem.userId)}className="flex w-full items-center gap-3 rounded-md px-2 py-2 select-none hover:bg-accent">- <Avatar label={mem.avatar} seed={mem.userId} size={32} presence={mem.status} dim={mem.status === "offline"} />+ <Avatar label={mem.avatar} seed={mem.userId} size={32} presence={mem.status} dim={isPresenceOffline(mem.status)} /><div className="min-w-0 flex-1 space-y-0.5 text-left">- <div className={`truncate text-sm leading-tight ${mem.status === "offline" ? "text-muted-foreground" : ""}`}>+ <div className={`truncate text-sm leading-tight ${isPresenceOffline(mem.status) ? "text-muted-foreground" : ""}`}>{mem.name}{showDiscriminator && mem.discriminator && (<span className="text-muted-foreground">#{mem.discriminator}</span>diff --git a/src/web/src/components/community/message-list-items.test.ts b/src/web/src/components/community/message-list-items.test.tsindex c940875c8..fbcbc5541 100644--- a/src/web/src/components/community/message-list-items.test.ts+++ b/src/web/src/components/community/message-list-items.test.ts@@ -51,6 +51,48 @@ describe("flattenMessageItems", () => {expect(items.map((i) => i.kind)).toEqual(["date-divider", "message", "new-divider", "message"])})+ it("emits a same-day new-divider with no dateLabel (no merge)", () => {+ const items = flattenMessageItems(+ [+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),+ ],+ "m2",+ )+ const newDivider = items.find((i) => i.kind === "new-divider")!+ expect(newDivider.dateLabel).toBeUndefined()+ })++ it("merges into ONE new-divider carrying a dateLabel when the unread anchor is the first message of a new day", () => {+ const items = flattenMessageItems(+ [+ msg({ id: "m1", createdAt: "2026-01-01T12:00:00.000Z" }),+ msg({ id: "m2", createdAt: "2026-01-02T12:00:00.000Z" }),+ ],+ "m2",+ )+ // No separate date-divider precedes the merged row — just message, then+ // the single new-divider carrying the day's label, then the message.+ expect(items.map((i) => i.kind)).toEqual(["date-divider", "message", "new-divider", "message"])+ const dividers = items.filter((i) => i.kind === "date-divider")+ expect(dividers).toHaveLength(1)+ const newDivider = items.find((i) => i.kind === "new-divider")!+ expect(typeof newDivider.dateLabel).toBe("string")+ expect(newDivider.dateLabel!.length).toBeGreaterThan(0)+ })++ it("emits a plain date-divider (no new-divider) when there is no unread anchor", () => {+ const items = flattenMessageItems(+ [+ msg({ id: "m1", createdAt: "2026-01-01T12:00:00.000Z" }),+ msg({ id: "m2", createdAt: "2026-01-02T12:00:00.000Z" }),+ ],+ undefined,+ )+ expect(items.some((i) => i.kind === "new-divider")).toBe(false)+ expect(items.filter((i) => i.kind === "date-divider")).toHaveLength(2)+ })+it("marks a message 'grouped' when it's a same-author chat reply within the grouping window on the same day", () => {const items = flattenMessageItems([@@ -163,6 +205,26 @@ describe("estimateRowHeight", () => {expect(estimateRowHeight(newDivider)).toBeLessThan(estimateRowHeight(message))})+ it("estimates a merged new-divider (with dateLabel) taller than a bare one, matching the date-divider height", () => {+ const merged = flattenMessageItems(+ [+ msg({ id: "m1", createdAt: "2026-01-01T12:00:00.000Z" }),+ msg({ id: "m2", createdAt: "2026-01-02T12:00:00.000Z" }),+ ],+ "m2",+ ).find((i) => i.kind === "new-divider")!+ const bare = flattenMessageItems(+ [+ msg({ id: "m1", createdAt: "2026-01-01T10:00:00.000Z" }),+ msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),+ ],+ "m2",+ ).find((i) => i.kind === "new-divider")!+ const dateDivider = flattenMessageItems([msg({ id: "m1" })], undefined).find((i) => i.kind === "date-divider")!+ expect(estimateRowHeight(merged)).toBeGreaterThan(estimateRowHeight(bare))+ expect(estimateRowHeight(merged)).toBe(estimateRowHeight(dateDivider))+ })+it("scales up with longer text content", () => {const items = flattenMessageItems([diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.tsindex b5fbed47b..882fdc8e2 100644--- a/src/web/src/components/community/message-list-items.ts+++ b/src/web/src/components/community/message-list-items.ts@@ -20,7 +20,7 @@ const MESSAGE_GROUP_WINDOW_MS = 7 * 60 * 1000// used — just not re-nested into a cluster array afterward.export type FlatItem =| { kind: "date-divider"; label: string; key: string }- | { kind: "new-divider"; key: string }+ | { kind: "new-divider"; key: string; dateLabel?: string }| { kind: "message"; m: RenderMsg; key: string }// Flatten a message array into one row per divider/message. Exported for@@ -34,11 +34,16 @@ export function flattenMessageItems(messages: Msg[], newDividerBefore: string |const prevDate = prev ? dateKey(prev.createdAt) : ""const curDate = dateKey(m.createdAt)const showDateDivider = !!(curDate && curDate !== prevDate)- if (showDateDivider) {- items.push({ kind: "date-divider", label: formatDateLabel(m.createdAt!), key: `date:${m.id}` })- }- if (m.id === newDividerBefore) {- items.push({ kind: "new-divider", key: "new-divider" })+ const isNewDivider = m.id === newDividerBefore+ if (showDateDivider && isNewDivider) {+ items.push({ kind: "new-divider", key: "new-divider", dateLabel: formatDateLabel(m.createdAt!) })+ } else {+ if (showDateDivider) {+ items.push({ kind: "date-divider", label: formatDateLabel(m.createdAt!), key: `date:${m.id}` })+ }+ if (isNewDivider) {+ items.push({ kind: "new-divider", key: "new-divider" })+ }}const grouped = !!(prev && m.type === "chat" && !m.replyTo && !showDateDivider && prev.authorName === m.authorName&& prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < MESSAGE_GROUP_WINDOW_MS)@@ -90,7 +95,7 @@ function estimateAttachmentsHeight(m: Msg): number {// Exported for direct unit testing (see message-list.test.ts).export function estimateRowHeight(item: FlatItem): number {if (item.kind === "date-divider") return DATE_DIVIDER_ESTIMATE_PX- if (item.kind === "new-divider") return NEW_DIVIDER_ESTIMATE_PX+ if (item.kind === "new-divider") return item.dateLabel ? DATE_DIVIDER_ESTIMATE_PX : NEW_DIVIDER_ESTIMATE_PXconst m = item.mlet height = MESSAGE_BASE_ESTIMATE_PX + estimateTextHeight(m.content) + estimateAttachmentsHeight(m)if (m.embeds?.length) height += EMBED_ESTIMATE_PX * m.embeds.lengthdiff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex 5b6839a30..a511df27c 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -360,7 +360,7 @@ export function MessageList({}}>{item.kind === "date-divider" && <DateDivider label={item.label} />}- {item.kind === "new-divider" && <NewDivider />}+ {item.kind === "new-divider" && <NewDivider dateLabel={item.dateLabel} />}{item.kind === "message" && (// `data-msg-id` anchors the IntersectionObserver in// `useChannelWatermark` — every currently-rendereddiff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex 96433bcd9..0b992c48e 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -15,6 +15,8 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltipimport { NumberTicker } from "@/components/ui/number-ticker"import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"import { formatMessageTime } from "./format-time"+import { avatarInitial } from "@/lib/community/avatar"+import { displayName } from "@/lib/community/display-name"import type { RenderMsg, OpenProfile } from "./_types"// Fallback ratio for an attachment image with no known dimensions@@ -195,7 +197,7 @@ export function Message({{embed.author.iconUrl ? (<img src={embed.author.iconUrl} alt="" className="size-5 rounded-full" />) : (- <span className="grid size-5 place-items-center rounded-full bg-muted text-[9px] font-semibold text-muted-foreground">{embed.author.name.charAt(0)}</span>+ <span className="grid size-5 place-items-center rounded-full bg-muted text-[9px] font-semibold text-muted-foreground">{avatarInitial(embed.author.name)}</span>)}{embed.author.url ? (<a href={embed.author.url} target="_blank" rel="noopener noreferrer" className="text-xs font-medium hover:underline">{embed.author.name}</a>@@ -247,7 +249,7 @@ export function Message({<div className="mt-2 flex flex-wrap gap-1">{m.reactions.map((r, i) => {const names = r.userIds?.length- ? r.userIds.map((id) => resolveUserName?.(id) ?? id).join(", ")+ ? r.userIds.map((id) => resolveUserName?.(id) ?? displayName(null)).join(", "): undefinedconst chip = (<buttondiff --git a/src/web/src/components/community/private-category-row.test.ts b/src/web/src/components/community/private-category-row.test.tsnew file mode 100644index 000000000..ed2f6f9e5--- /dev/null+++ b/src/web/src/components/community/private-category-row.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect, vi } from "vitest"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import { PrivateCategoryRow } from "./private-category-row"+import {+ PRIVATE_CATEGORY_LABEL,+ PRIVATE_CATEGORY_DESC_PRIVATE,+ PRIVATE_CATEGORY_DESC_PUBLIC,+ PRIVATE_CATEGORY_LOCKED_SUFFIX,+} from "@/lib/community/category-copy"++const render = (props: Parameters<typeof PrivateCategoryRow>[0]) =>+ renderToStaticMarkup(createElement(PrivateCategoryRow, props))++describe("PrivateCategoryRow", () => {+ it("always renders the shared label", () => {+ expect(render({ isPrivate: false })).toContain(PRIVATE_CATEGORY_LABEL)+ })++ it("shows the public copy when not private", () => {+ const html = render({ isPrivate: false, onToggle: vi.fn() })+ expect(html).toContain(PRIVATE_CATEGORY_DESC_PUBLIC)+ expect(html).not.toContain(PRIVATE_CATEGORY_DESC_PRIVATE)+ })++ it("shows the private copy when private", () => {+ const html = render({ isPrivate: true, onToggle: vi.fn() })+ expect(html).toContain(PRIVATE_CATEGORY_DESC_PRIVATE)+ expect(html).not.toContain(PRIVATE_CATEGORY_DESC_PUBLIC)+ })++ it("renders a Switch when onToggle is provided", () => {+ expect(render({ isPrivate: false, onToggle: vi.fn() })).toContain('data-slot="switch"')+ })++ it("hides the Switch and appends the locked suffix in read-only mode", () => {+ const html = render({ isPrivate: true, locked: true })+ expect(html).not.toContain('data-slot="switch"')+ expect(html).toContain(PRIVATE_CATEGORY_DESC_PRIVATE)+ expect(html).toContain(PRIVATE_CATEGORY_LOCKED_SUFFIX)+ })++ it("draws its copy from the shared constants (same private string both dialogs use)", () => {+ expect(PRIVATE_CATEGORY_DESC_PRIVATE).toBe(+ "Members create their own channels here, visible only to invited members.",+ )+ expect(PRIVATE_CATEGORY_DESC_PUBLIC).toBe(+ "Channels here are admin-managed and visible to everyone.",+ )+ })+})diff --git a/src/web/src/components/community/private-category-row.tsx b/src/web/src/components/community/private-category-row.tsxnew file mode 100644index 000000000..c6d4509b7--- /dev/null+++ b/src/web/src/components/community/private-category-row.tsx@@ -0,0 +1,32 @@+"use client"++import { Lock } from "lucide-react"+import { Switch } from "@/components/ui/switch"+import {+ PRIVATE_CATEGORY_LABEL,+ PRIVATE_CATEGORY_DESC_PRIVATE,+ PRIVATE_CATEGORY_DESC_PUBLIC,+ PRIVATE_CATEGORY_LOCKED_SUFFIX,+} from "@/lib/community/category-copy"++export function PrivateCategoryRow({ isPrivate, onToggle, locked }: {+ isPrivate: boolean+ onToggle?: (v: boolean) => void+ locked?: boolean+}) {+ const description = isPrivate+ ? locked+ ? `${PRIVATE_CATEGORY_DESC_PRIVATE} ${PRIVATE_CATEGORY_LOCKED_SUFFIX}`+ : PRIVATE_CATEGORY_DESC_PRIVATE+ : PRIVATE_CATEGORY_DESC_PUBLIC+ return (+ <div className="flex items-start gap-3 rounded-md border border-border bg-card px-3 py-2">+ <Lock className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium">{PRIVATE_CATEGORY_LABEL}</div>+ <div className="text-xs text-muted-foreground">{description}</div>+ </div>+ {onToggle && <Switch checked={isPrivate} onCheckedChange={onToggle} className="mt-0.5" />}+ </div>+ )+}diff --git a/src/web/src/components/community/profile-card.test.ts b/src/web/src/components/community/profile-card.test.tsindex be85b1fb3..7495b0baf 100644--- a/src/web/src/components/community/profile-card.test.ts+++ b/src/web/src/components/community/profile-card.test.ts@@ -1,47 +1,5 @@import { describe, it, expect } from "vitest"-import { generateGradient, resolveCardStatus } 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)- })-- it("is deterministic for the same userId seed", () => {- expect(generateGradient("usr_abc123")).toBe(generateGradient("usr_abc123"))- })-- it("varies across different userIds", () => {- expect(generateGradient("usr_abc123")).not.toBe(generateGradient("usr_xyz789"))- })-- it("keeps the same gradient when the display name changes but the userId seed is stable", () => {- // The card computes `generateGradient(data.userId ?? data.name)` — two- // renders of the same person (renamed in between) both seed on userId, so- // the banner colour must not shift.- const before = generateGradient("usr_stable")- const after = generateGradient("usr_stable")- expect(after).toBe(before)- })-})+import { resolveCardStatus } from "./profile-card"describe("resolveCardStatus — WS overlay wins over row seed", () => {it("uses the overlay entry when one exists", () => {diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsxindex 06d7cd560..19dcddcdc 100644--- a/src/web/src/components/community/profile-card.tsx+++ b/src/web/src/components/community/profile-card.tsx@@ -9,6 +9,7 @@ import { StatusEditor, hasStatus } from "./status-editor"import type { Profile } from "./_types"import type { Breakpoint } from "@/hooks/use-mobile"import { useCommunityWsStore } from "@/stores/community/ws"+import { gradientFromSeed } from "@/lib/community/gradient-from-seed"// Merge rule for the card's status pill: overlay wins over seed. The overlay// (`useCommunityWsStore.userStatuses`) is the same live source the member@@ -28,21 +29,6 @@ export function resolveCardStatus(return { emoji: seedEmoji ?? null, text: seedText ?? null }}-// Deterministic, on-brand banner gradient. The seed is the owner's stable-// userId (falling back to name only when the id isn't yet resolved), so-// renaming never shifts the banner colour. 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.-export function generateGradient(seed: string): string {- let hash = 0- for (let i = 0; i < seed.length; i++) {- hash = seed.charCodeAt(i) + ((hash << 5) - hash)- }- const hue1 = 60 + (Math.abs(hash) % 21)- const hue2 = 60 + (Math.abs(hash * 7) % 21)- return `linear-gradient(135deg, oklch(0.78 0.06 ${hue1}), oklch(0.68 0.05 ${hue2}))`-}-// Profile card — popover anchored at the click point on desktop, bottom sheet on mobile.// Status (emoji + text) is read live from `useCommunityWsStore.userStatuses` —// the same overlay the member list, friends list, and UserBar consume. The@@ -77,7 +63,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaif (mobile) onClose()else close()}- const gradient = generateGradient(data.userId ?? data.name)+ const gradient = gradientFromSeed(data.userId ?? data.name)const card = (<>{/* banner */}diff --git a/src/web/src/components/community/rail-folder.tsx b/src/web/src/components/community/rail-folder.tsxindex 9a0a2fad4..549fa98fe 100644--- a/src/web/src/components/community/rail-folder.tsx+++ b/src/web/src/components/community/rail-folder.tsx@@ -5,7 +5,7 @@ import { CSS } from "@dnd-kit/utilities"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"import { RailIndicator } from "./rail-indicator"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"-import { serverGradient } from "./server-gradient"+import { gradientFromSeed } from "@/lib/community/gradient-from-seed"import type { FolderServer } from "./_types"export function RailFolder({@@ -48,7 +48,7 @@ export function RailFolder({return s ? (<spankey={s.id}- style={s.icon ? undefined : { background: serverGradient(s.id) }}+ style={s.icon ? undefined : { background: gradientFromSeed(s.id) }}className={["grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsxindex 23f06d2dd..c354bf8ea 100644--- a/src/web/src/components/community/right-panel.tsx+++ b/src/web/src/components/community/right-panel.tsx@@ -3,6 +3,8 @@import { useState } from "react"import { Users, Pin, Search, MessagesSquare } from "lucide-react"import { Input } from "@/components/ui/input"+import { onEnterSubmit } from "@/lib/ime"+import { avatarInitial } from "@/lib/community/avatar"import { Skeleton } from "@/components/ui/skeleton"import { PanelShell } from "./panel-shell"import { MemberList } from "./member-list"@@ -78,7 +80,7 @@ export function RightPanelContent({className="flex w-full gap-2 rounded-md px-2 py-2 text-left hover:bg-accent"><div className="size-6 shrink-0 rounded-full bg-muted grid place-items-center text-xs font-medium">- {m.authorAvatar ?? m.authorName?.charAt(0) ?? "?"}+ {m.authorAvatar ?? avatarInitial(m.authorName ?? "")}</div><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2">@@ -178,7 +180,7 @@ function SearchPanel({ searchResults, initialQuery, showSearchInput, onOpenProfiplaceholder="Search messages"value={query}onChange={(e) => setQuery(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") submit() }}+ onKeyDown={onEnterSubmit(submit)}/></div>)}diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsxindex 289a24a85..999a183ff 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/server-rail.tsx@@ -14,7 +14,7 @@ import { SortableServer } from "./sortable-server"import { RailFolder } from "./rail-folder"import { CreateServerDialog } from "./create-server-dialog"import { useRailOrder, isFolderKey, extractFolderId } from "./use-rail-order"-import { serverGradient } from "./server-gradient"+import { gradientFromSeed } from "@/lib/community/gradient-from-seed"import type { Server, CommunityFolder, MobileZone, View } from "./_types"export const ServerRail = memo(function ServerRail({@@ -220,7 +220,7 @@ export const ServerRail = memo(function ServerRail({return s ? (<spankey={s.id}- style={s.icon ? undefined : { background: serverGradient(s.id) }}+ style={s.icon ? undefined : { background: gradientFromSeed(s.id) }}className={["grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",@@ -240,7 +240,7 @@ export const ServerRail = memo(function ServerRail({const icon = s.iconreturn (<div- style={icon ? undefined : { background: serverGradient(s.id) }}+ style={icon ? undefined : { background: gradientFromSeed(s.id) }}className={["grid size-10 place-items-center overflow-hidden rounded-xl text-sm font-semibold shadow-(--e2)",icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]",diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsxindex aa7981dd9..358d6f09a 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/server-settings.tsx@@ -14,10 +14,12 @@ import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"+import { avatarInitial } from "@/lib/community/avatar"import { Field } from "./field"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"import type { SettingsSection, Member, Role, InviteRow, AuditEntry, OpenProfile } from "./_types"+import { isServerOwner } from "./_types"const SETTABLE_ROLES: Role[] = ["admin", "member"]@@ -150,7 +152,7 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadI{serverIcon ? (<img src={serverIcon} alt="Server icon" className="size-20 rounded-2xl object-cover" />) : (- <div className="grid size-20 place-items-center rounded-2xl bg-primary text-2xl font-semibold text-primary-foreground">{name.charAt(0)}</div>+ <div className="grid size-20 place-items-center rounded-2xl bg-primary text-2xl font-semibold text-primary-foreground">{avatarInitial(name)}</div>)}<div><div className="text-sm font-medium">Server icon</div>@@ -284,7 +286,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad<div className="truncate text-[15px] font-medium">{m.name}</div><div className="text-xs text-muted-foreground">{capitalize(m.role)}</div></div>- {m.role === "owner" ? (+ {isServerOwner(m.role) ? (<Badge variant="secondary" className="gap-1"><Shield className="size-3.5" /> Owner</Badge>) : (<DropdownMenu>diff --git a/src/web/src/components/community/shell-frame.test.ts b/src/web/src/components/community/shell-frame.test.tsdeleted file mode 100644index b95cf9958..000000000--- a/src/web/src/components/community/shell-frame.test.ts+++ /dev/null@@ -1,21 +0,0 @@-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 b1e43a7de..d12a287ec 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -22,8 +22,10 @@ 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, Presence, Profile, View } from "./_types"+import type { MobileZone, Profile, View } from "./_types"import { resolveProfileTarget } from "./profile-lookup"+import { resolveProfilePresence } from "@/lib/community/presence"+import { avatarInitial } from "@/lib/community/avatar"import { signOut } from "@/lib/auth-client"import { clearPersistedCache } from "@/lib/query-persister"import { useCommunityStore } from "@/stores/community"@@ -52,27 +54,6 @@ 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@@ -333,7 +314,7 @@ export function ShellFrame({name: currentUser.name,userId: currentUser.id,discriminator: currentUser.discriminator,- avatar: currentUser.avatar || currentUser.name.charAt(0).toUpperCase(),+ avatar: currentUser.avatar || avatarInitial(currentUser.name),role: "You",about: currentUser.aboutMe ?? "",mutual: 0,@@ -360,7 +341,7 @@ export function ShellFrame({name,userId,// discriminator is undefined until the /profile fetch below hydrates it.- avatar: member?.avatar ?? name.charAt(0).toUpperCase(),+ avatar: member?.avatar ?? avatarInitial(name),role: displayRole,about,mutual: 0,diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsxindex 3efece996..6e544a06f 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/sortable-server.tsx@@ -8,7 +8,7 @@ import { RailIndicator } from "./rail-indicator"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { NumberTicker } from "@/components/ui/number-ticker"-import { serverGradient } from "./server-gradient"+import { gradientFromSeed } from "@/lib/community/gradient-from-seed"import type { Server } from "./_types"export function SortableServer({ server, active, onClick, onLeave, onOpenSettings, onOpenInvitePopover, onCreateFolder, groupTarget, inFolder, dragging: isDragActive }: { server: Server; active?: boolean; onClick: () => void; onLeave?: () => void; onOpenSettings?: () => void; onOpenInvitePopover?: () => void; onCreateFolder?: () => void; groupTarget?: boolean; inFolder?: boolean; dragging?: boolean }) {@@ -33,7 +33,7 @@ export function SortableServer({ server, active, onClick, onLeave, onOpenSettingonClick={active ? undefined : onClick}{...attributes}{...listeners}- style={server.icon ? undefined : { background: serverGradient(server.id) }}+ style={server.icon ? undefined : { background: gradientFromSeed(server.id) }}className={["grid size-10 touch-none place-items-center overflow-hidden text-sm font-semibold transition-all duration-150 active:cursor-grabbing",active ? "cursor-default rounded-xl" : "cursor-pointer rounded-[18px] hover:rounded-xl",diff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/user-bar.tsxindex 2f9c16582..16fc5714b 100644--- a/src/web/src/components/community/user-bar.tsx+++ b/src/web/src/components/community/user-bar.tsx@@ -5,6 +5,11 @@ import { Inbox, Settings } from "lucide-react"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Avatar } from "./avatar"import type { OpenProfile } from "./_types"+import { resolveProfilePresence } from "@/lib/community/presence"++// UserBar always renders the signed-in viewer, so presence resolves through+// the self → online branch and never consults an online set.+const EMPTY_ONLINE_SET: ReadonlySet<string> = new Set()export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {user: { id: string; name: string; avatar: string }@@ -32,7 +37,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} seed={user.id} size={28} presence="online" ringColor="var(--muted)" />+ <Avatar label={user.avatar} seed={user.id} size={28} presence={resolveProfilePresence(true, user.id, EMPTY_ONLINE_SET)} 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/components/email-toolbar.tsx b/src/web/src/components/email-toolbar.tsxindex 25e06bfee..cf9219119 100644--- a/src/web/src/components/email-toolbar.tsx+++ b/src/web/src/components/email-toolbar.tsx@@ -3,6 +3,7 @@import { useState, useRef, useEffect, useReducer } from "react";import type { Editor } from "@tiptap/react";import { cn } from "@/lib/utils";+import { onEnterSubmit } from "@/lib/ime";import { Button } from "@/components/ui/button";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import {@@ -298,9 +299,7 @@ export function EmailToolbar({ editor }: EmailToolbarProps) {ref={inputRef}value={displayText}onChange={(e) => setDisplayText(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") handleDialogSubmit();- }}+ onKeyDown={onEnterSubmit(handleDialogSubmit)}placeholder="Display text"/>)}@@ -309,9 +308,7 @@ export function EmailToolbar({ editor }: EmailToolbarProps) {ref={dialogMode === "image" || !selectionEmpty ? inputRef : undefined}value={urlValue}onChange={(e) => { setUrlValue(e.target.value); setUrlError(""); }}- onKeyDown={(e) => {- if (e.key === "Enter") handleDialogSubmit();- }}+ onKeyDown={onEnterSubmit(handleDialogSubmit)}placeholder={dialogMode === "link" ? "https://example.com" : "https://example.com/image.png"}type="url"aria-invalid={Boolean(urlError)}diff --git a/src/web/src/components/nav-user.tsx b/src/web/src/components/nav-user.tsxindex 187ed0cd4..34f6cc7c8 100644--- a/src/web/src/components/nav-user.tsx+++ b/src/web/src/components/nav-user.tsx@@ -18,6 +18,8 @@ import {} from "@/components/ui/dropdown-menu";import { Skeleton } from "@/components/ui/skeleton";import { LogOut, User } from "lucide-react";+import { displayName } from "@/lib/community/display-name";+import { avatarInitial } from "@/lib/community/avatar";export function NavUser() {const { data: session, isPending } = useSession();@@ -32,7 +34,7 @@ export function NavUser() {if (!mounted || isPending || !user)return <Skeleton className="size-10 rounded-xl" />;- const firstLetter = (user.name || "?").charAt(0).toUpperCase();+ const firstLetter = avatarInitial(displayName(user));return (<DropdownMenu>@@ -61,7 +63,7 @@ export function NavUser() {</div><div className="grid flex-1 text-left text-sm leading-tight"><span className="truncate font-medium">- {user.name}+ {displayName(user)}</span><span className="truncate text-xs text-muted-foreground">{user.email}diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsxindex efa4e5a71..a24fafa8b 100644--- a/src/web/src/components/ui/markdown-editor.tsx+++ b/src/web/src/components/ui/markdown-editor.tsx@@ -7,6 +7,7 @@ import Placeholder from "@tiptap/extension-placeholder";import Mention from "@tiptap/extension-mention";import { Markdown } from "@tiptap/markdown";import { cn } from "@/lib/utils";+import { isImeConfirming } from "@/lib/ime";import { isEmptyHtml, toAlookAddress } from "@alook/shared";import type { Agent } from "@alook/shared";import { createPortal } from "react-dom";@@ -149,6 +150,7 @@ function useMentionSuggestion(agents: Agent[] | undefined) {return true;}if (event.key === "Enter") {+ if (isImeConfirming(event)) return false;event.preventDefault();const agent = cur.items[cur.selectedIndex];if (agent && cur.command) cur.command({ id: agent.id, label: agent.name });diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex db9de9db5..ea30486ec 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -17,7 +17,7 @@ import type { ChannelType } from "@alook/shared"export type CreateChannelArgs = {serverId: string- categoryId: string+ categoryId: string | nullname: stringtype: ChannelType}diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 58a344c93..391fa2cfa 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -14,6 +14,7 @@ import type { Msg, Attachment } from "@/components/community/_types"import type { MessagesPage } from "@/hooks/community/use-messages"import type { PinsResponse } from "@/hooks/community/use-channel-panels"import type { MentionType } from "@alook/shared"+import { isBlocked } from "@alook/shared"/*** Message-scoped mutation hooks — the split of the God-context's@@ -301,7 +302,7 @@ export function useSendDmMessage() {// scrub the optimistic row and show a scoped toast rather than leaving a// `failed: true` bubble in place. Mirrors the old context's `onBlocked`// branch at contexts/community/context.tsx:1021-1027.- if (err instanceof ApiError && err.status === 403 && err.message === "blocked") {+ if (err instanceof ApiError && err.status === 403 && isBlocked(err.message)) {queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>removeById(c, ctx.tempId),)diff --git a/src/web/src/lib/agent-visibility.ts b/src/web/src/lib/agent-visibility.tsindex 0ca4c037e..977c6bccc 100644--- a/src/web/src/lib/agent-visibility.ts+++ b/src/web/src/lib/agent-visibility.ts@@ -1,3 +1,5 @@+import { isPublic } from "@alook/shared";+interface AgentRow {id: string;visibility: string;@@ -18,6 +20,6 @@ export function filterVisibleAgents<T extends AgentRow>(agentAccessList.filter((a) => a.userId === userId).map((a) => a.agentId),);return allAgents.filter(- (a) => a.visibility === "public" || a.ownerId === userId || accessSet.has(a.id),+ (a) => isPublic(a.visibility) || a.ownerId === userId || accessSet.has(a.id),);}diff --git a/src/web/src/lib/community/category-copy.ts b/src/web/src/lib/community/category-copy.tsnew file mode 100644index 000000000..d8ab99a98--- /dev/null+++ b/src/web/src/lib/community/category-copy.ts@@ -0,0 +1,10 @@+export const PRIVATE_CATEGORY_LABEL = "Private category"++export const PRIVATE_CATEGORY_DESC_PRIVATE =+ "Members create their own channels here, visible only to invited members."++export const PRIVATE_CATEGORY_DESC_PUBLIC =+ "Channels here are admin-managed and visible to everyone."++export const PRIVATE_CATEGORY_LOCKED_SUFFIX =+ "Privacy can’t be changed after creation."diff --git a/src/web/src/lib/community/display-name.test.ts b/src/web/src/lib/community/display-name.test.tsnew file mode 100644index 000000000..c044876be--- /dev/null+++ b/src/web/src/lib/community/display-name.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect } from "vitest"+import { displayName, emailPrefix, makeUserNameResolver } from "./display-name"++describe("emailPrefix", () => {+ it("returns the part before @", () => {+ expect(emailPrefix("[email protected]")).toBe("alice")+ })++ it("trims surrounding whitespace", () => {+ expect(emailPrefix(" [email protected] ")).toBe("bob")+ })++ it("returns empty string for null/undefined", () => {+ expect(emailPrefix(null)).toBe("")+ expect(emailPrefix(undefined)).toBe("")+ })+})++describe("displayName", () => {+ it("returns the trimmed name when present", () => {+ expect(displayName({ name: "Alice" })).toBe("Alice")+ expect(displayName({ name: " Alice " })).toBe("Alice")+ })++ it("falls back to the email prefix when name is empty", () => {+ expect(displayName({ name: "", email: "[email protected]" })).toBe("carol")+ expect(displayName({ name: " ", email: "[email protected]" })).toBe("carol")+ expect(displayName({ email: "[email protected]" })).toBe("dave")+ })++ it("returns 'Unknown member' when neither name nor email is present", () => {+ expect(displayName({})).toBe("Unknown member")+ expect(displayName(null)).toBe("Unknown member")+ expect(displayName(undefined)).toBe("Unknown member")+ expect(displayName({ name: null, email: null })).toBe("Unknown member")+ })++ it("never returns a raw id", () => {+ const id = "user_abc123"+ expect(displayName({ name: "", email: "" })).not.toBe(id)+ expect(displayName({})).toBe("Unknown member")+ })+})++describe("makeUserNameResolver", () => {+ const list = [+ { userId: "u1", name: "Alice" },+ { userId: "u2", name: "", email: "[email protected]" },+ { id: "u3", name: "Carol" },+ ]++ it("resolves a found row via displayName", () => {+ const resolve = makeUserNameResolver(list)+ expect(resolve("u1")).toBe("Alice")+ expect(resolve("u2")).toBe("bob")+ expect(resolve("u3")).toBe("Carol")+ })++ it("returns 'Unknown member' (not the id) for an unknown user", () => {+ const resolve = makeUserNameResolver(list)+ expect(resolve("missing")).toBe("Unknown member")+ expect(resolve("missing")).not.toBe("missing")+ })+})++describe("reaction tooltip resolution", () => {+ // Reaction tooltips resolve reactor ids through makeUserNameResolver over the+ // combined members + friends set. A reactor that arrived only over the WS+ // event (id, no name) and is absent from the loaded set must fall back to+ // "Unknown member" — never the raw user id.+ const roster = [+ { userId: "member_1", name: "Alice" },+ { userId: "friend_1", name: "", email: "[email protected]" },+ ]++ it("resolves a reactor found in members or friends to a name", () => {+ const resolve = makeUserNameResolver(roster)+ expect(resolve("member_1")).toBe("Alice")+ expect(resolve("friend_1")).toBe("bob")+ })++ it("resolves a live-WS reactor absent from the loaded set to 'Unknown member', never the id", () => {+ const resolve = makeUserNameResolver(roster)+ const liveOnlyReactorId = "user_live_only_99"+ expect(resolve(liveOnlyReactorId)).toBe("Unknown member")+ expect(resolve(liveOnlyReactorId)).not.toBe(liveOnlyReactorId)+ })+})diff --git a/src/web/src/lib/community/display-name.ts b/src/web/src/lib/community/display-name.tsnew file mode 100644index 000000000..51f4c5bb7--- /dev/null+++ b/src/web/src/lib/community/display-name.ts@@ -0,0 +1,31 @@+const UNKNOWN_MEMBER = "Unknown member"++export function emailPrefix(email?: string | null): string {+ return email?.split("@")[0]?.trim() ?? ""+}++export function displayName(user?: {+ name?: string | null+ email?: string | null+} | null): string {+ const name = user?.name?.trim()+ if (name) return name+ const prefix = emailPrefix(user?.email)+ if (prefix) return prefix+ return UNKNOWN_MEMBER+}++export function makeUserNameResolver(+ list: ReadonlyArray<{+ userId?: string | null+ id?: string | null+ name?: string | null+ email?: string | null+ }>,+): (userId: string) => string {+ return (userId: string) => {+ const row = list.find((r) => (r.userId ?? r.id) === userId)+ if (!row) return UNKNOWN_MEMBER+ return displayName(row)+ }+}diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 25540a8d9..1b7a25eef 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -13,7 +13,7 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, createLogger, WS_EVENTS } from "@alook/shared"+import { queries, createLogger, WS_EVENTS, isThread } from "@alook/shared"import type { CommunityWsEvent, Database } from "@alook/shared"import { getDb } from "../db"import { broadcastToUser } from "../broadcast"@@ -54,7 +54,7 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s*/async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {const rows = await queries.communityChannel.getChannelType(db, channelId)- if (rows === "thread") {+ if (isThread(rows)) {return queries.communityThread.listThreadParticipantUserIds(db, channelId)}return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {diff --git a/src/web/src/components/community/server-gradient.test.ts b/src/web/src/lib/community/gradient-from-seed.test.tssimilarity index 51%rename from src/web/src/components/community/server-gradient.test.tsrename to src/web/src/lib/community/gradient-from-seed.test.tsindex 20bc1785d..fce473cbe 100644--- a/src/web/src/components/community/server-gradient.test.ts+++ b/src/web/src/lib/community/gradient-from-seed.test.ts@@ -1,36 +1,36 @@import { describe, it, expect } from "vitest"import { BG_COLORS } from "@/components/avatar/avatar-parts"-import { serverGradient, serverGradientColors, serverGradientAngle } from "./server-gradient"+import { gradientFromSeed, gradientColorsFromSeed, gradientAngleFromSeed } from "./gradient-from-seed"const PRESET_VALUES = new Set(BG_COLORS.map((c) => c.value))-describe("serverGradientColors", () => {+describe("gradientColorsFromSeed", () => {it("picks three colors from the agent avatar preset palette", () => {- const colors = serverGradientColors("server_abc")+ const colors = gradientColorsFromSeed("seed_abc")expect(colors).toHaveLength(3)for (const c of colors) expect(PRESET_VALUES.has(c)).toBe(true)})it("picks three distinct colors", () => {- const colors = serverGradientColors("server_xyz")+ const colors = gradientColorsFromSeed("seed_xyz")expect(new Set(colors).size).toBe(3)})it("is deterministic for the same seed", () => {- expect(serverGradientColors("server_1")).toEqual(serverGradientColors("server_1"))+ expect(gradientColorsFromSeed("seed_1")).toEqual(gradientColorsFromSeed("seed_1"))})it("varies across different seeds", () => {- const a = serverGradientColors("server_1")- const b = serverGradientColors("server_2")+ const a = gradientColorsFromSeed("seed_1")+ const b = gradientColorsFromSeed("seed_2")expect(a).not.toEqual(b)})})-describe("serverGradientAngle", () => {+describe("gradientAngleFromSeed", () => {it("returns a degree value within [0, 360)", () => {- for (const seed of ["server_abc", "server_xyz", "server_1", "server_2"]) {- const angle = serverGradientAngle(seed)+ for (const seed of ["seed_abc", "seed_xyz", "seed_1", "seed_2"]) {+ const angle = gradientAngleFromSeed(seed)expect(angle).toBeGreaterThanOrEqual(0)expect(angle).toBeLessThan(360)expect(Number.isInteger(angle)).toBe(true)@@ -38,25 +38,25 @@ describe("serverGradientAngle", () => {})it("is deterministic for the same seed", () => {- expect(serverGradientAngle("server_1")).toBe(serverGradientAngle("server_1"))+ expect(gradientAngleFromSeed("seed_1")).toBe(gradientAngleFromSeed("seed_1"))})it("varies across different seeds", () => {- const angles = new Set(["server_1", "server_2", "server_3", "server_4"].map(serverGradientAngle))+ const angles = new Set(["seed_1", "seed_2", "seed_3", "seed_4"].map(gradientAngleFromSeed))expect(angles.size).toBeGreaterThan(1)})})-describe("serverGradient", () => {- it("builds a linear-gradient CSS value from a random angle and three preset colors", () => {- const css = serverGradient("server_abc")+describe("gradientFromSeed", () => {+ it("builds a linear-gradient CSS value from a seeded angle and three preset colors", () => {+ const css = gradientFromSeed("seed_abc")expect(css).toMatch(/^linear-gradient\(\d+deg, .+, .+, .+\)$/)- const [c0, c1, c2] = serverGradientColors("server_abc")- const angle = serverGradientAngle("server_abc")+ const [c0, c1, c2] = gradientColorsFromSeed("seed_abc")+ const angle = gradientAngleFromSeed("seed_abc")expect(css).toBe(`linear-gradient(${angle}deg, ${c0}, ${c1}, ${c2})`)})it("is deterministic for the same seed", () => {- expect(serverGradient("server_1")).toBe(serverGradient("server_1"))+ expect(gradientFromSeed("seed_1")).toBe(gradientFromSeed("seed_1"))})})diff --git a/src/web/src/components/community/server-gradient.ts b/src/web/src/lib/community/gradient-from-seed.tssimilarity index 63%rename from src/web/src/components/community/server-gradient.tsrename to src/web/src/lib/community/gradient-from-seed.tsindex 66b6f7031..e0d0ec7ef 100644--- a/src/web/src/components/community/server-gradient.ts+++ b/src/web/src/lib/community/gradient-from-seed.ts@@ -1,11 +1,11 @@/**- * Deterministic fallback background for servers without an uploaded icon.+ * Deterministic fallback gradient, seeded by a stable id.** Draws three distinct colors (and a gradient angle) from the same preset- * palette used by the agent avatar generator (`BG_COLORS`) so server and- * agent fallback visuals share one design language. Everything is seeded by- * the server id, so it looks random across servers but never flickers- * between renders/reloads.+ * palette used by the agent avatar generator (`BG_COLORS`) so every fallback+ * visual — server icons, the profile-card banner — shares one design+ * language. Everything is seeded, so it looks random across ids but never+ * flickers between renders/reloads.*/import { BG_COLORS } from "@/components/avatar/avatar-parts"@@ -28,7 +28,7 @@ function mulberry32(seed: number): () => number {}/** Three distinct preset colors from `BG_COLORS`, seeded by `seed`. */-export function serverGradientColors(seed: string): [string, string, string] {+export function gradientColorsFromSeed(seed: string): [string, string, string] {const rand = mulberry32(hashStr(seed))const pool = BG_COLORS.map((c) => c.value)const picked: string[] = []@@ -40,15 +40,15 @@ export function serverGradientColors(seed: string): [string, string, string] {}// Salted separately from the color pick so the angle doesn't move in lockstep-// with color choice (two servers with the same colors can still differ).-export function serverGradientAngle(seed: string): number {+// with color choice (two seeds with the same colors can still differ).+export function gradientAngleFromSeed(seed: string): number {const rand = mulberry32(hashStr(`${seed}:angle`))return Math.floor(rand() * 360)}-/** CSS `background` value for a server's fallback avatar. */-export function serverGradient(seed: string): string {- const [c0, c1, c2] = serverGradientColors(seed)- const angle = serverGradientAngle(seed)+/** CSS `background` value for a seeded fallback gradient. */+export function gradientFromSeed(seed: string): string {+ const [c0, c1, c2] = gradientColorsFromSeed(seed)+ const angle = gradientAngleFromSeed(seed)return `linear-gradient(${angle}deg, ${c0}, ${c1}, ${c2})`}diff --git a/src/web/src/lib/community/machine-name.test.ts b/src/web/src/lib/community/machine-name.test.tsnew file mode 100644index 000000000..bdb31b0b3--- /dev/null+++ b/src/web/src/lib/community/machine-name.test.ts@@ -0,0 +1,21 @@+import { describe, it, expect } from "vitest"+import { machineName } from "./machine-name"++describe("machineName", () => {+ it("prefers displayName when present", () => {+ expect(machineName({ displayName: "Studio", hostname: "mac-01" })).toBe("Studio")+ expect(machineName({ displayName: " Studio ", hostname: "mac-01" })).toBe("Studio")+ })++ it("falls back to hostname when displayName is empty", () => {+ expect(machineName({ displayName: "", hostname: "mac-01" })).toBe("mac-01")+ expect(machineName({ displayName: " ", hostname: "mac-01" })).toBe("mac-01")+ expect(machineName({ hostname: "mac-01" })).toBe("mac-01")+ })++ it("falls back to 'Unnamed machine' when neither is present", () => {+ expect(machineName({})).toBe("Unnamed machine")+ expect(machineName(null)).toBe("Unnamed machine")+ expect(machineName({ displayName: "", hostname: "" })).toBe("Unnamed machine")+ })+})diff --git a/src/web/src/lib/community/machine-name.ts b/src/web/src/lib/community/machine-name.tsnew file mode 100644index 000000000..8e0226d91--- /dev/null+++ b/src/web/src/lib/community/machine-name.ts@@ -0,0 +1,6 @@+export function machineName(m?: {+ displayName?: string | null+ hostname?: string | null+} | null): string {+ return m?.displayName?.trim() || m?.hostname?.trim() || "Unnamed machine"+}diff --git a/src/web/src/lib/community/member-payload.ts b/src/web/src/lib/community/member-payload.tsindex cff47b39b..07f11dfe4 100644--- a/src/web/src/lib/community/member-payload.ts+++ b/src/web/src/lib/community/member-payload.ts@@ -44,12 +44,19 @@ export type MappedMember = {// owner-scoped `isBot`/`ownerUserId` projection. The search route never emitted// bot fields (and doesn't select the columns), so it passes `botGating: false`// to stay byte-identical.+export function memberDisplay(+ nickname: string | null | undefined,+ userName: string | null | undefined,+): string {+ return nickname ?? userName ?? ""+}+export function mapMemberForApi(row: MemberRow,viewerUserId: string,opts?: { botGating?: boolean; isCreator?: boolean; source?: string },): MappedMember {- const display = row.nickname ?? row.userName ?? ""+ const display = memberDisplay(row.nickname, row.userName)const isOwnBot =!!opts?.botGating &&row.userIsBot === true &&diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex beda3c312..2c1d368d4 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -73,7 +73,35 @@ vi.mock("./audit", async () => {}})-import { createCommunityMessage } from "./message-handler"+import {+ createCommunityMessage,+ isDmTarget,+ isThreadTarget,+ isChannelTarget,+ type MessageTarget,+} from "./message-handler"++describe("message-target predicates", () => {+ const channel: MessageTarget = { kind: "channel", channelId: "c1", serverId: "s1" }+ const thread: MessageTarget = { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "s1" }+ const dm: MessageTarget = { kind: "dm", dmId: "d1", otherUserId: "u1" }++ it("isChannelTarget", () => {+ expect(isChannelTarget(channel)).toBe(true)+ expect(isChannelTarget(thread)).toBe(false)+ expect(isChannelTarget(dm)).toBe(false)+ })+ it("isThreadTarget", () => {+ expect(isThreadTarget(thread)).toBe(true)+ expect(isThreadTarget(channel)).toBe(false)+ expect(isThreadTarget(dm)).toBe(false)+ })+ it("isDmTarget", () => {+ expect(isDmTarget(dm)).toBe(true)+ expect(isDmTarget(channel)).toBe(false)+ expect(isDmTarget(thread)).toBe(false)+ })+})function messageRow(overrides: Partial<Record<string, unknown>> = {}) {return {diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex f0a8cfc82..bf84dd3df 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -23,6 +23,24 @@ export type MessageTarget =}| { kind: "dm"; dmId: string; otherUserId: string }+export function isDmTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "dm" }>+export function isDmTarget(kind: string): boolean+export function isDmTarget(target: { kind: string } | string): boolean {+ return (typeof target === "string" ? target : target.kind) === "dm"+}++export function isThreadTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "thread" }>+export function isThreadTarget(kind: string): boolean+export function isThreadTarget(target: { kind: string } | string): boolean {+ return (typeof target === "string" ? target : target.kind) === "thread"+}++export function isChannelTarget<T extends { kind: string }>(target: T): target is Extract<T, { kind: "channel" }>+export function isChannelTarget(kind: string): boolean+export function isChannelTarget(target: { kind: string } | string): boolean {+ return (typeof target === "string" ? target : target.kind) === "channel"+}+type IncomingAttachment = {url: stringfilename: string@@ -180,15 +198,15 @@ export async function createCommunityMessage(params: {const replyToId =typeof body.replyToId === "string" ? body.replyToId : undefinedconst mentionType: MentionType | undefined =- target.kind !== "dm" && isMentionType(body.mentionType)+ !isDmTarget(target) && isMentionType(body.mentionType)? body.mentionType: undefinedconst baseMessageData = {authorId,content,- channelId: target.kind === "dm" ? undefined : target.channelId,- dmConversationId: target.kind === "dm" ? target.dmId : undefined,+ channelId: isDmTarget(target) ? undefined : target.channelId,+ dmConversationId: isDmTarget(target) ? target.dmId : undefined,replyToId,mentionType,...(messageType !== undefined ? { type: messageType } : {}),@@ -242,7 +260,7 @@ export async function createCommunityMessage(params: {const author = await queries.user.getUserInternal(db, authorId)if (author?.isBot === true) {logAudit(db, {- serverId: target.kind === "dm" ? null : target.serverId,+ serverId: isDmTarget(target) ? null : target.serverId,actorId: authorId,action: COMMUNITY_AUDIT_ACTIONS.MESSAGE_AUTHORED_AS_BOT,targetType: "message",@@ -250,7 +268,7 @@ export async function createCommunityMessage(params: {changes: JSON.stringify({botId: authorId,target: target.kind,- targetId: target.kind === "dm" ? target.dmId : target.channelId,+ targetId: isDmTarget(target) ? target.dmId : target.channelId,messageId: row.id,source: source ?? "web",}),@@ -266,7 +284,7 @@ export async function createCommunityMessage(params: {const replyTargets = new Set<string>()if (!skipMentions && row.replyToId) {// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id path- const scope = target.kind === "dm" ? { dmConversationId: target.dmId } : { channelId: target.channelId }+ const scope = isDmTarget(target) ? { dmConversationId: target.dmId } : { channelId: target.channelId }const replyMsg = await queries.communityMessage.getMessageInScope(db, row.replyToId, scope)if (replyMsg) {replyMap.set(replyMsg.id, {@@ -297,7 +315,7 @@ export async function createCommunityMessage(params: {// subscribe the whole channel/server to every future reply (that would defeat// the notification dimension). See the thread-participation block below.const explicitMentionTargets = new Set<string>()- if (!skipMentions && target.kind !== "dm") {+ if (!skipMentions && !isDmTarget(target)) {// Resolve the audience up front when private; `null` = public (no clamp).// PERF (accepted): `isChannelPrivate` and `getPrivateChannelAudienceUserIds`// each climb `parentChannelId` for a thread — two parent lookups per message@@ -364,7 +382,7 @@ export async function createCommunityMessage(params: {// already scoped to the parent-channel audience by the block above.// Admins are NOT auto-added — only real participation joins the set. System /// card messages (`skipMentions`) don't add the author.- if (target.kind === "thread" && !skipMentions) {+ if (isThreadTarget(target) && !skipMentions) {const rows: { userId: string; source: "spoke" | "mention" }[] = [{ userId: authorId, source: "spoke" },]@@ -441,7 +459,7 @@ export async function createCommunityMessage(params: {if (liveMentions.length > 0 || liveReplies.length > 0) {const authorName = row.authorNameconst channelIdForBroadcast =- target.kind === "dm" ? undefined : target.channelId+ isDmTarget(target) ? undefined : target.channelIdfor (const userId of [...liveMentions, ...liveReplies]) {broadcastToUser(userId, {type: WS_EVENTS.MENTION_CREATE,@@ -453,7 +471,7 @@ export async function createCommunityMessage(params: {}}- if (target.kind === "dm") {+ if (isDmTarget(target)) {fanOutToDM(target.dmId,{@@ -480,7 +498,7 @@ export async function createCommunityMessage(params: {{ excludeUserId: fanoutExclude, wakeMessageRow },).catch(() => { })- if (target.kind === "thread") {+ if (isThreadTarget(target)) {const updated = await queries.communityChannel.getChannel(db,target.channelId,diff --git a/src/web/src/lib/community/presence.test.ts b/src/web/src/lib/community/presence.test.tsnew file mode 100644index 000000000..5f61d1fc7--- /dev/null+++ b/src/web/src/lib/community/presence.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from "vitest"+import { resolveProfilePresence, resolveRowPresence } from "./presence"++describe("resolveProfilePresence", () => {+ it("returns online for self regardless of onlineUserIds", () => {+ expect(resolveProfilePresence(true, undefined, new Set())).toBe("online")+ expect(resolveProfilePresence(true, "u1", new Set())).toBe("online")+ })++ it("returns online when targetUserId is in onlineUserIds", () => {+ expect(resolveProfilePresence(false, "u1", new Set(["u1", "u2"]))).toBe("online")+ })++ it("returns offline when targetUserId is resolved but not online", () => {+ expect(resolveProfilePresence(false, "u3", new Set(["u1", "u2"]))).toBe("offline")+ })++ it("returns undefined when targetUserId is undefined (no member/friend match)", () => {+ expect(resolveProfilePresence(false, undefined, new Set(["u1"]))).toBeUndefined()+ })+})++describe("resolveRowPresence", () => {+ it("returns online for the current user regardless of the online set", () => {+ expect(resolveRowPresence({ userId: "me" }, new Set(), "me")).toBe("online")+ expect(resolveRowPresence({ id: "me" }, new Set(), "me")).toBe("online")+ })++ it("returns online when the resolved id is in onlineUserIds", () => {+ expect(resolveRowPresence({ userId: "u1" }, new Set(["u1"]))).toBe("online")+ })++ it("returns offline when the resolved id is not online", () => {+ expect(resolveRowPresence({ userId: "u2" }, new Set(["u1"]))).toBe("offline")+ })++ it("normalizes the key as userId ?? id", () => {+ // userId wins when both present+ expect(resolveRowPresence({ userId: "u1", id: "other" }, new Set(["u1"]))).toBe("online")+ expect(resolveRowPresence({ userId: "u1", id: "other" }, new Set(["other"]))).toBe("offline")+ // falls back to id when userId is absent/nullish+ expect(resolveRowPresence({ id: "f1" }, new Set(["f1"]))).toBe("online")+ expect(resolveRowPresence({ userId: null, id: "f1" }, new Set(["f1"]))).toBe("online")+ })++ it("returns offline (never undefined) when no id resolves", () => {+ expect(resolveRowPresence({}, new Set(["u1"]))).toBe("offline")+ expect(resolveRowPresence({ userId: null, id: null }, new Set())).toBe("offline")+ })+})diff --git a/src/web/src/lib/community/presence.ts b/src/web/src/lib/community/presence.tsnew file mode 100644index 000000000..82e363264--- /dev/null+++ b/src/web/src/lib/community/presence.ts@@ -0,0 +1,45 @@+import type { Presence } from "@/components/community/_types"++/**+ * The single client-side presence-overlay helper.+ *+ * `member.status` / `friend.status` / `dm.status` from the list routes are NOT+ * live presence — the routes hardcode them at fetch time. Real presence only+ * exists by overlaying `useOnlineUserIds()` (the WS-maintained set) on the raw+ * row. Every call site that renders a member / friend / DM row must resolve+ * presence through this one helper so self-handling and key resolution stay+ * consistent instead of drifting per-site.+ *+ * Rules (unified across all sites):+ * - self → always "online" (the signed-in viewer is present by definition).+ * - a resolved id present in `onlineUserIds` → "online", else "offline".+ * - no id → `undefined` (only the ProfileCard path, which tolerates it).+ *+ * Pure functions (no React) so they're unit-testable without a render harness.+ */+export function resolveProfilePresence(+ isSelf: boolean,+ targetUserId: string | undefined,+ onlineUserIds: ReadonlySet<string>,+): Presence | undefined {+ if (isSelf) return "online"+ if (!targetUserId) return undefined+ return onlineUserIds.has(targetUserId) ? "online" : "offline"+}++/**+ * Row-overlay variant for member / friend / DM rows. Normalizes the id key+ * (`userId ?? id`) in ONE place, applies the self → online rule when+ * `currentUserId` is provided, and resolves a missing id to "offline" (the+ * concrete `Presence` these rows require). Delegates to+ * `resolveProfilePresence` so there is a single source of presence logic.+ */+export function resolveRowPresence(+ row: { userId?: string | null; id?: string | null },+ onlineUserIds: ReadonlySet<string>,+ currentUserId?: string,+): Presence {+ const id = row.userId ?? row.id ?? undefined+ const isSelf = !!id && !!currentUserId && id === currentUserId+ return resolveProfilePresence(isSelf, id, onlineUserIds) ?? "offline"+}diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex b50e30600..049c62810 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -18,6 +18,7 @@ import {userAvatarUrl,botAvatarUrl,} from "./storage"+import { isChannelTarget, isDmTarget } from "./message-handler"type UploadOk = {ok: true@@ -232,7 +233,7 @@ export async function runAttachmentUpload(const id = ctx.params?.idif (!id) {const label =- kind === "channel" ? "channel id" : kind === "dm" ? "dm id" : "id"+ isChannelTarget(kind) ? "channel id" : isDmTarget(kind) ? "dm id" : "id"return writeError(`missing ${label}`, 400)}diff --git a/src/web/src/lib/ime.test.ts b/src/web/src/lib/ime.test.tsnew file mode 100644index 000000000..3a43b345c--- /dev/null+++ b/src/web/src/lib/ime.test.ts@@ -0,0 +1,62 @@+import { describe, it, expect, vi } from "vitest"+import { isImeConfirming, onEnterSubmit } from "./ime"++describe("isImeConfirming", () => {+ it("is true when a React synthetic event's nativeEvent is composing", () => {+ expect(isImeConfirming({ nativeEvent: { isComposing: true } })).toBe(true)+ })++ it("is true when a native KeyboardEvent is composing", () => {+ expect(isImeConfirming({ isComposing: true })).toBe(true)+ })++ it("prefers nativeEvent over the top-level flag", () => {+ expect(isImeConfirming({ isComposing: true, nativeEvent: { isComposing: false } })).toBe(false)+ })++ it("is false when nothing is composing", () => {+ expect(isImeConfirming({ nativeEvent: { isComposing: false } })).toBe(false)+ expect(isImeConfirming({ isComposing: false })).toBe(false)+ expect(isImeConfirming({})).toBe(false)+ })+})++describe("onEnterSubmit", () => {+ const key = (over: Record<string, unknown>) => ({+ key: "Enter",+ preventDefault: vi.fn(),+ ...over,+ })++ it("does NOT call fn while confirming an IME candidate", () => {+ const fn = vi.fn()+ onEnterSubmit(fn)(key({ nativeEvent: { isComposing: true } }))+ expect(fn).not.toHaveBeenCalled()+ })++ it("calls fn on a clean Enter and prevents default", () => {+ const fn = vi.fn()+ const e = key({ nativeEvent: { isComposing: false } })+ onEnterSubmit(fn)(e)+ expect(fn).toHaveBeenCalledOnce()+ expect(e.preventDefault).toHaveBeenCalled()+ })++ it("calls onEscape on Escape", () => {+ const fn = vi.fn()+ const onEscape = vi.fn()+ onEnterSubmit(fn, { onEscape })(key({ key: "Escape" }))+ expect(onEscape).toHaveBeenCalledOnce()+ expect(fn).not.toHaveBeenCalled()+ })++ it("ignores Shift+Enter by default but honors allowShift", () => {+ const fn = vi.fn()+ onEnterSubmit(fn)(key({ shiftKey: true }))+ expect(fn).not.toHaveBeenCalled()++ const fn2 = vi.fn()+ onEnterSubmit(fn2, { allowShift: true })(key({ shiftKey: true }))+ expect(fn2).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/lib/ime.ts b/src/web/src/lib/ime.tsnew file mode 100644index 000000000..1a9781691--- /dev/null+++ b/src/web/src/lib/ime.ts@@ -0,0 +1,32 @@+type ComposingEvent = {+ isComposing?: boolean+ nativeEvent?: { isComposing?: boolean }+}++export function isImeConfirming(e: ComposingEvent): boolean {+ return e.nativeEvent?.isComposing ?? e.isComposing ?? false+}++type EnterKeyEvent = ComposingEvent & {+ key: string+ shiftKey?: boolean+ preventDefault: () => void+}++export function onEnterSubmit(+ fn: () => void,+ opts?: { onEscape?: () => void; allowShift?: boolean },+) {+ return (e: EnterKeyEvent) => {+ if (isImeConfirming(e)) return+ if (e.key === "Escape") {+ opts?.onEscape?.()+ return+ }+ if (e.key === "Enter") {+ if (!opts?.allowShift && e.shiftKey) return+ e.preventDefault()+ fn()+ }+ }+}