Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): derive avatars, gradients & mentions from stable ids (#360)
Gener8a56968f6109
diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 7f5cb45c3..476d118d7 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -486,6 +486,7 @@ export {export { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";export { parsePromptMentions } from "./utils/prompt-parser";export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parser";+export { 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";diff --git a/src/shared/src/utils/mention-token.ts b/src/shared/src/utils/mention-token.tsnew file mode 100644index 000000000..97c82b217--- /dev/null+++ b/src/shared/src/utils/mention-token.ts@@ -0,0 +1,6 @@+export const MENTION_TOKEN_RE = /@\[([^\]]+)\]\(([A-Za-z0-9_-]+)\)/g++export function stripMentionTokens(text: string): string {+ if (!text) return text+ return text.replace(MENTION_TOKEN_RE, (_m, label) => `@${label}`)+}diff --git a/src/shared/src/utils/prompt-parser.ts b/src/shared/src/utils/prompt-parser.tsindex 0f8de13f0..3e8af019f 100644--- a/src/shared/src/utils/prompt-parser.ts+++ b/src/shared/src/utils/prompt-parser.ts@@ -1,6 +1,8 @@import { toAlookAddress } from "./email"+import { MENTION_TOKEN_RE } from "./mention-token"export interface PromptAgent {+ id: stringname: stringemailHandle: string | nulldescription: string@@ -32,7 +34,11 @@ function isBoundary(prompt: string, endIndex: number): boolean {return true}-export function parsePromptMentions(prompt: string, agents: PromptAgent[]): ParseResult {+function enrichMention(name: string, emailHandle: string | null): string {+ return emailHandle ? `@${name} (${toAlookAddress(emailHandle)})` : `@${name}`+}++function parseBareNames(prompt: string, agents: PromptAgent[]): ParseResult {if (!prompt || agents.length === 0) return { enrichedPrompt: prompt, mentions: [] }const sorted = agents.slice().sort((a, b) => b.name.length - a.name.length)@@ -77,15 +83,49 @@ export function parsePromptMentions(prompt: string, agents: PromptAgent[]): Parsdescription: m.agent.description,}mentions.unshift(mention)+ result = result.slice(0, m.start) + enrichMention(m.agent.name, m.agent.emailHandle) + result.slice(m.end)+ }++ return { enrichedPrompt: result, mentions }+}- if (m.agent.emailHandle) {- const replacement = `@${m.agent.name} (${toAlookAddress(m.agent.emailHandle)})`- result = result.slice(0, m.start) + replacement + result.slice(m.end)+export function parsePromptMentions(prompt: string, agents: PromptAgent[]): ParseResult {+ if (!prompt) return { enrichedPrompt: prompt, mentions: [] }++ // Token pass — `@[Name](agentId)` resolves the exact agent by id. Runs even+ // when the agents list is empty so a raw token is never leaked into the+ // enriched prompt sent to the runtime; an unmatched token (agent deleted) is+ // stripped back to `@Name`. Text between tokens keeps the bare-name matching+ // for backward compatibility with historic / externally-sourced mentions.+ const byId = new Map(agents.map(a => [a.id, a]))+ const re = new RegExp(MENTION_TOKEN_RE.source, "g")+ const mentions: PromptMention[] = []+ let result = ""+ let last = 0+ let m: RegExpExecArray | null+ while ((m = re.exec(prompt)) !== null) {+ const between = parseBareNames(prompt.slice(last, m.index), agents)+ result += between.enrichedPrompt+ mentions.push(...between.mentions)++ const label = m[1]+ const agent = byId.get(m[2])+ if (agent) {+ result += enrichMention(agent.name, agent.emailHandle)+ mentions.push({+ name: agent.name,+ email: agent.emailHandle ? toAlookAddress(agent.emailHandle) : null,+ description: agent.description,+ })} else {- // Preserve canonical casing even without email- result = result.slice(0, m.start) + `@${m.agent.name}` + result.slice(m.end)+ result += `@${label}`}+ last = re.lastIndex}+ const tail = parseBareNames(prompt.slice(last), agents)+ result += tail.enrichedPrompt+ mentions.push(...tail.mentions)+return { enrichedPrompt: result, mentions }}diff --git a/src/shared/test/utils/mention-token.test.ts b/src/shared/test/utils/mention-token.test.tsnew file mode 100644index 000000000..a29227baa--- /dev/null+++ b/src/shared/test/utils/mention-token.test.ts@@ -0,0 +1,39 @@+import { describe, it, expect } from "vitest"+import { stripMentionTokens, MENTION_TOKEN_RE } from "../../src/utils/mention-token"++describe("stripMentionTokens", () => {+ it("strips a single token to @Name", () => {+ expect(stripMentionTokens("The @[Ada](ag_xk29) will handle it")).toBe("The @Ada will handle it")+ })++ it("strips multiple tokens", () => {+ expect(stripMentionTokens("@[Ada](ag_1) and @[Bob](ag_2)")).toBe("@Ada and @Bob")+ })++ it("mixes tokens with plain text", () => {+ expect(stripMentionTokens("hi @[Ada](ag_1), see you")).toBe("hi @Ada, see you")+ })++ it("leaves a normal markdown link untouched", () => {+ const link = "see [docs](https://example.com/a.b:c)"+ expect(stripMentionTokens(link)).toBe(link)+ })++ it("leaves a plain @Name untouched", () => {+ expect(stripMentionTokens("hey @Ada")).toBe("hey @Ada")+ })++ it("handles empty input", () => {+ expect(stripMentionTokens("")).toBe("")+ })++ it("MENTION_TOKEN_RE does not match a markdown link with url punctuation", () => {+ const re = new RegExp(MENTION_TOKEN_RE.source, "g")+ expect(re.test("[text](https://example.com/path)")).toBe(false)+ })++ it("MENTION_TOKEN_RE matches an ag_ id", () => {+ const re = new RegExp(MENTION_TOKEN_RE.source, "g")+ expect(re.test("@[Ada](ag_xk29AB_-)")).toBe(true)+ })+})diff --git a/src/shared/test/utils/prompt-parser.test.ts b/src/shared/test/utils/prompt-parser.test.tsindex d22ef8a22..5701e89c2 100644--- a/src/shared/test/utils/prompt-parser.test.ts+++ b/src/shared/test/utils/prompt-parser.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest"import { parsePromptMentions } from "../../src/utils/prompt-parser"const bot = (name: string, emailHandle: string | null = null, description = "") => ({+ id: `ag_${name.toLowerCase().replace(/[^a-z0-9]/g, "")}`,name,emailHandle,description,@@ -123,4 +124,41 @@ describe("parsePromptMentions", () => {expect(result.enrichedPrompt).toBe('(@Bot ([email protected])) and "@Bot ([email protected])"')expect(result.mentions).toHaveLength(2)})++ it("resolves a token by agent id and enriches", () => {+ const ada1 = { id: "ag_ada1", name: "Ada", emailHandle: "ada-one", description: "first" }+ const ada2 = { id: "ag_ada2", name: "Ada", emailHandle: "ada-two", description: "second" }+ const result = parsePromptMentions("The @[Ada](ag_ada2) will handle it", [ada1, ada2])+ expect(result.enrichedPrompt).toBe("The @Ada ([email protected]) will handle it")+ expect(result.mentions).toHaveLength(1)+ expect(result.mentions[0]).toEqual({ name: "Ada", email: "[email protected]", description: "second" })+ })++ it("picks the correct same-name agent by token id", () => {+ const ada1 = { id: "ag_ada1", name: "Ada", emailHandle: "ada-one", description: "" }+ const ada2 = { id: "ag_ada2", name: "Ada", emailHandle: "ada-two", description: "" }+ const result = parsePromptMentions("@[Ada](ag_ada1)", [ada1, ada2])+ expect(result.enrichedPrompt).toBe("@Ada ([email protected])")+ expect(result.mentions[0].email).toBe("[email protected]")+ })++ it("strips an unmatched token (agent deleted) back to @Name", () => {+ const result = parsePromptMentions("Ask @[Ada](ag_gone) about it", [bot("Other", "other")])+ expect(result.enrichedPrompt).toBe("Ask @Ada about it")+ expect(result.mentions).toHaveLength(0)+ })++ it("strips tokens even when the agent list is empty (no leaked token)", () => {+ const result = parsePromptMentions("Hey @[Ada](ag_ada1) do this", [])+ expect(result.enrichedPrompt).toBe("Hey @Ada do this")+ expect(result.mentions).toHaveLength(0)+ })++ it("handles a token mixed with a bare-name mention", () => {+ const ada = { id: "ag_ada1", name: "Ada", emailHandle: "ada", description: "" }+ const bob = bot("Bob", "bob")+ const result = parsePromptMentions("@[Ada](ag_ada1) ping @Bob", [ada, bob])+ expect(result.enrichedPrompt).toBe("@Ada ([email protected]) ping @Bob ([email protected])")+ expect(result.mentions).toHaveLength(2)+ })})diff --git a/src/web/src/app/(app)/studio/new/backfill.test.ts b/src/web/src/app/(app)/studio/new/backfill.test.tsnew file mode 100644index 000000000..f182869bc--- /dev/null+++ b/src/web/src/app/(app)/studio/new/backfill.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from "vitest";++type Member = { uid: string; name: string; emailHandle?: string };++function backfill(members: Member[], handles: { uid: string; handle: string }[]): Member[] {+ return members.map((m) => {+ const h = handles.find((h) => h.uid === m.uid);+ return h ? { ...m, emailHandle: h.handle } : m;+ });+}++describe("studio handle backfill by uid", () => {+ it("maps each same-name member to its own uid's handle without crossing", () => {+ const members: Member[] = [+ { uid: "a", name: "Ada" },+ { uid: "b", name: "Ada" },+ ];+ const handles = [+ { uid: "a", handle: "ada" },+ { uid: "b", handle: "ada-blue" },+ ];++ const result = backfill(members, handles);++ expect(result[0].emailHandle).toBe("ada");+ expect(result[1].emailHandle).toBe("ada-blue");+ });++ it("does not cross when response order differs from member order", () => {+ const members: Member[] = [+ { uid: "a", name: "Ada" },+ { uid: "b", name: "Ada" },+ ];+ const handles = [+ { uid: "b", handle: "ada-blue" },+ { uid: "a", handle: "ada" },+ ];++ const result = backfill(members, handles);++ expect(result[0].emailHandle).toBe("ada");+ expect(result[1].emailHandle).toBe("ada-blue");+ });++ it("leaves emailHandle unset for members with no matching uid", () => {+ const members: Member[] = [{ uid: "a", name: "Ada" }];+ const result = backfill(members, [{ uid: "z", handle: "zed" }]);+ expect(result[0].emailHandle).toBeUndefined();+ });+});diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex 48d085bb2..e42acb1d1 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -122,15 +122,15 @@ export function StudioOnboardingClient({});}, [onlineRuntimes]);- const resolveHandles = useCallback(async (memberNames: string[]) => {+ const resolveHandles = useCallback(async (members: { uid: string; name: string }[]) => {try {const res = await fetch("/api/studios/check-handles", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ names: memberNames }),+ body: JSON.stringify({ members }),});if (!res.ok) return null;- return (await res.json()) as { name: string; handle: string }[];+ return (await res.json()) as { uid: string; handle: string }[];} catch {return null;}@@ -142,6 +142,7 @@ export function StudioOnboardingClient({const generated = shuffleMembers(initialTemplate.members.length);const defaultRuntimeId = onlineRuntimes[0]?.id || "";const newMembers = initialTemplate.members.map((m, i) => ({+ uid: generated[i].uid,name: generated[i].name,role: m.role,description: m.description,@@ -151,11 +152,11 @@ export function StudioOnboardingClient({relationship: m.relationship,}));setMembers(newMembers);- resolveHandles(newMembers.map((m) => m.name)).then((handles) => {+ resolveHandles(newMembers.map((m) => ({ uid: m.uid, name: m.name }))).then((handles) => {if (handles) {setMembers((prev) =>prev.map((m) => {- const h = handles.find((r) => r.name === m.name);+ const h = handles.find((h) => h.uid === m.uid);return h ? { ...m, emailHandle: h.handle } : m;}),);@@ -170,6 +171,7 @@ export function StudioOnboardingClient({const generated = shuffleMembers(preset.members.length);const defaultRuntimeId = onlineRuntimes[0]?.id || "";const newMembers = preset.members.map((m, i) => ({+ uid: generated[i].uid,name: generated[i].name,role: m.role,description: m.description,@@ -179,10 +181,10 @@ export function StudioOnboardingClient({relationship: m.relationship,}));setMembers(newMembers);- const handles = await resolveHandles(newMembers.map((m) => m.name));+ const handles = await resolveHandles(newMembers.map((m) => ({ uid: m.uid, name: m.name })));if (handles) {setMembers((prev) => prev.map((m) => {- const h = handles.find((r) => r.name === m.name);+ const h = handles.find((h) => h.uid === m.uid);return h ? { ...m, emailHandle: h.handle } : m;}));}@@ -190,12 +192,12 @@ export function StudioOnboardingClient({const handleShuffle = async () => {const generated = shuffleMembers(members.length);- const newMembers = members.map((m, i) => ({ ...m, name: generated[i].name, avatarUrl: generated[i].avatarUrl, emailHandle: undefined }));+ const newMembers = members.map((m, i) => ({ ...m, uid: generated[i].uid, name: generated[i].name, avatarUrl: generated[i].avatarUrl, emailHandle: undefined }));setMembers(newMembers);- const handles = await resolveHandles(newMembers.map((m) => m.name));+ const handles = await resolveHandles(newMembers.map((m) => ({ uid: m.uid, name: m.name })));if (handles) {setMembers((prev) => prev.map((m) => {- const h = handles.find((r) => r.name === m.name);+ const h = handles.find((h) => h.uid === m.uid);return h ? { ...m, emailHandle: h.handle } : m;}));}diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsindex 02f86964e..e54f3529f 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts@@ -8,6 +8,9 @@ const mockGetMessage = vi.fn()const mockGetUserSelf = vi.fn()const mockGetUserInternal = vi.fn()const mockFanOutToChannel = vi.fn()+const mockListChildChannels = vi.fn()+const mockGetUsersByIds = vi.fn()+const mockGetFirstMessageByChannelIds = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -23,6 +26,7 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),createChannel: (...a: unknown[]) => mockCreateChannel(...a),+ listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),// createCommunityMessage's private-channel scoping guard is only hit// when there are mentions; the happy-path posts have none, so these// return public/empty.@@ -31,6 +35,7 @@ vi.mock("@alook/shared", async () => {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getFirstMessageByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),},communityMember: {listMembers: vi.fn(async () => []),@@ -42,6 +47,7 @@ vi.mock("@alook/shared", async () => {user: {getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),},},}@@ -77,7 +83,7 @@ vi.mock("@/lib/middleware/helpers", () => {}})-import { POST } from "./route"+import { GET, POST } from "./route"const ctx = { params: { id: "ch1" } } as any@@ -136,3 +142,40 @@ describe("POST /api/community/channels/[id]/posts — name normalization", () =>expect(mockCreateChannel).not.toHaveBeenCalled()})})++describe("GET /api/community/channels/[id]/posts — authorId", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })+ mockGetFirstMessageByChannelIds.mockResolvedValue([])+ })++ function getReq() {+ return new NextRequest("http://localhost/api/community/channels/ch1/posts")+ }++ it("carries each post's creatorId through as authorId", async () => {+ mockListChildChannels.mockResolvedValue([+ { id: "post1", name: "First", messageCount: 2, lastMessageAt: "2026-07-02T00:00:00.000Z", createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_alice", tags: [] },+ ])+ mockGetUsersByIds.mockResolvedValue([{ id: "u_alice", name: "Alice", image: null }])++ const res = await GET(getReq(), ctx)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.posts).toHaveLength(1)+ expect(body.posts[0].authorId).toBe("u_alice")+ })++ it("falls back to an empty authorId when the creator was deleted (creatorId null)", async () => {+ mockListChildChannels.mockResolvedValue([+ { id: "post1", name: "Orphan", messageCount: 0, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: null, tags: [] },+ ])+ mockGetUsersByIds.mockResolvedValue([])++ const res = await GET(getReq(), ctx)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.posts[0].authorId).toBe("")+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsindex f57c47876..fc0852320 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -64,6 +64,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {messageCount: t.messageCount ?? 0,lastMessageAt: t.lastMessageAt ?? t.createdAt,parent: { authorName, text: preview },+ authorId: t.creatorId ?? "",authorAvatar,tags: t.tags ?? [],preview,diff --git a/src/web/src/app/api/community/friends/pending/route.test.ts b/src/web/src/app/api/community/friends/pending/route.test.tsnew file mode 100644index 000000000..1951301f8--- /dev/null+++ b/src/web/src/app/api/community/friends/pending/route.test.ts@@ -0,0 +1,55 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const listPending = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityFriendship: {+ listPending: (...a: unknown[]) => listPending(...a),+ },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ }+})++import { GET } from "./route"++const req = new NextRequest("http://localhost/api/community/friends/pending")++describe("GET /api/community/friends/pending", () => {+ beforeEach(() => vi.clearAllMocks())++ it("threads the requester/addressee userId through — distinct from the friendship row id — so the avatar seed matches other surfaces", async () => {+ // Regression guard: the pending row's `id` is the friendship row id, not a+ // user id. Seeding <Avatar> off it made the same person render a different+ // shape avatar in the pending list vs. the friends list. The payload must+ // expose `userId` (the joined user.id) for the avatar seed.+ listPending.mockResolvedValue([+ { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "incoming" },+ ])+ const res = await GET(req, {} as never)+ expect(res.status).toBe(200)+ const body = await res.json() as { pending: Array<{ id: string; userId: string }> }+ expect(body.pending[0].id).toBe("fr_1")+ expect(body.pending[0].userId).toBe("u_person")+ })+})diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.tsindex e0e86c47c..c11e9c891 100644--- a/src/web/src/app/api/community/friends/pending/route.ts+++ b/src/web/src/app/api/community/friends/pending/route.ts@@ -9,6 +9,7 @@ export const GET = withAuth(async (_req, ctx) => {const rows = await queries.communityFriendship.listPending(db, ctx.userId)const pending = rows.map((r) => ({id: r.id,+ userId: r.userId,name: r.name,avatar: r.image ?? avatarInitial(r.name),kind: r.kind,diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.tsindex 42b0d0667..31a6bed44 100644--- a/src/web/src/app/api/conversations/[id]/messages/route.ts+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts@@ -1,5 +1,5 @@import { NextRequest } from "next/server";-import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions, truncateTitle } from "@alook/shared"+import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions, truncateTitle, stripMentionTokens } from "@alook/shared"import { getDb } from "@/lib/db"import { nanoid } from "nanoid";import { withAuth } from "@/lib/middleware/auth";@@ -184,7 +184,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}// Auto-title: conditional WHERE title = '' ensures only the first message sets it- queries.conversation.updateConversationTitle(db, id, truncateTitle(content)).catch(() => {});+ queries.conversation.updateConversationTitle(db, id, truncateTitle(stripMentionTokens(content))).catch(() => {});let enrichedContent = content;let mentionContext: Record<string, unknown> | undefined;diff --git a/src/web/src/app/api/studios/check-handles/route.test.ts b/src/web/src/app/api/studios/check-handles/route.test.tsindex 82b0ae524..48e17a049 100644--- a/src/web/src/app/api/studios/check-handles/route.test.ts+++ b/src/web/src/app/api/studios/check-handles/route.test.ts@@ -45,16 +45,30 @@ describe("POST /api/studios/check-handles", () => {mockGetExistingHandles.mockResolvedValue([]);});- it("returns unique handles for each name when none exist", async () => {- const req = makeReq({ names: ["Alice", "Bob"] });+ it("returns unique handles for each member keyed by uid when none exist", async () => {+ const req = makeReq({ members: [{ uid: "a", name: "Alice" }, { uid: "b", name: "Bob" }] });const res = await POST(req, {});const body = await res.json();expect(res.status).toBe(200);expect(body).toHaveLength(2);- expect(body[0].name).toBe("Alice");+ expect(body[0].uid).toBe("a");+ expect(body[0].handle).toBeTruthy();+ expect(body[1].uid).toBe("b");+ expect(body[1].handle).toBeTruthy();+ expect(body[0].handle).not.toBe(body[1].handle);+ });++ it("returns distinct handles for two same-name members keyed by uid", async () => {+ const req = makeReq({ members: [{ uid: "a", name: "Ada" }, { uid: "b", name: "Ada" }] });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toHaveLength(2);+ expect(body[0].uid).toBe("a");+ expect(body[1].uid).toBe("b");expect(body[0].handle).toBeTruthy();- expect(body[1].name).toBe("Bob");expect(body[1].handle).toBeTruthy();expect(body[0].handle).not.toBe(body[1].handle);});@@ -62,7 +76,7 @@ describe("POST /api/studios/check-handles", () => {it("skips handles that already exist in DB", async () => {mockGetExistingHandles.mockResolvedValue(["alice"]);- const req = makeReq({ names: ["Alice"] });+ const req = makeReq({ members: [{ uid: "a", name: "Alice" }] });const res = await POST(req, {});const body = await res.json();@@ -72,7 +86,7 @@ describe("POST /api/studios/check-handles", () => {});it("batch-fetches all candidates in a single call", async () => {- const req = makeReq({ names: ["Alice", "Bob", "Charlie"] });+ const req = makeReq({ members: [{ uid: "a", name: "Alice" }, { uid: "b", name: "Bob" }, { uid: "c", name: "Charlie" }] });await POST(req, {});expect(mockGetExistingHandles).toHaveBeenCalledTimes(1);@@ -80,14 +94,14 @@ describe("POST /api/studios/check-handles", () => {expect(handles.length).toBeGreaterThan(3);});- it("returns 400 if names array is empty", async () => {- const req = makeReq({ names: [] });+ it("returns 400 if members array is empty", async () => {+ const req = makeReq({ members: [] });const res = await POST(req, {});expect(res.status).toBe(400);});- it("returns 400 if names array exceeds 4", async () => {- const req = makeReq({ names: ["a", "b", "c", "d", "e"] });+ it("returns 400 if members array exceeds 4", async () => {+ const req = makeReq({ members: [{ uid: "a", name: "a" }, { uid: "b", name: "b" }, { uid: "c", name: "c" }, { uid: "d", name: "d" }, { uid: "e", name: "e" }] });const res = await POST(req, {});expect(res.status).toBe(400);});@@ -106,7 +120,7 @@ describe("POST /api/studios/check-handles", () => {Promise.resolve(handles));- const req = makeReq({ names: ["Alice"] });+ const req = makeReq({ members: [{ uid: "a", name: "Alice" }] });const res = await POST(req, {});const body = await res.json();diff --git a/src/web/src/app/api/studios/check-handles/route.ts b/src/web/src/app/api/studios/check-handles/route.tsindex 4a9234946..33ffe5cd8 100644--- a/src/web/src/app/api/studios/check-handles/route.ts+++ b/src/web/src/app/api/studios/check-handles/route.ts@@ -7,22 +7,22 @@ import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";export const POST = withAuth(async (req: NextRequest, ctx) => {- let body: { names: string[] };+ let body: { members: { uid: string; name: string }[] };try {- body = await req.json() as { names: string[] };+ body = await req.json() as { members: { uid: string; name: string }[] };} catch {return writeError("invalid request body", 400);}- if (!Array.isArray(body.names) || body.names.length === 0 || body.names.length > 4) {- return writeError("names must be an array of 1-4 strings", 400);+ if (!Array.isArray(body.members) || body.members.length === 0 || body.members.length > 4) {+ return writeError("members must be an array of 1-4 items", 400);}const db = getDb(ctx.env.DB);// Generate all candidate handles upfront- const candidatesPerName: { name: string; candidates: string[] }[] = [];- for (const name of body.names) {+ const candidatesPerName: { uid: string; name: string; candidates: string[] }[] = [];+ for (const { uid, name } of body.members) {const base = name.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);const candidates: string[] = [];if (isValidHandle(base)) candidates.push(base);@@ -31,7 +31,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const candidate = `${base}-${suffix}`.slice(0, 30);if (isValidHandle(candidate)) candidates.push(candidate);}- candidatesPerName.push({ name, candidates });+ candidatesPerName.push({ uid, name, candidates });}// Batch-fetch existence of all candidates in a single query@@ -42,9 +42,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Assign handles using in-memory Set lookupsconst usedHandles = new Set<string>();- const results: { name: string; handle: string }[] = [];+ const results: { uid: string; handle: string }[] = [];- for (const { name, candidates } of candidatesPerName) {+ for (const { uid, name, candidates } of candidatesPerName) {let handle: string | undefined;for (const candidate of candidates) {if (!existingHandles.has(candidate) && !usedHandles.has(candidate)) {@@ -57,7 +57,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {handle = `${base}-${nanoid(6)}`;}usedHandles.add(handle);- results.push({ name, handle });+ results.push({ uid, handle });}return writeJSON(results);diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsxindex b920c96b1..25c09d5cb 100644--- a/src/web/src/app/community/me/[dmId]/page.tsx+++ b/src/web/src/app/community/me/[dmId]/page.tsx@@ -358,7 +358,7 @@ function DmView() {unreadCount={unreadCount}hero={<>- <div className="relative mb-3 w-fit"><Avatar label={dm.avatar} size={64} /></div>+ <div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div><h2 className="text-2xl font-semibold leading-tight">{dm.name}</h2><p className="mt-1 text-sm text-muted-foreground">This is the beginning of your direct message history with <span className="font-medium text-foreground">{dm.name}</span>.</p></>diff --git a/src/web/src/app/community/preview/_mock.ts b/src/web/src/app/community/preview/_mock.tsindex b9f498c9c..dbd5d3495 100644--- a/src/web/src/app/community/preview/_mock.ts+++ b/src/web/src/app/community/preview/_mock.ts@@ -188,17 +188,17 @@ export const THREADS: Thread[] = [export const FORUM_POSTS: Record<string, ForumPost[]> = {"help-forum": [{- id: "fp_smtp", name: "Custom SMTP keeps timing out", authorAvatar: "j", messageCount: 6, lastMessageAt: "2026-06-25T09:50:00Z",+ id: "fp_smtp", name: "Custom SMTP keeps timing out", authorId: "u_jgtech", authorAvatar: "j", messageCount: 6, lastMessageAt: "2026-06-25T09:50:00Z",tags: ["email", "bug"], preview: "I set up a custom SMTP relay but sends time out after ~30s…",parent: { authorName: "jgtech", text: "I set up a custom SMTP relay but sends time out after ~30s. Anyone seen this?" },},{- id: "fp_preset", name: "Share your best agent presets", authorAvatar: "L", messageCount: 23, lastMessageAt: "2026-06-25T09:00:00Z",+ id: "fp_preset", name: "Share your best agent presets", authorId: "u_lindsay", authorAvatar: "L", messageCount: 23, lastMessageAt: "2026-06-25T09:00:00Z",tags: ["showcase"], preview: "Drop your favorite agent setups here — let's build a library.",parent: { authorName: "Lindsay", text: "Drop your favorite agent setups here — let's build a library." },},{- id: "fp_pricing", name: "How do per-agent limits scale?", authorAvatar: "A", messageCount: 4, lastMessageAt: "2026-06-25T07:30:00Z",+ id: "fp_pricing", name: "How do per-agent limits scale?", authorId: "u_azzo", authorAvatar: "A", messageCount: 4, lastMessageAt: "2026-06-25T07:30:00Z",tags: ["question", "billing"], preview: "Trying to understand how message limits work across a team…",parent: { authorName: "Azzo", text: "Trying to understand how message limits work across a team of agents." },},@@ -262,8 +262,8 @@ export const FRIENDS: Friend[] = []export const PENDING: PendingRequest[] = [- { id: "u_jg", name: "jgtech", avatar: "j", kind: "incoming" },- { id: "u_dist", name: "distagon", avatar: "d", kind: "outgoing" },+ { id: "fr_jg", userId: "u_jg", name: "jgtech", avatar: "j", kind: "incoming" },+ { id: "fr_dist", userId: "u_dist", name: "distagon", avatar: "d", kind: "outgoing" },]export const BLOCKED: BlockedUser[] = [diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex c36c33cdf..46ddd4731 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -343,11 +343,11 @@ export default function CommunityPreview() {// friend request actions — move rows between pending/blocked locallyconst friendActions = {- onAccept: (id: string) => { const req = pending.find((r) => r.id === id); setPending((p) => p.filter((r) => r.id !== id)); if (req) setFriendList((p) => [...p, { id: `fr_${req.id}`, name: req.name, avatar: req.avatar, status: "online", sub: "" }]); toast("Friend request accepted") },+ onAccept: (id: string) => { const req = pending.find((r) => r.id === id); setPending((p) => p.filter((r) => r.id !== id)); if (req) setFriendList((p) => [...p, { id: `fr_${req.id}`, userId: req.userId, name: req.name, avatar: req.avatar, status: "online", sub: "" }]); toast("Friend request accepted") },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}`, 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: username.charAt(0).toUpperCase(), 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") },}@@ -372,7 +372,7 @@ export default function CommunityPreview() {const id = `fp_local_${++postSeq}`const now = new Date().toISOString()const created: ForumPost = {- id, name: post.name, authorAvatar: "G", messageCount: 1, lastMessageAt: now,+ id, name: post.name, authorId: "u_gener", authorAvatar: "G", messageCount: 1, lastMessageAt: now,tags: post.tags, preview: post.content || "(no description)",parent: { authorName: "Gener", text: post.content || post.name },}@@ -463,7 +463,7 @@ export default function CommunityPreview() {{...profileProps}hero={<>- <div className="relative mb-3 w-fit"><Avatar label={dm.avatar} size={64} /></div>+ <div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div><h2 className="text-2xl font-semibold leading-tight">{dm.name}</h2><p className="mt-1 text-sm text-muted-foreground">This is the beginning of your direct message history with <span className="font-medium text-foreground">{dm.name}</span>.</p></>@@ -566,7 +566,7 @@ export default function CommunityPreview() {<ServerRail {...railProps} />{sidebar({ bordered: true })}</div>- <UserBar user={{ name: "Gener", avatar: "G" }} {...profileProps} onEditProfile={() => setEditingProfile(true)} />+ <UserBar user={{ id: "u_gener", name: "Gener", avatar: "G" }} {...profileProps} onEditProfile={() => setEditingProfile(true)} /></ResizablePanel><ResizableHandle className="bg-transparent" />@@ -601,7 +601,7 @@ export default function CommunityPreview() {<div className="flex min-h-0 flex-1">{sidebar({ noHeader: false })}</div>- <UserBar user={{ name: "Gener", avatar: "G" }} {...profileProps} onEditProfile={() => setEditingProfile(true)} />+ <UserBar user={{ id: "u_gener", name: "Gener", avatar: "G" }} {...profileProps} onEditProfile={() => setEditingProfile(true)} /></div></>)}diff --git a/src/web/src/components/agent-chat/chat-composer.tsx b/src/web/src/components/agent-chat/chat-composer.tsxindex 2aaa3bd50..a88292c0c 100644--- a/src/web/src/components/agent-chat/chat-composer.tsx+++ b/src/web/src/components/agent-chat/chat-composer.tsx@@ -16,7 +16,7 @@ import { Markdown } from "@tiptap/markdown";import { createPortal } from "react-dom";import { cn } from "@/lib/utils";import { rankMentionAgents } from "@/lib/mention-agents";-import { buildChatMentionExtension } from "@/lib/chat-mention-extension";+import { buildChatMentionExtension, mentionTokensToHtml } from "@/lib/chat-mention-extension";import { decodeChatEntities } from "@/lib/chat-markdown";import { toAlookAddress } from "@alook/shared";import type { Agent, AgentLink } from "@alook/shared";@@ -466,7 +466,7 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(if (!incoming) {editor.commands.clearContent();} else {- editor.commands.setContent((value || "").replaceAll("\n", "<br>"), { emitUpdate: false });+ editor.commands.setContent(mentionTokensToHtml((value || "").replaceAll("\n", "<br>")), { emitUpdate: false });}onEditorStateRef.current(editor.getText(), editor.state.selection.from - 1);}, [value, editor]);diff --git a/src/web/src/components/agent-chat/chat-view-parts.test.ts b/src/web/src/components/agent-chat/chat-view-parts.test.tsnew file mode 100644index 000000000..ad25ab544--- /dev/null+++ b/src/web/src/components/agent-chat/chat-view-parts.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect, vi } from "vitest"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import type { Agent } from "@alook/shared"++const agents: Agent[] = []++vi.mock("@/contexts/agent-context", () => ({+ useAgentContext: () => ({ agents }),+}))++vi.mock("@/components/agent-preview-card", () => ({+ AgentPreviewCard: ({ agent }: { agent: { id: string } }) =>+ createElement("div", { "data-preview-agent-id": agent.id }),+}))++import { MENTION_COMPONENTS } from "./chat-view-parts"++const agent = (id: string, name: string): Agent => ({+ id,+ workspace_id: "ws_1",+ runtime_id: "rt_1",+ name,+ description: "",+ instructions: "",+ runtime_mode: "daemon",+ runtime_config: {},+ status: "active",+ max_concurrent_tasks: 1,+ email_handle: null,+ avatar_url: null,+ visibility: "public",+ owner_id: null,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: "2024-01-01T00:00:00Z",+})++function render(props: Record<string, unknown>): string {+ const Mention = MENTION_COMPONENTS.mention+ return renderToStaticMarkup(createElement(Mention, props))+}++// The popover content (with the preview card carrying the resolved id) is lazy+// under SSR, so the load-bearing signal is the trigger: a resolved agent renders+// a clickable popover trigger, an unresolved one a plain text span.+const isClickable = (html: string) =>+ html.includes("cursor-pointer") && html.includes('data-slot="popover-trigger"')++describe("MentionHighlight", () => {+ it("resolves a same-name agent by data-agent-id (clickable), unaffected by a duplicate name", () => {+ agents.length = 0+ agents.push(agent("ag_ada1", "Ada"), agent("ag_ada2", "Ada"))+ expect(isClickable(render({ "data-agent-id": "ag_ada2", children: "@Ada" }))).toBe(true)+ })++ it("falls back to name only when there is no agent id (historic bare mention)", () => {+ agents.length = 0+ agents.push(agent("ag_bob", "Bob"))+ expect(isClickable(render({ children: "@Bob" }))).toBe(true)+ })++ it("does not name-fallback when an id is present — a gone agent renders non-clickable text", () => {+ agents.length = 0+ // A same-name agent exists under a different id; it must NOT be matched,+ // proving resolution is strictly by id, never by name, when an id is present.+ agents.push(agent("ag_other", "Ada"))+ const html = render({ "data-agent-id": "ag_gone", children: "@Ada" })+ expect(isClickable(html)).toBe(false)+ expect(html).toContain("@Ada")+ })+})diff --git a/src/web/src/components/agent-chat/chat-view-parts.tsx b/src/web/src/components/agent-chat/chat-view-parts.tsxindex 33842713b..6bc588fab 100644--- a/src/web/src/components/agent-chat/chat-view-parts.tsx+++ b/src/web/src/components/agent-chat/chat-view-parts.tsx@@ -21,7 +21,7 @@ function MentionHighlight(| string| undefined;let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;- if (!agent && typeof children === "string") {+ if (!agent && !agentId && typeof children === "string") {const nameToMatch = children.startsWith("@") ? children.slice(1) : children;agent = agents.find((a) => a.name.toLowerCase() === nameToMatch.toLowerCase(),diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsxindex c23d83fc3..cecc50fd9 100644--- a/src/web/src/components/agent-chat/message-list.tsx+++ b/src/web/src/components/agent-chat/message-list.tsx@@ -1,5 +1,5 @@import React, { memo } from "react";-import { parseEmailHandle, type Agent, type Artifact, type Message, type TaskApi as Task, type TaskMessageResponse } from "@alook/shared";+import { parseEmailHandle, stripMentionTokens, type Agent, type Artifact, type Message, type TaskApi as Task, type TaskMessageResponse } from "@alook/shared";import { cn } from "@/lib/utils";import { Button } from "@/components/ui/button";@@ -494,7 +494,7 @@ export const MessageItem = memo(function MessageItem({const [actionSheetOpen, setActionSheetOpen] = React.useState(false);const doCopy = React.useCallback(async () => {- const ok = await copy(msg.content);+ const ok = await copy(stripMentionTokens(msg.content));if (ok) toast.success("Copied to clipboard");else toast.error("Failed to copy");}, [copy, msg.content]);@@ -514,7 +514,7 @@ export const MessageItem = memo(function MessageItem({key: "quote",label: "Quote",icon: <MessageSquareQuote className="size-3.5" />,- onClick: () => onQuote(msg.id, msg.content.slice(0, 50)),+ onClick: () => onQuote(msg.id, stripMentionTokens(msg.content).slice(0, 50)),});}if (onReplyInThread && (msg.role === "assistant" || msg.role === "user")) {diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 81c09b2a6..8b2662b7c 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -119,7 +119,7 @@ export type Msg = {attachments?: Attachment[]reactions?: Reaction[]replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }- thread?: { id: string; name: string; messageCount: number; participants?: string[]; lastReplyAt?: string }+ thread?: { id: string; name: string; messageCount: number; lastReplyAt?: string }}// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s@@ -146,6 +146,7 @@ export type Thread = {}export type ForumPost = Thread & {+ authorId: stringauthorAvatar: stringtags: string[]preview: string@@ -189,6 +190,7 @@ export type Friend = {export type PendingRequest = {id: string+ userId: stringname: stringavatar: stringkind: "incoming" | "outgoing"diff --git a/src/web/src/components/community/avatar.test.ts b/src/web/src/components/community/avatar.test.tsnew file mode 100644index 000000000..bd3019cb1--- /dev/null+++ b/src/web/src/components/community/avatar.test.ts@@ -0,0 +1,55 @@+import { describe, it, expect } from "vitest"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import { Avatar } from "./avatar"++// React's `useId` embeds a per-render counter (`_R_1_`, `_R_2_`, …) into the+// SVG gradient/filter ids, so two independent renders never match byte-for-byte+// even when the derived shape is identical. Strip those so equality checks+// compare the derived avatar, not the render ordinal.+function normalize(html: string): string {+ return html.replace(/_R_[0-9a-z]+_/g, "_ID_")+}++function render(props: Parameters<typeof Avatar>[0]): string {+ return renderToStaticMarkup(createElement(Avatar, props))+}++describe("Avatar seed contract", () => {+ it("derives a shape avatar from the seed", () => {+ const html = render({ label: "Ada", seed: "usr_1" })+ expect(html).toContain("data-avatar-shape")+ expect(html).not.toContain('data-slot="avatar-fallback"')+ })++ it("drops to a single-letter fallback when no seed is given, never synthesising a shape", () => {+ const html = render({ label: "Ada" })+ expect(html).toContain('data-slot="avatar-fallback"')+ expect(html).toContain(">A<")+ expect(html).not.toContain("data-avatar-shape")+ })++ it("treats an empty-string seed the same as no seed (letter fallback)", () => {+ const html = render({ label: "Ada", seed: "" })+ expect(html).toContain('data-slot="avatar-fallback"')+ expect(html).not.toContain("data-avatar-shape")+ })++ it("is stable for the same seed", () => {+ expect(normalize(render({ label: "Ada", seed: "usr_1" }))).toBe(+ normalize(render({ label: "Ada", seed: "usr_1" })),+ )+ })++ it("keeps the same shape when the display name changes but the seed is stable", () => {+ const before = normalize(render({ label: "Ada", seed: "usr_1" }))+ const afterRename = normalize(render({ label: "Adelaide", seed: "usr_1" }))+ expect(afterRename).toBe(before)+ })++ it("produces different shapes for different seeds", () => {+ const a = normalize(render({ label: "Ada", seed: "usr_1" }))+ const b = normalize(render({ label: "Ada", seed: "usr_2" }))+ expect(a).not.toBe(b)+ })+})diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex a3f14608d..67cede8bf 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -19,8 +19,12 @@ function isUrl(s: string | undefined | null): boolean {return !!s && (s.startsWith("http://") || s.startsWith("https://") || s.startsWith("/"))}-export function Avatar({ label, src, size = 40, dim = false, presence, ringColor = "var(--background)" }: {+export function Avatar({ label, seed, src, size = 40, dim = false, presence, ringColor = "var(--background)" }: {label: string+ // Stable id the fallback shape avatar is derived from. Never a display name:+ // shape avatars must not shift on rename. When absent, we drop to a plain+ // single-letter fallback instead of synthesising a shape from `label`.+ seed?: stringsrc?: stringsize?: numberdim?: boolean@@ -35,7 +39,7 @@ export function Avatar({ label, src, size = 40, dim = false, presence, ringColorconst safeLabel = label || "?"const avatarConfig = parseAvatarUrl(safeLabel)const imageUrl = src || (isUrl(safeLabel) ? safeLabel : undefined)- const fallbackConfig = !imageUrl && !avatarConfig ? configFromName(safeLabel) : null+ const fallbackConfig = !imageUrl && !avatarConfig && seed ? configFromName(seed) : nullconst hasGenerated = !!avatarConfig || !!fallbackConfig// Priority: image URL > explicit avatar-config (avatar:{...}) > name-derived@@ -61,9 +65,10 @@ export function Avatar({ label, src, size = 40, dim = false, presence, ringColor<AvatarRenderer config={avatarConfig} size={size} className="size-full" /></span>) : fallbackConfig ? (- // No image, no config — synthesize one from the name so we never fall- // back to the plain letter (matches the design system's shape-avatar- // aesthetic).+ // No image, no picker config — synthesize a shape avatar from the+ // stable `seed` id (matches the design system's shape-avatar+ // aesthetic). Without a seed we skip this and render the plain letter+ // below, so a shape avatar is never derived from a display name.<span className="size-full rounded-full overflow-hidden"><AvatarRenderer config={fallbackConfig} size={size} className="size-full" /></span>diff --git a/src/web/src/components/community/channel-members-dialog.tsx b/src/web/src/components/community/channel-members-dialog.tsxindex 40851f11b..0e373e0ce 100644--- a/src/web/src/components/community/channel-members-dialog.tsx+++ b/src/web/src/components/community/channel-members-dialog.tsx@@ -82,7 +82,7 @@ export function ChannelMembersDialog({) : (members.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 || ""} size={32} />+ <Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} /><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{m.name ?? "Unknown"}@@ -137,7 +137,7 @@ export function ChannelMembersDialog({) : (filteredAddable.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 || ""} size={32} />+ <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><Button size="sm" disabled={addMember.isPending} onClick={() => onAdd(m.userId)}>Adddiff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex a83a49db2..54548d87e 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -36,7 +36,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {onClick={() => onOpenDm?.(d.dmConversationId)}className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent">- <Avatar label={d.otherUserAvatar} size={24} />+ <Avatar label={d.otherUserAvatar} seed={d.otherUserId} size={24} /><span className="min-w-0 flex-1 truncate">{d.otherUserName}</span><ChevronRight className="size-4 shrink-0 text-muted-foreground" /></button>@@ -91,7 +91,7 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {{mentions.map((mn) => (<div key={mn.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent"><button onClick={() => onOpenMention?.(mn)} className="flex min-w-0 flex-1 items-start gap-3 text-left">- <Avatar label={mn.m.authorAvatar ?? "?"} size={36} />+ <Avatar label={mn.m.authorAvatar ?? "?"} seed={mn.m.authorId} size={36} /><div className="min-w-0 flex-1"><div className="text-sm"><span className="font-medium">{mn.m.authorName}</span>{" "}diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex fe34370ef..05feb68f9 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -553,7 +553,7 @@ function MentionRow({ item, selected, showMembersHeader, onSelect }: {}}>{item.kind === "member" ? (- <Avatar label={item.avatar} size={24} presence={item.status} ringColor="var(--popover)" />+ <Avatar label={item.avatar} seed={item.userId} size={24} presence={item.status} ringColor="var(--popover)" />) : (<span className="grid size-6 place-items-center rounded-full bg-primary/15 text-primary">{item.kind === "everyone" ? <Users className="size-3.5" /> : <AtSign className="size-3.5" />}diff --git a/src/web/src/components/community/dm-header.tsx b/src/web/src/components/community/dm-header.tsxindex a9347ea7e..96be6d87d 100644--- a/src/web/src/components/community/dm-header.tsx+++ b/src/web/src/components/community/dm-header.tsx@@ -13,7 +13,7 @@ export function DmHeader({ dm, onBack }: {{onBack && (<Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back"><ChevronLeft className="size-5" /></Button>)}- <Avatar label={dm.avatar} size={24} presence={dm.status} />+ <Avatar label={dm.avatar} seed={dm.userId} size={24} presence={dm.status} /><h1 className="min-w-0 truncate text-base font-medium">{dm.name}{dm.discriminator && (diff --git a/src/web/src/components/community/dm-sidebar.tsx b/src/web/src/components/community/dm-sidebar.tsxindex ac4bfd778..d8bbb3129 100644--- a/src/web/src/components/community/dm-sidebar.tsx+++ b/src/web/src/components/community/dm-sidebar.tsx@@ -77,7 +77,7 @@ export const DmSidebar = memo(function DmSidebar({active ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",].join(" ")}>- <Avatar label={d.avatar} size={32} presence={isBlocked ? undefined : d.status} ringColor="var(--sidebar)" />+ <Avatar label={d.avatar} seed={d.userId} size={32} presence={isBlocked ? undefined : d.status} ringColor="var(--sidebar)" /><div className="min-w-0 flex-1 text-left"><div className="truncate text-sm leading-tight text-foreground">{d.name}</div><div className="truncate text-xs leading-tight text-muted-foreground">{d.preview}</div>diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsxindex fdf307073..ffd8d544c 100644--- a/src/web/src/components/community/edit-profile-dialog.tsx+++ b/src/web/src/components/community/edit-profile-dialog.tsx@@ -199,7 +199,7 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu<TabsContent value="profile"><div className="mx-auto max-w-md space-y-4"><div className="flex items-center gap-4">- <Avatar label={avatar} size={80} />+ <Avatar label={avatar} seed={userId ?? undefined} size={80} /><div><div className="text-sm font-medium">Avatar</div><div className="text-xs text-muted-foreground">PNG, JPG, or WEBP. You'll be able to crop and zoom before saving.</div>diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsxindex fd5f8d87c..a4cff5a1f 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/forum-view.tsx@@ -128,7 +128,7 @@ export function ForumView({className="flex flex-col gap-2 rounded-lg border border-border bg-card p-4 text-left transition-colors hover:border-primary/40 hover:bg-accent/40"><div className="flex items-center gap-2">- <Avatar label={p.authorAvatar} size={24} />+ <Avatar label={p.authorAvatar} seed={p.authorId} size={24} /><span className="text-xs text-muted-foreground" suppressHydrationWarning><span className="font-medium text-foreground">{p.parent.authorName}</span> · {formatRelativeTime(p.lastMessageAt)}</span>diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsxindex d9a687bfa..a5b76c798 100644--- a/src/web/src/components/community/friends-page.tsx+++ b/src/web/src/components/community/friends-page.tsx@@ -101,7 +101,7 @@ export function FriendsPage({/>}>- <Avatar label={f.avatar} size={32} presence={f.status} dim={f.status === "offline"} />+ <Avatar label={f.avatar} seed={f.userId} size={32} presence={f.status} dim={f.status === "offline"} /><div className="min-w-0 flex-1"><div className={`truncate text-sm font-medium ${f.status === "offline" ? "text-muted-foreground" : ""}`}>{f.name}@@ -180,7 +180,7 @@ export function FriendsPage({<div className="flex flex-col gap-1">{blocked.map((b) => (<div key={b.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">- <Avatar label={b.avatar} size={32} dim />+ <Avatar label={b.avatar} seed={b.userId} size={32} dim /><div className="min-w-0 flex-1 truncate text-sm font-medium">{b.name}</div><Button variant="secondary" size="sm" onClick={() => onUnblock?.(b.userId ?? b.id)}>Unblock</Button></div>@@ -223,7 +223,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()} size={28} />+ <Avatar label={u.image ?? u.name.charAt(0).toUpperCase()} 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">@@ -249,7 +249,7 @@ export function FriendsPage({<div className="flex flex-col gap-1">{pending.map((p) => (<div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">- <Avatar label={p.avatar} size={32} />+ <Avatar label={p.avatar} seed={p.userId} size={32} /><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{p.name}</div><div className="text-xs text-muted-foreground">{p.kind === "incoming" ? "Incoming request" : "Outgoing request"}</div>diff --git a/src/web/src/components/community/invite-dialog.tsx b/src/web/src/components/community/invite-dialog.tsxindex f7ff56367..e788cc7f1 100644--- a/src/web/src/components/community/invite-dialog.tsx+++ b/src/web/src/components/community/invite-dialog.tsx@@ -184,7 +184,7 @@ export function InviteDialog({key={f.id}className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">- <Avatar label={f.avatar || f.name} size={32} presence={f.status} ringColor="var(--popover)" />+ <Avatar label={f.avatar || f.name} seed={f.userId} size={32} presence={f.status} ringColor="var(--popover)" /><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{f.name}</div>{hasStatus(f.statusEmoji, f.statusText) && (diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsxindex fc7998ec6..8e77c0ac1 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/member-list.tsx@@ -256,7 +256,7 @@ function MemberRow({/>}>- <Avatar label={mem.avatar} size={32} presence={mem.status} dim={mem.status === "offline"} />+ <Avatar label={mem.avatar} seed={mem.userId} size={32} presence={mem.status} dim={mem.status === "offline"} /><div className="min-w-0 flex-1 text-left"><div className={`truncate text-sm leading-tight ${mem.status === "offline" ? "text-muted-foreground" : ""}`}>{mem.name}diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex c6d65f22e..96433bcd9 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -11,6 +11,7 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/componimport { Avatar } from "./avatar"import { MessageBody } from "./message-body"import { EmojiPickerPopover } from "./emoji-picker"+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import { NumberTicker } from "@/components/ui/number-ticker"import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"import { formatMessageTime } from "./format-time"@@ -126,7 +127,7 @@ export function Message({<div className="w-10 shrink-0" />) : (<button onClick={(e) => onOpenProfile?.(m.authorName ?? "", e, undefined, m.authorId)} className="shrink-0 self-start">- <Avatar label={m.authorAvatar ?? "?"} size={40} />+ <Avatar label={m.authorAvatar ?? "?"} seed={m.authorId} size={40} /></button>)}<div className="min-w-0 flex-1">@@ -244,25 +245,38 @@ export function Message({{m.reactions && (<div className="mt-2 flex flex-wrap gap-1">- {m.reactions.map((r, i) => (- <button- key={i}- onClick={() => onToggleReaction?.(r.emoji)}- title={r.userIds?.length ? r.userIds.map((id) => resolveUserName?.(id) ?? id).join(", ") : undefined}- className={[- "flex h-6 items-center gap-1 rounded-full px-2 text-sm",- r.me ? "border border-primary/50 bg-accent" : "bg-secondary",- ].join(" ")}- >- <span>{r.emoji}</span>- <NumberTicker value={r.count} className="text-xs text-muted-foreground" />- </button>- ))}- <EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>- <button className="grid h-6 w-7 place-items-center rounded-full bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction">- <SmilePlus className="size-4" />- </button>- </EmojiPickerPopover>+ {m.reactions.map((r, i) => {+ const names = r.userIds?.length+ ? r.userIds.map((id) => resolveUserName?.(id) ?? id).join(", ")+ : undefined+ const chip = (+ <button+ onClick={() => onToggleReaction?.(r.emoji)}+ className={[+ "flex h-6 items-center gap-1 rounded-md px-2 text-sm",+ r.me ? "border border-primary/50 bg-accent" : "bg-secondary",+ ].join(" ")}+ >+ <span>{r.emoji}</span>+ <NumberTicker value={r.count} className="text-xs text-muted-foreground" />+ </button>+ )+ if (!names) return <div key={i}>{chip}</div>+ return (+ <Tooltip key={i}>+ <TooltipTrigger render={chip} />+ <TooltipContent>Reacted by {names}</TooltipContent>+ </Tooltip>+ )+ })}+ <Tooltip>+ <EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>+ <TooltipTrigger render={<button className="grid h-6 w-7 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction" />}>+ <SmilePlus className="size-4" />+ </TooltipTrigger>+ </EmojiPickerPopover>+ <TooltipContent>Add reaction</TooltipContent>+ </Tooltip></div>)}@@ -271,15 +285,7 @@ export function Message({onClick={() => onOpenThread(m.thread!.id)}className="group/thread mt-2 flex items-center gap-2 rounded-md px-2 py-1 text-sm hover:bg-accent/60">- {m.thread.participants && m.thread.participants.length > 0 ? (- <div className="flex -space-x-2">- {m.thread.participants.slice(0, 3).map((p, i) => (- <Avatar key={i} label={p} size={20} />- ))}- </div>- ) : (- <MessagesSquare className="size-4 text-primary" />- )}+ <MessagesSquare className="size-4 text-primary" /><span className="font-medium text-primary">{m.thread.messageCount} {m.thread.messageCount === 1 ? "reply" : "replies"}</span>diff --git a/src/web/src/components/community/profile-card.test.ts b/src/web/src/components/community/profile-card.test.tsindex cc78aab8e..fa9c4201b 100644--- a/src/web/src/components/community/profile-card.test.ts+++ b/src/web/src/components/community/profile-card.test.ts@@ -24,4 +24,21 @@ describe("generateGradient", () => {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)+ })})diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsxindex c38ac9d26..70169eb74 100644--- a/src/web/src/components/community/profile-card.tsx+++ b/src/web/src/components/community/profile-card.tsx@@ -9,13 +9,15 @@ import { StatusEditor, hasStatus } from "./status-editor"import type { Profile } from "./_types"import type { Breakpoint } from "@/hooks/use-mobile"-// Deterministic, on-brand banner gradient. Hue is constrained to the warm band+// 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(name: string): string {+export function generateGradient(seed: string): string {let hash = 0- for (let i = 0; i < name.length; i++) {- hash = name.charCodeAt(i) + ((hash << 5) - hash)+ 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)@@ -46,7 +48,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdasetMsg("")mobile ? onClose() : close()}- const gradient = generateGradient(data.name)+ const gradient = generateGradient(data.userId ?? data.name)const card = (<>{/* banner */}@@ -64,7 +66,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaproportion the 64px avatar had at `-mt-8`. */}<div className="relative"><div className="rounded-full ring-[5px] ring-popover">- <Avatar label={data.avatar} size={77} presence={data.presence} ringColor="var(--popover)" />+ <Avatar label={data.avatar} seed={data.userId} size={77} presence={data.presence} ringColor="var(--popover)" /></div>{/* Status sits on the same row as the presence dot, just to itsright, instead of floating over the avatar's corner. The dotdiff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsxindex a1645aba6..1ea26d0b5 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/server-settings.tsx@@ -265,7 +265,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad><div className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-2"><button onClick={(e) => onOpenProfile?.(m.name, e, undefined, m.userId)} className="shrink-0">- <Avatar label={m.avatar} size={32} presence={m.status} ringColor="var(--card)" />+ <Avatar label={m.avatar} seed={m.userId} size={32} presence={m.status} ringColor="var(--card)" /></button><div className="min-w-0 flex-1"><div className="truncate text-[15px] font-medium">{m.name}</div>diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 000eb0c41..41d417669 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -636,7 +636,7 @@ export function ShellFrame({</ResizablePanelGroup></AppSurface><div className="absolute bottom-0 left-0 z-10" style={{ width: sidebarW + 56, marginLeft: -56 }}>- <UserBar user={{ name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} />+ <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} /></div></div>{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} />}@@ -655,7 +655,7 @@ export function ShellFrame({<ServerRail {...railProps} bottomInset={60} /><div className="flex min-h-0 flex-1 flex-col bg-sidebar"><div className="flex min-h-0 flex-1">{sidebar({ noHeader: false })}</div>- <UserBar user={{ name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} />+ <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} /></div></>)}diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsxindex 5812440f9..e3df2567d 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/thread-opener.tsx@@ -69,7 +69,7 @@ export function ThreadOpener({onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}className="shrink-0 self-start">- <Avatar label={avatarLabel} size={40} />+ <Avatar label={avatarLabel} seed={msg.authorId} size={40} /></button><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2">diff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/user-bar.tsxindex 05790dc8b..2f9c16582 100644--- a/src/web/src/components/community/user-bar.tsx+++ b/src/web/src/components/community/user-bar.tsx@@ -7,7 +7,7 @@ import { Avatar } from "./avatar"import type { OpenProfile } from "./_types"export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {- user: { name: string; avatar: string }+ user: { id: string; name: string; avatar: string }onOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: React.ReactNode@@ -23,7 +23,7 @@ export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread }}function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {- user: { name: string; avatar: string }+ user: { id: string; name: string; avatar: string }onOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: React.ReactNode@@ -32,7 +32,7 @@ function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {return (<div className="flex flex-1 items-center gap-2"><button onClick={(e) => onOpenProfile?.(user.name, e)} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <Avatar label={user.avatar} size={28} presence="online" ringColor="var(--muted)" />+ <Avatar label={user.avatar} seed={user.id} size={28} presence="online" ringColor="var(--muted)" /></button><button onClick={(e) => onOpenProfile?.(user.name, e)} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"><div className="truncate text-sm font-medium leading-tight">{user.name}</div>diff --git a/src/web/src/components/studio-onboarding/scenario-presets.ts b/src/web/src/components/studio-onboarding/scenario-presets.tsindex e2b8eec15..f7aa57955 100644--- a/src/web/src/components/studio-onboarding/scenario-presets.ts+++ b/src/web/src/components/studio-onboarding/scenario-presets.ts@@ -204,11 +204,12 @@ export const SCENARIO_PRESETS: ScenarioPreset[] = [];import { uniqueNamesGenerator, names } from "unique-names-generator";+import { nanoid } from "nanoid";import { randomConfig, serializeAvatarConfig } from "@/components/avatar";-export function shuffleMembers(count: number): { name: string; avatarUrl: string }[] {+export function shuffleMembers(count: number): { uid: string; name: string; avatarUrl: string }[] {const used = new Set<string>();- const result: { name: string; avatarUrl: string }[] = [];+ const result: { uid: string; name: string; avatarUrl: string }[] = [];for (let i = 0; i < count; i++) {let name: string;let attempts = 0;@@ -218,6 +219,7 @@ export function shuffleMembers(count: number): { name: string; avatarUrl: string} while (used.has(name) && attempts < 100);used.add(name);result.push({+ uid: nanoid(),name,avatarUrl: serializeAvatarConfig(randomConfig()),});diff --git a/src/web/src/components/studio-onboarding/team-preview.tsx b/src/web/src/components/studio-onboarding/team-preview.tsxindex 78c25f1b6..ad078cb43 100644--- a/src/web/src/components/studio-onboarding/team-preview.tsx+++ b/src/web/src/components/studio-onboarding/team-preview.tsx@@ -17,6 +17,7 @@ import type { AgentRuntime as Runtime } from "@alook/shared";import type { MemberRole } from "./scenario-presets";export interface TeamMember {+ uid: string;name: string;role: MemberRole;description: string;diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.tsindex bc437f668..d5c64e261 100644--- a/src/web/src/hooks/community/mutations/friends.test.ts+++ b/src/web/src/hooks/community/mutations/friends.test.ts@@ -82,7 +82,7 @@ describe("useAcceptFriendRequest — rollback", () => {capturedQc.setQueryData(communityKeys.friends(), {friends: [],blocked: [],- pending: [{ id: "f_1", name: "n", avatar: "N", kind: "incoming" }],+ pending: [{ id: "f_1", userId: "u_1", name: "n", avatar: "N", kind: "incoming" }],})apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await load()diff --git a/src/web/src/hooks/community/use-friends.test.ts b/src/web/src/hooks/community/use-friends.test.tsindex f155094c2..c8eb5bce8 100644--- a/src/web/src/hooks/community/use-friends.test.ts+++ b/src/web/src/hooks/community/use-friends.test.ts@@ -20,7 +20,7 @@ describe("useFriends / friendsQueryFn", () => {}).mockImplementationOnce(async (url: string) => {expect(url).toBe("/api/community/friends/pending")- return { pending: [{ id: "p_1", name: "n", avatar: "a", kind: "incoming" }] }+ return { pending: [{ id: "p_1", userId: "u_1", name: "n", avatar: "a", kind: "incoming" }] }})const { friendsQueryFn } = await import("./use-friends")diff --git a/src/web/src/lib/chat-mention-extension.test.ts b/src/web/src/lib/chat-mention-extension.test.tsindex 767168fcb..bbdd12de5 100644--- a/src/web/src/lib/chat-mention-extension.test.ts+++ b/src/web/src/lib/chat-mention-extension.test.ts@@ -1,13 +1,12 @@import { describe, it, expect } from "vitest";import { MarkdownManager } from "@tiptap/markdown";import StarterKit from "@tiptap/starter-kit";-import { buildChatMentionExtension } from "./chat-mention-extension";+import { buildChatMentionExtension, mentionTokensToHtml } from "./chat-mention-extension";/**- * TODO #0 acceptance (highest-risk assumption): a Mention node must serialize- * to byte-exact `@Name` in markdown — the wire format the backend already- * expects. This guards against a TipTap upgrade silently regressing the- * serializer back to `[@ id=... label=...]` or adding `\@` escaping.+ * A Mention node serializes to a `@[Name](agentId)` token in markdown — the+ * wire format the backend parses by id. This guards against a TipTap upgrade+ * silently regressing the serializer or adding `\@` escaping.*/// StarterKit is a bundle; the MarkdownManager wants flat extensions.@@ -47,25 +46,23 @@ const mention = (id: string, label: string) => ({const text = (t: string) => ({ type: "text", text: t });describe("chat mention markdown serialization", () => {- it("serializes a mention to byte-exact @Name", () => {+ it("serializes a mention to a @[Name](id) token", () => {expect(serialize(para(text("hi "), mention("a1", "Alice"), text(" there")))).toBe(- "hi @Alice there",+ "hi @[Alice](a1) there",);});it("does not escape the @ (no \\@)", () => {const md = serialize(para(mention("a1", "Alice")));- expect(md).toBe("@Alice");+ expect(md).toBe("@[Alice](a1)");expect(md).not.toContain("\\@");});- it("falls back to id when label is null/undefined", () => {- // renderMarkdown uses `label ?? id`, so a null label (never the case for- // real agent mentions, but defensive) serializes to the id.+ it("falls back to id in the label slot when label is null/undefined", () => {const md = serialize(para({ type: "mention", attrs: { id: "agent-7", label: null } }),);- expect(md).toBe("@agent-7");+ expect(md).toBe("@[agent-7](agent-7)");});it("serializes multiple mentions in one line", () => {@@ -73,6 +70,25 @@ describe("chat mention markdown serialization", () => {serialize(para(mention("a1", "Alice"), text(" and "), mention("b2", "Bob"), text(" hi")),),- ).toBe("@Alice and @Bob hi");+ ).toBe("@[Alice](a1) and @[Bob](b2) hi");+ });+});++describe("mentionTokensToHtml (draft restore)", () => {+ it("converts a token to mention HTML the parseHTML step can rebuild", () => {+ expect(mentionTokensToHtml("Hey @[Ada](ag_ada1) do this")).toBe(+ 'Hey <span data-type="mention" data-id="ag_ada1" data-label="Ada"></span> do this',+ );+ });++ it("converts multiple tokens", () => {+ expect(mentionTokensToHtml("@[Ada](ag_1) and @[Bob](ag_2)")).toBe(+ '<span data-type="mention" data-id="ag_1" data-label="Ada"></span> and <span data-type="mention" data-id="ag_2" data-label="Bob"></span>',+ );+ });++ it("leaves a normal markdown link untouched", () => {+ const link = "see [docs](https://example.com/a.b:c)";+ expect(mentionTokensToHtml(link)).toBe(link);});});diff --git a/src/web/src/lib/chat-mention-extension.ts b/src/web/src/lib/chat-mention-extension.tsindex 69f9a9963..87330d06c 100644--- a/src/web/src/lib/chat-mention-extension.ts+++ b/src/web/src/lib/chat-mention-extension.ts@@ -1,13 +1,30 @@import Mention from "@tiptap/extension-mention";+import { MENTION_TOKEN_RE } from "@alook/shared";++function escapeAttr(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll('"', """)+ .replaceAll("<", "<")+ .replaceAll(">", ">");+}++export function mentionTokensToHtml(value: string): string {+ return value.replace(+ MENTION_TOKEN_RE,+ (_m, label: string, id: string) =>+ `<span data-type="mention" data-id="${escapeAttr(id)}" data-label="${escapeAttr(label)}"></span>`,+ );+}/**- * Mention configured to serialize to byte-exact `@Name` in markdown.+ * Mention configured to serialize to a `@[Name](agentId)` token in markdown.** `@tiptap/markdown` reads `renderMarkdown` off the extension config via- * getExtensionField (keyed on the node name "mention"). Spike-verified: without- * it the manager emits `[@ id="..." label="..."]`; with it (and no escaping)- * `getMarkdown()` of "hi @Alice" === "hi @Alice". `renderText` keeps copy /- * getText() in sync. See plans/chat-input-tiptap-migration.md TODO #0.+ * getExtensionField (keyed on the node name "mention"). The token carries the+ * stable agent id so downstream parsing (highlight-mentions, prompt-parser)+ * resolves the exact agent by id instead of guessing by display name.+ * `renderText` keeps copy / getText() emitting the human-readable `@Name`.** These two fields aren't in TipTap's NodeConfig types (the markdown plugin* reads them dynamically), so the config is cast to the extend param type.@@ -18,6 +35,8 @@ export function buildChatMentionExtension() {return Mention.extend({markdownName: "mention",renderMarkdown: (node: { attrs: { id: string; label?: string | null } }) =>+ `@[${node.attrs.label ?? node.attrs.id}](${node.attrs.id})`,+ renderText: (node: { attrs: { id: string; label?: string | null } }) =>`@${node.attrs.label ?? node.attrs.id}`,} as MentionExtendConfig);}diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex c34bfc3cf..44add6a89 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -103,6 +103,21 @@ describe("rankMentionItems", () => {expect(items[3].id).toBe("m_mal")})+ it("carries the stable userId separately from the membership row id — so the popover avatar seed matches every other surface", () => {+ // Regression: the mention popover seeded its <Avatar> from the membership+ // row id while every other surface (member list, DMs, profile card) seeds+ // from the user id, so the same person rendered a different shape avatar in+ // the popover. The mention item must expose `userId` for the avatar seed,+ // while `id` stays the membership row id (used for #0042 disambiguation and+ // mention serialization). Fixture deliberately keeps id !== userId.+ const memberRoster: Member[] = [+ { id: "m_row", userId: "u_person", name: "Alice", avatar: "A", status: "online", sub: "", role: "member" },+ ]+ const item = rankMentionItems(memberRoster, "channel", "al").find((i) => i.kind === "member")!+ expect(item.id).toBe("m_row")+ expect((item as { userId: string }).userId).toBe("u_person")+ })+it("ranks substring members after prefix members", () => {const memberRoster: Member[] = [{ id: "m_al", userId: "u_al", name: "Alberta", avatar: "A", status: "online", sub: "", role: "member" },diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex 74451cfcc..e7cd1592f 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -7,6 +7,7 @@ export type MentionContext = "channel" | "thread" | "dm"type MemberMentionItem = {kind: "member"id: string+ userId: stringlabel: stringavatar: stringstatus: "online" | "offline"@@ -52,6 +53,7 @@ export function rankMentionItems(const item: MemberMentionItem = {kind: "member",id: m.id,+ userId: m.userId,label: m.name,avatar: m.avatar,status: m.status,diff --git a/src/web/src/lib/highlight-mentions.test.ts b/src/web/src/lib/highlight-mentions.test.tsindex db4fdee7a..2c8b2398b 100644--- a/src/web/src/lib/highlight-mentions.test.ts+++ b/src/web/src/lib/highlight-mentions.test.ts@@ -69,4 +69,39 @@ describe("highlightMentions", () => {expect(result).toContain('data-agent-id="ag_bob"')expect(result).toBe('<mention data-agent-id="ag_alice">@Alice</mention> talk to <mention data-agent-id="ag_bob">@Bob</mention>')})++ it("wraps a token by its agent id", () => {+ const result = highlightMentions("Hey @[Ada](ag_ada1) do this", [agent("Ada")])+ expect(result).toBe('Hey <mention data-agent-id="ag_ada1">@Ada</mention> do this')+ })++ it("locks a token to its id even with two same-name agents", () => {+ const agents = [+ { ...agent("Ada"), id: "ag_ada1" },+ { ...agent("Ada"), id: "ag_ada2" },+ ]+ const result = highlightMentions("@[Ada](ag_ada2)", agents)+ expect(result).toBe('<mention data-agent-id="ag_ada2">@Ada</mention>')+ })++ it("wraps a token even when agents is empty (no markdown link leak)", () => {+ const result = highlightMentions("Hey @[Ada](ag_ada1) do this", [])+ expect(result).toBe('Hey <mention data-agent-id="ag_ada1">@Ada</mention> do this')+ expect(result).not.toContain("](ag_ada1)")+ })++ it("wraps a token whose agent is unknown (deleted) — still not a markdown link", () => {+ const result = highlightMentions("Hey @[Ada](ag_gone) do this", [agent("TestBot")])+ expect(result).toBe('Hey <mention data-agent-id="ag_gone">@Ada</mention> do this')+ })++ it("handles a token mixed with a bare-name mention", () => {+ const result = highlightMentions("@[Ada](ag_ada1) and @Bob", [agent("Bob", "bob")])+ expect(result).toBe('<mention data-agent-id="ag_ada1">@Ada</mention> and <mention data-agent-id="ag_bob">@Bob</mention>')+ })++ it("does not treat a normal markdown link as a mention token", () => {+ const link = "see [docs](https://example.com/a.b:c) now"+ expect(highlightMentions(link, [agent("docs")])).toBe(link)+ })})diff --git a/src/web/src/lib/highlight-mentions.ts b/src/web/src/lib/highlight-mentions.tsindex c39e28c48..8a7fe59af 100644--- a/src/web/src/lib/highlight-mentions.ts+++ b/src/web/src/lib/highlight-mentions.ts@@ -1,4 +1,5 @@import type { Agent } from "@alook/shared"+import { MENTION_TOKEN_RE } from "@alook/shared"function isTrigger(text: string, atIndex: number): boolean {if (atIndex === 0) return true@@ -15,6 +16,27 @@ function isBoundary(text: string, endIndex: number): boolean {}export function highlightMentions(content: string, agents: Agent[]): string {+ if (!content || !content.includes("@")) return content++ // Token pass — id-based, independent of the agents array so a raw+ // `@[Name](agentId)` token never survives into <Streamdown> (where it would+ // render as a markdown link to the id). Text between tokens still runs+ // through the bare-name pass for backward compatibility with historic /+ // externally-sourced `@Name` mentions.+ const re = new RegExp(MENTION_TOKEN_RE.source, "g")+ let result = ""+ let last = 0+ let m: RegExpExecArray | null+ while ((m = re.exec(content)) !== null) {+ result += highlightBareNames(content.slice(last, m.index), agents)+ result += `<mention data-agent-id="${m[2]}">@${m[1]}</mention>`+ last = re.lastIndex+ }+ result += highlightBareNames(content.slice(last), agents)+ return result+}++function highlightBareNames(content: string, agents: Agent[]): string {if (!content || agents.length === 0 || !content.includes("@")) return contentconst sorted = agents.slice().sort((a, b) => b.name.length - a.name.length)