Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): preserve mention boundaries and real profiles (#987)

Gener33b3b3aadab9
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 760cc840f..10f26790f 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -822,7 +822,7 @@ export {
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 { extractMentionedUserIds, MENTION_TYPES, isMentionType, MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary } from "./utils/community-mentions";
export type { MentionCandidate, MentionType } from "./utils/community-mentions";
export { parseReleaseVersion, releaseVersionGte, semverGte } from "./semver";
export type { ReleaseVersion } from "./semver";
diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.ts
index 76923e6e4..f17b96338 100644
--- a/src/shared/src/utils/community-mentions.ts
+++ b/src/shared/src/utils/community-mentions.ts
@@ -39,7 +39,13 @@ export function isMentionType(value: unknown): value is MentionType {
return value === "everyone";
}
-const ID_CHAR_RE = /[\p{L}\p{N}_-]/u;
+export const MENTION_IDENTIFIER_CHARACTERS = /[\p{L}\p{N}_-]/u.source;
+const ID_CHAR_RE = new RegExp(MENTION_IDENTIFIER_CHARACTERS, "u");
+const MENTION_START_RE = new RegExp(`${MENTION_IDENTIFIER_CHARACTERS}$`, "u");
+
+export function isMentionStartBoundary(prefix: string): boolean {
+ return !MENTION_START_RE.test(prefix);
+}
function isBoundaryChar(ch: string | undefined): boolean {
if (ch === undefined) return true;
@@ -73,7 +79,7 @@ export function extractMentionedUserIds(
const at = content.indexOf("@", i);
if (at === -1) break;
// The character before "@" must be a boundary (or start of string).
- if (at > 0 && !isBoundaryChar(content[at - 1])) {
+ if (!isMentionStartBoundary(content.slice(0, at))) {
i = at + 1;
continue;
}
diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.ts
index 014115e04..b38b260ce 100644
--- a/src/shared/test/utils/community-mentions.test.ts
+++ b/src/shared/test/utils/community-mentions.test.ts
@@ -50,6 +50,10 @@ describe("extractMentionedUserIds", () => {
expect(extractMentionedUserIds("contact me@Alice#0001.com", ROSTER)).toEqual([]);
});
+ it.each(["mail", "回复", "é", "𠮷", "_", "-", "9"])("rejects an identifier prefix before a tagged mention: %s", (prefix) => {
+ expect(extractMentionedUserIds(`${prefix}@Alice#0001`, ROSTER)).toEqual([]);
+ });
+
it("handles unicode names via handle", () => {
expect(extractMentionedUserIds("早 @李雷#0005 好", ROSTER)).toEqual(["u5"]);
});
diff --git a/src/web/blog/AGENTS.md b/src/web/blog/AGENTS.md
index 685fb2035..8fd410b74 100644
--- a/src/web/blog/AGENTS.md
+++ b/src/web/blog/AGENTS.md
@@ -1,6 +1,6 @@
<!-- BEGIN:nextjs-agent-rules -->
-# This is NOT the Next.js you know
+## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index 3689524a6..524ffa7e5 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
currentUser: {
id: "self",
name: "Self",
+ discriminator: "0001",
avatar: "S",
avatarVersion: 0,
@@ -42,7 +43,7 @@ vi.mock("sonner", () => ({ toast: mocks.toast }))
vi.mock("@/lib/api/client", () => ({
ACCOUNT_DELETED_SIGN_IN_PATH: "/sign-in?account_deleted=1",
toastApiError: mocks.toastApiError,
- apiFetch: (path: string, options: { method?: string; body?: string }) => Promise.resolve(options?.method === "PATCH" ? mocks.updateProfile(JSON.parse(options.body!)) : mocks.query(path, options)).then((data) => ({ id: path.split("/").at(-2), name: "Remote", discriminator: "0001", image: null, avatarVersion: 0, bannerColor: null, aboutMe: "", mutualServers: 0, statusEmoji: null, statusText: null, kind: "human", ...data })),
+ apiFetch: (path: string, options: { method?: string; body?: string }) => Promise.resolve(options?.method === "PATCH" ? mocks.updateProfile(JSON.parse(options.body!)) : mocks.query(path, options)).then((data) => path.startsWith("/api/community/users/search?") ? { users: [], ...data } : ({ id: path.split("/").at(-2), name: "Remote", discriminator: "0001", image: null, avatarVersion: 0, bannerColor: null, aboutMe: "", mutualServers: 0, statusEmoji: null, statusText: null, kind: "human", ...data })),
}))
vi.mock("@/lib/community/image-crop", () => ({ validateIconSourceFile: mocks.validate }))
vi.mock("@/contexts/community/current-user", () => ({
@@ -68,10 +69,10 @@ vi.mock("@/stores/community/message-stream", async (importOriginal) => ({ ...awa
}),
}))
vi.mock("@/hooks/community/use-friends", () => ({
- useFriends: () => ({ data: { ids: ["remote"] }, friends: [{ id: "remote", userId: "remote", name: "Remote", avatar: "R", sub: "seed" }], pending: [], blocked: [] }),
+ useFriends: () => ({ data: { ids: ["remote"] }, friends: [{ id: "remote", userId: "remote", name: "Remote", discriminator: "0001", avatar: "R", sub: "seed" }], pending: [], blocked: [] }),
}))
vi.mock("@/hooks/community/use-server-members", () => ({
- useServerMembers: () => ({ members: [{ id: "remote", userId: "remote", name: "Remote", avatar: "R", sub: "seed" }] }),
+ useServerMembers: () => ({ members: [{ id: "remote", userId: "remote", name: "Remote", discriminator: "0001", avatar: "R", sub: "seed" }] }),
}))
vi.mock("@/hooks/community/mutations", async () => ({
...await vi.importActual<typeof import("@/hooks/community/mutations")>("@/hooks/community/mutations"),
@@ -81,21 +82,9 @@ vi.mock("@/hooks/community/mutations", async () => ({
vi.mock("@/hooks/community/use-dm-message-sender", () => ({
useDmMessageSender: () => ({ accept: mocks.acceptDm }),
}))
-vi.mock("@/components/community/social/profile-lookup", () => ({
- resolveProfileServerId: (_view: string, id?: string) => id,
+vi.mock("@/components/community/social/profile-lookup", async (original) => ({
+ ...await original<typeof import("@/components/community/social/profile-lookup")>(),
resolveProfileContextLabel: () => "Server member",
- resolveProfileTarget: (members: Array<{ userId: string; name: string }>, _friends: unknown, target: { name: string; userId?: string }) =>
- members.find((member) => member.userId === target.userId || member.name === target.name),
- resolveProfileUserId: (member?: { userId: string }, target?: string) => member?.userId ?? target,
- buildSelfProfile: (user: { id: string; name: string; avatar: string }) => ({
- name: user.name,
- userId: user.id,
- avatar: user.avatar,
- about: "About",
- mutual: 0,
- presence: "online",
- identity: { kind: "human" },
- }),
}))
vi.mock("@/lib/query-persister", () => ({ clearPersistedCache: mocks.clearCache }))
vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({
@@ -241,19 +230,72 @@ describe("useShellProfileController", () => {
expect(mocks.query).not.toHaveBeenCalled()
})
- it("does not infer self from matching name or discriminator", async () => {
+ it("does not infer self from a matching name with a different discriminator", async () => {
const hook = await renderController()
await act(async () => hook.current.openProfile(
"Self",
{ clientX: 6, clientY: 7 } as never,
- "0001",
+ "9999",
))
- expect(hook.current.profile?.data.name).toBe("Self")
- expect(hook.current.profile?.data.userId).toBeUndefined()
+ expect(hook.current.profile).toBeNull()
+ expect(mocks.query).toHaveBeenCalledWith("/api/community/users/search?q=Self%239999", expect.anything())
+ })
+
+ it("resolves the authenticated complete self handle without using the viewer-excluding search", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.openProfile("Self", { clientX: 2, clientY: 3 } as never, "0001"))
+ expect(hook.current.profile?.data.userId).toBe("self")
expect(mocks.query).not.toHaveBeenCalled()
})
+ it("does not create a literal card for an unresolved tagged target", async () => {
+ mocks.query.mockResolvedValue({ users: [] })
+ const hook = await renderController()
+ await act(async () => hook.current.openProfile("已交 /Alook", { clientX: 2, clientY: 3 } as never, "5620"))
+ await waitFor(() => expect(hook.queryClient.getQueryState(["community", "user-search", "已交 /Alook#5620"])?.status).toBe("success"))
+ expect(hook.current.profile).toBeNull()
+ expect(mocks.query).toHaveBeenCalledWith(`/api/community/users/search?q=${encodeURIComponent("已交 /Alook#5620")}`, expect.anything())
+ expect(mocks.query.mock.calls.some(([path]) => path.endsWith("/profile"))).toBe(false)
+ })
+
+ it("opens a real uncached handle only after lookup and then hydrates by its canonical id", async () => {
+ const lookup = deferred<{ users: Array<{ id: string; name: string; discriminator: string; image: null; avatarVersion: number }> }>()
+ mocks.query.mockImplementation((path: string) => path.includes("/search?") ? lookup.promise : Promise.resolve({ name: "John Doe", discriminator: "0042" }))
+ const hook = await renderController()
+ await act(async () => hook.current.openProfile("John Doe", { clientX: 2, clientY: 3 } as never, "0042"))
+ expect(hook.current.profile).toBeNull()
+ expect(mocks.query).toHaveBeenCalledWith("/api/community/users/search?q=John%20Doe%230042", expect.anything())
+ await act(async () => { lookup.resolve({ users: [{ id: "outside", name: "John Doe", discriminator: "0042", image: null, avatarVersion: 0 }] }) })
+ await waitFor(() => expect(hook.current.profile?.data.userId).toBe("outside"))
+ await waitFor(() => expect(mocks.query).toHaveBeenCalledWith("/api/community/users/outside/profile", expect.anything()))
+ expect(hook.current.profile?.data).not.toHaveProperty("name")
+ expect(hook.registry.collections.profiles.get("outside")?.name).toBe("John Doe")
+ })
+
+ it("queries a mismatched local tag instead of opening another same-name account", async () => {
+ mocks.query.mockImplementation((path: string) => Promise.resolve(path.includes("/search?")
+ ? { users: [{ id: "other", name: "Remote", discriminator: "9999", image: null, avatarVersion: 0 }] }
+ : { name: "Remote", discriminator: "9999" }))
+ const hook = await renderController()
+ await act(async () => hook.current.openProfile("Remote", { clientX: 2, clientY: 3 } as never, "9999"))
+ await waitFor(() => expect(hook.current.profile?.data.userId).toBe("other"))
+ expect(mocks.query.mock.calls.some(([path]) => path === "/api/community/users/remote/profile")).toBe(false)
+ })
+
+ it.each(["close", "another target"])("keeps a late handle response from reopening or replacing %s", async (action) => {
+ const lookup = deferred<{ users: Array<{ id: string; name: string; discriminator: string; image: null; avatarVersion: number }> }>()
+ mocks.query.mockImplementation((path: string) => path.includes("/search?") ? lookup.promise : Promise.resolve({}))
+ const hook = await renderController()
+ await act(async () => hook.current.openProfile("Outside", { clientX: 2, clientY: 3 } as never, "0042"))
+ expect(hook.current.profile).toBeNull()
+ await act(async () => action === "close"
+ ? hook.current.closeProfile()
+ : hook.current.openProfile("Remote", { clientX: 4, clientY: 5 } as never, undefined, "remote"))
+ await act(async () => { lookup.resolve({ users: [{ id: "outside", name: "Outside", discriminator: "0042", image: null, avatarVersion: 0 }] }); await lookup.promise })
+ expect(hook.current.profile?.data.userId ?? null).toBe(action === "close" ? null : "remote")
+ })
+
it("opens a remote seed before fetch and hydrates only card state", async () => {
const response = deferred<{
id: string
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index de25b405e..b68c023ce 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -10,11 +10,14 @@ import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import { usePathname, useSearchParams } from "next/navigation"
import { readBillingReturn } from "@/hooks/community/use-billing"
-import { parseNameAndTag } from "@alook/shared"
+import { formatHandle, parseNameAndTag } from "@alook/shared"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"
+import { apiFetchProfiles } from "@/lib/community/profile-seed"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { avatarInitial } from "@/lib/community/avatar"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"
import type {
@@ -117,7 +120,25 @@ export function useShellProfileController({
task.release()
}
}, [finishAvatarCrop, pendingAvatarCrop])
- const profileUserId = profileTarget?.data.userId
+ const lookupHandle = !profileTarget?.data.userId && profileTarget?.data.name && profileTarget.data.discriminator
+ ? formatHandle(profileTarget.data.name, profileTarget.data.discriminator)
+ : ""
+ const lookup = useQuery({
+ queryKey: ["community", "user-search", lookupHandle],
+ enabled: !!lookupHandle,
+ retry: false,
+ queryFn: async ({ signal, client }) => {
+ const data = await apiFetchProfiles<{
+ users: Array<{ id: string; name: string; discriminator: string; image: string | null; avatarVersion: number }>
+ }>(`/api/community/users/search?q=${encodeURIComponent(lookupHandle)}`, (response) => response.users.map((user) => ({
+ id: user.id,
+ identityAbout: { name: user.name, discriminator: user.discriminator },
+ avatar: { avatar: user.image ?? avatarInitial(user.name), avatarVersion: user.avatarVersion },
+ })), { signal }, getCommunityDbRegistry(client))
+ return data.users.map((user) => user.id)
+ },
+ })
+ const profileUserId = profileTarget?.data.userId ?? (lookupHandle ? lookup.data?.[0] : undefined)
const canMessage = !!profileUserId && profileUserId !== currentUser.id
&& friendsQuery.data !== undefined
&& !blocked.some((user) => user.userId === profileUserId)
@@ -125,10 +146,10 @@ export function useShellProfileController({
const canonicalProfile = useCanonicalCommunityProfile(profileUserId)
useQuery({ queryKey: communityKeys.profile(profileUserId ?? "__none__"), enabled: !!profileUserId && profileUserId !== currentUser.id,
queryFn: userProfileQueryFn(profileUserId ?? ""), staleTime: PROFILE_STALE_TIME_MS })
- const profile = useMemo<ShellProfileState | null>(() => profileTarget ? {
+ const profile = useMemo<ShellProfileState | null>(() => profileTarget && profileUserId ? {
...profileTarget,
data: {
- ...profileTarget.data,
+ userId: profileUserId,
contextLabel: resolveProfileContextLabel(profileServerId, members.find((member) => member.userId === profileUserId)),
mutual: canonicalProfile?.mutualServers ?? 0,
identity: canonicalProfile?.kind === "bot" && canonicalProfile.ownerUserId && canonicalProfile.ownerHandle
@@ -144,7 +165,9 @@ export function useShellProfileController({
discriminator?: string,
targetUserId?: string,
) => {
- const isSelf = !!targetUserId && targetUserId === currentUser.id
+ const isSelf = targetUserId
+ ? targetUserId === currentUser.id
+ : !!discriminator && name === currentUser.name && discriminator === currentUser.discriminator
if (isSelf) {
const selfMember = profileServerId
? members.find((member) => member.userId === currentUser.id)
@@ -177,7 +200,7 @@ export function useShellProfileController({
x,
y,
})
- }, [currentUser.id, friends, members, profileServerId, setProfile])
+ }, [currentUser.discriminator, currentUser.id, currentUser.name, friends, members, profileServerId, setProfile])
const openProfile = useCallback((
name: string,
diff --git a/src/web/src/components/community/social/profile-lookup.test.ts b/src/web/src/components/community/social/profile-lookup.test.ts
index 5b358e35e..7943ff30d 100644
--- a/src/web/src/components/community/social/profile-lookup.test.ts
+++ b/src/web/src/components/community/social/profile-lookup.test.ts
@@ -23,6 +23,13 @@ function member(overrides: Partial<Member>): Member {
}
describe("resolveProfileTarget", () => {
+ it("does not replace an unknown tag with a same-name member", () => {
+ expect(resolveProfileTarget([member({ name: "Gus", discriminator: "0042" })], [], { name: "Gus", discriminator: "0099" })).toBeUndefined()
+ })
+
+ it("does not replace an explicit user id with a same-name member", () => {
+ expect(resolveProfileTarget([member({ name: "Gus", userId: "other" })], [], { name: "Gus", userId: "missing" })).toBeUndefined()
+ })
it("resolves the exact member by userId when two members share a name — regression for the bug where profile cards collapsed to the first name match", () => {
const a = member({ id: "mem_a", userId: "user_a", name: "435669237", discriminator: "7892" })
const b = member({ id: "mem_b", userId: "user_b", name: "435669237", discriminator: "3759" })
diff --git a/src/web/src/components/community/social/profile-lookup.ts b/src/web/src/components/community/social/profile-lookup.ts
index 07db3a40a..b07ebfcbe 100644
--- a/src/web/src/components/community/social/profile-lookup.ts
+++ b/src/web/src/components/community/social/profile-lookup.ts
@@ -74,14 +74,10 @@ export function resolveProfileTarget(
target: { name: string; discriminator?: string; userId?: string },
): Member | Friend | undefined {
const { name, discriminator, userId } = target
- return (userId
- ? (members ?? []).find((m) => m.userId === userId)
+ if (userId) return (members ?? []).find((m) => m.userId === userId)
?? (friends ?? []).find((f) => f.userId === userId)
- : undefined)
- ?? (discriminator
- ? (members ?? []).find((m) => m.name === name && m.discriminator === discriminator)
- ?? (friends ?? []).find((f) => f.name === name && f.discriminator === discriminator)
- : undefined)
- ?? (members ?? []).find((m) => m.name === name)
+ if (discriminator) return (members ?? []).find((m) => m.name === name && m.discriminator === discriminator)
+ ?? (friends ?? []).find((f) => f.name === name && f.discriminator === discriminator)
+ return (members ?? []).find((m) => m.name === name)
?? (friends ?? []).find((f) => f.name === name)
}
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index c816dadee..1bebea208 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -40,6 +40,21 @@ describe("CLI prompt ref examples — tokenizer contract", () => {
})
describe("chatSyntaxPlugin — mention", () => {
+ it("keeps a bare at-sign in prose from swallowing a following channel ref", () => {
+ const children = paragraphChildren(parse("DM回复取消自动@已交 /Alook#5620/fix/#213"))
+ expect(children.some((child) => child.type === "mention")).toBe(false)
+ expect(children.find((child) => child.type === "channelRef")).toMatchObject({ value: "/Alook#5620/fix/#213" })
+ })
+
+ it.each(["mail", "回复", "é", "𠮷", "_", "-", "9"])("rejects an identifier prefix before a tagged mention: %s", (prefix) => {
+ expect(paragraphChildren(parse(`${prefix}@Alice#0001`)).some((child) => child.type === "mention")).toBe(false)
+ })
+
+ it.each(["John Doe", "李雷", "𠮷🎉", "*[Alice](https://example.com)*"])("retains a legal name after a boundary: %s", (name) => {
+ expect(paragraphChildren(parse(`(@${name}#0042)`)).find((child) => child.type === "mention"))
+ .toMatchObject({ value: `@${name}`, discriminator: "0042" })
+ })
+
it("recognizes a canonical handle before HTML-looking name text is split into sibling nodes", () => {
const children = paragraphChildren(parse("hi @<b>Alice</b>#0042 there"))
expect(children.map((child) => child.type)).toEqual(["text", "mention", "text"])
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index e891fa0a4..d2a36f9f3 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -6,6 +6,7 @@ import type { Element } from "hast"
import { codes } from "micromark-util-symbol"
import type { Construct, Effects, Extension, State, TokenizeContext } from "micromark-util-types"
import type { Plugin } from "unified"
+import { MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary } from "@alook/shared"
import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
import type { SpoilerNode } from "./spoiler-syntax"
@@ -125,8 +126,10 @@ const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}]
// digits (variable-width disc); the digit run is greedy so a widened 5+-digit
// tag matches in full. A hand-typed bare `@Alice` (no tag) is intentionally
// NOT a mention — it stays text.
-const MENTION_RE =
- /(?<!\/)(?:@everyone(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4,})/gu
+const MENTION_RE = new RegExp(
+ String.raw`(?<!/|${MENTION_IDENTIFIER_CHARACTERS})(?:@everyone(?!${MENTION_IDENTIFIER_CHARACTERS})|@[^@#\n\r]*[^@#\n\r\s]#\d{4,})`,
+ "gu",
+)
/** mdast node produced by `@name`/`@name#0042`/`@everyone`. */
export interface MentionNode {
@@ -172,7 +175,16 @@ declare module "micromark-util-types" {
function memberMentionSyntax(): Extension {
const construct: Construct = {
name: "memberMention",
- previous: (code) => code !== codes.slash,
+ previous(code) {
+ if (code === codes.slash) return false
+ if (code === null || code < 0) return true
+ let previous = String.fromCodePoint(code)
+ if (code >= 0xDC00 && code <= 0xDFFF) {
+ const tail = this.events.at(-1)?.[1]
+ if (tail) previous = this.sliceSerialize({ start: tail.start, end: this.now() })
+ }
+ return isMentionStartBoundary(previous)
+ },
tokenize: tokenizeMemberMention,
}
return { text: { [codes.atSign]: construct } }