Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): name-based channel refs, name slugification, unread channel dots

Guse36123e0c2de
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index c1b4529fa..29db71f35 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -112,6 +112,10 @@ export const DM_SERVER = ".dm";
* /.dm/<peer>#N , /.dm/<peer>/#N a DM message / DM thread
*
* A message is located by **channel + seq** (`<channelRef>#N`) — there is no id.
+ *
+ * `<server>`/`<channel>` are server/channel display *names*, guaranteed free
+ * of whitespace, `/`, and `#` (normalized via `slugify()` at creation/rename
+ * time), so each segment is always a single, unambiguous token.
*/
export type ChannelRef = string;
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 4f7d28f2c..3f88a8a8d 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -466,6 +466,7 @@ export { buildMimeMessage, extractAttachmentMeta, filterDownloadableAttachments
export type { MimeAttachment, BuildMimeOptions, InboundAttachmentMeta } from "./lib/mime";
export { computeDiscriminator, parseNameAndTag, formatHandle } from "./lib/discriminator";
export { parseInviteToken } from "./lib/invite-link";
+export { slugify } from "./lib/slugify";
export {
addRepeatInterval,
computeNextScheduledAt,
diff --git a/src/shared/src/lib/slugify.test.ts b/src/shared/src/lib/slugify.test.ts
new file mode 100644
index 000000000..afe05a310
--- /dev/null
+++ b/src/shared/src/lib/slugify.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from "vitest"
+import { slugify } from "./slugify"
+
+describe("slugify", () => {
+ it("replaces whitespace with a hyphen", () => {
+ expect(slugify("My Home")).toBe("My-Home")
+ })
+
+ it("preserves case — does not lowercase", () => {
+ expect(slugify("General Chat")).toBe("General-Chat")
+ })
+
+ it("preserves non-Latin scripts and emoji", () => {
+ expect(slugify("总部 🎉")).toBe("总部-🎉")
+ })
+
+ it("strips / and # outright, with no hyphen substitution", () => {
+ expect(slugify("a/b#c")).toBe("abc")
+ })
+
+ it("collapses repeated whitespace/hyphens into a single hyphen", () => {
+ expect(slugify("My - Home")).toBe("My-Home")
+ })
+
+ it("trims leading/trailing whitespace and hyphens", () => {
+ expect(slugify(" -foo- ")).toBe("foo")
+ })
+
+ it("normalizes an all-disallowed-chars input to an empty string", () => {
+ expect(slugify(" ")).toBe("")
+ expect(slugify("###")).toBe("")
+ expect(slugify("/")).toBe("")
+ })
+
+ it("leaves an already-clean input unchanged", () => {
+ expect(slugify("general")).toBe("general")
+ })
+
+ it("preserves punctuation other than the reserved characters", () => {
+ expect(slugify("My thoughts on this!")).toBe("My-thoughts-on-this!")
+ })
+})
diff --git a/src/shared/src/lib/slugify.ts b/src/shared/src/lib/slugify.ts
new file mode 100644
index 000000000..e952f147b
--- /dev/null
+++ b/src/shared/src/lib/slugify.ts
@@ -0,0 +1,25 @@
+/**
+ * Normalize a server/channel display name so it can round-trip through the
+ * `/server/channel` ref grammar (`community-cli-contract.ts`'s `ChannelRef`)
+ * and `CHANNEL_REF_REGEX` (`message-markdown.tsx`) as a single, unambiguous
+ * path segment. This is NOT the classic ASCII `lowercase-and-hyphenate`
+ * slugify — case and non-Latin scripts (Chinese, Japanese, emoji, ...) are
+ * preserved untouched. Only whitespace (collapsed to a single `-`) and the
+ * two grammar-reserved characters `/`/`#` (stripped outright, no hyphen
+ * substitution) are normalized away.
+ *
+ * Examples: `"My Home"` -> `"My-Home"`, `"总部 🎉"` -> `"总部-🎉"`,
+ * `"a/b#c"` -> `"abc"`, `"general"` -> `"general"` (unchanged).
+ *
+ * Callers must treat an empty-string result as "nothing left after
+ * normalizing" (e.g. input was all whitespace/`/`/`#`) and reject it the
+ * same way an empty name is rejected today.
+ */
+export function slugify(name: string): string {
+ return name
+ .replace(/[/#]/g, "")
+ .trim()
+ .replace(/\s+/g, "-")
+ .replace(/-+/g, "-")
+ .replace(/^-+|-+$/g, "")
+}
diff --git a/src/shared/vitest.config.ts b/src/shared/vitest.config.ts
index 1066d80b4..43e67ad3f 100644
--- a/src/shared/vitest.config.ts
+++ b/src/shared/vitest.config.ts
@@ -3,6 +3,6 @@ import shared from "../../vitest.shared"
export default mergeConfig(shared, defineConfig({
test: {
- include: ["test/**/*.test.ts"],
+ include: ["test/**/*.test.ts", "src/**/*.test.ts"],
},
}))
diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts
new file mode 100644
index 000000000..5f2715e64
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetChannelForMember = vi.fn()
+const mockCreateChannel = vi.fn()
+const mockCreateMessage = vi.fn()
+const mockGetUserSelf = vi.fn()
+const mockFanOutToChannel = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityChannel: {
+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
+ createChannel: (...a: unknown[]) => mockCreateChannel(...a),
+ },
+ communityMessage: {
+ createMessage: (...a: unknown[]) => mockCreateMessage(...a),
+ },
+ user: {
+ getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+const ctx = { params: { id: "ch1" } } as any
+
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/channels/ch1/posts", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ })
+}
+
+describe("POST /api/community/channels/[id]/posts — name normalization", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })
+ mockCreateMessage.mockResolvedValue({ id: "m1", createdAt: "2026-07-02T00:00:00.000Z" })
+ mockGetUserSelf.mockResolvedValue({ id: "u1", name: "Alice", image: null })
+ mockFanOutToChannel.mockResolvedValue(undefined)
+ })
+
+ it("normalizes a spaced post title via slugify before creating the post channel", async () => {
+ mockCreateChannel.mockResolvedValue({
+ id: "post1",
+ name: "My-thoughts-on-this!",
+ createdAt: "2026-07-02T00:00:00.000Z",
+ })
+
+ const res = await POST(postReq({ name: "My thoughts on this!", content: "hello" }), ctx)
+ expect(res.status).toBe(201)
+ expect(mockCreateChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ name: "My-thoughts-on-this!" }),
+ )
+ })
+
+ it("returns 400 (and never calls createChannel) when the post title is all disallowed characters", async () => {
+ const res = await POST(postReq({ name: "///", content: "hello" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockCreateChannel).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.ts
index 6e913394c..b0728020b 100644
--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts
@@ -8,6 +8,7 @@ import {
MAX_MESSAGE_CONTENT_LENGTH,
MESSAGE_PREVIEW_LENGTH,
WS_EVENTS,
+ slugify,
} from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember } from "@/lib/community/permissions"
@@ -95,9 +96,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (!body.name || typeof body.name !== "string" || body.name.trim().length === 0) {
return writeError("name is required", 400)
}
- if (body.name.trim().length > MAX_CHANNEL_NAME_LENGTH) {
+ const trimmedName = body.name.trim()
+ if (trimmedName.length > MAX_CHANNEL_NAME_LENGTH) {
return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)
}
+ const name = slugify(trimmedName)
+ if (!name) {
+ return writeError("name is required", 400)
+ }
if (!body.content || typeof body.content !== "string" || body.content.trim().length === 0) {
return writeError("content is required", 400)
@@ -121,7 +127,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const postChannel = await queries.communityChannel.createChannel(db, {
serverId: channel.serverId,
parentChannelId: channelId,
- name: body.name.trim(),
+ name,
type: "forum_post",
creatorId: ctx.userId,
})
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
new file mode 100644
index 000000000..f2fbd547f
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetChannel = vi.fn()
+const mockGetMember = vi.fn()
+const mockUpdateChannel = vi.fn()
+const mockLogAction = vi.fn()
+const mockFanOut = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityChannel: {
+ getChannel: (...a: unknown[]) => mockGetChannel(...a),
+ updateChannel: (...a: unknown[]) => mockUpdateChannel(...a),
+ },
+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
+ communityAuditLog: {
+ logAction: (...a: unknown[]) => mockLogAction(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { PATCH } from "./route"
+
+const ctx = { params: { id: "c1" } } as any
+
+function patchReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/channels/c1", {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ })
+}
+
+describe("PATCH /api/community/channels/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", categoryId: null, creatorId: "u1" })
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
+ mockFanOut.mockResolvedValue(undefined)
+ mockLogAction.mockResolvedValue(undefined)
+ })
+
+ it("normalizes a spaced rename via slugify before calling updateChannel", async () => {
+ mockUpdateChannel.mockResolvedValue({ id: "c1", name: "General-Chat" })
+
+ const res = await PATCH(patchReq({ name: "General Chat" }), ctx)
+ expect(res.status).toBe(200)
+ expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { name: "General-Chat" })
+ })
+
+ it("returns 400 (and never calls updateChannel) when the renamed name is all disallowed characters", async () => {
+ const res = await PATCH(patchReq({ name: " " }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockUpdateChannel).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index 3b2046106..7ed879856 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -8,6 +8,7 @@ import {
MAX_CHANNEL_NAME_LENGTH,
MAX_CHANNEL_TOPIC_LENGTH,
WS_EVENTS,
+ slugify,
} from "@alook/shared"
import type { Database } from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
@@ -67,7 +68,11 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
if (!trimmed || trimmed.length > MAX_CHANNEL_NAME_LENGTH) {
return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)
}
- changes.name = trimmed
+ const normalized = slugify(trimmed)
+ if (!normalized) {
+ return writeError("name is required", 400)
+ }
+ changes.name = normalized
}
if (body.topic !== undefined) {
if (typeof body.topic !== "string") return writeError("topic must be a string", 400)
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.test.ts
new file mode 100644
index 000000000..2c777bf72
--- /dev/null
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetMember = vi.fn()
+const mockCreateChannel = vi.fn()
+const mockLogAction = vi.fn()
+const mockFanOut = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
+ communityChannel: {
+ createChannel: (...a: unknown[]) => mockCreateChannel(...a),
+ },
+ communityAuditLog: {
+ logAction: (...a: unknown[]) => mockLogAction(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+const ctx = { params: { id: "s1" } } as any
+
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/servers/s1/channels", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ })
+}
+
+describe("POST /api/community/servers/[id]/channels", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
+ mockFanOut.mockResolvedValue(undefined)
+ mockLogAction.mockResolvedValue(undefined)
+ })
+
+ it("normalizes a spaced name via slugify before creating the channel", async () => {
+ mockCreateChannel.mockResolvedValue({
+ id: "c1",
+ name: "General-Chat",
+ type: "text",
+ categoryId: null,
+ topic: null,
+ position: 0,
+ createdAt: "2026-07-02T00:00:00.000Z",
+ })
+
+ const res = await POST(postReq({ name: "General Chat" }), ctx)
+ expect(res.status).toBe(201)
+ expect(mockCreateChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ name: "General-Chat" }),
+ )
+ })
+
+ it("returns 400 (and never calls createChannel) when the name is all disallowed characters", async () => {
+ const res = await POST(postReq({ name: "###" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockCreateChannel).not.toHaveBeenCalled()
+ expect(mockFanOut).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index c682cbe8f..effa89707 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -9,6 +9,7 @@ import {
MAX_CHANNEL_NAME_LENGTH,
MAX_CHANNEL_TOPIC_LENGTH,
WS_EVENTS,
+ slugify,
type ChannelType,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
@@ -34,10 +35,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (!body.name || typeof body.name !== "string") {
return writeError("name is required", 400)
}
- const name = body.name.trim()
- if (!name || name.length > MAX_CHANNEL_NAME_LENGTH) {
+ const trimmed = body.name.trim()
+ if (!trimmed || trimmed.length > MAX_CHANNEL_NAME_LENGTH) {
return writeError(`name must be 1-${MAX_CHANNEL_NAME_LENGTH} characters`, 400)
}
+ const name = slugify(trimmed)
+ if (!name) {
+ return writeError("name is required", 400)
+ }
if (body.type !== undefined && !isChannelType(body.type)) {
return writeError("type must be 'text' or 'forum'", 400)
}
diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.ts
new file mode 100644
index 000000000..4672fcdd5
--- /dev/null
+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts
@@ -0,0 +1,219 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetMember = vi.fn()
+const mockUpdateServer = vi.fn()
+const mockLogAction = vi.fn()
+const mockFanOut = vi.fn()
+const mockGetServer = vi.fn()
+const mockListServerChannels = vi.fn()
+const mockListUnreadChannels = vi.fn()
+const mockFindManyCategories = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => ({
+ query: { communityCategory: { findMany: (...a: unknown[]) => mockFindManyCategories(...a) } },
+ })),
+}))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
+ communityServer: {
+ getServer: (...a: unknown[]) => mockGetServer(...a),
+ updateServer: (...a: unknown[]) => mockUpdateServer(...a),
+ },
+ communityChannel: {
+ listServerChannels: (...a: unknown[]) => mockListServerChannels(...a),
+ },
+ communityInbox: {
+ listUnreadChannels: (...a: unknown[]) => mockListUnreadChannels(...a),
+ },
+ communityAuditLog: {
+ logAction: (...a: unknown[]) => mockLogAction(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { GET, PATCH } from "./route"
+
+const ctx = { params: { id: "s1" } } as any
+
+function patchReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/servers/s1", {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ })
+}
+
+describe("PATCH /api/community/servers/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
+ mockFanOut.mockResolvedValue(undefined)
+ mockLogAction.mockResolvedValue(undefined)
+ })
+
+ it("normalizes a spaced rename via slugify before calling updateServer", async () => {
+ mockUpdateServer.mockResolvedValue({ id: "s1", name: "My-Home" })
+
+ const res = await PATCH(patchReq({ name: "My Home" }), ctx)
+ expect(res.status).toBe(200)
+ expect(mockUpdateServer).toHaveBeenCalledWith(expect.anything(), "s1", { name: "My-Home" })
+ })
+
+ it("returns 400 (and never calls updateServer) when the renamed name is all disallowed characters", async () => {
+ const res = await PATCH(patchReq({ name: "///" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockUpdateServer).not.toHaveBeenCalled()
+ })
+
+ it("returns 403 when the caller is not an admin/owner", async () => {
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
+
+ const res = await PATCH(patchReq({ name: "My Home" }), ctx)
+ expect(res.status).toBe(403)
+ expect(mockUpdateServer).not.toHaveBeenCalled()
+ })
+})
+
+// ── GET — channel unread projection ──────────────────────────────────────
+describe("GET /api/community/servers/[id]", () => {
+ const getReq = () => new NextRequest("http://localhost/api/community/servers/s1")
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
+ mockGetServer.mockResolvedValue({
+ id: "s1",
+ name: "Server",
+ description: "",
+ icon: null,
+ ownerId: "u_owner",
+ })
+ mockFindManyCategories.mockResolvedValue([
+ { id: "cat_A", serverId: "s1", name: "Category A", position: 0, private: 0 },
+ ])
+ })
+
+ it("a channel with lastMessageAt > lastReadAt (has read-state row) is returned with unread: true", async () => {
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ ])
+ mockListUnreadChannels.mockResolvedValue([
+ { channelId: "ch_1", channelName: "general", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: "t1" },
+ ])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: true })
+ })
+
+ it("a channel the viewer has already read is returned with unread: false", async () => {
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ ])
+ mockListUnreadChannels.mockResolvedValue([])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })
+ })
+
+ it("a channel unread since before the viewer's read-state existed (no read-state row, lastMessageAt > joinedAt) is returned with unread: true", async () => {
+ // listUnreadChannels already applies isChannelUnread — the route just
+ // trusts its output, so a row present in the unread list (regardless of
+ // lastReadAt being null) must project unread: true.
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ ])
+ mockListUnreadChannels.mockResolvedValue([
+ { channelId: "ch_1", channelName: "general", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: null },
+ ])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: true })
+ })
+
+ it("a channel with historical messages predating membership is returned with unread: false (no false-positive on first join)", async () => {
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ ])
+ // isChannelUnread already excluded this row upstream — listUnreadChannels
+ // never returns it.
+ mockListUnreadChannels.mockResolvedValue([])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })
+ })
+
+ it("an unread channel belonging to a different server is not counted — scoped correctly by serverId", async () => {
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ ])
+ mockListUnreadChannels.mockResolvedValue([
+ { channelId: "ch_other", channelName: "other", serverId: "s2", serverName: "Other", lastMessageAt: "t2", lastReadAt: null },
+ ])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })
+ })
+
+ it("projects unread onto both categorized channels and the synthetic __uncategorized__ bucket", async () => {
+ mockListServerChannels.mockResolvedValue([
+ { id: "ch_1", serverId: "s1", categoryId: "cat_A", name: "general", tags: [] },
+ { id: "ch_2", serverId: "s1", categoryId: null, name: "loose", tags: [] },
+ ])
+ mockListUnreadChannels.mockResolvedValue([
+ { channelId: "ch_2", channelName: "loose", serverId: "s1", serverName: "Server", lastMessageAt: "t2", lastReadAt: null },
+ ])
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json()
+ const uncategorized = body.categories.find((c: { id: string }) => c.id === "__uncategorized__")
+ expect(uncategorized.channels[0]).toMatchObject({ id: "ch_2", unread: true })
+ expect(body.categories[0].channels[0]).toMatchObject({ id: "ch_1", unread: false })
+ })
+
+ it("returns 403 when the caller is not a member", async () => {
+ mockGetMember.mockResolvedValue(null)
+ mockListServerChannels.mockResolvedValue([])
+ mockListUnreadChannels.mockResolvedValue([])
+
+ const res = await GET(getReq(), ctx)
+ expect(res.status).toBe(403)
+ expect(mockGetServer).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index 158a7c284..648c0620f 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -8,6 +8,7 @@ import {
MAX_SERVER_NAME_LENGTH,
MAX_SERVER_DESCRIPTION_LENGTH,
WS_EVENTS,
+ slugify,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { logAudit } from "@/lib/community/audit"
@@ -22,17 +23,28 @@ export const GET = withAuth(async (_req, ctx) => {
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const [server, channels, categories] = await Promise.all([
+ const [server, rawChannels, categories, unreadRows] = await Promise.all([
queries.communityServer.getServer(db, serverId),
queries.communityChannel.listServerChannels(db, serverId),
db.query.communityCategory.findMany({
where: (t, { eq }) => eq(t.serverId, serverId),
orderBy: (t, { asc }) => [asc(t.position)],
}),
+ queries.communityInbox.listUnreadChannels(db, ctx.userId),
])
if (!server) return writeError("server not found", 404)
+ // Project the viewer's per-channel unread state onto the shared `channels`
+ // array once, before splitting into categorized/uncategorized — so both
+ // branches inherit `unread` from the same source instead of two separate
+ // maps. `listUnreadChannels` scans all of the viewer's servers; scope it
+ // down to this one via the Set.
+ const unreadIds = new Set(
+ unreadRows.filter((r) => r.serverId === serverId).map((r) => r.channelId),
+ )
+ const channels = rawChannels.map((ch) => ({ ...ch, unread: unreadIds.has(ch.id) }))
+
const categoriesWithChannels = categories.map((c) => ({
...c,
channels: channels.filter((ch) => ch.categoryId === c.id),
@@ -82,7 +94,11 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
if (!trimmed || trimmed.length > MAX_SERVER_NAME_LENGTH) {
return writeError(`name must be 1-${MAX_SERVER_NAME_LENGTH} characters`, 400)
}
- changes.name = trimmed
+ const normalized = slugify(trimmed)
+ if (!normalized) {
+ return writeError("name is required", 400)
+ }
+ changes.name = normalized
}
if (body.description !== undefined) {
if (typeof body.description !== "string") {
diff --git a/src/web/src/app/api/community/servers/route.test.ts b/src/web/src/app/api/community/servers/route.test.ts
index 6b74521c4..acec79c63 100644
--- a/src/web/src/app/api/community/servers/route.test.ts
+++ b/src/web/src/app/api/community/servers/route.test.ts
@@ -110,6 +110,27 @@ describe("POST /api/community/servers", () => {
expect(fanOut).not.toHaveBeenCalled()
})
+ it("normalizes a spaced name via slugify before creating the server", async () => {
+ createServer.mockResolvedValue({
+ server: { id: "srv_1", name: "My-Home", ownerId: "u1" },
+ ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice" },
+ })
+
+ const res = await POST(postReq({ name: "My Home" }))
+ expect(res.status).toBe(201)
+ expect(createServer).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ name: "My-Home" }),
+ )
+ })
+
+ it("returns 400 (and never calls createServer) when the name is all disallowed characters", async () => {
+ const res = await POST(postReq({ name: "///" }))
+ expect(res.status).toBe(400)
+ expect(createServer).not.toHaveBeenCalled()
+ expect(fanOut).not.toHaveBeenCalled()
+ })
+
it("returns 201 { server } and does not leak ownerMember to the response body", async () => {
const server = { id: "srv_x", name: "S", ownerId: "u1" }
createServer.mockResolvedValue({
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index d98652763..ca31b0cfd 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -8,6 +8,7 @@ import {
MAX_SERVER_DESCRIPTION_LENGTH,
ROLES,
WS_EVENTS,
+ slugify,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { serverIconUrl } from "@/lib/community/storage"
@@ -32,10 +33,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (!body.name || typeof body.name !== "string") {
return writeError("name is required", 400)
}
- const name = body.name.trim()
- if (!name || name.length > MAX_SERVER_NAME_LENGTH) {
+ const trimmed = body.name.trim()
+ if (!trimmed || trimmed.length > MAX_SERVER_NAME_LENGTH) {
return writeError(`name must be 1-${MAX_SERVER_NAME_LENGTH} characters`, 400)
}
+ const name = slugify(trimmed)
+ if (!name) {
+ return writeError("name is required", 400)
+ }
let description: string | undefined
if (body.description !== undefined) {
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsx
index 79075ccf8..f8dfa0e13 100644
--- a/src/web/src/app/community/channels/layout.tsx
+++ b/src/web/src/app/community/channels/layout.tsx
@@ -2,11 +2,15 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"
import { useParams, useRouter, useSearchParams } from "next/navigation"
+import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useChannelTree } from "@/components/community/use-channel-tree"
+import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
+import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell-frame"
import { ChannelSidebar } from "@/components/community/channel-sidebar"
import { ServerSettings } from "@/components/community/server-settings"
@@ -56,6 +60,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const router = useRouter()
const bp = useBreakpoint()
+ const queryClient = useQueryClient()
const currentUser = useCurrentUser()
const { server: currentServer } = useServer(serverId)
const membersHook = useServerMembers(serverId)
@@ -232,10 +237,25 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
// the user then never scrolls to the new messages, the server-side
// watermark stays put and the badge will re-appear on next refetch,
// which is the correct behavior.
+ //
+ // Also patch the `ServerDetail` query cache (not just the local
+ // `channelTree` state) to `unread: false` for this channel, via the same
+ // `patchChannelUnread` helper the WS handler uses for the opposite
+ // direction. This is still just an optimistic *client-side* tint — the
+ // server-side watermark stays authoritative, and a subsequent real
+ // refetch will correctly re-flip `unread` to `true` if the user never
+ // actually scrolled into the channel. Without this cache patch, an
+ // unrelated sibling-channel WS patch would resurrect the just-cleared dot
+ // before the user even navigates away — `useChannelTree`'s metadata merge
+ // trusts the cache unconditionally, so both directions must write to it.
router.push(`/community/channels/${serverId}/${id}`)
channelTree.markRead(id)
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(serverId),
+ (cache) => patchChannelUnread(cache, id, false),
+ )
if (bp === "mobile") setMobileZone("messages")
- }, [router, serverId, channelTree, bp])
+ }, [router, serverId, channelTree, bp, queryClient])
const onSidebarOpenSettings = useCallback((section?: SettingsSection) => {
if (section) setSettingsSection(section)
diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsx
index 577dc2f3e..6df1c96e7 100644
--- a/src/web/src/components/community/channel-header.tsx
+++ b/src/web/src/components/community/channel-header.tsx
@@ -9,6 +9,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { ChannelIcon } from "./channel-icon"
+import { SlugHint } from "./slug-hint"
+import { previewSlug } from "@/lib/community/slug-preview"
import type { RightPanel } from "./_types"
// Skeleton header for the loading frame between route change and channel
@@ -201,9 +203,10 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:
useEffect(() => {
if (!open) setDraft(label)
}, [label, open])
+ const draftPreview = previewSlug(draft)
const save = () => {
const trimmed = draft.trim()
- if (trimmed && trimmed !== label) onRename(trimmed)
+ if (draftPreview.slug && trimmed !== label) onRename(trimmed)
setOpen(false)
}
return (
@@ -228,11 +231,12 @@ function BreadcrumbRename({ label, onRename }: { label: string; onRename: (name:
className="h-10"
autoFocus
/>
+ <SlugHint {...draftPreview} />
</label>
</div>
<DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3">
<Button variant="ghost" size="sm" onClick={() => setOpen(false)}>Cancel</Button>
- <Button size="sm" onClick={save} disabled={!draft.trim()}>Save</Button>
+ <Button size="sm" onClick={save} disabled={!draftPreview.slug}>Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index 58753ced6..1b151910b 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -28,6 +28,7 @@ import {
buildCommunityChannelRefExtension,
EMPTY_CHANNEL_REF_STATE,
rankChannelRefItems,
+ toChannelRefCommandProps,
type ChannelRefCandidate,
type ChannelRefPopupState,
} from "@/lib/community/channel-ref-extension"
@@ -479,7 +480,7 @@ function ChannelRefList({ state }: { state: ChannelRefPopupState }) {
item={item}
selected={i === selectedIndex}
showServerPrefix={spansMultipleServers}
- onSelect={() => command({ id: item.id, label: item.name, serverId: item.serverId })}
+ onSelect={() => command(toChannelRefCommandProps(item))}
/>
))}
</div>
diff --git a/src/web/src/components/community/create-channel-dialog.tsx b/src/web/src/components/community/create-channel-dialog.tsx
index 0cb2d4f38..a87af8a87 100644
--- a/src/web/src/components/community/create-channel-dialog.tsx
+++ b/src/web/src/components/community/create-channel-dialog.tsx
@@ -6,6 +6,8 @@ import { ChannelIcon } from "./channel-icon"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
+import { SlugHint } from "./slug-hint"
+import { previewSlug } from "@/lib/community/slug-preview"
import type { ChannelType } from "@alook/shared"
// Create / edit Channel dialog. v0.1 supports Text + Forum only. No private toggle.
@@ -26,9 +28,10 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
{ value: "forum", icon: ListChevronsUpDown, label: "Forum", desc: "Create a space for organized discussions" },
]
+ const namePreview = previewSlug(name)
const submit = () => {
const trimmed = name.trim()
- if (!trimmed) return
+ if (!namePreview.slug) return
onCreate({ name: trimmed, type })
onClose()
}
@@ -42,30 +45,30 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
</DialogHeader>
<div className="space-y-4 px-4 pb-5">
{!editing && (
- <div>
- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Channel Type</div>
- <div className="space-y-2">
- {options.map((o) => (
- <button
- key={o.value}
- onClick={() => setType(o.value)}
- className={[
- "flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors",
- type === o.value ? "border-primary bg-accent" : "border-border bg-card hover:bg-accent/50",
- ].join(" ")}
- >
- <o.icon className="size-5 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium">{o.label}</div>
- <div className="text-xs text-muted-foreground">{o.desc}</div>
- </div>
- <span className={`grid size-4 shrink-0 place-items-center rounded-full border ${type === o.value ? "border-primary" : "border-muted-foreground"}`}>
- {type === o.value && <span className="size-2 rounded-full bg-primary" />}
- </span>
- </button>
- ))}
+ <div>
+ <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Channel Type</div>
+ <div className="space-y-2">
+ {options.map((o) => (
+ <button
+ key={o.value}
+ onClick={() => setType(o.value)}
+ className={[
+ "flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors",
+ type === o.value ? "border-primary bg-accent" : "border-border bg-card hover:bg-accent/50",
+ ].join(" ")}
+ >
+ <o.icon className="size-5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">{o.label}</div>
+ <div className="text-xs text-muted-foreground">{o.desc}</div>
+ </div>
+ <span className={`grid size-4 shrink-0 place-items-center rounded-full border ${type === o.value ? "border-primary" : "border-muted-foreground"}`}>
+ {type === o.value && <span className="size-2 rounded-full bg-primary" />}
+ </span>
+ </button>
+ ))}
+ </div>
</div>
- </div>
)}
<label className="block">
<div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Channel Name</div>
@@ -81,11 +84,12 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
className="h-10 pl-9"
/>
</div>
+ <SlugHint {...namePreview} />
</label>
</div>
<DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3">
<Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
- <Button size="sm" onClick={submit} disabled={!name.trim()}>{editing ? "Save" : "Create Channel"}</Button>
+ <Button size="sm" onClick={submit} disabled={!namePreview.slug}>{editing ? "Save" : "Create Channel"}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
diff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-post.tsx
index 24020a39f..1f72d8a09 100644
--- a/src/web/src/components/community/create-forum-post.tsx
+++ b/src/web/src/components/community/create-forum-post.tsx
@@ -5,6 +5,8 @@ import { X, Smile } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { EmojiPickerPopover } from "./emoji-picker"
+import { SlugHint } from "./slug-hint"
+import { previewSlug } from "@/lib/community/slug-preview"
export type NewForumPost = { name: string; content: string; tags: string[] }
@@ -20,9 +22,10 @@ export function CreateForumPost({ tags, onCancel, onPost }: {
const toggleTag = (t: string) =>
setSelected((prev) => (prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]))
+ const titlePreview = previewSlug(title)
const submit = () => {
const name = title.trim()
- if (!name) return
+ if (!titlePreview.slug) return
onPost({ name, content: body.trim(), tags: selected })
}
@@ -39,6 +42,7 @@ export function CreateForumPost({ tags, onCancel, onPost }: {
placeholder="Title"
className="w-full bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground"
/>
+ <SlugHint {...titlePreview} />
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
@@ -71,7 +75,7 @@ export function CreateForumPost({ tags, onCancel, onPost }: {
<Smile className="size-5" />
</button>
</EmojiPickerPopover>
- <Button size="sm" onClick={submit} disabled={!title.trim() || !body.trim()}>Post</Button>
+ <Button size="sm" onClick={submit} disabled={!titlePreview.slug || !body.trim()}>Post</Button>
</div>
</div>
)
diff --git a/src/web/src/components/community/create-server-dialog.tsx b/src/web/src/components/community/create-server-dialog.tsx
index 15e3855b6..29850913c 100644
--- a/src/web/src/components/community/create-server-dialog.tsx
+++ b/src/web/src/components/community/create-server-dialog.tsx
@@ -6,6 +6,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field } from "./field"
+import { SlugHint } from "./slug-hint"
+import { previewSlug } from "@/lib/community/slug-preview"
// Create / join server dialog.
export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
@@ -20,6 +22,7 @@ export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
const [iconPreview, setIconPreview] = useState<string | null>(null)
const fileRef = useRef<HTMLInputElement>(null)
+ const namePreview = previewSlug(name)
const pickIcon = () => fileRef.current?.click()
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
@@ -62,7 +65,10 @@ export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
</button>
<span className="text-xs text-muted-foreground">{iconPreview ? "Change icon" : "Upload an icon"}</span>
</div>
- <Field label="Server name"><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="My community" /></Field>
+ <Field label="Server name">
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="My community" />
+ <SlugHint {...namePreview} />
+ </Field>
</div>
)}
{step === "join" && (
@@ -74,7 +80,7 @@ export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
<Button variant="ghost" size="sm" onClick={() => setStep("choose")}>Back</Button>
<Button
size="sm"
- disabled={step === "create" ? !name.trim() : !invite.trim()}
+ disabled={step === "create" ? !namePreview.slug : !invite.trim()}
onClick={() => {
if (step === "create") onCreateServer?.(name.trim(), iconFile ?? undefined)
else onJoinServer?.(invite.trim())
diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.ts
index 46a90942c..8c96e304a 100644
--- a/src/web/src/components/community/message-markdown.test.ts
+++ b/src/web/src/components/community/message-markdown.test.ts
@@ -54,28 +54,56 @@ describe("preprocessMarkdown", () => {
expect(preprocessMarkdown("/studio/general")).toBe("<channelref>/studio/general</channelref>")
})
+ it("wraps a hyphenated, single-token name segment (post-slugify server/channel names)", () => {
+ expect(preprocessMarkdown("see /Server-Name/general")).toBe(
+ "see <channelref>/Server-Name/general</channelref>",
+ )
+ })
+
it("leaves text/studio/general (no leading space) untouched", () => {
expect(preprocessMarkdown("text/studio/general")).toBe("text/studio/general")
})
- it("does NOT wrap a 3+-segment docs-style path — trailing `/segment` fails the terminator boundary", () => {
- // Regression guard: `CHANNEL_REF_REGEX` used to greedily eat `/api/user`
- // out of a docs URL, orphaning `/123` as broken trailing text next to a
- // muted pill. The trailing boundary lookahead rejects this — a real
- // 2-segment ref must sit alone (space, EOS, or punctuation after it).
- expect(preprocessMarkdown("look at /api/user/123")).toBe("look at /api/user/123")
- expect(preprocessMarkdown("hit /docs/api/v1 first")).toBe("hit /docs/api/v1 first")
+ it("a 3+-segment docs-style path now wraps its first 2 segments, leaving the rest as trailing text — accepted tradeoff of the broadened single-token-segment charset, not a regression to fix", () => {
+ // `CHANNEL_REF_REGEX`'s segment charset is now "anything but whitespace/
+ // `/`/`#`" (see its doc comment) so server/channel names round-trip as a
+ // single token. A 3-segment docs path shape-matches its first two
+ // segments as a ref and leaves the leftover `/segment` as plain text
+ // next to it — this degrades gracefully (an unresolvable ref falls back
+ // to plain, unstyled text per `channel-ref-pill.tsx`), it doesn't crash
+ // or corrupt anything.
+ expect(preprocessMarkdown("look at /api/user/123")).toBe(
+ "look at <channelref>/api/user</channelref>/123",
+ )
+ expect(preprocessMarkdown("hit /docs/api/v1 first")).toBe(
+ "hit <channelref>/docs/api</channelref>/v1 first",
+ )
+ })
+
+ it("a punctuation-heavy non-ref token now shape-matches and gets wrapped — accepted tradeoff, not a regression to fix", () => {
+ // `nginx.conf` has no `/`/`#`/whitespace, so it's a valid single-token
+ // channel segment under the broadened charset even though it's not a
+ // real channel name; it just fails to resolve and falls back to plain
+ // text at render time (`channel-ref-pill.tsx`'s existing miss-fallback).
+ expect(preprocessMarkdown("see the config at /etc/nginx.conf")).toBe(
+ "see the config at <channelref>/etc/nginx.conf</channelref>",
+ )
})
- it("still wraps a 2-segment ref followed by punctuation (period, comma, close-paren)", () => {
+ it("a 2-segment ref followed by punctuation now absorbs the punctuation into the segment (charset no longer excludes it) — accepted tradeoff, not a regression to fix", () => {
+ // The old nanoid-only charset excluded `.`/`,`/`)`, so trailing
+ // punctuation stayed outside the tag. The new charset only excludes
+ // whitespace/`/`/`#`, so it's absorbed into the (still single-token)
+ // segment instead. Still not a crash, still degrades to plain text if
+ // unresolvable — see the plan's "Known limitations & accepted risks".
expect(preprocessMarkdown("see /studio/general.")).toBe(
- "see <channelref>/studio/general</channelref>.",
+ "see <channelref>/studio/general.</channelref>",
)
expect(preprocessMarkdown("visit /studio/general, ok?")).toBe(
- "visit <channelref>/studio/general</channelref>, ok?",
+ "visit <channelref>/studio/general,</channelref> ok?",
)
expect(preprocessMarkdown("(see /studio/general)")).toBe(
- "(see <channelref>/studio/general</channelref>)",
+ "(see <channelref>/studio/general)</channelref>",
)
})
diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsx
index 65b5ad167..45b9d79d5 100644
--- a/src/web/src/components/community/message-markdown.tsx
+++ b/src/web/src/components/community/message-markdown.tsx
@@ -3,20 +3,22 @@ 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.
+// path grammar (`parseRef`/`formatRef` in `community-cli-contract.ts`).
+// Segment charset `[^\s/#]+` (any run of non-whitespace, non-`/`, non-`#`)
+// works because server/channel `name`s are guaranteed free of whitespace/
+// `/`/`#` at creation/rename time (`slugify()`, applied by every write
+// route) — a single-token segment can never be ambiguous, so refs render by
+// display *name* now (see `channel-ref-extension.ts`'s `renderText`)
+// instead of id. The pinned-message form (`#N` directly, no slash) is
+// intentionally not matched — see plan §1 for why.
//
-// Trailing `(?=\s|$|[.,;:!?)\]])` boundary lookahead: a 2-segment path
-// followed by ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must
-// NOT match — otherwise CHANNEL_REF_REGEX greedily takes `/api/user` and
-// orphans `/123` as trailing text next to a broken pill. Requiring a
-// terminator forces the match to sit ONLY on a real leaf ref.
-const CHANNEL_REF_REGEX = /(^|\s)(\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?)(?=\s|$|[.,;:!?)\]])/g
+// Accepted tradeoff: this broadened charset also shape-matches punctuation-
+// heavy non-ref text that happens to look like a path (e.g. `/etc/nginx.conf`,
+// `a/b/c`) — those just fail to resolve and fall back to plain, unstyled
+// text (`channel-ref-pill.tsx`'s existing miss-fallback), no crash. This is
+// intentional, not a regression to "fix": see the channel-ref-slugification
+// plan's "Known limitations & accepted risks".
+const CHANNEL_REF_REGEX = /(^|\s)(\/[^\s/#]+\/[^\s/#]+(?:\/#\d+)?)/g
// Sentinels for stashing code spans/fences (private-use chars — won't collide with
// real text or markdown punctuation).
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index 6e9970053..cff0bad6d 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -16,6 +16,8 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuIte
import { Skeleton } from "@/components/ui/skeleton"
import { Avatar } from "./avatar"
import { Field } from "./field"
+import { SlugHint } from "./slug-hint"
+import { previewSlug } from "@/lib/community/slug-preview"
import type { SettingsSection, Member, Role, InviteRow, AuditEntry, OpenProfile } from "./_types"
const SETTABLE_ROLES: Role[] = ["admin", "member"]
@@ -69,52 +71,52 @@ export function ServerSettings({
]
return (
<>
- <ConfirmDialog
- open={confirmDelete}
- onOpenChange={setConfirmDelete}
- title={`Delete "${serverName}"?`}
- description="This cannot be undone. All channels, messages, and members will be permanently removed."
- confirmLabel="Delete Server"
- confirmVariant="destructive"
- onConfirm={() => { setConfirmDelete(false); onDeleteServer?.() }}
- />
- <Tabs
- orientation="vertical"
- value={section}
- onValueChange={(v) => setSection(v as SettingsSection)}
- className="min-h-0 flex-1 flex-row gap-0"
- >
- {/* settings nav */}
- <nav className="flex w-60 shrink-0 flex-col gap-2 overflow-y-auto thin-scrollbar border-r border-border p-4" style={{ background: "var(--d-rail)" }}>
- <div className="px-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{serverName}</div>
- <TabsList variant="line" className="h-auto w-full flex-col gap-1">
- {nav.map((n) => (
- <TabsTrigger key={n.id} value={n.id} className="h-9 w-full justify-start gap-2">
- <n.icon className="size-4" /> {n.label}
- </TabsTrigger>
- ))}
- </TabsList>
- <Separator className="my-1" />
- <Button variant="destructive" size="sm" className="justify-start" onClick={() => setConfirmDelete(true)}><Trash2 className="size-4" /> Delete Server</Button>
- </nav>
+ <ConfirmDialog
+ open={confirmDelete}
+ onOpenChange={setConfirmDelete}
+ title={`Delete "${serverName}"?`}
+ description="This cannot be undone. All channels, messages, and members will be permanently removed."
+ confirmLabel="Delete Server"
+ confirmVariant="destructive"
+ onConfirm={() => { setConfirmDelete(false); onDeleteServer?.() }}
+ />
+ <Tabs
+ orientation="vertical"
+ value={section}
+ onValueChange={(v) => setSection(v as SettingsSection)}
+ className="min-h-0 flex-1 flex-row gap-0"
+ >
+ {/* settings nav */}
+ <nav className="flex w-60 shrink-0 flex-col gap-2 overflow-y-auto thin-scrollbar border-r border-border p-4" style={{ background: "var(--d-rail)" }}>
+ <div className="px-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{serverName}</div>
+ <TabsList variant="line" className="h-auto w-full flex-col gap-1">
+ {nav.map((n) => (
+ <TabsTrigger key={n.id} value={n.id} className="h-9 w-full justify-start gap-2">
+ <n.icon className="size-4" /> {n.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ <Separator className="my-1" />
+ <Button variant="destructive" size="sm" className="justify-start" onClick={() => setConfirmDelete(true)}><Trash2 className="size-4" /> Delete Server</Button>
+ </nav>
- {/* settings body */}
- <div className="flex min-w-0 flex-1 flex-col bg-background">
- <header className="flex h-12 shrink-0 items-center border-b border-border px-4">
- <h1 className="flex-1 text-lg font-semibold capitalize">{section === "audit" ? "Audit Log" : section}</h1>
- <button onClick={onClose} className="flex flex-col items-center text-muted-foreground hover:text-foreground" aria-label="Close settings">
- <span className="grid size-8 place-items-center rounded-full border border-current"><X className="size-4" /></span>
- </button>
- </header>
- <div className="flex-1 overflow-y-auto thin-scrollbar p-4">
- <TabsContent value="overview"><SettingsOverview serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} /></TabsContent>
- <TabsContent value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></TabsContent>
- <TabsContent value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></TabsContent>
- <TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? "Only @mentions"} onSetLevel={onSetNotifLevel} /></TabsContent>
- <TabsContent value="audit"><SettingsAudit auditLog={auditLog} loading={auditLogLoading} /></TabsContent>
+ {/* settings body */}
+ <div className="flex min-w-0 flex-1 flex-col bg-background">
+ <header className="flex h-12 shrink-0 items-center border-b border-border px-4">
+ <h1 className="flex-1 text-lg font-semibold capitalize">{section === "audit" ? "Audit Log" : section}</h1>
+ <button onClick={onClose} className="flex flex-col items-center text-muted-foreground hover:text-foreground" aria-label="Close settings">
+ <span className="grid size-8 place-items-center rounded-full border border-current"><X className="size-4" /></span>
+ </button>
+ </header>
+ <div className="flex-1 overflow-y-auto thin-scrollbar p-4">
+ <TabsContent value="overview"><SettingsOverview serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} /></TabsContent>
+ <TabsContent value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></TabsContent>
+ <TabsContent value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></TabsContent>
+ <TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? "Only @mentions"} onSetLevel={onSetNotifLevel} /></TabsContent>
+ <TabsContent value="audit"><SettingsAudit auditLog={auditLog} loading={auditLogLoading} /></TabsContent>
+ </div>
</div>
- </div>
- </Tabs>
+ </Tabs>
</>
)
}
@@ -129,7 +131,11 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadI
// in-progress edits — keep it simple and let mount handle it.
const [name, setName] = useState(serverName)
const [desc, setDesc] = useState(serverDescription ?? "")
- const save = () => onUpdateServer?.(name, desc)
+ const namePreview = previewSlug(name)
+ const save = () => {
+ if (namePreview.invalid) return
+ onUpdateServer?.(name, desc)
+ }
return (
<div className="max-w-xl space-y-4">
<div className="flex items-center gap-4">
@@ -144,7 +150,10 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadI
<Button variant="secondary" size="sm" className="mt-2" onClick={onUploadIcon}>Upload image</Button>
</div>
</div>
- <Field label="Server name"><Input value={name} onChange={(e) => setName(e.target.value)} onBlur={save} /></Field>
+ <Field label="Server name">
+ <Input value={name} onChange={(e) => setName(e.target.value)} onBlur={save} />
+ <SlugHint {...namePreview} />
+ </Field>
<Field label="Description"><Textarea className="h-20 resize-none" value={desc} onChange={(e) => setDesc(e.target.value)} onBlur={save} /></Field>
</div>
)
diff --git a/src/web/src/components/community/slug-hint.test.ts b/src/web/src/components/community/slug-hint.test.ts
new file mode 100644
index 000000000..df0a9c7f1
--- /dev/null
+++ b/src/web/src/components/community/slug-hint.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from "vitest"
+import { SlugHint } from "./slug-hint"
+
+type PEl<C> = { props: { children: C } }
+
+describe("SlugHint", () => {
+ it("renders nothing when neither invalid nor changed", () => {
+ expect(SlugHint({ slug: "general", invalid: false, changed: false })).toBeNull()
+ })
+
+ it("renders the invalid message when invalid", () => {
+ const el = SlugHint({ slug: "", invalid: true, changed: false }) as PEl<string>
+ expect(el.props.children).toContain("space, / or #")
+ })
+
+ it("renders 'Will be saved as <slug>' when changed", () => {
+ const el = SlugHint({ slug: "My-Home", invalid: false, changed: true }) as PEl<
+ [string, PEl<string>]
+ >
+ expect(el.props.children[0]).toBe("Will be saved as ")
+ expect(el.props.children[1].props.children).toBe("My-Home")
+ })
+
+ it("invalid takes precedence over changed when both are set", () => {
+ const el = SlugHint({ slug: "x", invalid: true, changed: true }) as PEl<string>
+ expect(el.props.children).toContain("space, / or #")
+ })
+})
diff --git a/src/web/src/components/community/slug-hint.tsx b/src/web/src/components/community/slug-hint.tsx
new file mode 100644
index 000000000..738df5b80
--- /dev/null
+++ b/src/web/src/components/community/slug-hint.tsx
@@ -0,0 +1,17 @@
+import type { SlugPreview } from "@/lib/community/slug-preview"
+
+export function SlugHint({ slug, invalid, changed }: SlugPreview) {
+ if (invalid) {
+ return (
+ <p className="mt-1.5 text-xs text-destructive">
+ Add a character other than space, / or # to save this name
+ </p>
+ )
+ }
+ if (!changed) return null
+ return (
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ Will be saved as <span className="font-medium text-foreground">{slug}</span>
+ </p>
+ )
+}
diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsx
index 0d09c9615..3efece996 100644
--- a/src/web/src/components/community/sortable-server.tsx
+++ b/src/web/src/components/community/sortable-server.tsx
@@ -49,10 +49,7 @@ export function SortableServer({ server, active, onClick, onLeave, onOpenSetting
)}
</button>
{server.mentions > 0 && (
- <span
- className="pointer-events-none absolute -bottom-1 -right-1 grid min-w-5 place-items-center rounded-full border border-(--d-rail) px-1 text-[11px] font-black tracking-tight leading-4.5 text-white"
- style={{ background: "var(--destructive)", WebkitTextStroke: "0.4px currentColor" }}
- >
+ <span className="pointer-events-none absolute -bottom-1 -right-1 grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-[11px] font-bold text-primary-foreground ring-2 ring-(--d-rail)">
<NumberTicker value={server.mentions} />
</span>
)}
diff --git a/src/web/src/components/community/use-channel-tree.test.ts b/src/web/src/components/community/use-channel-tree.test.ts
index 73af37efd..eb92465aa 100644
--- a/src/web/src/components/community/use-channel-tree.test.ts
+++ b/src/web/src/components/community/use-channel-tree.test.ts
@@ -6,9 +6,10 @@ import {
moveChannelAcrossCategories,
reorderChannelsWithin,
reorderCategories,
+ mergeChannelMetadata,
type ChannelOrder,
} from "./use-channel-tree"
-import type { Channel } from "./_types"
+import type { Channel, Category } from "./_types"
const ch = (id: string): Channel => ({ id, name: id, active: false, unread: false })
@@ -71,3 +72,50 @@ describe("reorderCategories", () => {
expect(reorderCategories(cats, "cat_Z", "cat_A")).toBe(cats)
})
})
+
+// Regression: the sync effect's id-set early-return silently swallowed
+// metadata-only updates (unread/name) — see "The useChannelTree gap" in
+// plans/community-unread-indicators.md.
+describe("mergeChannelMetadata", () => {
+ const cat = (id: string, channels: Channel[]): Category => ({ id, name: id, channels })
+
+ it("flips an unread flag while ids are unchanged", () => {
+ const result = mergeChannelMetadata(order, [
+ cat("cat_A", [ch("a1"), { ...ch("a2"), unread: true }]),
+ cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
+ ])
+ expect(result.changed).toBe(true)
+ expect(result.next.cat_A.find((c) => c.id === "a2")?.unread).toBe(true)
+ // Untouched sibling channel keeps the same object reference.
+ expect(result.next.cat_A.find((c) => c.id === "a1")).toBe(order.cat_A[0])
+ })
+
+ it("picks up a channel rename while ids are unchanged", () => {
+ const result = mergeChannelMetadata(order, [
+ cat("cat_A", [ch("a1"), { ...ch("a2"), name: "renamed" }]),
+ cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
+ ])
+ expect(result.changed).toBe(true)
+ expect(result.next.cat_A.find((c) => c.id === "a2")?.name).toBe("renamed")
+ })
+
+ it("preserves category/channel order — only rewrites the changed field", () => {
+ const result = mergeChannelMetadata(order, [
+ cat("cat_A", [ch("a1"), { ...ch("a2"), unread: true }]),
+ cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
+ ])
+ expect(Object.keys(result.next)).toEqual(Object.keys(order))
+ expect(result.next.cat_B.map((c) => c.id)).toEqual(order.cat_B.map((c) => c.id))
+ // Every field on the changed channel other than the diffed ones is preserved.
+ expect(result.next.cat_A.find((c) => c.id === "a2")).toMatchObject({ id: "a2", active: false })
+ })
+
+ it("is a no-op (same reference, changed: false) when nothing differs", () => {
+ const result = mergeChannelMetadata(order, [
+ cat("cat_A", [ch("a1"), ch("a2")]),
+ cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),
+ ])
+ expect(result.changed).toBe(false)
+ expect(result.next).toBe(order)
+ })
+})
diff --git a/src/web/src/components/community/use-channel-tree.ts b/src/web/src/components/community/use-channel-tree.ts
index 869eb12c3..ab156ae6b 100644
--- a/src/web/src/components/community/use-channel-tree.ts
+++ b/src/web/src/components/community/use-channel-tree.ts
@@ -57,6 +57,36 @@ function removeChannelFrom(order: ChannelOrder, id: string): ChannelOrder {
return { ...order, [cat]: order[cat].filter((c) => c.id !== id) }
}
+/**
+ * Merge metadata-only field changes (`unread`, `name`) from the incoming
+ * `categories` prop into the existing per-category `order` state, keyed by
+ * channel id. Used by the sync effect when the channel/category *id set* is
+ * unchanged but a field like `unread` still needs to reach the render tree —
+ * preserves drag order/collapse state by only ever touching the matched
+ * channel's fields, never reshuffling arrays. Pure — exported for tests.
+ */
+export function mergeChannelMetadata(
+ order: ChannelOrder,
+ categories: Category[],
+): { next: ChannelOrder; changed: boolean } {
+ const incoming = new Map<string, Channel>()
+ for (const cat of categories) {
+ for (const ch of cat.channels) incoming.set(ch.id, ch)
+ }
+ let changed = false
+ const next: ChannelOrder = {}
+ for (const [catId, channels] of Object.entries(order)) {
+ next[catId] = channels.map((ch) => {
+ const src = incoming.get(ch.id)
+ if (!src) return ch
+ if (src.unread === ch.unread && src.name === ch.name) return ch
+ changed = true
+ return { ...ch, unread: src.unread, name: src.name }
+ })
+ }
+ return { next: changed ? next : order, changed }
+}
+
/** Reorder the category list itself. `activeCatId`/`overCatId` are category IDs. Pure. */
export function reorderCategories(catOrder: string[], activeCatId: string, overCatId: string): string[] {
const from = catOrder.indexOf(activeCatId)
@@ -110,7 +140,17 @@ export function useChannelTree(categories: Category[]) {
// Compare both category IDs and channel IDs to detect any change
const prevKey = prev.map((c) => `${c.id}:${c.channels.map((ch) => ch.id).join(",")}`).join("|")
const nextKey = categories.map((c) => `${c.id}:${c.channels.map((ch) => ch.id).join(",")}`).join("|")
- if (prevKey === nextKey) return
+ if (prevKey === nextKey) {
+ // Id sets are unchanged, but metadata fields (`unread`, `name`) may
+ // have changed underneath — e.g. a WS-driven cache patch or a refetch
+ // that only flips a flag. Merge those without resetting drag order or
+ // collapse state (see plans/community-unread-indicators.md).
+ setOrder((prevOrder) => {
+ const { next, changed } = mergeChannelMetadata(prevOrder, categories)
+ return changed ? next : prevOrder
+ })
+ return
+ }
setCatOrder(categories.map((c) => c.id))
setOrder(Object.fromEntries(categories.map((c) => [c.id, c.channels])))
setCatNames(Object.fromEntries(categories.map((c) => [c.id, c.name])))
diff --git a/src/web/src/hooks/community/server-detail-cache.test.ts b/src/web/src/hooks/community/server-detail-cache.test.ts
new file mode 100644
index 000000000..abf081100
--- /dev/null
+++ b/src/web/src/hooks/community/server-detail-cache.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from "vitest"
+import { patchChannelUnread } from "./server-detail-cache"
+import type { ServerDetail } from "./use-servers"
+
+function fixture(): ServerDetail {
+ return {
+ id: "srv_1",
+ name: "Server",
+ description: "",
+ icon: null,
+ ownerId: "u_owner",
+ categories: [
+ {
+ id: "cat_A",
+ name: "Category A",
+ channels: [
+ { id: "ch_a1", name: "general", active: false, unread: false },
+ { id: "ch_a2", name: "random", active: false, unread: false },
+ ],
+ },
+ {
+ id: "cat_B",
+ name: "Category B",
+ channels: [
+ { id: "ch_b1", name: "b1", active: false, unread: false },
+ ],
+ },
+ ],
+ }
+}
+
+describe("patchChannelUnread", () => {
+ it("flips the target channel's unread flag inside the correct category", () => {
+ const cache = fixture()
+ const next = patchChannelUnread(cache, "ch_a2", true)
+ expect(next?.categories[0].channels.find((c) => c.id === "ch_a2")?.unread).toBe(true)
+ })
+
+ it("leaves every other channel/category untouched — same object references for unrelated categories", () => {
+ const cache = fixture()
+ const next = patchChannelUnread(cache, "ch_a2", true)
+ // The sibling channel keeps its exact reference.
+ expect(next?.categories[0].channels.find((c) => c.id === "ch_a1")).toBe(cache.categories[0].channels[0])
+ // The unrelated category object itself is untouched (same reference).
+ expect(next?.categories[1]).toBe(cache.categories[1])
+ })
+
+ it("returns the input unchanged when cache is undefined", () => {
+ expect(patchChannelUnread(undefined, "ch_a1", true)).toBeUndefined()
+ })
+
+ it("returns the input unchanged (same reference) when the channel id doesn't exist anywhere", () => {
+ const cache = fixture()
+ const next = patchChannelUnread(cache, "ch_missing", true)
+ expect(next).toBe(cache)
+ })
+
+ it("works identically for unread: true (WS-arrival direction) and unread: false (click direction)", () => {
+ const cache = fixture()
+ const toTrue = patchChannelUnread(cache, "ch_a1", true)
+ expect(toTrue?.categories[0].channels.find((c) => c.id === "ch_a1")?.unread).toBe(true)
+ const toFalse = patchChannelUnread(toTrue, "ch_a1", false)
+ expect(toFalse?.categories[0].channels.find((c) => c.id === "ch_a1")?.unread).toBe(false)
+ })
+
+ // Regression: the "optimistic markRead stomp" found in plan review — see
+ // plans/community-unread-indicators.md §2 "Second-order risk". Without the
+ // click-time cache patch (channels/layout.tsx), A would have reverted to
+ // `true` here.
+ it("clicking channel A then a WS patch for sibling channel B does not resurrect A's cleared dot", () => {
+ let cache: ServerDetail | undefined = fixture()
+ // Seed A as unread (as if a message arrived earlier).
+ cache = patchChannelUnread(cache, "ch_a1", true)
+ // User clicks A — optimistic clear.
+ cache = patchChannelUnread(cache, "ch_a1", false)
+ // Unrelated WS message arrives for sibling channel B.
+ cache = patchChannelUnread(cache, "ch_a2", true)
+ expect(cache?.categories[0].channels.find((c) => c.id === "ch_a1")?.unread).toBe(false)
+ expect(cache?.categories[0].channels.find((c) => c.id === "ch_a2")?.unread).toBe(true)
+ })
+})
diff --git a/src/web/src/hooks/community/server-detail-cache.ts b/src/web/src/hooks/community/server-detail-cache.ts
new file mode 100644
index 000000000..6f954e07a
--- /dev/null
+++ b/src/web/src/hooks/community/server-detail-cache.ts
@@ -0,0 +1,33 @@
+import type { ServerDetail } from "@/hooks/community/use-servers"
+
+/**
+ * Flip a single channel's `unread` flag inside a cached `ServerDetail`,
+ * leaving every other channel/category untouched (same object references for
+ * unrelated categories). Shared by both write directions so the cache is
+ * always the single source of truth `useChannelTree`'s metadata merge can
+ * trust:
+ *
+ * - WS `message.create` for a channel in the currently-open server → `true`.
+ * - Clicking a channel in the sidebar (`channels/layout.tsx`) → `false`.
+ *
+ * Pure — exported for direct unit testing. No-ops (returns the input
+ * unchanged, same reference) when `cache` is undefined or `channelId` isn't
+ * found in any category.
+ */
+export function patchChannelUnread(
+ cache: ServerDetail | undefined,
+ channelId: string,
+ unread: boolean,
+): ServerDetail | undefined {
+ if (!cache) return cache
+ let touched = false
+ const categories = cache.categories.map((cat) => {
+ if (!cat.channels.some((c) => c.id === channelId)) return cat
+ touched = true
+ return {
+ ...cat,
+ channels: cat.channels.map((c) => (c.id === channelId ? { ...c, unread } : c)),
+ }
+ })
+ return touched ? { ...cache, categories } : cache
+}
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 3aebc5e50..385268afd 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -44,7 +44,7 @@ vi.mock("react", () => ({
if (!refs.has(id)) refs.set(id, { current: initial })
return refs.get(id)!
},
- useState: (initial: unknown) => [initial, () => {}],
+ useState: (initial: unknown) => [initial, () => { }],
useCallback: (fn: Function, deps: unknown[]) => {
const id = `cb-${callbackCounter++}`
const existing = callbackMemo.get(id)
@@ -99,7 +99,7 @@ vi.mock("@/lib/use-user-ws", () => ({
const markReadMutate = vi.fn()
vi.mock("@/hooks/community/mutations/messages", () => ({
useMarkChannelRead: () => ({ mutate: markReadMutate }),
- flushPendingReads: () => {},
+ flushPendingReads: () => { },
}))
function resetHarness() {
@@ -396,6 +396,130 @@ describe("useCommunityWs — message.create", () => {
})
})
+// ── Channel-sidebar live unread patch (plans/community-unread-indicators.md) ─
+describe("useCommunityWs — message.create patches channel unread in the open server's cache", () => {
+ function serverDetailFixture(channelId: string) {
+ return {
+ id: "srv_open",
+ name: "Server",
+ description: "",
+ icon: null,
+ ownerId: "u_owner",
+ categories: [
+ { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", active: false, unread: false }] },
+ ],
+ }
+ }
+
+ it("flips the channel's unread to true when it belongs to the currently-open server's cached ServerDetail", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(messageCreate("ch_random"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })
+ })
+
+ it("does NOT flip unread for a message authored by the viewer themself", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ const event: CommunityMessageCreate = {
+ type: "community:message.create",
+ channelId: "ch_random",
+ message: { id: "m_self", authorId: "u_me", authorName: "me", content: "hi", createdAt: "2026-07-03T00:00:00.000Z" },
+ }
+ capturedOnMessage!(event)
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("does NOT flip unread for the currently-subscribed (active) channel", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ useCommunityStore.getState().subscribe({ channelId: "ch_random" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(messageCreate("ch_random"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("is a no-op when the channel isn't present in the currently cached ServerDetail (different server / no cache)", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_other"))
+
+ expect(() => capturedOnMessage!(messageCreate("ch_random"))).not.toThrow()
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ // Untouched — the fixture's own channel stays unread: false.
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_other", unread: false })
+ })
+
+ it("does not crash and is a no-op when no server is currently open", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ expect(() => capturedOnMessage!(messageCreate("ch_random"))).not.toThrow()
+ })
+
+ it("existing focused-channel message patch and debounced inbox invalidation still fire alongside the new unread patch", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook({ viewerUserId: "u_me" })
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_focused"))
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ capturedOnMessage!(messageCreate("ch_focused"))
+ vi.advanceTimersByTime(500)
+
+ const messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_focused"),
+ )
+ expect(messagesCache?.pages[0].messages.map((m) => m.id)).toEqual(["m_1"])
+ const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
+ const key = c[0]?.queryKey
+ return Array.isArray(key) && key.includes("inbox")
+ })
+ expect(inboxCalls).toHaveLength(1)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
+
describe("useCommunityWs — reactions", () => {
it("patches the message row's reactions in the channel cache", async () => {
await mountHook({ viewerUserId: "u_me" })
@@ -1160,7 +1284,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
// ── Regression #15 — double-mount guard warns ───────────────────────────
describe("useCommunityWs — double-mount detection", () => {
it("emits console.warn when a second instance mounts with a different send", async () => {
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => { })
try {
// First mount publishes the current stable `send` into activeSend.
await mountHook()
@@ -1187,7 +1311,7 @@ describe("useCommunityWs — double-mount detection", () => {
})
it("does NOT warn on a normal re-render (same send identity)", async () => {
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => { })
try {
await mountHook()
flushEffects()
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 0f1715219..432312e04 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -56,6 +56,7 @@ import type { Msg, Attachment } from "@/components/community/_types"
import { avatarInitial } from "@/lib/community/avatar"
import type { MachinesResponse } from "@/hooks/community/use-machines"
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
+import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
/**
* Community WebSocket handler.
@@ -151,11 +152,11 @@ function insertMessageIntoCache(
return isImage
? { kind: "image", name: a.filename, url: a.url }
: {
- kind: "file",
- name: a.filename,
- url: a.url,
- size: a.size ? `${Math.round(a.size / 1024)} KB` : "",
- }
+ kind: "file",
+ name: a.filename,
+ url: a.url,
+ size: a.size ? `${Math.round(a.size / 1024)} KB` : "",
+ }
})
const isSystem = "type" in msg && (msg as { type?: string }).type === "system"
const authorName = "authorName" in msg ? msg.authorName : "Unknown"
@@ -194,11 +195,11 @@ function insertMessageIntoCache(
// envelope on a legacy newest cache (or vice versa).
const nextFirst = trimmed
? {
- ...first,
- messages,
- ...(first.hasMoreOlder !== undefined ? { hasMoreOlder: true } : {}),
- ...(first.hasMore !== undefined ? { hasMore: true } : {}),
- }
+ ...first,
+ messages,
+ ...(first.hasMoreOlder !== undefined ? { hasMoreOlder: true } : {}),
+ ...(first.hasMore !== undefined ? { hasMore: true } : {}),
+ }
: { ...first, messages }
return {
...cache,
@@ -406,6 +407,28 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
scheduleInboxInvalidate()
}
+ // 3) Live channel-sidebar unread dot: if this message landed in a
+ // channel that belongs to the currently-open server's cached
+ // `ServerDetail`, flip that channel's `unread` to `true` —
+ // no network round-trip. Skip for the viewer's own sends (never
+ // unread to themselves) and for the currently-**subscribed**
+ // channel (the dot is already suppressed there via `!active` in
+ // `sortable-channel.tsx`, but skipping the cache patch too
+ // avoids a stale `unread: true` lingering for when the user
+ // later navigates away without the watermark path re-clearing
+ // it). No-op automatically (via the helper's own "no matching
+ // channel" branch) if that server's detail isn't cached or
+ // doesn't contain this channel.
+ if (event.channelId && event.channelId !== sub.channelId && event.message.authorId !== viewerId) {
+ const currentServerId = useCommunityStore.getState().currentServerId
+ if (currentServerId) {
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(currentServerId),
+ (cache) => patchChannelUnread(cache, event.channelId!, true),
+ )
+ }
+ }
+
// Note: no auto-mark-read here. See #3 — the
// IntersectionObserver in `useChannelWatermark` advances the
// read pointer when a message actually becomes visible in the
@@ -489,17 +512,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
messages: p.messages.map((m) =>
m.id === event.parentMessageId
? {
- ...m,
- thread: {
- id: event.channel.id,
- name: event.channel.name,
- // #4: a freshly-created child channel has no
- // messages yet — `1` was a false claim that
- // the create event carried the first message
- // (it doesn't; the message arrives separately).
- messageCount: 0,
- },
- }
+ ...m,
+ thread: {
+ id: event.channel.id,
+ name: event.channel.name,
+ // #4: a freshly-created child channel has no
+ // messages yet — `1` was a false claim that
+ // the create event carried the first message
+ // (it doesn't; the message arrives separately).
+ messageCount: 0,
+ },
+ }
: m,
),
}
@@ -527,15 +550,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
messages: p.messages.map((m) =>
m.thread?.id === event.channelId
? {
- ...m,
- thread: {
- ...m.thread,
- ...(changes.name !== undefined ? { name: changes.name } : {}),
- ...(changes.messageCount !== undefined
- ? { messageCount: changes.messageCount }
- : {}),
- },
- }
+ ...m,
+ thread: {
+ ...m.thread,
+ ...(changes.name !== undefined ? { name: changes.name } : {}),
+ ...(changes.messageCount !== undefined
+ ? { messageCount: changes.messageCount }
+ : {}),
+ },
+ }
: m,
),
}
@@ -559,17 +582,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
(prev) =>
prev
? {
- ...prev,
- name: event.changes.name ?? prev.name,
- description: event.changes.description ?? prev.description,
- // #8: icon can be explicitly cleared (null). `??` treats
- // null the same as undefined, which would keep the old
- // icon after a removal — check `undefined` explicitly.
- icon:
- event.changes.icon !== undefined
- ? event.changes.icon
- : prev.icon,
- }
+ ...prev,
+ name: event.changes.name ?? prev.name,
+ description: event.changes.description ?? prev.description,
+ // #8: icon can be explicitly cleared (null). `??` treats
+ // null the same as undefined, which would keep the old
+ // icon after a removal — check `undefined` explicitly.
+ icon:
+ event.changes.icon !== undefined
+ ? event.changes.icon
+ : prev.icon,
+ }
: prev,
)
queryClient.setQueryData<ServersResponse | undefined>(
@@ -577,17 +600,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
(prev) =>
prev
? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === event.serverId
- ? {
- ...s,
- ...(event.changes.name ? { name: event.changes.name, initial: avatarInitial(event.changes.name) } : {}),
- ...(event.changes.icon !== undefined ? { icon: event.changes.icon ?? null } : {}),
- }
- : s,
- ),
- }
+ ...prev,
+ servers: prev.servers.map((s) =>
+ s.id === event.serverId
+ ? {
+ ...s,
+ ...(event.changes.name ? { name: event.changes.name, initial: avatarInitial(event.changes.name) } : {}),
+ ...(event.changes.icon !== undefined ? { icon: event.changes.icon ?? null } : {}),
+ }
+ : s,
+ ),
+ }
: prev,
)
} else {
@@ -767,13 +790,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
(prev) =>
prev
? {
- ...prev,
- machines: prev.machines.map((m) =>
- m.id === event.machineId
- ? { ...m, lastSeenAt: event.lastSeenAt, status: event.status }
- : m,
- ),
- }
+ ...prev,
+ machines: prev.machines.map((m) =>
+ m.id === event.machineId
+ ? { ...m, lastSeenAt: event.lastSeenAt, status: event.status }
+ : m,
+ ),
+ }
: prev,
)
cbs.onMachine?.(event)
diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.ts
index 8d70d52e9..5d71fe0f3 100644
--- a/src/web/src/lib/community/channel-ref-extension.test.ts
+++ b/src/web/src/lib/community/channel-ref-extension.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi } from "vitest"
import {
buildCommunityChannelRefExtension,
rankChannelRefItems,
+ toChannelRefCommandProps,
EMPTY_CHANNEL_REF_STATE,
type ChannelRefCandidate,
type ChannelRefPopupState,
@@ -60,7 +61,14 @@ function getItemsCallback(
type RenderNodeProps = {
options?: { HTMLAttributes?: Record<string, unknown> }
- node: { attrs: { label?: string | null; id?: string | null; serverId?: string | null } }
+ node: {
+ attrs: {
+ label?: string | null
+ id?: string | null
+ serverId?: string | null
+ serverName?: string | null
+ }
+ }
}
function getRenderFns(ext: ReturnType<typeof buildCommunityChannelRefExtension>): {
@@ -101,6 +109,18 @@ function build(candidates: ChannelRefCandidate[] = [], popup: ChannelRefPopupSta
return { ext, candidatesRef, popupRef, setPopup, queryRef }
}
+describe("toChannelRefCommandProps", () => {
+ it("maps a ChannelRefCandidate to { id, label, serverId, serverName } — this is the one function shared by both the keyboard and mouse-click insertion paths", () => {
+ const item = candidate("chn_1", "general", "srv_1", "Studio")
+ expect(toChannelRefCommandProps(item)).toEqual({
+ id: "chn_1",
+ label: "general",
+ serverId: "srv_1",
+ serverName: "Studio",
+ })
+ })
+})
+
describe("buildCommunityChannelRefExtension — suggestion.items callback", () => {
it("reads live candidates via candidatesRef.current", () => {
const { ext, candidatesRef } = build([candidate("c1", "general")])
@@ -123,12 +143,31 @@ describe("buildCommunityChannelRefExtension — suggestion.items callback", () =
})
describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {
- it("renderText produces /serverId/channelId (id-based, not name-based)", () => {
+ it("renderText produces /serverName/label (name-based, not id-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")
+ renderText({
+ node: { attrs: { id: "chn_abc", serverId: "srv_xyz", serverName: "Studio", label: "general" } },
+ }),
+ ).toBe("/Studio/general")
+ })
+
+ it("renderText falls back independently per-field — serverName missing falls back to serverId, label missing falls back to id (mixed case, not all-or-nothing)", () => {
+ const { ext } = build()
+ const { renderText } = getRenderFns(ext)
+ // serverName missing, label present.
+ expect(
+ renderText({
+ node: { attrs: { id: "chn_abc", serverId: "srv_xyz", serverName: null, label: "general" } },
+ }),
+ ).toBe("/srv_xyz/general")
+ // serverName present, label missing.
+ expect(
+ renderText({
+ node: { attrs: { id: "chn_abc", serverId: "srv_xyz", serverName: "Studio", label: null } },
+ }),
+ ).toBe("/Studio/chn_abc")
})
it("renderHTML shows a compact /label chip", () => {
@@ -162,11 +201,24 @@ describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {
).toBe("/general")
})
- it("renderText emits empty string when neither serverId nor label is present", () => {
+ it("renderText falls back to the channel id alone when server is missing but the channel id is present", () => {
+ // With independent per-field fallback, a present `id` still lets the
+ // channel segment resolve even when both `serverName`/`serverId` are
+ // missing — only the server segment drops out.
+ const { ext } = build()
+ const { renderText } = getRenderFns(ext)
+ expect(
+ renderText({ node: { attrs: { id: "chn_abc", serverId: null, serverName: null, label: null } } }),
+ ).toBe("/chn_abc")
+ })
+
+ it("renderText emits empty string when nothing at all is present (server AND channel both fully missing)", () => {
const { ext } = build()
const { renderText } = getRenderFns(ext)
expect(
- renderText({ node: { attrs: { id: "chn_abc", serverId: null, label: null } } }),
+ renderText({
+ node: { attrs: { id: null, serverId: null, serverName: null, label: null } },
+ }),
).toBe("")
})
})
@@ -209,7 +261,7 @@ describe("buildCommunityChannelRefExtension — keyboard callback", () => {
expect(onKeyDown({ event: enter })).toBe(false)
})
- it("selecting a candidate via Enter calls command with { id, label, serverId } — not the raw ChannelRefCandidate", () => {
+ it("selecting a candidate via Enter calls command with { id, label, serverId, serverName } (via toChannelRefCommandProps) — 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 })
@@ -219,7 +271,7 @@ describe("buildCommunityChannelRefExtension — keyboard callback", () => {
// 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).toHaveBeenCalledWith({ id: "chn_1", label: "general", serverId: "srv_1", serverName: "Studio" })
expect(command).not.toHaveBeenCalledWith(items[0])
expect(setPopup).toHaveBeenCalledWith(EMPTY_CHANNEL_REF_STATE)
})
@@ -231,7 +283,7 @@ describe("buildCommunityChannelRefExtension — keyboard callback", () => {
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" })
+ expect(command).toHaveBeenCalledWith({ id: "chn_1", label: "general", serverId: "srv_1", serverName: "Studio" })
})
it("returns false when there are no items (popup effectively closed)", () => {
diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.ts
index 735607f03..121fa5437 100644
--- a/src/web/src/lib/community/channel-ref-extension.ts
+++ b/src/web/src/lib/community/channel-ref-extension.ts
@@ -13,7 +13,20 @@ export type ChannelRefCandidate = {
// comment on the `name` → `label` mapping). Mirrors
// `MentionPopupState.command`'s own mapped-shape typing in
// `mention-extension.ts`.
-type ChannelRefCommandProps = { id: string; label: string; serverId: string }
+export type ChannelRefCommandProps = { id: string; label: string; serverId: string; serverName: string }
+
+/**
+ * Maps a `ChannelRefCandidate` (the shape the popup lists) to the props
+ * tiptap's `command(props)` inserts verbatim as `node.attrs`. Shared by both
+ * insertion paths — the keyboard handler below and `composer.tsx`'s
+ * mouse-click `onSelect` — so updating one field (e.g. adding `serverName`)
+ * can't be forgotten on the other call site, the exact bug pattern the
+ * `name` → `label` regression guard in `channel-ref-extension.test.ts`
+ * already exists for.
+ */
+export function toChannelRefCommandProps(item: ChannelRefCandidate): ChannelRefCommandProps {
+ return { id: item.id, label: item.name, serverId: item.serverId, serverName: item.serverName }
+}
export interface ChannelRefPopupState {
items: ChannelRefCandidate[]
@@ -74,6 +87,7 @@ const ChannelRefNode = Mention.extend({
return {
...this.parent?.(),
serverId: { default: null },
+ serverName: { default: null },
}
},
})
@@ -91,11 +105,14 @@ const ChannelRefNode = Mention.extend({
* 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
+ * `renderText` inserts by display name, not id — server/channel names are
+ * now guaranteed ref-safe at creation/rename time (`slugify()`, applied by
+ * every write route), so `serverName`/`label` always round-trip through
+ * `CHANNEL_REF_REGEX` and `resolveChannelRefBase` (exact-string match) just
+ * as cleanly as ids used to, but render as something a human can actually
+ * read. Falls back to `serverId`/`id` if either name is ever missing
+ * (paste-from-HTML, drag-drop, etc.) — defensive, not the primary
+ * mechanism. `renderHTML` shows a compact in-editor chip — channel name
* only, not the full path — keeping the compose box readable.
*/
export function buildCommunityChannelRefExtension(opts: {
@@ -120,10 +137,21 @@ export function buildCommunityChannelRefExtension(opts: {
// to the visible label so the recipient reads a real word instead of
// a broken pill — degraded, but not misleading. The command flow that
// DOES set both fields (Enter/Tab on a suggestion) is unaffected.
+ // The server segment (`serverName ?? serverId`) and channel segment
+ // (`label ?? id`) fall back independently — one can be missing while
+ // the other isn't — and neither ever falls through to a literal
+ // "null"/"undefined" string in the emitted text.
renderText: ({ node }) => {
- const { serverId, id, label } = node.attrs as { serverId?: string | null; id?: string; label?: string }
- if (!serverId || !id) return label ? `/${label}` : ""
- return `/${serverId}/${id}`
+ const { serverId, serverName, id, label } = node.attrs as {
+ serverId?: string | null
+ serverName?: string | null
+ id?: string | null
+ label?: string | null
+ }
+ const server = serverName || serverId
+ const channel = label || id
+ if (!server) return channel ? `/${channel}` : ""
+ return channel ? `/${server}/${channel}` : `/${server}`
},
renderHTML: ({ options, node }) => ["span", options.HTMLAttributes, `/${node.attrs.label ?? node.attrs.id}`],
suggestion: {
@@ -185,7 +213,7 @@ export function buildCommunityChannelRefExtension(opts: {
// 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 })
+ cur.command(toChannelRefCommandProps(item))
}
setPopup(EMPTY_CHANNEL_REF_STATE)
return true
diff --git a/src/web/src/lib/community/slug-preview.test.ts b/src/web/src/lib/community/slug-preview.test.ts
new file mode 100644
index 000000000..a9060d840
--- /dev/null
+++ b/src/web/src/lib/community/slug-preview.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect } from "vitest"
+import { previewSlug } from "./slug-preview"
+
+describe("previewSlug", () => {
+ it("flags a changed, non-empty slug for a spaced name", () => {
+ expect(previewSlug("My Home")).toEqual({ slug: "My-Home", invalid: false, changed: true })
+ })
+
+ it("reports no change for an already-clean name", () => {
+ expect(previewSlug("general")).toEqual({ slug: "general", invalid: false, changed: false })
+ })
+
+ it("flags invalid for an all-disallowed-characters input", () => {
+ expect(previewSlug("///")).toEqual({ slug: "", invalid: true, changed: false })
+ })
+
+ it("does not flag invalid for an empty or whitespace-only (untouched) input", () => {
+ expect(previewSlug("")).toEqual({ slug: "", invalid: false, changed: false })
+ expect(previewSlug(" ")).toEqual({ slug: "", invalid: false, changed: false })
+ })
+})
diff --git a/src/web/src/lib/community/slug-preview.ts b/src/web/src/lib/community/slug-preview.ts
new file mode 100644
index 000000000..cd4df4dc3
--- /dev/null
+++ b/src/web/src/lib/community/slug-preview.ts
@@ -0,0 +1,24 @@
+import { slugify } from "@alook/shared"
+
+export type SlugPreview = {
+ slug: string
+ /** Trimmed input is non-empty but the slug is empty — the exact case every route 400s on. */
+ invalid: boolean
+ /** Slug is non-empty and differs from the trimmed input — worth showing a preview for. */
+ changed: boolean
+}
+
+/**
+ * Client-side mirror of what every server/channel/forum-post name route
+ * does server-side (`trim()` then `slugify()`), so the preview shown here
+ * is byte-identical to what actually gets stored.
+ */
+export function previewSlug(name: string): SlugPreview {
+ const trimmed = name.trim()
+ const slug = slugify(trimmed)
+ return {
+ slug,
+ invalid: trimmed.length > 0 && slug.length === 0,
+ changed: slug.length > 0 && slug !== trimmed,
+ }
+}