Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): clickable channel refs, gradient server icons, prompt docs

Gus11ff10694cee
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f26b52d00..b4a7b8ffd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -348,6 +348,9 @@ importers:
'@tiptap/markdown':
specifier: ^3.27.1
version: 3.27.1(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
+ '@tiptap/pm':
+ specifier: ^3.27.1
+ version: 3.27.1
'@tiptap/react':
specifier: ^3.27.1
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index 4ae95309e..95e7f9272 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -73,4 +73,14 @@ describe("buildCliSystemPrompt", () => {
expect(prompt).toContain("alook");
expect(prompt).toContain("Alook");
});
+
+ it("tells the agent that channel refs also render as clickable links when written inline in message text", () => {
+ // Contract check, not prose pinning (see file-level comment above): both
+ // lifecycle kinds share `messagingSection()`, so a single stable phrase
+ // covering "refs work inline, not just as --target" is enough — no need
+ // to duplicate per lifecycle kind.
+ const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ expect(prompt).toContain("also work inline");
+ expect(prompt).toContain("clickable channel");
+ });
});
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 5394c1cc8..1ecbd3245 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -132,7 +132,7 @@ function messagingSection(): string {
"",
"- Send a reply — two options depending on length:",
` - Short: \`${CLI} message send --target <ref> --text "brief reply"\``,
- ` - Long: write body to a file, then \`${CLI} message send --target <ref> --file /path/to/msg.txt\``,
+ ` - Long&Complicated: write body to a tmp file, then \`${CLI} message send --target <ref> --file /path/to/msg.md\``,
"- Address your reply to where the message came from.",
"",
"### Channel refs & addressing",
@@ -150,6 +150,12 @@ function messagingSection(): string {
"Use the `channel` field from received messages as the `--target` when replying.",
"To reply in a thread, use the thread ref (`/<server>/<channel>/#N`).",
"",
+ "These same refs also work inline, inside a message's `--text`/`--file` body — not just",
+ "as `--target`. Write `/<server>/<channel>` or `/<server>/<channel>/#N` anywhere in your",
+ "message text (preceded by a space or at the start) and it renders as a clickable channel",
+ "or thread link for human readers in the web client. Use this to cross-reference other",
+ "channels/threads naturally instead of describing them in prose.",
+ "",
"### Message shape",
"",
`When you call \`${CLI} inbox pull\`, you receive messages as JSON objects:`,
@@ -225,7 +231,7 @@ function channelAwarenessSection(): string {
"",
"- Reply where the message came from — same channel or thread.",
"- Post results in the channel that owns the topic.",
- "- When uncertain, check the channel's stated description or history.",
+ "- When uncertain, check the channel's history or just DM the relevant friends.",
].join("\n");
}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 97b6b74f5..6984cad8b 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -461,6 +461,10 @@ export async function getMessage(db: Database, messageId: string) {
// No ordering guarantee — callers build a Map<id, row> and hydrate by id.
// Unknown ids silently drop out via the natural WHERE id IN (...) semantics.
+//
+// `seq` is included so callers resolving a thread's parent message (e.g. the
+// threads route, plan community-channel-ref.md §3) can surface the parent's
+// per-channel sequence without a separate lookup.
export async function getMessagesByIds(db: Database, ids: string[]) {
if (ids.length === 0) return [];
const rows = await db
@@ -476,6 +480,7 @@ export async function getMessagesByIds(db: Database, ids: string[]) {
createdAt: communityMessage.createdAt,
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
+ seq: communityMessage.seq,
authorName: user.name,
authorEmail: user.email,
authorImage: user.image,
diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.ts
index cb3abc007..10c21e93b 100644
--- a/src/shared/src/db/queries/community/server.ts
+++ b/src/shared/src/db/queries/community/server.ts
@@ -36,7 +36,7 @@ export async function createServer(
.insert(communityCategory)
.values({
serverId: server!.id,
- name: "Text Channels",
+ name: "All",
position: 0,
})
.returning();
diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.ts
index f727c0608..00bcf5aae 100644
--- a/src/shared/test/queries/server.test.ts
+++ b/src/shared/test/queries/server.test.ts
@@ -141,7 +141,7 @@ describe("createServer", () => {
expect(result.ownerMember.userImage).toBeNull();
});
- it("seeds category 'Text Channels', channel 'general' (text), and exactly one owner member row with railOrder=0", async () => {
+ it("seeds category 'All', channel 'general' (text), and exactly one owner member row with railOrder=0", async () => {
const { db, insertCalls } = createDbMock({
insertReturns: [[serverRow], [categoryRow], [], [memberRow]],
selectReturns: [[{ name: "Alice" }]],
@@ -167,7 +167,7 @@ describe("createServer", () => {
expect(insertCalls[1].table).toBe(communityCategory);
expect(insertCalls[1].values).toMatchObject({
serverId: "srv_1",
- name: "Text Channels",
+ name: "All",
position: 0,
});
diff --git a/src/web/package.json b/src/web/package.json
index cd43273f5..1ec6d153a 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -49,6 +49,7 @@
"@tiptap/extension-text-align": "^3.27.1",
"@tiptap/extension-underline": "^3.27.1",
"@tiptap/markdown": "^3.27.1",
+ "@tiptap/pm": "^3.27.1",
"@tiptap/react": "^3.27.1",
"@tiptap/starter-kit": "^3.27.1",
"@types/mdx": "^2.0.14",
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
index 92fdfc634..240a1a973 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
@@ -116,6 +116,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
content: "parent-content",
authorName: "Alice",
authorEmail: "[email protected]",
+ seq: 7,
},
])
mockGetUsersByIds.mockResolvedValue([
@@ -128,13 +129,18 @@ describe("GET /api/community/channels/[id]/threads", () => {
const res = await GET(req(), ctx)
expect(res.status).toBe(200)
- const body = await res.json() as { threads: Array<{ id: string; parent: { authorName: string; text: string } }> }
+ const body = await res.json() as { threads: Array<{ id: string; parent: { authorName: string; text: string }; parentSeq?: number }> }
expect(body.threads).toEqual([
- { id: "t-A", name: "A", kind: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", parent: { authorName: "Alice", text: "parent-content" } },
+ { id: "t-A", name: "A", kind: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", parent: { authorName: "Alice", text: "parent-content" }, parentSeq: 7 },
{ id: "t-B", name: "B", kind: "thread", messageCount: 2, lastMessageAt: "2026-06-30T00:00:00.000Z", parent: { authorName: "Bob", text: "first-in-B" } },
{ id: "t-C", name: "C", kind: "thread", messageCount: 1, lastMessageAt: "2026-06-30T00:00:00.000Z", parent: { authorName: "Carol", text: "" } },
])
+ // t-B/t-C were created from a creator (no parent message) — parentSeq
+ // must be omitted, not `undefined`-valued, so a naive `"parentSeq" in
+ // thread` check on the client can't be fooled by an explicit undefined.
+ expect(Object.keys(body.threads[1])).not.toContain("parentSeq")
+ expect(Object.keys(body.threads[2])).not.toContain("parentSeq")
expect(mockGetMessagesByIds).toHaveBeenCalledTimes(1)
expect(mockGetUsersByIds).toHaveBeenCalledTimes(1)
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.ts
index 6e5d98d68..ea9c47638 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts
@@ -54,6 +54,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const threads = childChannels.map((t) => {
let parent = { authorName: "", text: "" }
+ let parentSeq: number | undefined
if (t.parentMessageId) {
const msg = parentMessageMap.get(t.parentMessageId)
if (msg) {
@@ -61,6 +62,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
authorName: msg.authorName,
text: (msg.content ?? "").slice(0, 100),
}
+ parentSeq = msg.seq
}
} else if (t.creatorId) {
const creator = creatorMap.get(t.creatorId)
@@ -77,6 +79,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
messageCount: t.messageCount ?? 0,
lastMessageAt: t.lastMessageAt ?? t.createdAt,
parent,
+ ...(parentSeq !== undefined ? { parentSeq } : {}),
}
})
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index 7ab36c465..ecdb994a5 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -109,6 +109,19 @@ function ChannelView() {
const isForum = channelInServer?.type === "forum"
const isChildChannel = !channelInServer && !!currentServer?.categories
+ // `/`-autocomplete candidates for both Composer call sites below — single
+ // server, so no directory hook needed here (see `me/[dmId]/page.tsx` for
+ // the cross-server DM case).
+ const channelRefCandidates = useMemo(() => {
+ const allChannels = currentServer?.categories?.flatMap((c) => c.channels) ?? []
+ return allChannels.map((ch) => ({
+ id: ch.id,
+ name: ch.name,
+ serverId,
+ serverName: currentServer?.name ?? "",
+ }))
+ }, [currentServer, serverId])
+
const messagesQuery = useMessages(channelId)
const { messages, isLoading: messagesLoading } = messagesQuery
@@ -526,6 +539,7 @@ function ChannelView() {
context="thread"
members={composerMembers}
onSearchMembers={membersHook.searchMembers}
+ channelRefCandidates={channelRefCandidates}
onSend={sendMessage}
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
@@ -636,6 +650,7 @@ function ChannelView() {
context="channel"
members={composerMembers}
onSearchMembers={membersHook.searchMembers}
+ channelRefCandidates={channelRefCandidates}
onSend={sendMessage}
onCreateThread={() => setCreatingThread(true)}
onTyping={handleTyping}
diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsx
index 672766a86..252547f92 100644
--- a/src/web/src/app/community/me/[dmId]/page.tsx
+++ b/src/web/src/app/community/me/[dmId]/page.tsx
@@ -18,6 +18,7 @@ import { useOnlineUserIds } from "@/stores/community/ws"
import { useDms } from "@/hooks/community/use-dms"
import { useFriends } from "@/hooks/community/use-friends"
import { useDmMessages } from "@/hooks/community/use-messages"
+import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import {
useSendDmMessage,
useToggleReactionApi,
@@ -66,6 +67,17 @@ function DmView() {
messages,
isLoading: messagesLoading,
} = useDmMessages(dmId)
+ // DM composer has no "current server" — flatten every member server's
+ // channels into one cross-server candidate list so a `/`-ref can be
+ // dropped into a DM (see plan community-channel-ref.md §6).
+ const { directory: channelRefDirectory } = useChannelRefDirectory()
+ const channelRefCandidates = useMemo(
+ () =>
+ channelRefDirectory.flatMap((s) =>
+ s.channels.map((ch) => ({ id: ch.id, name: ch.name, serverId: s.id, serverName: s.name })),
+ ),
+ [channelRefDirectory],
+ )
const typingUsers = useCommunityStore((s) => s.typingUsers)
const sendDmMessage = useSendDmMessage()
const toggleReaction = useToggleReactionApi()
@@ -232,6 +244,7 @@ function DmView() {
// no candidate pool needed. Passing [] keeps the Member[] typing
// honest without shimming friends into a member shape.
members={[]}
+ channelRefCandidates={channelRefCandidates}
onSend={sendDmMsg}
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 29c830e43..70f576745 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -1401,6 +1401,15 @@
text-decoration-color: var(--primary-foreground);
}
+/* Channel-ref chip (composer `/`-autocomplete) — same underline treatment
+ as `.mention-highlight` so the two in-editor pills read consistently. */
+.channel-ref-highlight {
+ text-decoration: underline;
+ text-decoration-color: var(--foreground);
+ text-underline-offset: 2px;
+ text-decoration-thickness: 1.5px;
+}
+
/* User bubble markdown — inherit text color from primary-foreground parent */
.markdown-user,
.markdown-user code:not(pre code) {
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index b0d0661d8..1f00ec090 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -124,6 +124,10 @@ export type Thread = {
messageCount: number
lastMessageAt: string
parent: { authorName: string; text: string }
+ // The root message's per-channel seq, when the thread was created from a
+ // parent message (omitted for threads with no parent, e.g. forum posts).
+ // Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.
+ parentSeq?: number
}
export type ForumPost = Thread & {
diff --git a/src/web/src/components/community/channel-ref-pill.test.ts b/src/web/src/components/community/channel-ref-pill.test.ts
new file mode 100644
index 000000000..15673f257
--- /dev/null
+++ b/src/web/src/components/community/channel-ref-pill.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect } from "vitest"
+import { describeChannelRefPillView } from "./channel-ref-pill"
+import type { ResolvedChannelRef } from "@/lib/community/channel-ref"
+
+const server = { id: "srv_1", name: "Studio" }
+const channel = { id: "chn_1", name: "general" }
+
+function resolved(overrides: Partial<ResolvedChannelRef> = {}): ResolvedChannelRef {
+ return { server, channel, ...overrides }
+}
+
+describe("describeChannelRefPillView", () => {
+ it("resolved: null, directoryLoading: true → muted", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1",
+ resolved: null,
+ directoryLoading: true,
+ thread: null,
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({ kind: "muted", label: "/srv_1/chn_1" })
+ })
+
+ it("resolved: null, directoryLoading: false → plain with text equal to the original ref", () => {
+ const view = describeChannelRefPillView({
+ ref: "/usr/bin/ls",
+ resolved: null,
+ directoryLoading: false,
+ thread: null,
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({ kind: "plain", text: "/usr/bin/ls" })
+ })
+
+ it("resolved present, no threadRootSeq → pill, no serverPrefix when resolved.server.id === currentServerId", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1",
+ resolved: resolved(),
+ directoryLoading: false,
+ thread: null,
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({
+ kind: "pill",
+ label: "general",
+ serverPrefix: undefined,
+ href: { serverId: "srv_1", channelId: "chn_1" },
+ })
+ })
+
+ it("resolved.server.id !== currentServerId → pill with serverPrefix set to the server's name", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1",
+ resolved: resolved(),
+ directoryLoading: false,
+ thread: null,
+ currentServerId: "srv_other",
+ })
+ expect(view).toEqual({
+ kind: "pill",
+ label: "general",
+ serverPrefix: "Studio",
+ href: { serverId: "srv_1", channelId: "chn_1" },
+ })
+ })
+
+ it("threadRootSeq set, thread: undefined (loading) → muted", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1/#42",
+ resolved: resolved({ threadRootSeq: 42 }),
+ directoryLoading: false,
+ thread: undefined,
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({ kind: "muted", label: "general" })
+ })
+
+ it("threadRootSeq set, thread found → pill targeting the thread id, label = thread name", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1/#42",
+ resolved: resolved({ threadRootSeq: 42 }),
+ directoryLoading: false,
+ thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({
+ kind: "pill",
+ label: "Thread about X",
+ serverPrefix: undefined,
+ href: { serverId: "srv_1", channelId: "thr_1" },
+ })
+ })
+
+ it("threadRootSeq set, thread: null (loaded, no match) → pill targeting the base channel — no invented thread link, but carries threadSuffix for the caller to render as trailing plain text", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1/#42",
+ resolved: resolved({ threadRootSeq: 42 }),
+ directoryLoading: false,
+ thread: null,
+ currentServerId: "srv_1",
+ })
+ expect(view).toEqual({
+ kind: "pill",
+ label: "general",
+ serverPrefix: undefined,
+ href: { serverId: "srv_1", channelId: "chn_1" },
+ threadSuffix: 42,
+ })
+ })
+
+ it("cross-server thread-degrade case still sets serverPrefix and threadSuffix", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1/#42",
+ resolved: resolved({ threadRootSeq: 42 }),
+ directoryLoading: false,
+ thread: null,
+ currentServerId: "srv_other",
+ })
+ expect(view.kind).toBe("pill")
+ expect((view as { serverPrefix?: string; threadSuffix?: number }).serverPrefix).toBe("Studio")
+ expect((view as { serverPrefix?: string; threadSuffix?: number }).threadSuffix).toBe(42)
+ })
+
+ it("resolved thread found → pill does NOT carry threadSuffix (suffix is only for the degrade case)", () => {
+ const view = describeChannelRefPillView({
+ ref: "/srv_1/chn_1/#42",
+ resolved: resolved({ threadRootSeq: 42 }),
+ directoryLoading: false,
+ thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
+ currentServerId: "srv_1",
+ })
+ expect((view as { threadSuffix?: number }).threadSuffix).toBeUndefined()
+ })
+})
diff --git a/src/web/src/components/community/channel-ref-pill.tsx b/src/web/src/components/community/channel-ref-pill.tsx
new file mode 100644
index 000000000..6db08bbe8
--- /dev/null
+++ b/src/web/src/components/community/channel-ref-pill.tsx
@@ -0,0 +1,144 @@
+"use client"
+
+import type React from "react"
+import { useRouter } from "next/navigation"
+import { ChannelPill } from "./inline-marks"
+import { resolveChannelRefBase, type ResolvedChannelRef } from "@/lib/community/channel-ref"
+import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
+import { useThreads } from "@/hooks/community/use-channel-panels"
+import { useCommunityStore } from "@/stores/community"
+
+export type ChannelRefPillView =
+ | { kind: "plain"; text: string }
+ | { kind: "muted"; label: string }
+ | {
+ kind: "pill"
+ label: string
+ serverPrefix?: string
+ href: { serverId: string; channelId: string }
+ // Set only in the "thread ref resolved to a channel but not a matching
+ // thread" degrade case — the caller renders this as plain text right
+ // after the pill, since a `/#N` suffix is never part of the clickable
+ // target (see decision table below).
+ threadSuffix?: number
+ }
+
+/**
+ * Pure — takes already-computed inputs, decides what to render. No hooks.
+ * This repo has no jsdom/testing-library, so a component that calls
+ * `useChannelRefDirectory`/`useThreads`/`useCommunityStore`/`useRouter`
+ * directly can't be unit-tested the way this function can — mirrors the
+ * precedent set by `use-server-members.ts`, which extracts its reducers so
+ * hookless logic stays testable and leaves the hook wiring itself untested.
+ *
+ * Decision table:
+ * - `resolved === null` (still loading OR genuinely unresolved) →
+ * `directoryLoading ? "muted" : "plain"` (plain text = `ref`, untouched
+ * fallback — never a broken-looking pill).
+ * - `resolved` present, no `threadRootSeq` → `"pill"`, label =
+ * `resolved.channel.name`, `serverPrefix` set only when the ref points at
+ * a different server than the one currently open.
+ * - `resolved` present, `threadRootSeq` set:
+ * - `thread === undefined` (still loading) → `"muted"` (base channel label).
+ * - `thread` found (`parentSeq` match) → `"pill"` targeting the thread id,
+ * label = thread name.
+ * - `thread === null` (loaded, no match) → `"pill"` targeting the base
+ * channel — graceful degrade. The caller is responsible for appending
+ * the literal `/#{threadRootSeq}` as separate plain trailing text next
+ * to the pill, since that suffix is never part of the clickable target.
+ */
+export function describeChannelRefPillView(args: {
+ ref: string
+ resolved: ResolvedChannelRef | null
+ directoryLoading: boolean
+ thread: { id: string; name: string; parentSeq?: number } | null | undefined
+ currentServerId: string | null
+}): ChannelRefPillView {
+ const { ref, resolved, directoryLoading, thread, currentServerId } = args
+
+ if (!resolved) {
+ return directoryLoading ? { kind: "muted", label: ref } : { kind: "plain", text: ref }
+ }
+
+ const serverPrefix = resolved.server.id !== currentServerId ? resolved.server.name : undefined
+
+ if (resolved.threadRootSeq === undefined) {
+ return {
+ kind: "pill",
+ label: resolved.channel.name,
+ serverPrefix,
+ href: { serverId: resolved.server.id, channelId: resolved.channel.id },
+ }
+ }
+
+ if (thread === undefined) {
+ return { kind: "muted", label: resolved.channel.name }
+ }
+
+ if (thread === null) {
+ return {
+ kind: "pill",
+ label: resolved.channel.name,
+ serverPrefix,
+ href: { serverId: resolved.server.id, channelId: resolved.channel.id },
+ threadSuffix: resolved.threadRootSeq,
+ }
+ }
+
+ return {
+ kind: "pill",
+ label: thread.name,
+ serverPrefix,
+ href: { serverId: resolved.server.id, channelId: thread.id },
+ }
+}
+
+/**
+ * Connected shell — thin. Reads its text content as the raw ref, calls the
+ * hooks, hands everything to `describeChannelRefPillView`, and renders
+ * `ChannelPill`/plain text from the returned descriptor.
+ *
+ * Hook-call rule (not negotiable — a common Rules of Hooks trap):
+ * `useThreads` is called UNCONDITIONALLY on every render, relying on the
+ * hook's own `enabled: !!channelId` gate for the "don't fetch" case — never
+ * wrap the `useThreads(...)` call itself in an `if`/early-return.
+ */
+export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
+ const ref = String(children ?? "")
+ const router = useRouter()
+ const currentServerId = useCommunityStore((s) => s.currentServerId)
+ const { directory, isLoading: directoryLoading } = useChannelRefDirectory()
+
+ const resolved = resolveChannelRefBase(directory, ref)
+
+ const threadChannelId = resolved?.threadRootSeq !== undefined ? resolved.channel.id : null
+ const { threads, isLoading: threadsLoading } = useThreads(threadChannelId)
+ const thread = !threadChannelId
+ ? null
+ : threadsLoading
+ ? undefined
+ : threads.find((t) => t.parentSeq === resolved?.threadRootSeq) ?? null
+
+ const view = describeChannelRefPillView({
+ ref,
+ resolved,
+ directoryLoading,
+ thread,
+ currentServerId,
+ })
+
+ if (view.kind === "plain") return <>{view.text}</>
+ if (view.kind === "muted") return <ChannelPill muted>{view.label}</ChannelPill>
+
+ return (
+ <>
+ <ChannelPill
+ serverPrefix={view.serverPrefix}
+ onClick={() => router.push(`/community/channels/${view.href.serverId}/${view.href.channelId}`)}
+ >
+ {view.label}
+ </ChannelPill>
+ {view.threadSuffix !== undefined && <span className="text-muted-foreground">/#{view.threadSuffix}</span>}
+ </>
+ )
+}
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index ec6077f95..00433528c 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -10,6 +10,7 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuIte
import { Skeleton } from "@/components/ui/skeleton"
import { useFileAttachments } from "@/hooks/use-file-attachments"
import { Avatar } from "./avatar"
+import { ChannelIcon } from "./channel-icon"
import { EmojiPickerPopover } from "./emoji-picker"
import type { Member } from "./_types"
import type { MentionType } from "@alook/shared"
@@ -22,13 +23,20 @@ import {
type MentionItem,
type MentionPopupState,
} from "@/lib/community/mention-extension"
+import {
+ buildCommunityChannelRefExtension,
+ EMPTY_CHANNEL_REF_STATE,
+ rankChannelRefItems,
+ type ChannelRefCandidate,
+ type ChannelRefPopupState,
+} from "@/lib/community/channel-ref-extension"
// Composer — plain-text TipTap editor with a chat-style @-mention popover.
// Users type raw markdown which MessageBody/Streamdown renders on display.
// Enter sends, Shift+Enter adds a newline; while the mention popover is open
// Enter/Tab/Arrow keys drive selection instead. @everyone / @here are virtual
// candidates in channel + thread contexts (hidden in DM).
-export function Composer({ channel, context, members, onSearchMembers, onSend, onCreateThread, onTyping, replyingTo, onCancelReply, autoFocus = false }: {
+export function Composer({ channel, context, members, onSearchMembers, channelRefCandidates = [], onSend, onCreateThread, onTyping, replyingTo, onCancelReply, autoFocus = false }: {
channel: string
context: MentionContext
members: Member[]
@@ -37,6 +45,11 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
// and hits `/servers/:id/members/search`. Undefined for surfaces that don't
// have a server roster (DM composer).
onSearchMembers?: (query: string) => void
+ // `/`-autocomplete candidates. Single-server list for channel/thread
+ // composers; cross-server flattened list (via `useChannelRefDirectory()`)
+ // for DM composers. Always provided by the caller — empty array is fine,
+ // the popup just shows nothing on `/`.
+ channelRefCandidates?: ChannelRefCandidate[]
onSend?: (markdown: string, attachments?: File[], mentionType?: MentionType) => void
onCreateThread?: () => void
onTyping?: () => void
@@ -65,6 +78,10 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
const mentionPopupRef = useRef(mentionPopup)
useEffect(() => { mentionPopupRef.current = mentionPopup }, [mentionPopup])
+ const [channelRefPopup, setChannelRefPopup] = useState<ChannelRefPopupState>(EMPTY_CHANNEL_REF_STATE)
+ const channelRefPopupRef = useRef(channelRefPopup)
+ useEffect(() => { channelRefPopupRef.current = channelRefPopup }, [channelRefPopup])
+
// The mention extension is built ONCE — its suggestion callbacks read refs
// at runtime so live `members`/`context` updates are visible without
// rebuilding the editor (which would reset its state).
@@ -97,6 +114,21 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
}),
)
+ // Same "built once, refs read at runtime" pattern as the mention extension.
+ const channelRefCandidatesRef = useRef(channelRefCandidates)
+ const channelRefQueryRef = useRef<string>("")
+ useEffect(() => { channelRefCandidatesRef.current = channelRefCandidates }, [channelRefCandidates])
+
+ // eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not render
+ const [channelRefExtension] = useState(() =>
+ buildCommunityChannelRefExtension({
+ candidatesRef: channelRefCandidatesRef,
+ popupRef: channelRefPopupRef,
+ setPopup: setChannelRefPopup,
+ queryRef: channelRefQueryRef,
+ }),
+ )
+
// Re-rank + push a new popup state whenever `members` changes AND the popup
// is open. Without this, tiptap's `suggestion.items` only fires on
// caret/query updates — so remote-arrival changes to `members` (e.g. a
@@ -122,6 +154,19 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
})
}, [members, context])
+ // Same re-rank-on-candidates-change effect, mirrored for the channel-ref popup.
+ useEffect(() => {
+ const cur = channelRefPopupRef.current
+ if (!cur.command) return
+ const next = rankChannelRefItems(channelRefCandidates, channelRefQueryRef.current)
+ if (channelRefItemsEqual(cur.items, next)) return
+ setChannelRefPopup({
+ ...cur,
+ items: next,
+ selectedIndex: cur.selectedIndex < next.length ? cur.selectedIndex : 0,
+ })
+ }, [channelRefCandidates])
+
const editor = useEditor({
immediatelyRender: false,
extensions: [
@@ -141,6 +186,7 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
}),
Placeholder.configure({ placeholder: context === "channel" ? `Message /${channel}` : `Message ${channel}` }),
mentionExtension,
+ channelRefExtension,
],
editorProps: {
attributes: {
@@ -155,7 +201,9 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
// the suggestion plugin gets Enter/Arrow/Tab/Esc as designed.
const mentionOpen =
mentionPopupRef.current.items.length > 0 && mentionPopupRef.current.command !== null
- if (mentionOpen) return false
+ const channelRefOpen =
+ channelRefPopupRef.current.items.length > 0 && channelRefPopupRef.current.command !== null
+ if (mentionOpen || channelRefOpen) return false
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault()
@@ -179,6 +227,7 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
editor.commands.clearContent()
setPendingFiles([])
setMentionPopup(EMPTY_MENTION_STATE)
+ setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)
}
// Auto-focus on mount + on channel switch. `<Composer>` is not remounted
@@ -206,6 +255,7 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
onDrop={handleDrop}
>
<CommunityMentionList state={mentionPopup} />
+ <ChannelRefList state={channelRefPopup} />
{/* reply context bar — attached above the input */}
{replyingTo && (
@@ -367,6 +417,94 @@ function CommunityMentionList({ state }: { state: MentionPopupState }) {
)
}
+// Structural equality on the channel-ref popup's `items` array — same
+// no-op-skip purpose as `itemsEqual` above.
+function channelRefItemsEqual(a: ChannelRefCandidate[], b: ChannelRefCandidate[]): boolean {
+ if (a === b) return true
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) {
+ if (a[i].id !== b[i].id || a[i].name !== b[i].name || a[i].serverId !== b[i].serverId) return false
+ }
+ return true
+}
+
+// Portal-rendered `/`-ref popup. Mirrors `CommunityMentionList` — anchored
+// above the caret via clientRect(), highlighted row synced to hover.
+function ChannelRefList({ state }: { state: ChannelRefPopupState }) {
+ const listRef = useRef<HTMLDivElement>(null)
+ const { items, selectedIndex, command, rect } = state
+
+ useEffect(() => {
+ if (!listRef.current) return
+ const el = listRef.current.children[selectedIndex] as HTMLElement | undefined
+ el?.scrollIntoView({ block: "nearest" })
+ }, [selectedIndex])
+
+ if (!rect || items.length === 0 || !command) return null
+
+ const POPUP_WIDTH = 256
+ const VIEWPORT_MARGIN = 8
+ const maxLeft = typeof window !== "undefined"
+ ? Math.max(VIEWPORT_MARGIN, window.innerWidth - POPUP_WIDTH - VIEWPORT_MARGIN)
+ : rect.left
+ const clampedLeft = Math.min(rect.left, maxLeft)
+
+ // The list spans multiple servers (the DM case) when any two candidates
+ // differ on serverId — only then does each row show its "serverName /"
+ // prefix, so same-server lists stay clean.
+ const spansMultipleServers = items.some((it) => it.serverId !== items[0]?.serverId)
+
+ return createPortal(
+ <div
+ className="fixed z-100 w-64 overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-(--e2)"
+ style={{ top: rect.top - 4, left: clampedLeft, transform: "translateY(-100%)" }}
+ >
+ <div ref={listRef} className="max-h-60 overflow-y-auto thin-scrollbar py-1">
+ {items.map((item, i) => (
+ <ChannelRefRow
+ key={item.id}
+ item={item}
+ selected={i === selectedIndex}
+ showServerPrefix={spansMultipleServers}
+ onSelect={() => command({ id: item.id, label: item.name, serverId: item.serverId })}
+ />
+ ))}
+ </div>
+ </div>,
+ document.body,
+ )
+}
+
+function ChannelRefRow({ item, selected, showServerPrefix, onSelect }: {
+ item: ChannelRefCandidate
+ selected: boolean
+ showServerPrefix: boolean
+ onSelect: () => void
+}) {
+ return (
+ <button
+ type="button"
+ role="option"
+ aria-selected={selected}
+ className={[
+ "flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors",
+ selected ? "bg-accent" : "hover:bg-accent/50",
+ ].join(" ")}
+ onMouseDown={(e) => {
+ // mousedown (not click) — same rationale as MentionRow.
+ e.preventDefault()
+ onSelect()
+ }}
+ >
+ <ChannelIcon className="size-3.5 text-muted-foreground" />
+ <span className="font-medium">
+ {showServerPrefix && <span className="text-muted-foreground">{item.serverName} / </span>}
+ {item.name}
+ </span>
+ </button>
+ )
+}
+
function MentionRow({ item, selected, showMembersHeader, onSelect }: {
item: MentionItem
selected: boolean
diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsx
index 09efc7829..7d18bf454 100644
--- a/src/web/src/components/community/inline-marks.tsx
+++ b/src/web/src/components/community/inline-marks.tsx
@@ -49,12 +49,40 @@ export function MentionPill({
return <span className={className}>{children}</span>
}
-// #channel pill — leading hash icon, strips a literal "#" from the label.
-export function ChannelPill({ children }: { children?: React.ReactNode }) {
- return (
- <span className="inline-flex items-center gap-1 rounded-lg bg-accent px-1 font-medium text-foreground">
+// Channel-ref pill — leading channel icon + name. `onClick` navigates
+// (rendered as a `<button>` when present, a `<span>` otherwise — same
+// on/off pattern as `MentionPill`). `serverPrefix` renders a small
+// "prefix /" segment before the name for cross-server refs. `muted` dims
+// the pill for the "still resolving" state (see `channel-ref-pill.tsx`).
+export function ChannelPill({
+ children,
+ onClick,
+ serverPrefix,
+ muted,
+}: {
+ children?: React.ReactNode
+ onClick?: (e: React.MouseEvent) => void
+ serverPrefix?: string
+ muted?: boolean
+}) {
+ const className = [
+ "inline-flex items-center gap-1 rounded-lg bg-accent px-1 font-medium text-foreground",
+ muted ? "opacity-60" : "",
+ onClick ? "cursor-pointer hover:underline" : "",
+ ].join(" ")
+ const content = (
+ <>
<ChannelIcon className="text-xs" />
- {String(children).replace(/^#/, "")}
- </span>
+ {serverPrefix && <span className="text-muted-foreground">{serverPrefix} /</span>}
+ {children}
+ </>
)
+ if (onClick) {
+ return (
+ <button type="button" onClick={onClick} className={className}>
+ {content}
+ </button>
+ )
+ }
+ return <span className={className}>{content}</span>
}
diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.ts
index 7980ba457..0d4c1091f 100644
--- a/src/web/src/components/community/message-markdown.test.ts
+++ b/src/web/src/components/community/message-markdown.test.ts
@@ -43,19 +43,36 @@ describe("preprocessMarkdown", () => {
expect(preprocessMarkdown("@here ping")).toBe('<mention data-everyone="1">@here</mention> ping')
})
- it("wraps #channel and preserves the leading separator", () => {
- expect(preprocessMarkdown("see #general")).toBe("see <channel>#general</channel>")
- expect(preprocessMarkdown("#general")).toBe("<channel>#general</channel>")
+ it("the old #channel step/tag no longer exists — #general renders as plain text", () => {
+ // Regression guard for the retired legacy chip (plan community-channel-ref.md).
+ expect(preprocessMarkdown("see #general")).toBe("see #general")
+ expect(preprocessMarkdown("#general")).toBe("#general")
})
- it("leaves @ / # / || inside inline code literal", () => {
+ it("wraps /server/channel preceded by a space or at start-of-string into <channelref>, preserving the leading separator outside the tag", () => {
+ expect(preprocessMarkdown("see /studio/general")).toBe("see <channelref>/studio/general</channelref>")
+ expect(preprocessMarkdown("/studio/general")).toBe("<channelref>/studio/general</channelref>")
+ })
+
+ it("leaves text/studio/general (no leading space) untouched", () => {
+ expect(preprocessMarkdown("text/studio/general")).toBe("text/studio/general")
+ })
+
+ it("wraps the thread form /studio/general/#42", () => {
+ expect(preprocessMarkdown("see /studio/general/#42")).toBe(
+ "see <channelref>/studio/general/#42</channelref>",
+ )
+ })
+
+ it("leaves @ / # / || / channel-refs inside inline code literal", () => {
expect(preprocessMarkdown("use `@Lindsay` here")).toBe("use `@Lindsay` here")
expect(preprocessMarkdown("`#general`")).toBe("`#general`")
expect(preprocessMarkdown("`||x||`")).toBe("`||x||`")
+ expect(preprocessMarkdown("`/studio/general`")).toBe("`/studio/general`")
})
it("leaves content inside fenced code literal", () => {
- const fenced = "```\n@Lindsay #general ||x||\n```"
+ const fenced = "```\n@Lindsay #general /studio/general ||x||\n```"
expect(preprocessMarkdown(fenced)).toBe(fenced)
})
@@ -63,23 +80,34 @@ describe("preprocessMarkdown", () => {
expect(preprocessMarkdown("steps:\n> do it")).toBe("steps:\n\n> do it")
})
- it("leaves community invite URLs literal in the body (auto-link handles them)", () => {
+ it("leaves community invite URLs literal in the body (auto-link handles them) — regression guard for the invite-URL stash fix", () => {
// Preprocess no longer rewrites invite URLs — they stay as plain text so
// streamdown auto-links them; the card renders separately via
- // extractInviteTokens.
+ // extractInviteTokens. Must round-trip COMPLETELY unchanged (literal
+ // equality, not just `.toContain()`) — this confirms invite URLs are
+ // stashed BEFORE `CHANNEL_REF_REGEX` runs (which would otherwise
+ // shape-match `/community/invite` as a two-segment channel ref and split
+ // the URL across a `<channelref>` tag boundary, breaking streamdown's
+ // GFM autolink of the whole URL).
expect(preprocessMarkdown("join /community/invite/abc123XYZ")).toBe(
"join /community/invite/abc123XYZ",
)
})
+ it("regression guard: the full-origin invite URL form also round-trips unchanged", () => {
+ expect(preprocessMarkdown("join https://alook.ai/community/invite/xY9k2vW7aQ")).toBe(
+ "join https://alook.ai/community/invite/xY9k2vW7aQ",
+ )
+ })
+
it("handles a mix and round-trips stashed code unchanged", () => {
- const input = "Here's the **setup**:\n> Clone the repo\n`pnpm install`\nping @Gus in #dev"
+ const input = "Here's the **setup**:\n> Clone the repo\n`pnpm install`\nping @Gus in /studio/dev"
const out = preprocessMarkdown(input)
expect(out).toContain("**setup**")
expect(out).toContain("\n\n> Clone the repo")
expect(out).toContain("`pnpm install`")
expect(out).toContain("<mention>@Gus</mention>")
- expect(out).toContain("<channel>#dev</channel>")
+ expect(out).toContain("<channelref>/studio/dev</channelref>")
})
})
diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsx
index 7cceae907..0869f2297 100644
--- a/src/web/src/components/community/message-markdown.tsx
+++ b/src/web/src/components/community/message-markdown.tsx
@@ -1,5 +1,16 @@
import type React from "react"
-import { Spoiler, MentionPill, ChannelPill } from "./inline-marks"
+import { Spoiler, MentionPill } from "./inline-marks"
+import { ChannelRefPill } from "./channel-ref-pill"
+
+// Match a `/server/channel` or `/server/channel/#N` (thread) ref — the CLI's
+// path grammar (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment
+// charset `[A-Za-z0-9_-]+` is the nanoid alphabet every `communityServer.id`/
+// `communityChannel.id` is generated with, so a compact ref must be built from
+// ids (see `channel-ref-extension.ts`'s `renderText`) — display names with
+// spaces/punctuation can't round-trip through this regex (same limitation the
+// legacy `#channel-name` chip had). The pinned-message form (`#N` directly, no
+// slash) is intentionally not matched — see plan §1 for why.
+const CHANNEL_REF_REGEX = /(^|\s)(\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?)/g
// Sentinels for stashing code spans/fences (private-use chars — won't collide with
// real text or markdown punctuation).
@@ -50,6 +61,13 @@ export function preprocessMarkdown(text: string): string {
let out = text
.replace(/```[\s\S]*?```/g, protect) // fenced code
.replace(/`[^`\n]*`/g, protect) // inline code
+ // Stash invite-link URLs BEFORE `CHANNEL_REF_REGEX` runs — `/community/invite/<token>`
+ // shape-matches the channel-ref regex too (server="community", channel="invite"),
+ // which would otherwise wrap `/community/invite` in a `<channelref>` tag and
+ // leave the token as a disconnected trailing text node, breaking streamdown's
+ // GFM autolinking of the whole URL. A fresh (non-shared) regex copy avoids
+ // inheriting `lastIndex` from `INVITE_URL_RE`/other callers.
+ out = out.replace(new RegExp(INVITE_URL_RE.source, "g"), protect)
out = out
// CommonMark needs a blank line before a blockquote; chat-style quotes are line-by-line.
// Insert one so a `> ` that immediately follows text still renders as a quote.
@@ -71,16 +89,22 @@ export function preprocessMarkdown(text: string): string {
const bare = m.replace(/#\d{4}$/, "")
return tagMatch ? `<mention data-tag="${tagMatch[1]}">${bare}</mention>` : `<mention>${bare}</mention>`
})
- .replace(/(^|\s)#([\w-]+)/g, (_m, pre, name) => `${pre}<channel>#${name}</channel>`)
+ // `/server/channel` refs (see `CHANNEL_REF_REGEX`'s doc comment). Leading
+ // boundary `(^|\s)` kept outside the tag, same convention the old
+ // `#channel` step used — `" /channel-ref"` matches, `"text/channel-ref"`
+ // doesn't. The tag's content is fed straight into `@alook/shared`'s
+ // `parseRef` at render time (`channel-ref-pill.tsx`), reusing the exact
+ // grammar the backend already uses.
+ .replace(CHANNEL_REF_REGEX, (_m, pre, ref) => `${pre}<channelref>${ref}</channelref>`)
return out.replace(new RegExp(`${S0}(\\d+)${S1}`, "g"), (_m, i) => stash[Number(i)])
}
export const MD_ALLOWED_TAGS = {
spoiler: [],
mention: ["data-everyone", "data-tag"],
- channel: [],
+ channelref: [],
}
-export const MD_LITERAL_TAGS = ["spoiler", "mention", "channel"]
+export const MD_LITERAL_TAGS = ["spoiler", "mention", "channelref"]
// A mention pill's rendered text is always `@name` (see `preprocessMarkdown`,
// which already drops the `#0042` discriminator) — this strips the leading
@@ -96,7 +120,11 @@ export const MD_COMPONENTS = {
mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => (
<MentionPill everyone={rest["data-everyone"] === "1"}>{children}</MentionPill>
),
- channel: ({ children }: { children?: React.ReactNode }) => <ChannelPill>{children}</ChannelPill>,
+ // `channelref` is fully self-sufficient via hooks (resolves via
+ // `useChannelRefDirectory`, navigates via `useRouter`) — unlike `mention`,
+ // it needs no closure injected by `buildMdComponents`, so the same static
+ // entry is reused there too (see the spread below).
+ channelref: ChannelRefPill,
} as Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>
// Same as `MD_COMPONENTS`, but the `mention` pill opens the profile card on
diff --git a/src/web/src/components/community/rail-folder.tsx b/src/web/src/components/community/rail-folder.tsx
index 4987103ee..9a0a2fad4 100644
--- a/src/web/src/components/community/rail-folder.tsx
+++ b/src/web/src/components/community/rail-folder.tsx
@@ -5,6 +5,7 @@ import { CSS } from "@dnd-kit/utilities"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
import { RailIndicator } from "./rail-indicator"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
+import { serverGradient } from "./server-gradient"
import type { FolderServer } from "./_types"
export function RailFolder({
@@ -45,7 +46,14 @@ export function RailFolder({
{Array.from({ length: 4 }).map((_, i) => {
const s = folderServers[i]
return s ? (
- <span key={s.id} className="grid aspect-square place-items-center overflow-hidden rounded-sm bg-card text-[7px] font-semibold text-muted-foreground">
+ <span
+ key={s.id}
+ style={s.icon ? undefined : { background: serverGradient(s.id) }}
+ className={[
+ "grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
+ s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
+ ].join(" ")}
+ >
{s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : s.initial}
</span>
) : (
diff --git a/src/web/src/components/community/server-gradient.test.ts b/src/web/src/components/community/server-gradient.test.ts
new file mode 100644
index 000000000..20bc1785d
--- /dev/null
+++ b/src/web/src/components/community/server-gradient.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect } from "vitest"
+import { BG_COLORS } from "@/components/avatar/avatar-parts"
+import { serverGradient, serverGradientColors, serverGradientAngle } from "./server-gradient"
+
+const PRESET_VALUES = new Set(BG_COLORS.map((c) => c.value))
+
+describe("serverGradientColors", () => {
+ it("picks three colors from the agent avatar preset palette", () => {
+ const colors = serverGradientColors("server_abc")
+ expect(colors).toHaveLength(3)
+ for (const c of colors) expect(PRESET_VALUES.has(c)).toBe(true)
+ })
+
+ it("picks three distinct colors", () => {
+ const colors = serverGradientColors("server_xyz")
+ expect(new Set(colors).size).toBe(3)
+ })
+
+ it("is deterministic for the same seed", () => {
+ expect(serverGradientColors("server_1")).toEqual(serverGradientColors("server_1"))
+ })
+
+ it("varies across different seeds", () => {
+ const a = serverGradientColors("server_1")
+ const b = serverGradientColors("server_2")
+ expect(a).not.toEqual(b)
+ })
+})
+
+describe("serverGradientAngle", () => {
+ it("returns a degree value within [0, 360)", () => {
+ for (const seed of ["server_abc", "server_xyz", "server_1", "server_2"]) {
+ const angle = serverGradientAngle(seed)
+ expect(angle).toBeGreaterThanOrEqual(0)
+ expect(angle).toBeLessThan(360)
+ expect(Number.isInteger(angle)).toBe(true)
+ }
+ })
+
+ it("is deterministic for the same seed", () => {
+ expect(serverGradientAngle("server_1")).toBe(serverGradientAngle("server_1"))
+ })
+
+ it("varies across different seeds", () => {
+ const angles = new Set(["server_1", "server_2", "server_3", "server_4"].map(serverGradientAngle))
+ expect(angles.size).toBeGreaterThan(1)
+ })
+})
+
+describe("serverGradient", () => {
+ it("builds a linear-gradient CSS value from a random angle and three preset colors", () => {
+ const css = serverGradient("server_abc")
+ expect(css).toMatch(/^linear-gradient\(\d+deg, .+, .+, .+\)$/)
+ const [c0, c1, c2] = serverGradientColors("server_abc")
+ const angle = serverGradientAngle("server_abc")
+ expect(css).toBe(`linear-gradient(${angle}deg, ${c0}, ${c1}, ${c2})`)
+ })
+
+ it("is deterministic for the same seed", () => {
+ expect(serverGradient("server_1")).toBe(serverGradient("server_1"))
+ })
+})
diff --git a/src/web/src/components/community/server-gradient.ts b/src/web/src/components/community/server-gradient.ts
new file mode 100644
index 000000000..66b6f7031
--- /dev/null
+++ b/src/web/src/components/community/server-gradient.ts
@@ -0,0 +1,54 @@
+/**
+ * Deterministic fallback background for servers without an uploaded icon.
+ *
+ * Draws three distinct colors (and a gradient angle) from the same preset
+ * palette used by the agent avatar generator (`BG_COLORS`) so server and
+ * agent fallback visuals share one design language. Everything is seeded by
+ * the server id, so it looks random across servers but never flickers
+ * between renders/reloads.
+ */
+import { BG_COLORS } from "@/components/avatar/avatar-parts"
+
+function hashStr(s: string): number {
+ let h = 0
+ for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0
+ return Math.abs(h)
+}
+
+// mulberry32 — small, fast seeded PRNG. A raw `hash % length` would bias
+// consecutive picks toward nearby indices; this gives an even spread.
+function mulberry32(seed: number): () => number {
+ let a = seed
+ return () => {
+ a = (a + 0x6d2b79f5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/** Three distinct preset colors from `BG_COLORS`, seeded by `seed`. */
+export function serverGradientColors(seed: string): [string, string, string] {
+ const rand = mulberry32(hashStr(seed))
+ const pool = BG_COLORS.map((c) => c.value)
+ const picked: string[] = []
+ for (let i = 0; i < 3 && pool.length > 0; i++) {
+ const idx = Math.floor(rand() * pool.length)
+ picked.push(pool.splice(idx, 1)[0]!)
+ }
+ return picked as [string, string, string]
+}
+
+// Salted separately from the color pick so the angle doesn't move in lockstep
+// with color choice (two servers with the same colors can still differ).
+export function serverGradientAngle(seed: string): number {
+ const rand = mulberry32(hashStr(`${seed}:angle`))
+ return Math.floor(rand() * 360)
+}
+
+/** CSS `background` value for a server's fallback avatar. */
+export function serverGradient(seed: string): string {
+ const [c0, c1, c2] = serverGradientColors(seed)
+ const angle = serverGradientAngle(seed)
+ return `linear-gradient(${angle}deg, ${c0}, ${c1}, ${c2})`
+}
diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsx
index d0b4766b4..3b8e5f135 100644
--- a/src/web/src/components/community/server-rail.tsx
+++ b/src/web/src/components/community/server-rail.tsx
@@ -14,6 +14,7 @@ import { SortableServer } from "./sortable-server"
import { RailFolder } from "./rail-folder"
import { CreateServerDialog } from "./create-server-dialog"
import { useRailOrder, isFolderKey, extractFolderId } from "./use-rail-order"
+import { serverGradient } from "./server-gradient"
import type { Server, CommunityFolder, MobileZone, View } from "./_types"
export const ServerRail = memo(function ServerRail({
@@ -205,7 +206,14 @@ export const ServerRail = memo(function ServerRail({
{Array.from({ length: 4 }).map((_, idx) => {
const s = folder.servers[idx]
return s ? (
- <span key={s.id} className="grid aspect-square place-items-center overflow-hidden rounded-sm bg-card text-[7px] font-semibold text-muted-foreground">
+ <span
+ key={s.id}
+ style={s.icon ? undefined : { background: serverGradient(s.id) }}
+ className={[
+ "grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
+ s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
+ ].join(" ")}
+ >
{s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : s.initial}
</span>
) : (
@@ -217,13 +225,16 @@ export const ServerRail = memo(function ServerRail({
}
const s = serverById.get(dragActiveId) ?? folderServerMap.get(dragActiveId)
if (!s) return null
+ const icon = s.icon
return (
- <div className="grid size-10 place-items-center overflow-hidden rounded-xl bg-secondary text-sm font-semibold text-foreground shadow-(--e2)">
- {"icon" in s && s.icon ? (
- <img src={s.icon} alt={s.name} className="size-full object-cover" />
- ) : (
- s.initial
- )}
+ <div
+ style={icon ? undefined : { background: serverGradient(s.id) }}
+ className={[
+ "grid size-10 place-items-center overflow-hidden rounded-xl text-sm font-semibold shadow-(--e2)",
+ icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]",
+ ].join(" ")}
+ >
+ {icon ? <img src={icon} alt={s.name} className="size-full object-cover" /> : s.initial}
</div>
)
})()}
diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsx
index 492b2849e..0d09c9615 100644
--- a/src/web/src/components/community/sortable-server.tsx
+++ b/src/web/src/components/community/sortable-server.tsx
@@ -8,6 +8,7 @@ import { RailIndicator } from "./rail-indicator"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { NumberTicker } from "@/components/ui/number-ticker"
+import { serverGradient } from "./server-gradient"
import type { Server } from "./_types"
export function SortableServer({ server, active, onClick, onLeave, onOpenSettings, onOpenInvitePopover, onCreateFolder, groupTarget, inFolder, dragging: isDragActive }: { server: Server; active?: boolean; onClick: () => void; onLeave?: () => void; onOpenSettings?: () => void; onOpenInvitePopover?: () => void; onCreateFolder?: () => void; groupTarget?: boolean; inFolder?: boolean; dragging?: boolean }) {
@@ -32,9 +33,13 @@ export function SortableServer({ server, active, onClick, onLeave, onOpenSetting
onClick={active ? undefined : onClick}
{...attributes}
{...listeners}
+ style={server.icon ? undefined : { background: serverGradient(server.id) }}
className={[
"grid size-10 touch-none place-items-center overflow-hidden text-sm font-semibold transition-all duration-150 active:cursor-grabbing",
- active ? "cursor-default rounded-xl bg-primary text-primary-foreground" : "cursor-pointer rounded-[18px] bg-card hover:rounded-xl hover:bg-primary hover:text-primary-foreground",
+ active ? "cursor-default rounded-xl" : "cursor-pointer rounded-[18px] hover:rounded-xl",
+ server.icon
+ ? active ? "bg-primary text-primary-foreground" : "bg-card hover:bg-primary hover:text-primary-foreground"
+ : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] hover:brightness-110",
].join(" ")}
>
{server.icon ? (
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.test.ts
new file mode 100644
index 000000000..0ee1a13aa
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-ref-directory.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect } from "vitest"
+import { buildChannelRefDirectory } from "./use-channel-ref-directory"
+import type { Server, Category } from "@/components/community/_types"
+import type { ServerDetail } from "./use-servers"
+
+function server(id: string, name: string): Server {
+ return { id, name, initial: name[0], active: false, mentions: 0 }
+}
+
+function detail(id: string, name: string, categories: Category[]): ServerDetail {
+ return { id, name, description: "", icon: null, ownerId: "u1", categories }
+}
+
+function category(id: string, channels: Array<{ id: string; name: string }>): Category {
+ return {
+ id,
+ name: id,
+ channels: channels.map((c) => ({ id: c.id, name: c.name, active: false, unread: false })),
+ }
+}
+
+describe("buildChannelRefDirectory", () => {
+ it("flattens each server's categories[].channels into one channels array per server", () => {
+ const servers = [server("s1", "Studio")]
+ const detailsById = {
+ s1: detail("s1", "Studio", [
+ category("cat1", [{ id: "c1", name: "general" }, { id: "c2", name: "random" }]),
+ category("cat2", [{ id: "c3", name: "dev" }]),
+ ]),
+ }
+ const directory = buildChannelRefDirectory(servers, detailsById)
+ expect(directory).toEqual([
+ {
+ id: "s1",
+ name: "Studio",
+ channels: [
+ { id: "c1", name: "general" },
+ { id: "c2", name: "random" },
+ { id: "c3", name: "dev" },
+ ],
+ },
+ ])
+ })
+
+ it("a server with no fetched detail yet yields an empty channels array, not a crash", () => {
+ const servers = [server("s1", "Studio"), server("s2", "Other")]
+ const detailsById = { s1: detail("s1", "Studio", [category("cat1", [{ id: "c1", name: "general" }])]) }
+ const directory = buildChannelRefDirectory(servers, detailsById)
+ expect(directory).toEqual([
+ { id: "s1", name: "Studio", channels: [{ id: "c1", name: "general" }] },
+ { id: "s2", name: "Other", channels: [] },
+ ])
+ })
+
+ it("returns [] for an empty server list", () => {
+ expect(buildChannelRefDirectory([], {})).toEqual([])
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.ts
new file mode 100644
index 000000000..ea271c9ba
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts
@@ -0,0 +1,71 @@
+"use client"
+
+import { useMemo } from "react"
+import { useQueries } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { useServers, serverQueryFn, type ServerDetail } from "./use-servers"
+import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
+import type { Server } from "@/components/community/_types"
+
+/**
+ * Pure — flattens each server's `categories[].channels` into one `channels`
+ * array per server. A server whose detail hasn't loaded yet (or is
+ * genuinely still loading) contributes an empty `channels` array rather than
+ * being omitted or crashing — `resolveChannelRefBase` then simply can't
+ * resolve into it yet (falls back to plain/muted text upstream), and the
+ * directory backfills once the detail query resolves.
+ */
+export function buildChannelRefDirectory(
+ servers: Server[],
+ detailsById: Record<string, ServerDetail | undefined>,
+): ChannelRefDirectory {
+ return servers.map((s) => {
+ const detail = detailsById[s.id]
+ const channels = detail?.categories?.flatMap((c) => c.channels.map((ch) => ({ id: ch.id, name: ch.name }))) ?? []
+ return { id: s.id, name: s.name, channels }
+ })
+}
+
+/**
+ * Directory of every channel-ref-resolvable server + channel the current
+ * user is a member of. Fetches every member server's channel list in
+ * parallel via `useQueries` (reusing `serverQueryFn`/`communityKeys.server`
+ * so the cache is shared with any already-mounted single-server `useServer`
+ * call), then flattens via `buildChannelRefDirectory`.
+ *
+ * Scope decision: eagerly resolves refs to ANY server the user is a member
+ * of, not just the currently open one — simpler and more correct than
+ * lazily fetching only the referenced server, at the cost of fetching every
+ * member server's channel list as soon as a channel-ref pill is on screen
+ * (bounded, cached, parallel).
+ */
+export function useChannelRefDirectory(): {
+ directory: ChannelRefDirectory
+ isLoading: boolean
+} {
+ const { servers } = useServers()
+
+ const results = useQueries({
+ queries: servers.map((s) => ({
+ queryKey: communityKeys.server(s.id),
+ queryFn: serverQueryFn(s.id),
+ })),
+ })
+
+ const detailsById = useMemo(() => {
+ const map: Record<string, ServerDetail | undefined> = {}
+ servers.forEach((s, i) => {
+ map[s.id] = results[i]?.data
+ })
+ return map
+ }, [servers, results])
+
+ const directory = useMemo(
+ () => buildChannelRefDirectory(servers, detailsById),
+ [servers, detailsById],
+ )
+
+ const isLoading = results.some((r) => r.isLoading)
+
+ return { directory, isLoading }
+}
diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.ts
new file mode 100644
index 000000000..3dcf362c5
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref-extension.test.ts
@@ -0,0 +1,218 @@
+import { describe, it, expect, vi } from "vitest"
+import {
+ buildCommunityChannelRefExtension,
+ rankChannelRefItems,
+ EMPTY_CHANNEL_REF_STATE,
+ type ChannelRefCandidate,
+ type ChannelRefPopupState,
+} from "./channel-ref-extension"
+
+const candidate = (id: string, name: string, serverId = "s1", serverName = "Studio"): ChannelRefCandidate => ({
+ id,
+ name,
+ serverId,
+ serverName,
+})
+
+describe("rankChannelRefItems", () => {
+ const candidates = [
+ candidate("c1", "general"),
+ candidate("c2", "gear-talk"),
+ candidate("c3", "random"),
+ ]
+
+ it("ranks prefix matches before substring matches, case-insensitively", () => {
+ const items = rankChannelRefItems(candidates, "GE")
+ expect(items.map((i) => i.id)).toEqual(["c1", "c2"])
+ })
+
+ it("returns everything (prefix bucket) for an empty query", () => {
+ const items = rankChannelRefItems(candidates, "")
+ expect(items.map((i) => i.id)).toEqual(["c1", "c2", "c3"])
+ })
+
+ it("caps the list at the same limit convention as rankMentionItems (8)", () => {
+ const many = Array.from({ length: 20 }, (_, i) => candidate(`c${i}`, `chan${i}`))
+ expect(rankChannelRefItems(many, "").length).toBe(8)
+ })
+
+ it("puts substring-only matches after prefix matches", () => {
+ const items = rankChannelRefItems(
+ [candidate("c1", "abc-general"), candidate("c2", "general")],
+ "general",
+ )
+ expect(items.map((i) => i.id)).toEqual(["c2", "c1"])
+ })
+})
+
+// Reach into the extension the same way the composer does — read
+// `configuration.suggestion.items` off the configured node, mirroring
+// `mention-extension.test.ts`'s introspection style (no jsdom/browser).
+function getItemsCallback(
+ ext: ReturnType<typeof buildCommunityChannelRefExtension>,
+): (props: { query: string }) => unknown[] {
+ const config = (ext as unknown as { config: { addOptions?: () => { suggestion?: { items?: unknown } } } }).config
+ const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { items?: unknown } } }).options
+ const items = (opts?.suggestion as { items: (props: { query: string }) => unknown[] } | undefined)?.items
+ if (!items) throw new Error("suggestion.items not found")
+ return items
+}
+
+type RenderNodeProps = {
+ options?: { HTMLAttributes?: Record<string, unknown> }
+ node: { attrs: { label?: string | null; id?: string | null; serverId?: string | null } }
+}
+
+function getRenderFns(ext: ReturnType<typeof buildCommunityChannelRefExtension>): {
+ renderText: (props: RenderNodeProps) => string
+ renderHTML: (props: RenderNodeProps) => unknown
+} {
+ const config = (ext as unknown as {
+ config: { addOptions?: () => { renderText?: unknown; renderHTML?: unknown } }
+ }).config
+ const opts =
+ config.addOptions?.() ??
+ (ext as unknown as { options?: { renderText?: unknown; renderHTML?: unknown } }).options
+ const renderText = opts?.renderText as ((props: RenderNodeProps) => string) | undefined
+ const renderHTML = opts?.renderHTML as ((props: RenderNodeProps) => unknown) | undefined
+ if (!renderText || !renderHTML) throw new Error("renderText/renderHTML not found")
+ return { renderText, renderHTML }
+}
+
+function getKeyDownCallback(
+ ext: ReturnType<typeof buildCommunityChannelRefExtension>,
+): (props: { event: KeyboardEvent }) => boolean {
+ const config = (ext as unknown as { config: { addOptions?: () => { suggestion?: { render?: unknown } } } }).config
+ const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { render?: unknown } } }).options
+ const render = (opts?.suggestion as { render?: () => { onKeyDown?: unknown } } | undefined)?.render
+ if (!render) throw new Error("suggestion.render not found")
+ const handlers = render()
+ const onKeyDown = handlers.onKeyDown as ((props: { event: KeyboardEvent }) => boolean) | undefined
+ if (!onKeyDown) throw new Error("onKeyDown not found")
+ return onKeyDown
+}
+
+function build(candidates: ChannelRefCandidate[] = [], popup: ChannelRefPopupState = EMPTY_CHANNEL_REF_STATE) {
+ const candidatesRef = { current: candidates }
+ const popupRef = { current: popup }
+ const setPopup = vi.fn()
+ const queryRef = { current: "" }
+ const ext = buildCommunityChannelRefExtension({ candidatesRef, popupRef, setPopup, queryRef })
+ return { ext, candidatesRef, popupRef, setPopup, queryRef }
+}
+
+describe("buildCommunityChannelRefExtension — suggestion.items callback", () => {
+ it("reads live candidates via candidatesRef.current", () => {
+ const { ext, candidatesRef } = build([candidate("c1", "general")])
+ const items = getItemsCallback(ext)
+ expect(items({ query: "" })).toEqual([candidate("c1", "general")])
+
+ // Live ref — mutate after the extension is built; items() must see it.
+ candidatesRef.current = [candidate("c1", "general"), candidate("c2", "random")]
+ expect((items({ query: "" }) as ChannelRefCandidate[]).map((i) => i.id)).toEqual(["c1", "c2"])
+ })
+
+ it("updates the shared queryRef.current on each items() call", () => {
+ const { ext, queryRef } = build([candidate("c1", "general")])
+ const items = getItemsCallback(ext)
+ items({ query: "gen" })
+ expect(queryRef.current).toBe("gen")
+ items({ query: "general" })
+ expect(queryRef.current).toBe("general")
+ })
+})
+
+describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {
+ it("renderText produces /serverId/channelId (id-based, not name-based)", () => {
+ const { ext } = build()
+ const { renderText } = getRenderFns(ext)
+ expect(
+ renderText({ node: { attrs: { id: "chn_abc", serverId: "srv_xyz", label: "general" } } }),
+ ).toBe("/srv_xyz/chn_abc")
+ })
+
+ it("renderHTML shows a compact /label chip", () => {
+ const { ext } = build()
+ const { renderHTML } = getRenderFns(ext)
+ const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: "general", id: "chn_abc" } } })
+ expect(spec).toEqual(["span", {}, "/general"])
+ })
+
+ it("renderHTML falls back to id when label is missing", () => {
+ const { ext } = build()
+ const { renderHTML } = getRenderFns(ext)
+ const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: null, id: "chn_abc" } } })
+ expect(spec).toEqual(["span", {}, "/chn_abc"])
+ })
+})
+
+describe("buildCommunityChannelRefExtension — keyboard callback", () => {
+ it("ArrowDown/ArrowUp wrap the selectedIndex", () => {
+ const items = [candidate("c1", "a"), candidate("c2", "b")]
+ const { ext, popupRef, setPopup } = build(items, {
+ items,
+ selectedIndex: 0,
+ command: vi.fn(),
+ rect: null,
+ })
+ const onKeyDown = getKeyDownCallback(ext)
+
+ const down = { key: "ArrowDown", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: down })).toBe(true)
+ expect(setPopup).toHaveBeenCalledWith(expect.objectContaining({ selectedIndex: 1 }))
+
+ popupRef.current = { ...popupRef.current, selectedIndex: 0 }
+ const up = { key: "ArrowUp", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: up })).toBe(true)
+ expect(setPopup).toHaveBeenCalledWith(expect.objectContaining({ selectedIndex: 1 }))
+ })
+
+ it("Escape closes the popup", () => {
+ const items = [candidate("c1", "a")]
+ const { ext, setPopup } = build(items, { items, selectedIndex: 0, command: vi.fn(), rect: null })
+ const onKeyDown = getKeyDownCallback(ext)
+ const esc = { key: "Escape", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: esc })).toBe(true)
+ expect(setPopup).toHaveBeenCalledWith(EMPTY_CHANNEL_REF_STATE)
+ })
+
+ it("IME composition bails (returns false) even with the popup open", () => {
+ const items = [candidate("c1", "a")]
+ const { ext } = build(items, { items, selectedIndex: 0, command: vi.fn(), rect: null })
+ const onKeyDown = getKeyDownCallback(ext)
+ const enter = { key: "Enter", preventDefault: vi.fn(), isComposing: true } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: enter })).toBe(false)
+ })
+
+ it("selecting a candidate via Enter calls command with { id, label, serverId } — not the raw ChannelRefCandidate", () => {
+ const command = vi.fn()
+ const items = [candidate("chn_1", "general", "srv_1", "Studio")]
+ const { ext, setPopup } = build(items, { items, selectedIndex: 0, command, rect: null })
+ const onKeyDown = getKeyDownCallback(ext)
+ const enter = { key: "Enter", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: enter })).toBe(true)
+ // Regression guard for the name→label mapping bug: passing the raw
+ // candidate through as-is would leave `attrs.label` `null` and silently
+ // render "/null" in the in-editor chip.
+ expect(command).toHaveBeenCalledWith({ id: "chn_1", label: "general", serverId: "srv_1" })
+ expect(command).not.toHaveBeenCalledWith(items[0])
+ expect(setPopup).toHaveBeenCalledWith(EMPTY_CHANNEL_REF_STATE)
+ })
+
+ it("Tab also selects the highlighted candidate", () => {
+ const command = vi.fn()
+ const items = [candidate("chn_1", "general", "srv_1", "Studio")]
+ const { ext } = build(items, { items, selectedIndex: 0, command, rect: null })
+ const onKeyDown = getKeyDownCallback(ext)
+ const tab = { key: "Tab", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: tab })).toBe(true)
+ expect(command).toHaveBeenCalledWith({ id: "chn_1", label: "general", serverId: "srv_1" })
+ })
+
+ it("returns false when there are no items (popup effectively closed)", () => {
+ const { ext } = build([], { ...EMPTY_CHANNEL_REF_STATE })
+ const onKeyDown = getKeyDownCallback(ext)
+ const enter = { key: "Enter", preventDefault: vi.fn(), isComposing: false } as unknown as KeyboardEvent
+ expect(onKeyDown({ event: enter })).toBe(false)
+ })
+})
diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.ts
new file mode 100644
index 000000000..fc40029a9
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref-extension.ts
@@ -0,0 +1,193 @@
+import Mention from "@tiptap/extension-mention"
+import { PluginKey } from "@tiptap/pm/state"
+
+export type ChannelRefCandidate = {
+ id: string // channelId (nanoid)
+ name: string // channel display name, for the popup row + in-editor chip
+ serverId: string // nanoid
+ serverName: string // for the popup row when listing across servers
+}
+
+// The shape actually passed to tiptap's `command(props)` — NOT
+// `ChannelRefCandidate` (see `buildCommunityChannelRefExtension`'s doc
+// comment on the `name` → `label` mapping). Mirrors
+// `MentionPopupState.command`'s own mapped-shape typing in
+// `mention-extension.ts`.
+export type ChannelRefCommandProps = { id: string; label: string; serverId: string }
+
+export interface ChannelRefPopupState {
+ items: ChannelRefCandidate[]
+ selectedIndex: number
+ command: ((props: ChannelRefCommandProps) => void) | null
+ rect: DOMRect | null
+}
+
+export const EMPTY_CHANNEL_REF_STATE: ChannelRefPopupState = {
+ items: [],
+ selectedIndex: 0,
+ command: null,
+ rect: null,
+}
+
+const CHANNEL_REF_LIMIT = 8
+
+/**
+ * Pure ranker — exported for tests. Prefix-then-substring on `name`,
+ * case-insensitive, capped at the same limit convention as
+ * `rankMentionItems`. No context/DM-empty-list special case is needed here
+ * (unlike mentions) — the CALLER decides what candidates to pass in
+ * (single-server list for channel/thread composers, cross-server flattened
+ * list for DM composers via `useChannelRefDirectory()`); the ranking logic
+ * itself is identical either way.
+ */
+export function rankChannelRefItems(
+ candidates: ChannelRefCandidate[],
+ query: string,
+): ChannelRefCandidate[] {
+ const q = query.toLowerCase()
+ const prefix: ChannelRefCandidate[] = []
+ const substr: ChannelRefCandidate[] = []
+ for (const c of candidates) {
+ const name = c.name.toLowerCase()
+ if (!q || name.startsWith(q)) prefix.push(c)
+ else if (name.includes(q)) substr.push(c)
+ }
+ return [...prefix, ...substr].slice(0, CHANNEL_REF_LIMIT)
+}
+
+type SuggestionProps = {
+ items: ChannelRefCandidate[]
+ command: (props: ChannelRefCommandProps) => void
+ clientRect?: (() => DOMRect | null) | null
+}
+
+/**
+ * Load-bearing rename: the default `Mention` export always creates a node
+ * literally named `"mention"` — the composer already registers one
+ * `Mention` instance for `@`, so two extensions sharing one node name in the
+ * same editor schema is a genuine ProseMirror schema error. `.extend({ name:
+ * "channelRef", addAttributes() {...} })` avoids that.
+ */
+const ChannelRefNode = Mention.extend({
+ name: "channelRef",
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ serverId: { default: null },
+ }
+ },
+})
+
+/**
+ * Channel-ref extension wired to the community Composer's popup state.
+ * Mirrors `buildCommunityMentionExtension` — see that file's doc comment for
+ * the overall ref-based-callback rationale.
+ *
+ * `suggestion.char = "/"`, `allowedPrefixes` left at the library default
+ * (`[' ']`, start-of-line included) — exactly the "must follow a space"
+ * rule from the spec, no custom `allow` callback needed. The explicit
+ * `pluginKey` below is good practice for debugging/introspection but isn't
+ * itself load-bearing (anonymous `new PluginKey()` calls already get an
+ * auto-incrementing unique suffix in `prosemirror-state`) — the node
+ * **name** rename above is what actually avoids the schema collision.
+ *
+ * `renderText` inserts by id, not display name — ids are nanoid
+ * (`[A-Za-z0-9_-]`), always round-trip through `CHANNEL_REF_REGEX` and
+ * `resolveChannelRefBase` (which tries id-match first), whereas an arbitrary
+ * display name might not (names with spaces/punctuation can't be typed as a
+ * compact ref). `renderHTML` shows a compact in-editor chip — channel name
+ * only, not the full path — keeping the compose box readable.
+ */
+export function buildCommunityChannelRefExtension(opts: {
+ candidatesRef: { current: ChannelRefCandidate[] }
+ popupRef: { current: ChannelRefPopupState }
+ setPopup: (
+ next: ChannelRefPopupState | ((cur: ChannelRefPopupState) => ChannelRefPopupState),
+ ) => void
+ // Optional. Kept in sync with the Composer's own query-tracking ref so the
+ // "candidates changed while the popup is open" re-rank effect can re-use
+ // the query the user actually sees — same purpose as the mention
+ // extension's `queryRef`.
+ queryRef?: { current: string }
+}) {
+ const { candidatesRef, popupRef, setPopup, queryRef } = opts
+
+ return ChannelRefNode.configure({
+ HTMLAttributes: { class: "channel-ref-highlight" },
+ renderText: ({ node }) => `/${node.attrs.serverId}/${node.attrs.id}`,
+ renderHTML: ({ options, node }) => ["span", options.HTMLAttributes, `/${node.attrs.label ?? node.attrs.id}`],
+ suggestion: {
+ char: "/",
+ pluginKey: new PluginKey("channelRefSuggestion"),
+ items: ({ query }: { query: string }) => {
+ if (queryRef) queryRef.current = query
+ return rankChannelRefItems(candidatesRef.current, query)
+ },
+ render: () => ({
+ onStart: (props: SuggestionProps) => {
+ setPopup({
+ items: props.items ?? [],
+ selectedIndex: 0,
+ command: props.command,
+ rect: props.clientRect?.() ?? null,
+ })
+ },
+ onUpdate: (props: SuggestionProps) => {
+ setPopup((cur) => ({
+ items: props.items ?? [],
+ selectedIndex:
+ cur.selectedIndex < (props.items?.length ?? 0)
+ ? cur.selectedIndex
+ : 0,
+ command: props.command,
+ rect: props.clientRect?.() ?? null,
+ }))
+ },
+ onKeyDown: ({ event }: { event: KeyboardEvent }) => {
+ if (event.isComposing) return false
+ const cur = popupRef.current
+ if (cur.items.length === 0) return false
+ if (event.key === "ArrowDown") {
+ event.preventDefault()
+ setPopup({
+ ...cur,
+ selectedIndex: (cur.selectedIndex + 1) % cur.items.length,
+ })
+ return true
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault()
+ setPopup({
+ ...cur,
+ selectedIndex:
+ (cur.selectedIndex - 1 + cur.items.length) % cur.items.length,
+ })
+ return true
+ }
+ if (event.key === "Enter" || event.key === "Tab") {
+ event.preventDefault()
+ const item = cur.items[cur.selectedIndex]
+ // Explicit field-name mapping — tiptap's `command(props)` inserts
+ // a node with `attrs: {...props}` verbatim. `ChannelRefCandidate`
+ // has no `label` field, so passing it through as-is would leave
+ // `node.attrs.label` `null` and the in-editor chip would render
+ // literally as "/null" (the sent message text is unaffected,
+ // since `renderText` doesn't read `label` — this only shows up
+ // visually in the compose box).
+ if (item && cur.command) {
+ cur.command({ id: item.id, label: item.name, serverId: item.serverId })
+ }
+ setPopup(EMPTY_CHANNEL_REF_STATE)
+ return true
+ }
+ if (event.key === "Escape") {
+ setPopup(EMPTY_CHANNEL_REF_STATE)
+ return true
+ }
+ return false
+ },
+ onExit: () => setPopup(EMPTY_CHANNEL_REF_STATE),
+ }),
+ },
+ })
+}
diff --git a/src/web/src/lib/community/channel-ref.test.ts b/src/web/src/lib/community/channel-ref.test.ts
new file mode 100644
index 000000000..c93b9ee31
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect } from "vitest"
+import { resolveChannelRefBase, type ChannelRefDirectory } from "./channel-ref"
+
+const directory: ChannelRefDirectory = [
+ {
+ id: "srv_studio",
+ name: "studio",
+ channels: [
+ { id: "chn_general", name: "general" },
+ { id: "chn_random", name: "random" },
+ ],
+ },
+ {
+ id: "srv_other",
+ name: "other",
+ channels: [{ id: "chn_dup", name: "general" }],
+ },
+]
+
+describe("resolveChannelRefBase", () => {
+ it("resolves a bare /server/channel by id for both segments", () => {
+ const resolved = resolveChannelRefBase(directory, "/srv_studio/chn_general")
+ expect(resolved?.server.id).toBe("srv_studio")
+ expect(resolved?.channel.id).toBe("chn_general")
+ expect(resolved?.threadRootSeq).toBeUndefined()
+ })
+
+ it("resolves by exact display name for both segments", () => {
+ const resolved = resolveChannelRefBase(directory, "/studio/general")
+ expect(resolved?.server.id).toBe("srv_studio")
+ expect(resolved?.channel.id).toBe("chn_general")
+ })
+
+ it("id match takes precedence over a colliding name match", () => {
+ // A server literally named "srv_studio" would collide with the id lookup
+ // for the first directory entry — id-first precedence must win.
+ const collidingDirectory: ChannelRefDirectory = [
+ { id: "srv_studio", name: "studio", channels: [{ id: "chn_general", name: "general" }] },
+ { id: "srv_named_like_id", name: "srv_studio", channels: [{ id: "chn_other", name: "other" }] },
+ ]
+ const resolved = resolveChannelRefBase(collidingDirectory, "/srv_studio/chn_general")
+ expect(resolved?.server.id).toBe("srv_studio")
+ })
+
+ it("two same-named servers resolve to the first one in directory order", () => {
+ const dupServers: ChannelRefDirectory = [
+ { id: "srv_a", name: "dup", channels: [{ id: "chn_a", name: "general" }] },
+ { id: "srv_b", name: "dup", channels: [{ id: "chn_b", name: "general" }] },
+ ]
+ const resolved = resolveChannelRefBase(dupServers, "/dup/general")
+ expect(resolved?.server.id).toBe("srv_a")
+ })
+
+ it("two same-named channels within one server resolve to the first one in array order", () => {
+ const dupChannels: ChannelRefDirectory = [
+ {
+ id: "srv_studio",
+ name: "studio",
+ channels: [
+ { id: "chn_first", name: "dup" },
+ { id: "chn_second", name: "dup" },
+ ],
+ },
+ ]
+ const resolved = resolveChannelRefBase(dupChannels, "/studio/dup")
+ expect(resolved?.channel.id).toBe("chn_first")
+ })
+
+ it("returns null when the server isn't in the directory", () => {
+ expect(resolveChannelRefBase(directory, "/nope/general")).toBeNull()
+ })
+
+ it("returns null when the channel isn't in the resolved server", () => {
+ expect(resolveChannelRefBase(directory, "/studio/nope")).toBeNull()
+ })
+
+ it("resolves the thread form /server/channel/#42 and surfaces threadRootSeq: 42", () => {
+ const resolved = resolveChannelRefBase(directory, "/studio/general/#42")
+ expect(resolved?.channel.id).toBe("chn_general")
+ expect(resolved?.threadRootSeq).toBe(42)
+ })
+
+ it("returns null instead of throwing on malformed input (fails parseRef)", () => {
+ expect(resolveChannelRefBase(directory, "not-a-ref")).toBeNull()
+ expect(resolveChannelRefBase(directory, "/onlyserver")).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
new file mode 100644
index 000000000..2bb04fdb7
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -0,0 +1,70 @@
+import { parseRef } from "@alook/shared"
+
+/**
+ * Client-side "directory" of every channel-ref-resolvable server + channel —
+ * built from already-fetched data (see `use-channel-ref-directory.ts`), not
+ * a fresh fetch per ref. Mirrors the shape the backend resolves against
+ * (`resolveServerByNameForMember`/`resolveChannelByNameForMember`), scoped to
+ * whatever servers/channels the client already has loaded.
+ */
+export type ChannelRefDirectoryChannel = { id: string; name: string }
+export type ChannelRefDirectoryServer = {
+ id: string
+ name: string
+ channels: ChannelRefDirectoryChannel[]
+}
+export type ChannelRefDirectory = ChannelRefDirectoryServer[]
+
+export type ResolvedChannelRef = {
+ server: ChannelRefDirectoryServer
+ channel: ChannelRefDirectoryChannel
+ threadRootSeq?: number
+}
+
+/**
+ * Resolve a raw `/server/channel` (or `/server/channel/#N`) ref string
+ * against an already-fetched client-side directory. Mirrors
+ * `resolveServerByNameForMember`/`resolveChannelByNameForMember`'s
+ * id-then-exact-name lookup precedence, but purely in-memory — no network
+ * call, and no ambiguity error.
+ *
+ * Ambiguity tie-break (deliberately simpler than the backend): server/channel
+ * names aren't unique in the schema, and the backend surfaces 2+ name matches
+ * as a `hint`-carrying 400 the caller must resolve. This function does NOT
+ * replicate that — it takes the FIRST match in `directory`/`channels` array
+ * order (plain `Array.prototype.find` semantics) and stops. A duplicate-name
+ * collision is rare, and the consequence here is just "click navigates to the
+ * other same-named channel" — not data loss — so this is an accepted,
+ * documented simplification, not a bug.
+ *
+ * Returns `null` on any miss (unknown server, unknown channel, or malformed
+ * ref) — this is the false-positive guard the caller (`describeChannelRefPillView`)
+ * relies on to fall back to plain text instead of rendering a broken pill.
+ */
+export function resolveChannelRefBase(
+ directory: ChannelRefDirectory,
+ ref: string,
+): ResolvedChannelRef | null {
+ let parsed: ReturnType<typeof parseRef>
+ try {
+ parsed = parseRef(ref)
+ } catch {
+ return null
+ }
+
+ const server =
+ directory.find((s) => s.id === parsed.server) ??
+ directory.find((s) => s.name === parsed.server)
+ if (!server) return null
+
+ const channel =
+ server.channels.find((c) => c.id === parsed.channel) ??
+ server.channels.find((c) => c.name === parsed.channel)
+ if (!channel) return null
+
+ return {
+ server,
+ channel,
+ ...(parsed.threadRootSeq !== undefined ? { threadRootSeq: parsed.threadRootSeq } : {}),
+ }
+}