Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add server rail unread indicators (#609)

Gener1039e99e64f3
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 93f23e5d2..d137bd25c 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -50,6 +50,7 @@ export const SPEC_SECONDS = {
"37-server-rail-pdd.spec.ts": 10,
"38-community-navigation-checkpoint-matrix.spec.ts": 60,
"39-mobile-composer-send.spec.ts": 45,
+ "40-server-rail-unread.spec.ts": 60,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 71754e8c6..58826ce96 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([323, 324, 324, 328, 328])
+ expect(totals.sort((left, right) => left - right)).toEqual([335, 336, 338, 339, 339])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index cd4b27e3a..b38934c7e 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -11,6 +11,7 @@ import {
import { user } from "../../schema";
import type { Database } from "../../index";
import { listParticipatingThreadIds } from "./thread";
+import { listVisibleChannelIdsForUser } from "./channel";
import { reachIsParticipantSet } from "../../../utils/community-roles";
import { hasUnreadAttentionSql, notificationEligibleSql } from "./notification-eligibility";
@@ -301,6 +302,15 @@ export async function listEligibleUnreadChannels(
);
}
+export async function listEligibleUnreadServerIds(
+ db: Database,
+ userId: string
+): Promise<string[]> {
+ const visibleChannelIds = await listVisibleChannelIdsForUser(db, userId);
+ const rows = await listEligibleUnreadChannels(db, userId, visibleChannelIds);
+ return [...new Set(rows.map((row) => row.serverId))];
+}
+
/**
* Project every unread forum opener under an already-authorized parent scope.
*
diff --git a/src/shared/test/queries/community-server-unread.test.ts b/src/shared/test/queries/community-server-unread.test.ts
new file mode 100644
index 000000000..c03723c52
--- /dev/null
+++ b/src/shared/test/queries/community-server-unread.test.ts
@@ -0,0 +1,90 @@
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import type { Database } from "../../src/db"
+import { listEligibleUnreadServerIds } from "../../src/db/queries/community/inbox"
+
+describe("listEligibleUnreadServerIds", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (id TEXT PRIMARY KEY, name TEXT NOT NULL, discriminator TEXT NOT NULL, image TEXT, deleted_at TEXT);
+ CREATE TABLE community_server (id TEXT PRIMARY KEY, name TEXT NOT NULL, discriminator TEXT NOT NULL, owner_id TEXT NOT NULL, description TEXT, icon TEXT, created_at TEXT NOT NULL);
+ CREATE TABLE community_server_member (id TEXT PRIMARY KEY, server_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT, rail_order INTEGER, joined_at TEXT NOT NULL);
+ CREATE TABLE community_category (id TEXT PRIMARY KEY, server_id TEXT NOT NULL, name TEXT NOT NULL, position INTEGER, private INTEGER, creator_id TEXT);
+ CREATE TABLE community_channel (id TEXT PRIMARY KEY, server_id TEXT, category_id TEXT, name TEXT, type TEXT NOT NULL, topic TEXT, position INTEGER, parent_channel_id TEXT, creator_id TEXT, message_count INTEGER, archived INTEGER NOT NULL, parent_message_id TEXT, last_message_at TEXT, created_at TEXT NOT NULL);
+ CREATE TABLE community_channel_member (id TEXT PRIMARY KEY, channel_id TEXT NOT NULL, user_id TEXT NOT NULL, relation TEXT NOT NULL, source TEXT, added_by TEXT, added_at TEXT NOT NULL);
+ CREATE TABLE community_message (id TEXT PRIMARY KEY, author_id TEXT NOT NULL, content TEXT NOT NULL, type TEXT, mention_type TEXT, reply_to_id TEXT, embeds TEXT, created_at TEXT NOT NULL, channel_id TEXT NOT NULL, seq INTEGER NOT NULL, friendship_id TEXT, client_nonce TEXT);
+ CREATE TABLE community_read_state (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, channel_id TEXT NOT NULL, last_read_at TEXT NOT NULL, last_read_message_id TEXT, last_read_seq INTEGER NOT NULL);
+ CREATE TABLE community_notification_setting (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, server_id TEXT, channel_id TEXT, level TEXT NOT NULL);
+ CREATE TABLE community_mention (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, user_id TEXT NOT NULL, kind TEXT NOT NULL, read INTEGER NOT NULL);
+
+ INSERT INTO user (id, name, discriminator) VALUES ('viewer', 'Viewer', '0001'), ('author', 'Author', '0002');
+ INSERT INTO community_server (id, name, discriminator, owner_id, created_at) VALUES
+ ('server-a', 'A', '0001', 'author', '2025-01-01T00:00:00Z'),
+ ('server-b', 'B', '0002', 'author', '2025-01-01T00:00:00Z');
+ INSERT INTO community_server_member (id, server_id, user_id, joined_at) VALUES
+ ('member-a', 'server-a', 'viewer', '2026-01-01T00:00:00Z'),
+ ('member-b', 'server-b', 'viewer', '2026-01-01T00:00:00Z');
+ INSERT INTO community_category (id, server_id, name, private) VALUES
+ ('private-a', 'server-a', 'private', 1);
+ INSERT INTO community_channel (id, server_id, category_id, name, type, archived, created_at) VALUES
+ ('channel-a', 'server-a', NULL, 'a', 'text', 0, '2026-01-01T00:00:00Z'),
+ ('hidden-a', 'server-a', 'private-a', 'hidden', 'text', 0, '2026-01-01T00:00:00Z'),
+ ('channel-b', 'server-b', NULL, 'b', 'text', 0, '2026-01-01T00:00:00Z'),
+ ('dm', NULL, NULL, NULL, 'dm', 0, '2026-01-01T00:00:00Z');
+ INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES
+ ('a-1', 'author', 'a1', '2026-01-02T00:00:00Z', 'channel-a', 1),
+ ('a-2', 'author', 'a2', '2026-01-03T00:00:00Z', 'channel-a', 2),
+ ('hidden-1', 'author', 'hidden', '2026-01-03T00:00:00Z', 'hidden-a', 1),
+ ('b-1', 'author', 'b1', '2026-01-02T00:00:00Z', 'channel-b', 1),
+ ('dm-1', 'author', 'dm', '2026-01-03T00:00:00Z', 'dm', 1);
+ INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES
+ ('read-a', 'viewer', 'channel-a', '2026-01-02T00:00:00Z', 'a-1', 1),
+ ('read-b', 'viewer', 'channel-b', '2026-01-02T00:00:00Z', 'b-1', 1);
+ `)
+ db = drizzle(sqlite) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("returns distinct server ids from the canonical visibility, cursor, and policy gates", async () => {
+ await expect(listEligibleUnreadServerIds(db, "viewer")).resolves.toEqual(["server-a"])
+
+ sqlite.exec(`
+ INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq)
+ VALUES ('b-2', 'author', 'b2', '2026-01-04T00:00:00Z', 'channel-b', 2);
+ `)
+ await expect(listEligibleUnreadServerIds(db, "viewer")).resolves.toEqual([
+ "server-a",
+ "server-b",
+ ])
+ })
+
+ it("clears only from authoritative cursor/policy state", async () => {
+ sqlite.exec(`
+ INSERT INTO community_channel (id, server_id, category_id, name, type, archived, created_at)
+ VALUES ('channel-a-2', 'server-a', NULL, 'a-2', 'text', 0, '2026-01-01T00:00:00Z');
+ INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq)
+ VALUES ('a-second-1', 'author', 'second', '2026-01-04T00:00:00Z', 'channel-a-2', 1);
+ UPDATE community_read_state SET last_read_seq = 2 WHERE id = 'read-a';
+ `)
+ await expect(listEligibleUnreadServerIds(db, "viewer")).resolves.toEqual(["server-a"])
+
+ sqlite.exec(`
+ INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES ('read-a-2', 'viewer', 'channel-a-2', '2026-01-04T00:00:00Z', 'a-second-1', 1);
+ `)
+ await expect(listEligibleUnreadServerIds(db, "viewer")).resolves.toEqual([])
+
+ sqlite.exec(`
+ UPDATE community_read_state SET last_read_seq = 1 WHERE id = 'read-a';
+ INSERT INTO community_notification_setting (id, user_id, server_id, level)
+ VALUES ('mute-a', 'viewer', 'server-a', 'nothing');
+ `)
+ await expect(listEligibleUnreadServerIds(db, "viewer")).resolves.toEqual([])
+ })
+})
diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.ts
index 521d0e002..d9532ac5a 100644
--- a/src/web/src/app/api/community/servers/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/route.bot.test.ts
@@ -27,6 +27,7 @@ const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
const mockGetUserInternal = vi.fn()
const mockGetBotBinding = vi.fn()
const mockListUserServers = vi.fn()
+const mockListEligibleUnreadServerIds = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -38,6 +39,10 @@ vi.mock("@alook/shared", async () => {
user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },
communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },
communityServer: { listUserServers: (...a: unknown[]) => mockListUserServers(...a) },
+ communityInbox: {
+ ...actual.queries.communityInbox,
+ listEligibleUnreadServerIds: (...a: unknown[]) => mockListEligibleUnreadServerIds(...a),
+ },
},
}
})
@@ -62,6 +67,7 @@ describe("GET /api/community/servers — bot path (folded listServers)", () => {
mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })
mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })
mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })
+ mockListEligibleUnreadServerIds.mockRejectedValue(new Error("human unread source failed"))
})
it("401 without Authorization (no crk_ → human path, no session)", async () => {
@@ -84,6 +90,8 @@ describe("GET /api/community/servers — bot path (folded listServers)", () => {
])
// Scoping red line: the bot sees only ITS OWN servers (actor.userId=bot_1).
expect(mockListUserServers).toHaveBeenCalledWith(expect.anything(), "bot_1")
+ expect(mockListEligibleUnreadServerIds).not.toHaveBeenCalled()
+ expect(body.servers.every((server) => !("unread" in server))).toBe(true)
})
it("200 with an empty list when the bot is in no servers", async () => {
@@ -91,5 +99,6 @@ describe("GET /api/community/servers — bot path (folded listServers)", () => {
const res = await GET(req({ Authorization: "Bearer crk_abc" }))
expect(res.status).toBe(200)
expect((await res.json()).servers).toEqual([])
+ expect(mockListEligibleUnreadServerIds).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/servers/route.human.test.ts b/src/web/src/app/api/community/servers/route.human.test.ts
new file mode 100644
index 000000000..5d48a6312
--- /dev/null
+++ b/src/web/src/app/api/community/servers/route.human.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest, NextResponse } from "next/server"
+
+const mocks = vi.hoisted(() => ({
+ listUserServers: vi.fn(),
+ listEligibleUnreadServerIds: vi.fn(),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ kind: "db" })) }))
+vi.mock("@/lib/community/storage", () => ({
+ serverIconUrl: vi.fn((row: { icon?: string | null }) => row.icon ?? null),
+}))
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: (handler: (...args: any[]) => unknown) =>
+ (req: NextRequest) => handler(req, {
+ env: { DB: {} },
+ actor: { kind: "human", userId: "viewer", email: "[email protected]" },
+ }),
+ rejectBot: vi.fn(() => null),
+}))
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+}))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityServer: {
+ ...actual.queries.communityServer,
+ listUserServers: (...args: unknown[]) => mocks.listUserServers(...args),
+ },
+ communityInbox: {
+ ...actual.queries.communityInbox,
+ listEligibleUnreadServerIds: (...args: unknown[]) => mocks.listEligibleUnreadServerIds(...args),
+ },
+ },
+ }
+})
+
+import { GET } from "./route"
+
+describe("GET /api/community/servers — human unread seed", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.listUserServers.mockResolvedValue([
+ { id: "server-a", name: "A", icon: null },
+ { id: "server-b", name: "B", icon: null },
+ ])
+ })
+
+ it("adds an explicit boolean to every human row from one unread-id scan", async () => {
+ mocks.listEligibleUnreadServerIds.mockResolvedValue(["server-b"])
+
+ const response = await GET(new NextRequest("http://localhost/api/community/servers"))
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({
+ servers: [
+ { id: "server-a", name: "A", icon: null, unread: false },
+ { id: "server-b", name: "B", icon: null, unread: true },
+ ],
+ })
+ expect(mocks.listEligibleUnreadServerIds).toHaveBeenCalledTimes(1)
+ expect(mocks.listEligibleUnreadServerIds).toHaveBeenCalledWith(expect.anything(), "viewer")
+ })
+
+ it("fails the human canonical response when its unread source fails", async () => {
+ mocks.listEligibleUnreadServerIds.mockRejectedValue(new Error("unread failed"))
+
+ await expect(GET(new NextRequest("http://localhost/api/community/servers")))
+ .rejects.toThrow("unread failed")
+ })
+})
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index f661a82b4..a35bc9efe 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -14,14 +14,6 @@ import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { serverIconUrl } from "@/lib/community/storage"
-/**
- * GET — list "my servers", serving both a human and a bot via the unified actor
- * (plan §4 FOLD of /agent/listServers, §9 phase 4). Both list via
- * `listUserServers(actor.userId)`; the response is a superset (full server rows
- * incl. id+name+icon) — the web client uses the UI fields, the bot's daemon
- * projects each row down to `{id, name}` (the old lean listServers shape).
- * No actor.kind branch needed: `userId` is common to both callers.
- */
export const GET = withCommunityActor(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const rows = await withD1Retry(
@@ -29,7 +21,18 @@ export const GET = withCommunityActor(async (_req, ctx) => {
{ route: "community/servers:list" },
)
const servers = rows.map((row) => ({ ...row, icon: serverIconUrl(row) }))
- return writeJSON({ servers })
+ if (ctx.actor.kind === "bot") return writeJSON({ servers })
+
+ const unreadServerIds = new Set(await withD1Retry(
+ () => queries.communityInbox.listEligibleUnreadServerIds(db, ctx.actor.userId),
+ { route: "community/servers:unread" },
+ ))
+ return writeJSON({
+ servers: servers.map((server) => ({
+ ...server,
+ unread: unreadServerIds.has(server.id),
+ })),
+ })
})
/**
diff --git a/src/web/src/components/community/shell/rail-folder.test.ts b/src/web/src/components/community/shell/rail-folder.test.ts
new file mode 100644
index 000000000..b992fd5b0
--- /dev/null
+++ b/src/web/src/components/community/shell/rail-folder.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from "vitest"
+import { railFolderPropsEqual } from "./rail-folder"
+
+const base = {
+ folderId: "folder",
+ open: false,
+ active: false,
+ unread: false,
+ onToggle: vi.fn(),
+ folderServers: [{ id: "server", name: "Server", initial: "S", icon: null }],
+}
+
+describe("RailFolder memo boundary", () => {
+ it("rerenders for aggregate unread/open/active but ignores callback identity", () => {
+ expect(railFolderPropsEqual(base, { ...base, onToggle: vi.fn() })).toBe(true)
+ expect(railFolderPropsEqual(base, { ...base, unread: true })).toBe(false)
+ expect(railFolderPropsEqual(base, { ...base, open: true })).toBe(false)
+ expect(railFolderPropsEqual(base, { ...base, active: true })).toBe(false)
+ })
+
+ it("rerenders only when thumbnail presentation changes", () => {
+ expect(railFolderPropsEqual(base, {
+ ...base,
+ folderServers: base.folderServers.map((server) => ({ ...server })),
+ })).toBe(true)
+ expect(railFolderPropsEqual(base, {
+ ...base,
+ folderServers: [{ ...base.folderServers[0]!, icon: "/new.png" }],
+ })).toBe(false)
+ })
+})
diff --git a/src/web/src/components/community/shell/rail-folder.tsx b/src/web/src/components/community/shell/rail-folder.tsx
index 69d8441ef..6307c71aa 100644
--- a/src/web/src/components/community/shell/rail-folder.tsx
+++ b/src/web/src/components/community/shell/rail-folder.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useEffect, useRef } from "react"
+import { memo, useEffect, useRef } from "react"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
import { RailIndicator } from "./rail-indicator"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
@@ -9,14 +9,12 @@ import { tid } from "@/lib/community/testids"
import type { FolderServer } from "@/lib/community/models/navigation"
import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
-export function RailFolder({
- folderId, open, onToggle, activeId, folderServers, onUngroup, dragging: isDragActive,
- preview, registerItem, onMove,
-}: {
+type RailFolderProps = {
folderId: string
open: boolean
+ active: boolean
+ unread: boolean
onToggle: () => void
- activeId: string
folderServers: FolderServer[]
onUngroup?: () => void
dragging?: boolean
@@ -27,7 +25,12 @@ export function RailFolder({
dragHandle: HTMLElement,
) => () => void
onMove?: (source: RailEntity, focusTarget: HTMLElement) => void
-}) {
+}
+
+function RailFolderImpl({
+ folderId, open, active, unread, onToggle, folderServers, onUngroup, dragging: isDragActive,
+ preview, registerItem, onMove,
+}: RailFolderProps) {
const rootRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
useEffect(() => {
@@ -52,7 +55,11 @@ export function RailFolder({
className={`pointer-events-none absolute left-1/2 z-10 h-0.5 w-9 -translate-x-1/2 rounded-full bg-primary ${preview === "reorder-before" ? "-top-1" : "-bottom-1"}`}
/>
)}
- <RailIndicator active={!open && folderServers.some((s) => s.id === activeId)} />
+ <RailIndicator
+ active={active}
+ unread={unread}
+ testId={tid.serverRailFolderIndicator(folderId)}
+ />
<button
ref={buttonRef}
data-testid={tid.serverRailFolder(folderId)}
@@ -97,3 +104,28 @@ export function RailFolder({
</Tooltip>
)
}
+
+export function railFolderPropsEqual(prev: RailFolderProps, next: RailFolderProps) {
+ if (
+ prev.folderId !== next.folderId ||
+ prev.open !== next.open ||
+ prev.active !== next.active ||
+ prev.unread !== next.unread ||
+ prev.dragging !== next.dragging ||
+ prev.preview !== next.preview ||
+ !!prev.onUngroup !== !!next.onUngroup ||
+ !!prev.registerItem !== !!next.registerItem ||
+ !!prev.onMove !== !!next.onMove ||
+ prev.folderServers.length !== next.folderServers.length
+ ) return false
+ return prev.folderServers.every((server, index) => {
+ const other = next.folderServers[index]
+ return !!other &&
+ server.id === other.id &&
+ server.name === other.name &&
+ server.initial === other.initial &&
+ server.icon === other.icon
+ })
+}
+
+export const RailFolder = memo(RailFolderImpl, railFolderPropsEqual)
diff --git a/src/web/src/components/community/shell/rail-indicator.test.ts b/src/web/src/components/community/shell/rail-indicator.test.ts
new file mode 100644
index 000000000..abc4351ce
--- /dev/null
+++ b/src/web/src/components/community/shell/rail-indicator.test.ts
@@ -0,0 +1,39 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { describe, expect, it } from "vitest"
+import { tid } from "@/lib/community/testids"
+import { RailIndicator } from "./rail-indicator"
+
+function markup(props: Parameters<typeof RailIndicator>[0]) {
+ return renderToStaticMarkup(createElement(RailIndicator, props))
+}
+
+describe("RailIndicator", () => {
+ it.each([
+ [{ active: true, unread: true }, "h-10"],
+ [{ active: false, unread: true }, "h-2.5"],
+ [{ active: false, unread: false }, "h-0"],
+ ] as const)("resolves resting height precedence for %o", (props, height) => {
+ const html = markup(props)
+ expect(html).toContain(height)
+ expect(html).toContain("w-1")
+ expect(html).toContain("bg-foreground")
+ expect(html).toContain("rounded-r-full")
+ expect(html).toContain("duration-150")
+ if (!props.active) {
+ expect(html).toContain("group-hover:h-5")
+ expect(html).toContain("group-focus-within:h-5")
+ } else {
+ expect(html).not.toContain("group-hover:h-5")
+ }
+ })
+
+ it("exposes the canonical geometry locator", () => {
+ expect(markup({ testId: "indicator-id" })).toContain('data-testid="indicator-id"')
+ })
+
+ it("builds the canonical server and folder indicator locators", () => {
+ expect(tid.serverRailIndicator("server-id")).toBe("community-server-rail-indicator-server-id")
+ expect(tid.serverRailFolderIndicator("folder-id")).toBe("community-server-rail-folder-indicator-folder-id")
+ })
+})
diff --git a/src/web/src/components/community/shell/rail-indicator.tsx b/src/web/src/components/community/shell/rail-indicator.tsx
index db6efe5d7..400e97236 100644
--- a/src/web/src/components/community/shell/rail-indicator.tsx
+++ b/src/web/src/components/community/shell/rail-indicator.tsx
@@ -1,11 +1,20 @@
-// Left rail indicator — 3 states: active (40px), hover (20px), default (hidden).
-// Parent must be `group relative`.
-export function RailIndicator({ active }: { active?: boolean }) {
+export function RailIndicator({
+ active,
+ unread,
+ testId,
+}: {
+ active?: boolean
+ unread?: boolean
+ testId?: string
+}) {
return (
<span
+ data-testid={testId}
className={[
"absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- active ? "h-10" : "h-0 group-hover:h-5",
+ active
+ ? "h-10"
+ : `${unread ? "h-2.5" : "h-0"} group-hover:h-5 group-focus-within:h-5`,
].join(" ")}
/>
)
diff --git a/src/web/src/components/community/shell/server-rail.pending.test.ts b/src/web/src/components/community/shell/server-rail.pending.test.ts
index 9106e922d..a03dec17f 100644
--- a/src/web/src/components/community/shell/server-rail.pending.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.test.ts
@@ -47,8 +47,8 @@ vi.mock("@/lib/community-onboarding", () => ({
}))
const servers = [
- { id: "a", name: "A", initial: "A", active: true, mentions: 0 },
- { id: "b", name: "B", initial: "B", active: false, mentions: 0 },
+ { id: "a", name: "A", initial: "A", active: true, unread: false, mentions: 0 },
+ { id: "b", name: "B", initial: "B", active: false, unread: false, mentions: 0 },
]
const folders = [{
id: "one",
@@ -119,6 +119,39 @@ describe("ServerRail one-in-flight structural guard", () => {
})
afterEach(() => vi.unstubAllGlobals())
+ it("aggregates unread only while collapsed and preserves it on the expanded child", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ const unreadServers = servers.map((server) => ({
+ ...server,
+ unread: server.id === "b",
+ }))
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerRail, {
+ servers: unreadServers,
+ folders,
+ view: "server",
+ onHome: vi.fn(),
+ }))
+ })
+
+ expect(renderer.root.findByType("rail-folder").props).toMatchObject({
+ open: false,
+ active: false,
+ unread: true,
+ })
+
+ await act(async () => renderer.root.findByType("rail-folder").props.onToggle())
+
+ expect(renderer.root.findByType("rail-folder").props).toMatchObject({
+ open: true,
+ active: false,
+ unread: false,
+ })
+ const child = renderer.root.findAllByType("sortable-server")
+ .find((node) => node.props.server.id === "b")
+ expect(child?.props.server.unread).toBe(true)
+ })
+
it.each(["create-first", "ungroup-first"] as const)(
"allows one PATCH when stale create and ungroup callbacks race: %s",
async (order) => {
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 10d97e8e5..f8172796c 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -26,7 +26,7 @@ import {
} from "@/lib/community/server-rail-model"
import { useServerRailPdd } from "./use-server-rail-pdd"
import { useServerRailCommit } from "@/hooks/community/mutations"
-import type { Server, CommunityFolder, FolderServer } from "@/lib/community/models/navigation"
+import type { Server, CommunityFolder } from "@/lib/community/models/navigation"
import type { View } from "@/components/community/shell/shell-types"
import {
completeCommunityOnboarding,
@@ -99,6 +99,11 @@ export const ServerRail = memo(function ServerRail({
const stateRef = useRef(state)
const mutationPendingRef = useRef(false)
const railMutation = useServerRailCommit()
+ const serverIdentityOrder = servers.map((server) => server.id).join("\0")
+ const serverIds = useMemo(
+ () => serverIdentityOrder ? serverIdentityOrder.split("\0") : [],
+ [serverIdentityOrder],
+ )
const claimMutation = useCallback(() => {
if (mutationPendingRef.current) {
@@ -130,11 +135,11 @@ export const ServerRail = memo(function ServerRail({
useEffect(() => {
setState((current) => railStateFromData(
- servers.map((server) => server.id),
+ serverIds,
folders,
current.expanded,
))
- }, [folders, servers])
+ }, [folders, serverIds])
useEffect(() => {
sessionStorage.setItem("rail-open-folders", JSON.stringify(state.expanded))
@@ -313,15 +318,9 @@ export const ServerRail = memo(function ServerRail({
: null
const dragging = (entity: RailEntity) => dragSource?.kind === entity.kind
&& dragSource.id === entity.id
- const folderServers = (folderId: string): FolderServer[] => (state.folders[folderId] ?? [])
+ const folderServers = (folderId: string): Server[] => (state.folders[folderId] ?? [])
.map((serverId) => serverById.get(serverId))
.filter((server): server is Server => !!server)
- .map((server) => ({
- id: server.id,
- name: server.name,
- initial: server.initial,
- icon: server.icon ?? null,
- }))
return (
<nav aria-label="Server navigation" className="flex min-h-0 w-14 shrink-0 flex-col items-center overflow-hidden pt-2">
@@ -387,13 +386,14 @@ export const ServerRail = memo(function ServerRail({
<RailFolder
folderId={folderId}
open={open}
+ active={!open && serversInFolder.some((server) => server.id === activeId)}
+ unread={!open && serversInFolder.some((server) => server.unread)}
onToggle={() => setState((current) => ({
...current,
expanded: current.expanded.includes(folderId)
? current.expanded.filter((id) => id !== folderId)
: [...current.expanded, folderId],
}))}
- activeId={activeId}
folderServers={serversInFolder}
onUngroup={() => ungroupFolder(folderId)}
dragging={dragging({ kind: "folder", id: folderId })}
@@ -407,7 +407,7 @@ export const ServerRail = memo(function ServerRail({
{serversInFolder.map((server) => (
<SortableServer
key={server.id}
- server={{ ...server, active: false, mentions: serverById.get(server.id)?.mentions ?? 0, isOwner: serverById.get(server.id)?.isOwner }}
+ server={server}
active={view !== "dm" && activeId === server.id}
onClick={() => pickServer(server.id)}
onPrefetch={() => onServerPrefetch?.(server.id)}
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index a86b143f7..01f70148e 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -108,7 +108,11 @@ function SortableServerImpl({
className={`pointer-events-none absolute left-1/2 z-10 h-0.5 w-9 -translate-x-1/2 rounded-full bg-primary ${preview === "reorder-before" ? "-top-1" : "-bottom-1"}`}
/>
)}
- <RailIndicator active={active} />
+ <RailIndicator
+ active={active}
+ unread={server.unread}
+ testId={tid.serverRailIndicator(server.id)}
+ />
<div
className={[
"relative size-10 transition-[border-radius,background-color,border-color,opacity,transform] duration-150",
@@ -247,7 +251,7 @@ function SortableServerImpl({
// whole rail (N servers × their Tooltip/Avatar)
// re-renders on every tick — the SortableServer/TooltipTrigger ×N in
// perf:switch after the lazy-overlay pass.
-function serverPropsEqual(prev: SortableServerProps, next: SortableServerProps): boolean {
+export function serverPropsEqual(prev: SortableServerProps, next: SortableServerProps): boolean {
const a = prev.server;
const b = next.server;
return (
@@ -255,6 +259,7 @@ function serverPropsEqual(prev: SortableServerProps, next: SortableServerProps):
a.name === b.name &&
a.initial === b.initial &&
a.icon === b.icon &&
+ a.unread === b.unread &&
a.mentions === b.mentions &&
a.isOwner === b.isOwner &&
prev.active === next.active &&
diff --git a/src/web/src/components/community/shell/sortable-server.unread.test.ts b/src/web/src/components/community/shell/sortable-server.unread.test.ts
new file mode 100644
index 000000000..71f653575
--- /dev/null
+++ b/src/web/src/components/community/shell/sortable-server.unread.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest"
+import { serverPropsEqual } from "./sortable-server"
+
+const base = {
+ server: {
+ id: "server",
+ name: "Server",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 2,
+ icon: null,
+ },
+ onClick: vi.fn(),
+}
+
+describe("SortableServer unread memo boundary", () => {
+ it("rerenders for owned unread changes while ignoring callback identity", () => {
+ expect(serverPropsEqual(base, { ...base, onClick: vi.fn() })).toBe(true)
+ expect(serverPropsEqual(base, {
+ ...base,
+ server: { ...base.server, unread: true },
+ })).toBe(false)
+ })
+
+ it("keeps mention and unread as independent presentation fields", () => {
+ expect(serverPropsEqual(base, {
+ ...base,
+ server: { ...base.server, mentions: 3 },
+ })).toBe(false)
+ expect(base.server).toMatchObject({ unread: false, mentions: 2 })
+ })
+})
diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsx
index c1c066b0c..d9d313e91 100644
--- a/src/web/src/components/home/landing-shell-motion.tsx
+++ b/src/web/src/components/home/landing-shell-motion.tsx
@@ -68,13 +68,13 @@ import styles from "./landing-shell-motion.module.css"
import { useLandingMotionPlayback } from "./use-landing-motion-playback"
const SERVERS: Server[] = [
- { id: "gus", name: "Gus", initial: "G", active: true, mentions: 0, isOwner: true, icon: null },
+ { id: "gus", name: "Gus", initial: "G", active: true, unread: false, mentions: 0, isOwner: true, icon: null },
]
const SPACE_SERVERS: Server[] = [
- { id: "work", name: "Studio", initial: "S", active: true, mentions: 0, isOwner: true, icon: null },
- { id: "life", name: "Home", initial: "H", active: false, mentions: 0, isOwner: true, icon: null },
- { id: "play", name: "Game Night", initial: "G", active: false, mentions: 0, isOwner: true, icon: null },
+ { id: "work", name: "Studio", initial: "S", active: true, unread: false, mentions: 0, isOwner: true, icon: null },
+ { id: "life", name: "Home", initial: "H", active: false, unread: false, mentions: 0, isOwner: true, icon: null },
+ { id: "play", name: "Game Night", initial: "G", active: false, unread: false, mentions: 0, isOwner: true, icon: null },
]
const OVERVIEW_SERVERS: Server[] = [
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
index 626808063..571f49895 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
@@ -394,6 +394,44 @@ describe("useCommunityWs — operation bundles", () => {
}
})
+ it("merges a fetching unread fence with batch mention invalidations into one replacement", async () => {
+ await mountHook({ viewerUserId: "viewer-1" })
+ const key = communityKeys.servers()
+ capturedQueryClient.setQueryData(key, {
+ servers: [{ id: "server-1", unread: false, mentions: 5 }],
+ })
+ let queryCalls = 0
+ const queryFn = ({ signal }: { signal: AbortSignal }) => {
+ queryCalls += 1
+ if (queryCalls > 1) {
+ return Promise.resolve({
+ servers: [{ id: "server-1", unread: true, mentions: 6 }],
+ })
+ }
+ return new Promise<never>((_resolve, reject) => {
+ signal.addEventListener("abort", () => {
+ reject(new DOMException("aborted", "AbortError"))
+ }, { once: true })
+ })
+ }
+ const first = capturedQueryClient.fetchQuery({ queryKey: key, queryFn, staleTime: 0 })
+ .catch(() => undefined)
+ await vi.waitFor(() => expect(queryCalls).toBe(1))
+ const cancel = vi.spyOn(capturedQueryClient, "cancelQueries")
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ capturedOnMessage!(await batchFor("message-fenced-mention", mentionEvents))
+
+ await vi.waitFor(() => expect(queryCalls).toBe(2))
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData<{
+ servers: Array<{ unread: boolean; mentions: number }>
+ }>(key)?.servers[0]).toMatchObject({ unread: true, mentions: 6 }))
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(invalidate.mock.calls.filter(([filters]) =>
+ JSON.stringify(filters.queryKey) === JSON.stringify(key))).toHaveLength(1)
+ await first
+ })
+
it("treats repair-then-late-bundle mention state as authoritative invalidation, never arithmetic", async () => {
vi.useFakeTimers()
try {
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index db32fbc38..45025398c 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -29,6 +29,15 @@ export function invalidateServersList(
})
}
+export function fenceServersList(
+ projection: CommunityWsProjectionTransaction,
+) {
+ projection.fence("servers-list", {
+ queryKey: communityKeys.servers(),
+ exact: true,
+ })
+}
+
export function invalidateChannelMembers(
projection: CommunityWsProjectionTransaction,
channelId: string,
diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
index d35416a44..652b6c1b2 100644
--- a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
+++ b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
@@ -53,6 +53,56 @@ describe("community WS projection transaction", () => {
])
})
+ it("upgrades a normal invalidation to one exact fence in either order", async () => {
+ for (const order of ["invalidate-first", "fence-first"] as const) {
+ const queryClient = new QueryClient()
+ const cancel = vi.spyOn(queryClient, "cancelQueries").mockResolvedValue()
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()
+ const refetch = vi.spyOn(queryClient, "refetchQueries").mockResolvedValue()
+ const filters = { queryKey: ["community", "servers"] as const, exact: true }
+
+ runCommunityWsProjectionTransaction(queryClient, (transaction) => {
+ if (order === "invalidate-first") transaction.invalidate("servers-list", filters)
+ transaction.fence("servers-list", filters)
+ if (order === "fence-first") transaction.invalidate("servers-list", filters)
+ })
+ await vi.waitFor(() => expect(refetch).toHaveBeenCalledTimes(1))
+
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(invalidate).toHaveBeenCalledWith({ ...filters, refetchType: "none" })
+ expect(refetch).toHaveBeenCalledWith({ ...filters, type: "all" })
+ }
+ })
+
+ it("starts cancellation before projection and waits for it before refetch", async () => {
+ const queryClient = new QueryClient()
+ let release!: () => void
+ const cancellation = new Promise<void>((resolve) => { release = resolve })
+ const order: string[] = []
+ vi.spyOn(queryClient, "cancelQueries").mockImplementation(() => {
+ order.push("cancel")
+ return cancellation
+ })
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockImplementation(async () => {
+ order.push("invalidate")
+ })
+ vi.spyOn(queryClient, "refetchQueries").mockImplementation(async () => {
+ order.push("refetch")
+ })
+
+ runCommunityWsProjectionTransaction(queryClient, (transaction) => {
+ transaction.fence("servers-list", { queryKey: ["community", "servers"], exact: true })
+ transaction.project(() => order.push("project"))
+ })
+ expect(order).toEqual(["cancel", "project"])
+ expect(invalidate).not.toHaveBeenCalled()
+
+ release()
+ await vi.waitFor(() => expect(order).toContain("refetch"))
+ expect(invalidate).toHaveBeenCalledTimes(1)
+ expect(order).toEqual(["cancel", "project", "invalidate", "refetch"])
+ })
+
it("flushes queued invalidations when projection fails", () => {
const queryClient = new QueryClient()
const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()
diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.ts b/src/web/src/hooks/community/community-ws/projection-transaction.ts
index fc4bab2a0..44bc78147 100644
--- a/src/web/src/hooks/community/community-ws/projection-transaction.ts
+++ b/src/web/src/hooks/community/community-ws/projection-transaction.ts
@@ -2,6 +2,7 @@ import {
hashKey,
notifyManager,
type InvalidateQueryFilters,
+ type FetchQueryOptions,
type QueryClient,
} from "@tanstack/react-query"
@@ -18,10 +19,13 @@ export function getCommunityWsProjectionFlushError(error: unknown) {
export type CommunityWsProjectionTransaction = {
project: <T>(effect: () => T) => T
invalidate: (owner: string, filters: InvalidateQueryFilters) => void
+ fence: (owner: string, filters: InvalidateQueryFilters) => void
}
type PendingInvalidation = {
filters: InvalidateQueryFilters
+ cancellation?: Promise<void>
+ replacementOptions?: FetchQueryOptions
}
function createProjectionTransaction(
@@ -37,11 +41,45 @@ function createProjectionTransaction(
const identity = hashKey([owner, filters])
if (!pending.has(identity)) pending.set(identity, { filters })
},
+ fence: (owner, filters) => {
+ if (flushed) throw new Error("community WS projection transaction already flushed")
+ const identity = hashKey([owner, filters])
+ const current = pending.get(identity)
+ if (current?.cancellation) return
+ const query = queryClient.getQueryCache().findAll(filters)[0]
+ const replacementOptions = query
+ ? { ...query.options, staleTime: 0 } as FetchQueryOptions
+ : undefined
+ const cancellation = queryClient.cancelQueries(filters)
+ if (current) {
+ current.cancellation = cancellation
+ current.replacementOptions = replacementOptions
+ } else {
+ pending.set(identity, { filters, cancellation, replacementOptions })
+ }
+ },
flushInvalidations: () => {
if (flushed) return
flushed = true
- for (const { filters } of pending.values()) {
- void queryClient.invalidateQueries(filters)
+ for (const { filters, cancellation, replacementOptions } of pending.values()) {
+ if (cancellation) {
+ void cancellation.then(async () => {
+ await queryClient.invalidateQueries({
+ ...filters,
+ refetchType: "none",
+ })
+ if (replacementOptions) {
+ await queryClient.fetchQuery(replacementOptions)
+ } else {
+ await queryClient.refetchQueries({
+ ...filters,
+ type: "all",
+ })
+ }
+ })
+ } else {
+ void queryClient.invalidateQueries(filters)
+ }
}
},
}
diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.ts
index 02ecf06c9..5ca7ed407 100644
--- a/src/web/src/hooks/community/community-ws/social-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts
@@ -343,6 +343,86 @@ describe("useCommunityWs — message.create patches channel unread in the open s
expect(servers?.servers[0].mentions).toBe(3)
})
+ it("projects the addressed background server row to unread without touching siblings", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const sibling = { id: "srv_y", name: "Y", initial: "Y", active: false, unread: false, mentions: 0 }
+ capturedQueryClient.setQueryData(communityKeys.servers(), {
+ servers: [
+ { id: "srv_x", name: "X", initial: "X", active: false, unread: false, mentions: 0 },
+ sibling,
+ ],
+ })
+
+ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
+
+ const data = capturedQueryClient.getQueryData<{
+ servers: Array<{ id: string; unread: boolean }>
+ }>(communityKeys.servers())!
+ expect(data.servers.map(({ id, unread }) => ({ id, unread }))).toEqual([
+ { id: "srv_x", unread: true },
+ { id: "srv_y", unread: false },
+ ])
+ expect(data.servers[1]).toBe(sibling)
+ })
+
+ it("preserves response/list/row identity and skips invalidation for an idle already-true row", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const row = { id: "srv_x", name: "X", initial: "X", active: false, unread: true, mentions: 0 }
+ const seeded = { servers: [row] }
+ capturedQueryClient.setQueryData(communityKeys.servers(), seeded)
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
+
+ const data = capturedQueryClient.getQueryData(communityKeys.servers())
+ expect(data).toBe(seeded)
+ expect((data as typeof seeded).servers).toBe(seeded.servers)
+ expect((data as typeof seeded).servers[0]).toBe(row)
+ expect(invalidate).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["absent", undefined],
+ ["cached false", false],
+ ["cached true", true],
+ ] as const)("fences a %s in-flight server-list request and converges to post-commit true", async (_label, cachedUnread) => {
+ await mountHook({ viewerUserId: "u_me" })
+ const key = communityKeys.servers()
+ if (cachedUnread !== undefined) {
+ capturedQueryClient.setQueryData(key, {
+ servers: [{ id: "srv_x", name: "X", initial: "X", active: false, unread: cachedUnread, mentions: 0 }],
+ })
+ }
+ let calls = 0
+ let firstAborted = false
+ const queryFn = ({ signal }: { signal: AbortSignal }) => {
+ calls += 1
+ if (calls > 1) {
+ return Promise.resolve({
+ servers: [{ id: "srv_x", name: "X", initial: "X", active: false, unread: true, mentions: 0 }],
+ })
+ }
+ return new Promise<never>((_resolve, reject) => {
+ signal.addEventListener("abort", () => {
+ firstAborted = true
+ reject(new DOMException("aborted", "AbortError"))
+ }, { once: true })
+ })
+ }
+ const first = capturedQueryClient.fetchQuery({ queryKey: key, queryFn, staleTime: 0 })
+ .catch(() => undefined)
+ await vi.waitFor(() => expect(calls).toBe(1))
+
+ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
+
+ await vi.waitFor(() => expect(calls).toBe(2))
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData<{
+ servers: Array<{ unread: boolean }>
+ }>(key)?.servers[0]?.unread).toBe(true))
+ expect(firstAborted).toBe(true)
+ await first
+ })
+
it("leaves an absent or unrelated server rail cache unchanged on a legacy mention bump", async () => {
await mountHook({ viewerUserId: "u_me" })
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index fff7ff6e7..8fc03fa2e 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -21,6 +21,7 @@ import {
} from "@/hooks/community/use-forum-sidebar-threads"
import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
import {
+ fenceServersList,
invalidateFriends,
invalidateServersList,
} from "./invalidation-projections"
@@ -94,6 +95,20 @@ export function handleUnreadBump(
// (its unread clears on read anyway) — compare against the ROW being
// lit, so a thread bump whose parent is open still suppresses.
if (event.userId === viewerId && sidebarChannelId !== sub.channelId) {
+ if (event.serverId) {
+ const serversKey = communityKeys.servers()
+ if (queryClient.getQueryState(serversKey)?.fetchStatus === "fetching") {
+ fenceServersList(projection)
+ }
+ queryClient.setQueryData<ServersResponse | undefined>(serversKey, (prev) => {
+ if (!prev) return prev
+ const index = prev.servers.findIndex((server) => server.id === event.serverId)
+ if (index < 0 || prev.servers[index]?.unread) return prev
+ const servers = [...prev.servers]
+ servers[index] = { ...servers[index]!, unread: true }
+ return { ...prev, servers }
+ })
+ }
// Channel-tree dot: patch the RIGHT server's detail. `serverId`
// (inbox-dot-ws-driven) lets an other-server message light its dot
// — previously only the open server was patched, so cross-server
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index 88c4ab5d3..136ac7748 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -44,13 +44,14 @@ describe("useServers / serversQueryFn", () => {
ownerId: "u_1",
role: "owner",
mentions: 3,
+ unread: true,
},
{ id: "srv_2", name: "Beta", discriminator: "12345", icon: null, role: "member" },
],
})
const { serversQueryFn } = await import("./use-servers")
const data = await serversQueryFn()
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers")
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", { signal: undefined })
expect(data.servers[0].initial).toBe("A")
expect(data.servers[0].isOwner).toBe(true)
expect(data.servers[0].mentions).toBe(3)
@@ -58,12 +59,10 @@ describe("useServers / serversQueryFn", () => {
expect(data.servers[0].discriminator).toBe("0042")
expect(data.servers[0].description).toBe("Build together")
expect(data.servers[0].ownerId).toBe("u_1")
- // `unread` has been removed from the Server type — the mapper must not
- // project it. Pin the invariant so a future revival gets caught.
- expect((data.servers[0] as { unread?: boolean }).unread).toBeUndefined()
+ expect(data.servers[0].unread).toBe(true)
expect(data.servers[1].mentions).toBe(0)
expect(data.servers[1].isOwner).toBe(false)
- expect((data.servers[1] as { unread?: boolean }).unread).toBeUndefined()
+ expect(data.servers[1].unread).toBe(false)
})
it("preserves mentions when provided; defaults to 0 when omitted", async () => {
@@ -79,6 +78,18 @@ describe("useServers / serversQueryFn", () => {
expect(data.servers[1].mentions).toBe(0)
})
+ it("passes TanStack's abort signal to the canonical request", async () => {
+ apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ const controller = new AbortController()
+ const { serversQueryFn } = await import("./use-servers")
+
+ await serversQueryFn({ signal: controller.signal } as never)
+
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", {
+ signal: controller.signal,
+ })
+ })
+
it("populates queryClient at communityKeys.servers()", async () => {
apiFetchMock.mockResolvedValueOnce({ servers: [] })
const { serversQueryFn } = await import("./use-servers")
@@ -116,7 +127,7 @@ describe("useServer / serverQueryFn", () => {
})
const { serverQueryFn } = await import("./use-servers")
const data = await serverQueryFn(new QueryClient(), "srv_1")()
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers")
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.any(Object))
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/categories")
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/channels")
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/unreads")
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index a6df42fa8..d16b07141 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -4,6 +4,7 @@ import {
useQuery,
useQueryClient,
type QueryClient,
+ type QueryFunctionContext,
type UseQueryResult,
} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
@@ -28,6 +29,7 @@ type RawServerRow = {
icon: string | null
role?: string
mentions?: number
+ unread?: boolean
description?: string | null
ownerId: string
}
@@ -39,8 +41,12 @@ export type ServersResponse = { servers: Server[] }
// per render (a fresh `[]` would churn the reference).
const EMPTY_SERVERS: readonly Server[] = Object.freeze([])
-export const serversQueryFn = async (): Promise<ServersResponse> => {
- const data = await apiFetch<{ servers: RawServerRow[] }>("/api/community/servers")
+export const serversQueryFn = async (
+ context?: QueryFunctionContext,
+): Promise<ServersResponse> => {
+ const data = await apiFetch<{ servers: RawServerRow[] }>("/api/community/servers", {
+ signal: context?.signal,
+ })
const servers: Server[] = data.servers.map((s) => ({
id: s.id,
name: s.name,
@@ -49,6 +55,7 @@ export const serversQueryFn = async (): Promise<ServersResponse> => {
ownerId: s.ownerId,
initial: avatarInitial(s.name),
active: false,
+ unread: s.unread ?? false,
// Defensive fallback: the API always projects `mentions` now, but during
// rolling deploys or from cached stale responses the field could still be
// absent — treat it as 0 rather than NaN.
diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.ts
index 0c9f93ffd..f79a9b7f2 100644
--- a/src/web/src/lib/community/models/navigation.ts
+++ b/src/web/src/lib/community/models/navigation.ts
@@ -11,6 +11,7 @@ export type Server = {
ownerId?: string
initial: string
active: boolean
+ unread: boolean
mentions: number
isOwner?: boolean
icon?: string | null
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index aeed0c7b7..5865a1b7a 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -16,6 +16,8 @@ export const tid = {
serverAdd: "community-server-add",
serverRailScroll: "community-server-rail-scroll",
serverRailFolder: (id: string) => `community-server-folder-${id}`,
+ serverRailIndicator: (id: string) => `community-server-rail-indicator-${id}`,
+ serverRailFolderIndicator: (id: string) => `community-server-rail-folder-indicator-${id}`,
serverRailInsert: (id: string) => `community-server-rail-insert-${id}`,
serverRailInsertFolder: (id: string) => `community-server-rail-insert-folder-${id}`,
serverRailMoveDestination: "community-server-rail-move-destination",
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
index a20ad2c63..2efd1f671 100644
--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -199,10 +199,23 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const requestStart = requests.length
const frameStart = proxy.frames.length
await readObserverGate.block()
- const staleInboxResponse = page.waitForResponse((response) => (
- response.request().method() === "GET"
- && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
- ))
+ const staleInboxResponse = page.waitForResponse(async (response) => {
+ if (
+ response.request().method() !== "GET"
+ || new URL(response.url()).pathname !== "/api/community/users/me/inbox/unreads"
+ || response.status() !== 200
+ ) return false
+ const payload = await response.json() as {
+ servers: Array<{ channels: Array<{
+ channelId: string
+ children: Array<{ channelId: string }>
+ }> }>
+ }
+ return payload.servers.some((server) => server.channels.some((channel) => (
+ channel.channelId === channelA
+ || channel.children.some((child) => child.channelId === channelA)
+ )))
+ })
const readResponse = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname === `/api/community/channels/${channelA}/read`
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
new file mode 100644
index 000000000..ab67860e8
--- /dev/null
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -0,0 +1,126 @@
+import type { Locator, Page } from "@playwright/test"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { memberInfo, seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+async function indicatorHeight(indicator: Locator) {
+ return indicator.evaluate((element) => element.getBoundingClientRect().height)
+}
+
+async function expectIndicatorHeight(indicator: Locator, height: number) {
+ await expect.poll(() => indicatorHeight(indicator), { timeout: 20_000 }).toBe(height)
+}
+
+async function createSingleServerFolder(page: Page, serverId: string) {
+ const icon = page.getByTestId(tid.serverIcon(serverId))
+ await icon.focus()
+ await expect(icon.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]")).toBeVisible()
+ await icon.click({ button: "right" })
+ const response = page.waitForResponse((candidate) => (
+ candidate.request().method() === "PATCH"
+ && new URL(candidate.url()).pathname === "/api/community/users/me/server-rail"
+ ))
+ await page.getByRole("menuitem", { name: "Create group" }).click()
+ expect((await response).status()).toBe(200)
+}
+
+test("server unread owns exact rail geometry, folder aggregation, read clear, and mobile parity", async ({ asUser }, testInfo) => {
+ test.setTimeout(150_000)
+ const stamp = Date.now()
+ const foregroundServer = await seedServer("alice", `Unread foreground ${stamp}`)
+ const backgroundServer = await seedServer("alice", `Unread background ${stamp}`)
+ const foregroundChannel = await seedChannel("alice", foregroundServer, `foreground-${stamp}`)
+ const backgroundChannel = await seedChannel("alice", backgroundServer, `background-${stamp}`)
+ await seedJoinServer("alice", "bob", foregroundServer)
+ await seedJoinServer("alice", "bob", backgroundServer)
+ const bobInfo = await memberInfo("alice", backgroundServer, userId("bob"))
+ const { page } = await asUser("bob")
+ await page.setViewportSize({ width: 1280, height: 900 })
+ await page.goto(`/c/channels/${foregroundServer}/${foregroundChannel}`)
+ await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toBeVisible({ timeout: 30_000 })
+
+ const backgroundIndicator = page.getByTestId(tid.serverRailIndicator(backgroundServer))
+ await expectIndicatorHeight(backgroundIndicator, 0)
+ const firstBody = `background unread ${stamp}`
+ await seedMessage("alice", backgroundChannel, firstBody)
+ await expectIndicatorHeight(backgroundIndicator, 10)
+
+ const backgroundIcon = page.getByTestId(tid.serverIcon(backgroundServer))
+ await backgroundIcon.hover()
+ await expectIndicatorHeight(backgroundIndicator, 20)
+ await page.mouse.move(300, 300)
+ await expectIndicatorHeight(backgroundIndicator, 10)
+ await backgroundIcon.focus()
+ await expectIndicatorHeight(backgroundIndicator, 20)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
+ await expectIndicatorHeight(backgroundIndicator, 10)
+
+ await createSingleServerFolder(page, backgroundServer)
+ const folder = page.locator(`[data-testid^="${tid.serverRailFolder("")}"]`).first()
+ await expect(folder).toBeVisible()
+ const folderTestId = await folder.getAttribute("data-testid")
+ if (!folderTestId) throw new Error("missing folder testid")
+ const folderId = folderTestId.slice(tid.serverRailFolder("").length)
+ const folderIndicator = page.getByTestId(tid.serverRailFolderIndicator(folderId))
+ await expectIndicatorHeight(folderIndicator, 0)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
+ await expectIndicatorHeight(backgroundIndicator, 10)
+ await folder.click()
+ await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toHaveCount(0)
+ await page.mouse.move(300, 300)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
+ await expectIndicatorHeight(folderIndicator, 10)
+ await folder.click()
+ await expect(backgroundIcon).toBeVisible()
+ await page.mouse.move(300, 300)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
+ await expectIndicatorHeight(backgroundIndicator, 10)
+
+ await backgroundIcon.click()
+ await expectIndicatorHeight(backgroundIndicator, 40)
+ const backgroundChannelRow = page.getByTestId(tid.channelRow(backgroundChannel))
+ await expect(backgroundChannelRow).toBeVisible({ timeout: 30_000 })
+ const readResponse = page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${backgroundChannel}/read`
+ ))
+ await page.goto(`/c/channels/${backgroundServer}/${backgroundChannel}`)
+ await expect(page.getByText(firstBody, { exact: true })).toBeVisible({ timeout: 30_000 })
+ expect((await readResponse).status()).toBe(200)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${foregroundServer}/${foregroundChannel}`,
+ )
+ await expectIndicatorHeight(folderIndicator, 0)
+
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${foregroundServer}`)
+ if (await backgroundIcon.count() === 0) {
+ await folder.click()
+ await expect(backgroundIcon).toBeVisible()
+ }
+ await page.mouse.move(300, 300)
+ await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
+ const alice = await asUser("alice")
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${backgroundServer}/${backgroundChannel}`)
+ const secondBody = `mobile background mention ${stamp}`
+ const editable = composerEditable(alice.page)
+ await editable.click()
+ await editable.pressSequentially(`@${bobInfo.name.slice(0, 3)}`)
+ await alice.page.getByTestId(tid.mentionOption(bobInfo.id)).click()
+ await editable.pressSequentially(` ${secondBody}`)
+ await alice.page.keyboard.press("Enter")
+ await expectIndicatorHeight(backgroundIndicator, 10)
+ await expect(page.getByTestId(tid.railUnreadBadge(backgroundServer))).toBeVisible()
+ await page.screenshot({
+ path: testInfo.outputPath("server-rail-unread-390.png"),
+ fullPage: true,
+ })
+
+ const seed = await page.request.get("/api/community/servers")
+ expect(seed.status()).toBe(200)
+ const body = await seed.json() as { servers: Array<{ id: string; unread: boolean }> }
+ expect(body.servers.find((server) => server.id === backgroundServer)?.unread).toBe(true)
+})