Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): consistency pass — read consumption, member resolution, icons (#362)

Genera227bcf7c67b
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index cd1aa337d..9f5a6d625 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -34,6 +34,7 @@ export * as communityServer from "./queries/community/server";
export * as communityChannel from "./queries/community/channel";
export * as communityCategory from "./queries/community/category";
export * as communityMember from "./queries/community/member";
+export * as communityMembersResolver from "./queries/community/members-resolver";
export * as communityMessage from "./queries/community/message";
export * as communityFriendship from "./queries/community/friendship";
export * as communityDm from "./queries/community/dm";
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index e006ac16b..96832de45 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -14,6 +14,9 @@ export interface UnreadChannelRow {
channelName: string;
serverId: string;
serverName: string;
+ // Raw stored channel type (text | forum | thread | forum_post). Threaded
+ // through to the inbox so it can render the same entity icon as the sidebar.
+ type: string | null;
lastMessageAt: string;
lastReadAt: string | null;
// null for a top-level channel; set for a thread / forum-post child. The
@@ -73,6 +76,7 @@ export async function listUnreadChannels(
channelName: communityChannel.name,
serverId: communityChannel.serverId,
serverName: communityServer.name,
+ type: communityChannel.type,
parentChannelId: communityChannel.parentChannelId,
lastMessageAt: communityChannel.lastMessageAt,
lastReadAt: communityReadState.lastReadAt,
@@ -119,6 +123,7 @@ export async function listUnreadChannels(
channelName: r.channelName,
serverId: r.serverId,
serverName: r.serverName,
+ type: r.type,
parentChannelId: r.parentChannelId,
lastMessageAt: r.lastMessageAt!,
lastReadAt: r.lastReadAt,
diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.ts
new file mode 100644
index 000000000..5c48ee059
--- /dev/null
+++ b/src/shared/src/db/queries/community/members-resolver.ts
@@ -0,0 +1,129 @@
+import { eq } from "drizzle-orm";
+import {
+ communityChannel,
+ communityCategory,
+ communityServerMember,
+} from "../../community-schema";
+import type { Database } from "../../index";
+import type { CommunityRole } from "../../../utils/community-roles";
+import {
+ getPrivateChannelAudienceUserIds,
+ isChannelPrivate,
+ listChannelMemberUserIds,
+} from "./channel";
+import { listMemberUserIds } from "./member";
+
+// Scopes whose member set is derived, not stored. A thread / forum_post has no
+// roster of its own — it inherits the audience of its anchor channel.
+export type ScopeKind = "channel" | "thread" | "post";
+
+// Why a user is in the resolved set. Lets callers distinguish an explicitly
+// added private-channel member from an inherited public-channel member or a
+// server admin who sees everything.
+export type MemberSource = "explicit" | "inherited" | "admin";
+
+export type ScopeMember = {
+ userId: string;
+ role: CommunityRole;
+ source: MemberSource;
+};
+
+/**
+ * The single source of truth for "who is in this scope." Consolidates the
+ * public/private split that fan-out and the WS DO used to hand-roll:
+ *
+ * - public / uncategorized channel (or a thread/post anchored to one) →
+ * every server member (unfiltered — matches `listMemberUserIds`, so a
+ * soft-deleted user is still in the set; a dead user simply has no live
+ * socket to receive a broadcast).
+ * - private-category channel (or a thread/post anchored to one) → the
+ * channel audience: explicit members ∪ anchor creator ∪ server
+ * admins/owner (delegates to `getPrivateChannelAudienceUserIds`, which
+ * already climbs `parentChannelId`).
+ *
+ * `thread` / `post` resolve identically to `channel` — every reader climbs to
+ * the anchor — so the scope tag is documentation, not branching.
+ */
+export async function resolveScopeMemberUserIds(
+ db: Database,
+ { scopeId }: { scope: ScopeKind; scopeId: string }
+): Promise<string[]> {
+ const channel = await db
+ .select({ serverId: communityChannel.serverId })
+ .from(communityChannel)
+ .where(eq(communityChannel.id, scopeId))
+ .limit(1);
+ if (channel.length === 0) return [];
+
+ if (await isChannelPrivate(db, scopeId)) {
+ return getPrivateChannelAudienceUserIds(db, scopeId);
+ }
+ return listMemberUserIds(db, channel[0]!.serverId);
+}
+
+/**
+ * Same resolution as `resolveScopeMemberUserIds`, tagged with each member's
+ * server role and the reason they belong to the scope:
+ * - `admin` — server owner/admin (always in every audience).
+ * - `explicit` — an explicitly added private-channel member or the anchor
+ * creator.
+ * - `inherited` — a plain server member of a public/uncategorized channel.
+ */
+export async function resolveScopeMembers(
+ db: Database,
+ { scope, scopeId }: { scope: ScopeKind; scopeId: string }
+): Promise<ScopeMember[]> {
+ const userIds = await resolveScopeMemberUserIds(db, { scope, scopeId });
+ if (userIds.length === 0) return [];
+
+ const target = await db
+ .select({
+ id: communityChannel.id,
+ serverId: communityChannel.serverId,
+ parentChannelId: communityChannel.parentChannelId,
+ })
+ .from(communityChannel)
+ .where(eq(communityChannel.id, scopeId))
+ .limit(1);
+ if (target.length === 0) return [];
+ const serverId = target[0]!.serverId;
+ const anchorId = target[0]!.parentChannelId ?? target[0]!.id;
+
+ // Server roles for every resolved user — scoped to this server up front.
+ const roleRows = await db
+ .select({ userId: communityServerMember.userId, role: communityServerMember.role })
+ .from(communityServerMember)
+ .where(eq(communityServerMember.serverId, serverId));
+ const roleByUser = new Map<string, CommunityRole>();
+ for (const r of roleRows) roleByUser.set(r.userId, r.role as CommunityRole);
+
+ const isPrivate = await isChannelPrivate(db, scopeId);
+
+ // For a private anchor, "explicit" = the added channel members ∪ the anchor
+ // creator. Everyone else in the set is an admin/owner.
+ const explicit = new Set<string>();
+ if (isPrivate) {
+ for (const id of await listChannelMemberUserIds(db, anchorId)) explicit.add(id);
+ const anchor = await db
+ .select({ creatorId: communityChannel.creatorId })
+ .from(communityChannel)
+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
+ .where(eq(communityChannel.id, anchorId))
+ .limit(1);
+ const creatorId = anchor[0]?.creatorId;
+ if (creatorId) explicit.add(creatorId);
+ }
+
+ return userIds.map((userId) => {
+ const role = roleByUser.get(userId) ?? "member";
+ let source: MemberSource;
+ if (!isPrivate) {
+ source = role === "owner" || role === "admin" ? "admin" : "inherited";
+ } else if (explicit.has(userId)) {
+ source = "explicit";
+ } else {
+ source = "admin";
+ }
+ return { userId, role, source };
+ });
+}
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index ae201c05e..479c5e4c2 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -166,6 +166,7 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
channelName: "channel A",
serverId: "srv_1",
serverName: "server 1",
+ type: "forum",
parentChannelId: null,
lastMessageAt: t2,
lastReadAt: t1,
@@ -178,6 +179,8 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
expect(result[0]!.channelId).toBe("ch_A");
expect(result[0]!.lastMessageAt).toBe(t2);
expect(result[0]!.lastReadAt).toBe(t1);
+ // `type` is carried through so the inbox can render the entity icon.
+ expect(result[0]!.type).toBe("forum");
});
it("archived channels are filtered out even when unread", async () => {
diff --git a/src/shared/test/queries/community-members-resolver.test.ts b/src/shared/test/queries/community-members-resolver.test.ts
new file mode 100644
index 000000000..cc21edf69
--- /dev/null
+++ b/src/shared/test/queries/community-members-resolver.test.ts
@@ -0,0 +1,157 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+// Mock the underlying channel/member primitives the resolver builds on, so we
+// test the resolver's split + source-tagging logic in isolation (no real DB).
+const mockIsChannelPrivate = vi.fn<() => Promise<boolean>>();
+const mockGetPrivateChannelAudienceUserIds = vi.fn<() => Promise<string[]>>();
+const mockListChannelMemberUserIds = vi.fn<() => Promise<string[]>>();
+const mockListMemberUserIds = vi.fn<() => Promise<string[]>>();
+
+vi.mock("../../src/db/queries/community/channel", () => ({
+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...(a as [])),
+ getPrivateChannelAudienceUserIds: (...a: unknown[]) =>
+ mockGetPrivateChannelAudienceUserIds(...(a as [])),
+ listChannelMemberUserIds: (...a: unknown[]) => mockListChannelMemberUserIds(...(a as [])),
+}));
+
+vi.mock("../../src/db/queries/community/member", () => ({
+ listMemberUserIds: (...a: unknown[]) => mockListMemberUserIds(...(a as [])),
+}));
+
+import {
+ resolveScopeMemberUserIds,
+ resolveScopeMembers,
+} from "../../src/db/queries/community/members-resolver";
+import type { Database } from "../../src/index";
+
+/**
+ * `makeDb` returns a fake Database whose `.select().from().where().limit()`
+ * chain resolves to a queued set of rows. The resolver calls `.select` twice
+ * for the id path (channel lookup) and more for the member path; we queue rows
+ * per invocation so each `await` gets the intended shape.
+ */
+function makeDb(rowQueues: Record<string, unknown[][]>): Database {
+ const counters: Record<string, number> = {};
+ const builder = (rows: unknown[]) => {
+ const b: Record<string, unknown> = {};
+ b.select = () => b;
+ b.from = () => b;
+ b.leftJoin = () => b;
+ b.where = () => b;
+ b.limit = () => Promise.resolve(rows);
+ b.then = (resolve: (v: unknown) => void) => resolve(rows);
+ return b;
+ };
+ // `select` pops the next queued row-set keyed by call order across all
+ // `select` invocations. We key queues by a label the tests set up.
+ const db = {
+ select: () => {
+ const key = "select";
+ const idx = counters[key] ?? 0;
+ counters[key] = idx + 1;
+ const q = rowQueues[key] ?? [];
+ return builder(q[idx] ?? []);
+ },
+ } as unknown as Database;
+ return db;
+}
+
+const CHANNEL = "chan-1";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("resolveScopeMemberUserIds", () => {
+ it("private channel → the private audience (explicit ∪ creator ∪ admins)", async () => {
+ mockIsChannelPrivate.mockResolvedValue(true);
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1", "u2", "admin1"]);
+ const db = makeDb({ select: [[{ serverId: "srv-1" }]] });
+
+ const ids = await resolveScopeMemberUserIds(db, { scope: "channel", scopeId: CHANNEL });
+
+ expect(ids).toEqual(["u1", "u2", "admin1"]);
+ expect(mockGetPrivateChannelAudienceUserIds).toHaveBeenCalledTimes(1);
+ expect(mockListMemberUserIds).not.toHaveBeenCalled();
+ });
+
+ it("public / uncategorized channel → all server members (unfiltered)", async () => {
+ mockIsChannelPrivate.mockResolvedValue(false);
+ mockListMemberUserIds.mockResolvedValue(["u1", "u2", "u3"]);
+ const db = makeDb({ select: [[{ serverId: "srv-1" }]] });
+
+ const ids = await resolveScopeMemberUserIds(db, { scope: "channel", scopeId: CHANNEL });
+
+ expect(ids).toEqual(["u1", "u2", "u3"]);
+ expect(mockListMemberUserIds).toHaveBeenCalledTimes(1);
+ expect(mockGetPrivateChannelAudienceUserIds).not.toHaveBeenCalled();
+ });
+
+ it("thread / post resolve identically to channel (delegates to the same primitives)", async () => {
+ mockIsChannelPrivate.mockResolvedValue(true);
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"]);
+ const db = makeDb({ select: [[{ serverId: "srv-1" }]] });
+
+ const ids = await resolveScopeMemberUserIds(db, { scope: "thread", scopeId: CHANNEL });
+ expect(ids).toEqual(["u1"]);
+ });
+
+ it("unknown channel → empty (scope isolation — nothing leaks)", async () => {
+ const db = makeDb({ select: [[]] }); // channel lookup returns no rows
+ const ids = await resolveScopeMemberUserIds(db, { scope: "channel", scopeId: "nope" });
+ expect(ids).toEqual([]);
+ expect(mockIsChannelPrivate).not.toHaveBeenCalled();
+ });
+});
+
+describe("resolveScopeMembers — source tagging", () => {
+ it("public channel: owner/admin → admin, plain member → inherited", async () => {
+ mockIsChannelPrivate.mockResolvedValue(false);
+ mockListMemberUserIds.mockResolvedValue(["owner1", "admin1", "member1"]);
+ const db = makeDb({
+ select: [
+ [{ serverId: "srv-1" }], // resolveScopeMemberUserIds channel lookup
+ [{ serverId: "srv-1" }], // resolveScopeMembers target lookup
+ [ // role rows
+ { userId: "owner1", role: "owner" },
+ { userId: "admin1", role: "admin" },
+ { userId: "member1", role: "member" },
+ ],
+ ],
+ });
+
+ const members = await resolveScopeMembers(db, { scope: "channel", scopeId: CHANNEL });
+
+ expect(members).toEqual([
+ { userId: "owner1", role: "owner", source: "admin" },
+ { userId: "admin1", role: "admin", source: "admin" },
+ { userId: "member1", role: "member", source: "inherited" },
+ ]);
+ });
+
+ it("private channel: explicit member/creator → explicit, others → admin", async () => {
+ mockIsChannelPrivate.mockResolvedValue(true);
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["member1", "creator1", "admin1"]);
+ mockListChannelMemberUserIds.mockResolvedValue(["member1"]);
+ const db = makeDb({
+ select: [
+ [{ serverId: "srv-1" }], // resolveScopeMemberUserIds channel lookup
+ [{ serverId: "srv-1", parentChannelId: null }], // resolveScopeMembers target lookup
+ [ // role rows
+ { userId: "member1", role: "member" },
+ { userId: "creator1", role: "member" },
+ { userId: "admin1", role: "admin" },
+ ],
+ [{ creatorId: "creator1" }], // anchor creator lookup
+ ],
+ });
+
+ const members = await resolveScopeMembers(db, { scope: "channel", scopeId: CHANNEL });
+
+ expect(members).toEqual([
+ { userId: "member1", role: "member", source: "explicit" },
+ { userId: "creator1", role: "member", source: "explicit" },
+ { userId: "admin1", role: "admin", source: "admin" },
+ ]);
+ });
+});
diff --git a/src/web/src/app/api/community/inbox/unreads/route.test.ts b/src/web/src/app/api/community/inbox/unreads/route.test.ts
index 7a53db8ee..d33c10806 100644
--- a/src/web/src/app/api/community/inbox/unreads/route.test.ts
+++ b/src/web/src/app/api/community/inbox/unreads/route.test.ts
@@ -54,12 +54,13 @@ vi.mock("@/lib/middleware/helpers", () => {
import { GET } from "./route"
-function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null }>) {
+function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; type: string | null; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null }>) {
return {
channelId: "c1",
channelName: "general",
serverId: "s1",
serverName: "Server 1",
+ type: "text" as string | null,
parentChannelId: null,
lastMessageAt: "2026-06-25T10:00:00Z",
lastReadAt: null,
@@ -282,4 +283,41 @@ describe("GET /api/community/inbox/unreads", () => {
const body = await res.json()
expect(body.servers[0].channels[0].children).toEqual([])
})
+
+ // ── Entity type plumbing (drives the inbox icon) ───────────────────────────
+
+ it("surfaces channel `type` so the inbox can pick the right entity icon", async () => {
+ mockListUnreadChannels.mockResolvedValue([
+ row({ channelId: "c1", channelName: "general", type: "text" }),
+ row({ channelId: "c2", channelName: "help-forum", type: "forum", lastMessageAt: "2026-06-25T09:00:00Z" }),
+ ])
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))
+ const body = await res.json()
+ const byId = Object.fromEntries(
+ body.servers[0].channels.map((c: { channelId: string; type?: string }) => [c.channelId, c.type]),
+ )
+ expect(byId).toEqual({ c1: "text", c2: "forum" })
+ })
+
+ it("surfaces child `type` (thread / forum_post) on nested rows", async () => {
+ mockListUnreadChannels.mockResolvedValue([
+ row({ channelId: "c1", channelName: "general", type: "text" }),
+ row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),
+ ])
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))
+ const body = await res.json()
+ const parent = body.servers[0].channels[0]
+ expect(parent.type).toBe("text")
+ expect(parent.children[0].type).toBe("thread")
+ })
+
+ it("carries `type` from getChannelsByIds when the parent is backfilled", async () => {
+ mockListUnreadChannels.mockResolvedValue([
+ row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1" }),
+ ])
+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "help-forum", serverId: "s1", type: "forum" }])
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))
+ const body = await res.json()
+ expect(body.servers[0].channels[0].type).toBe("forum")
+ })
})
diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/inbox/unreads/route.ts
index 116ebb8cc..c062e4e55 100644
--- a/src/web/src/app/api/community/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/inbox/unreads/route.ts
@@ -47,10 +47,11 @@ export const GET = withAuth(async (req, ctx) => {
// Split unread rows into top-level channels and child threads/forum-posts.
// A child nests under its `parentChannelId`; a parent surfaces in the tree
// even when it has no direct unread of its own (only unread children).
- type UnreadChild = { channelId: string; channelName: string; lastMessageAt: string; mentionCount: number }
+ type UnreadChild = { channelId: string; channelName: string; type: string | null; lastMessageAt: string; mentionCount: number }
type ParentNode = {
channelId: string
channelName: string
+ type: string | null
serverId: string
serverName: string
lastMessageAt: string
@@ -75,6 +76,7 @@ export const GET = withAuth(async (req, ctx) => {
list.push({
channelId: row.channelId,
channelName: row.channelName,
+ type: row.type,
lastMessageAt: row.lastMessageAt,
mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,
})
@@ -84,6 +86,7 @@ export const GET = withAuth(async (req, ctx) => {
parents.set(row.channelId, {
channelId: row.channelId,
channelName: row.channelName,
+ type: row.type,
serverId: row.serverId,
serverName: row.serverName,
lastMessageAt: row.lastMessageAt,
@@ -110,6 +113,7 @@ export const GET = withAuth(async (req, ctx) => {
parents.set(pid, {
channelId: pid,
channelName: ch.name,
+ type: ch.type,
serverId: ch.serverId,
// serverName + a sort timestamp are backfilled from the child rows
// below (those rows carry serverName via the communityServer join).
@@ -166,9 +170,10 @@ export const GET = withAuth(async (req, ctx) => {
.map((c) => ({
channelId: c.channelId,
channelName: c.channelName,
+ type: c.type ?? undefined,
lastMessageAt: c.lastMessageAt,
mentionCount: c.mentionCount,
- children: c.children,
+ children: c.children.map((k) => ({ ...k, type: k.type ?? undefined })),
})),
}))
allServers.sort((a, b) => {
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index 71c8323c7..d9eb643db 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -26,6 +26,7 @@ import { useServerMembers } from "@/hooks/community/use-server-members"
import { useMessages } from "@/hooks/community/use-messages"
import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"
import { useChannelWatermark } from "@/hooks/community/use-channel-watermark"
+import { useEagerChannelRead } from "@/hooks/community/use-eager-channel-read"
import {
useThreads,
useForumPosts,
@@ -219,6 +220,16 @@ function ChannelView() {
const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)
useChannelWatermark({ channelId, messages, scrollRootEl })
+ // Eager mark-read on open — clears this channel/thread from the inbox the
+ // moment it's opened, while the frozen `readSnapshot` above keeps the "New"
+ // divider anchored to the pre-open pointer. Gated on the snapshot having
+ // settled (fetching done; `null` = never-visited is a valid resolved state).
+ useEagerChannelRead({
+ channelId,
+ isChildChannel,
+ snapshotReady: !readSnapshotFetching,
+ })
+
// `↓ N` unread count for the anchor-window path — server truth
// (`latestSeq - viewerLastReadSeq`). Clamped to 0 in case the read
// pointer somehow overshot latestSeq (e.g. a bot updated latestSeq
@@ -342,8 +353,10 @@ function ChannelView() {
setRightPanel((p) => (p === k ? null : k))
const enterThread = (id: string) => {
+ // No eager read PUT here — the thread page's `useEagerChannelRead` fires it
+ // on mount AFTER its read-state snapshot latches, so the "New" divider
+ // still anchors to the pre-open pointer. A PUT here would race the snapshot.
router.push(`/community/channels/${params.serverId}/${id}`)
- apiFetch(`/api/community/threads/${id}/read`, { method: "PUT" }).catch(() => { })
}
const openProfile: OpenProfile = (name, e, discriminator, userId) => {
diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsx
index 25c09d5cb..3d0fe8a75 100644
--- a/src/web/src/app/community/me/[dmId]/page.tsx
+++ b/src/web/src/app/community/me/[dmId]/page.tsx
@@ -21,6 +21,7 @@ import { useFriends } from "@/hooks/community/use-friends"
import { useDmMessages } from "@/hooks/community/use-messages"
import { useDmReadStateSnapshot } from "@/hooks/community/use-dm-read-state"
import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
+import { useEagerDmRead } from "@/hooks/community/use-eager-dm-read"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import {
useSendDmMessage,
@@ -154,6 +155,11 @@ function DmView() {
const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)
useDmWatermark({ dmId, messages, scrollRootEl })
+ // Eager mark-read on open — clears this DM from the inbox immediately while
+ // the frozen `readSnapshot` above keeps the "New" divider anchored to the
+ // pre-open pointer. Gated on the snapshot having settled.
+ useEagerDmRead({ dmId, snapshotReady: !readSnapshotFetching })
+
// `↓ N` unread count. Same math as channel: server truth is
// `latestSeq - viewerLastReadSeq`. Clamp to 0 in case the read pointer
// overshoots (e.g. a race between the read-state snapshot and a fresh
diff --git a/src/web/src/app/privacy/page.tsx b/src/web/src/app/privacy/page.tsx
index 7c3331246..6e57d0545 100644
--- a/src/web/src/app/privacy/page.tsx
+++ b/src/web/src/app/privacy/page.tsx
@@ -161,8 +161,7 @@ export default function PrivacyPage() {
If you have any questions about this Privacy Policy, You can contact us at{" "}
<a href="mailto:[email protected]" className={linkClass}>
- </a>
- .
+ </a>.
</p>
</section>
</div>
diff --git a/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx b/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx
index 627a64c95..390abb327 100644
--- a/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx
+++ b/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx
@@ -83,7 +83,6 @@ export function BotAvatarPickerDialog({ image, onChange }: BotAvatarPickerDialog
: null,
);
setActiveKind(nowPhoto ? "photo" : "procedural");
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [image]);
const emitForTab = (nextTab: "generate" | "photo", config: AvatarConfig, photo: PhotoDraft | null) => {
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 8b2662b7c..af4152ffb 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -12,6 +12,7 @@
import type React from "react"
import type { ChannelType, CommunityRole } from "@alook/shared"
+import type { EntityKind } from "./entity-icon"
// ── Presence / enums ───────────────────────────────────────────────────────
export type Presence = "online" | "offline"
@@ -274,6 +275,9 @@ export type Mention = {
type UnreadChild = {
channelId: string
channelName: string
+ // Raw stored channel type — drives the inbox entity icon (thread/forum_post
+ // → MessagesSquare). Optional for backward-compat with cached responses.
+ type?: EntityKind
lastMessageAt: string
mentionCount: number
}
@@ -287,6 +291,9 @@ export type UnreadServer = {
channels: Array<{
channelId: string
channelName: string
+ // Raw stored channel type — drives the inbox entity icon so a forum
+ // channel shows the forum glyph, not a generic hash.
+ type?: EntityKind
lastMessageAt: string
mentionCount: number
children: UnreadChild[]
diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsx
index e4ebf85c4..b768166d0 100644
--- a/src/web/src/components/community/channel-header.tsx
+++ b/src/web/src/components/community/channel-header.tsx
@@ -2,13 +2,14 @@
import { useEffect, useState } from "react"
import type { LucideIcon } from "lucide-react"
-import { Bell, BellOff, Pin, Users, MessagesSquare, ListChevronsUpDown, ChevronLeft, Check, Pencil, MoreHorizontal } from "lucide-react"
+import { Bell, BellOff, Pin, Users, MessagesSquare, ChevronLeft, Check, Pencil, MoreHorizontal } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { ChannelIcon } from "./channel-icon"
+import { EntityIcon } from "./entity-icon"
import { SlugHint } from "./slug-hint"
import { previewSlug } from "@/lib/community/slug-preview"
import { serverGradient } from "./server-gradient"
@@ -53,6 +54,10 @@ export function ChannelHeader({
tools?: { threads?: boolean; pinned?: boolean; members?: boolean }
}) {
+ // The parent-channel entity glyph (breadcrumb crumb + non-breadcrumb badge)
+ // is `<EntityIcon kind={...}>`. The `<ChannelIcon>` breadcrumb SEPARATOR
+ // below is a different glyph — leave it.
+ const entityKind = forum ? "forum" : "text"
const tool = (k: Exclude<RightPanel, null>, Icon: LucideIcon, label: string) => (
<Button
variant="ghost"
@@ -73,7 +78,7 @@ export function ChannelHeader({
{breadcrumb ? (
<>
<button onClick={breadcrumb.onNavigateBack} className={`flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors ${server ? "" : "ml-1"}`}>
- {forum ? <ListChevronsUpDown className="size-4 shrink-0" /> : <ChannelIcon className="text-base" />}
+ <EntityIcon kind={entityKind} className="size-4 shrink-0" />
<span className="truncate text-base font-medium">{channel}</span>
</button>
<ChannelIcon className="shrink-0 text-base text-muted-foreground/60" />
@@ -85,7 +90,7 @@ export function ChannelHeader({
) : (
<>
<div className={`grid size-6 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground ${server ? "" : "ml-1"}`}>
- {forum ? <ListChevronsUpDown className="size-4" /> : <ChannelIcon className="text-base" />}
+ <EntityIcon kind={entityKind} className="size-4" />
</div>
<span className="truncate text-base font-semibold">{channel}</span>
</>
diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsx
index 54548d87e..9afb8df2d 100644
--- a/src/web/src/components/community/community-inbox-popover.tsx
+++ b/src/web/src/components/community/community-inbox-popover.tsx
@@ -1,4 +1,5 @@
-import { ChevronRight, CornerDownRight, Hash, Inbox, MoreHorizontal, Trash2 } from "lucide-react"
+import { ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"
+import { EntityIcon } from "./entity-icon"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
@@ -52,7 +53,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {
onClick={() => onOpenChannel?.(s.serverId, c.channelId)}
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
>
- <Hash className="size-4 shrink-0 text-muted-foreground" />
+ <EntityIcon kind={c.type} className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{c.channelName}</span>
<MentionBadge count={c.mentionCount} />
<ChevronRight className="size-4 shrink-0 text-muted-foreground" />
@@ -64,7 +65,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {
onClick={() => onOpenChannel?.(s.serverId, child.channelId)}
className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"
>
- <CornerDownRight className="size-3.5 shrink-0 text-muted-foreground" />
+ <EntityIcon kind={child.type} className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-muted-foreground">{child.channelName}</span>
<MentionBadge count={child.mentionCount} />
<ChevronRight className="size-4 shrink-0 text-muted-foreground" />
diff --git a/src/web/src/components/community/create-category-dialog.tsx b/src/web/src/components/community/create-category-dialog.tsx
index e83e530be..2520cd371 100644
--- a/src/web/src/components/community/create-category-dialog.tsx
+++ b/src/web/src/components/community/create-category-dialog.tsx
@@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Field } from "./field"
-// Create Category dialog — name + private toggle (defaults to private). In a
+// Create Category dialog — name + private toggle (defaults to public). In a
// private category any member can create a channel, but each channel is visible
// only to its creator + invited members (and admins). A public category's
// channels are admin-managed and visible to everyone.
@@ -18,7 +18,7 @@ export function CreateCategoryDialog({ onClose, onCreate, canTogglePrivate = tru
canTogglePrivate?: boolean
}) {
const [name, setName] = useState("")
- const [isPrivate, setIsPrivate] = useState(true)
+ const [isPrivate, setIsPrivate] = useState(false)
const submit = () => {
const trimmed = name.trim()
if (!trimmed) return
diff --git a/src/web/src/components/community/create-channel-dialog.tsx b/src/web/src/components/community/create-channel-dialog.tsx
index 574fa15de..e42d6348c 100644
--- a/src/web/src/components/community/create-channel-dialog.tsx
+++ b/src/web/src/components/community/create-channel-dialog.tsx
@@ -1,8 +1,7 @@
"use client"
import { useState } from "react"
-import { ListChevronsUpDown } from "lucide-react"
-import { ChannelIcon } from "./channel-icon"
+import { EntityIcon } from "./entity-icon"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
@@ -23,9 +22,9 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
const [type, setType] = useState<ChannelType>(initial?.type ?? "text")
const [name, setName] = useState(initial?.name ?? "")
- const options: { value: ChannelType; icon: typeof ListChevronsUpDown | typeof ChannelIcon; label: string; desc: string }[] = [
- { value: "text", icon: ChannelIcon, label: "Text", desc: "Send messages, images, emoji, and opinions" },
- { value: "forum", icon: ListChevronsUpDown, label: "Forum", desc: "Create a space for organized discussions" },
+ const options: { value: ChannelType; label: string; desc: string }[] = [
+ { value: "text", label: "Text", desc: "Send messages, images, emoji, and opinions" },
+ { value: "forum", label: "Forum", desc: "Create a space for organized discussions" },
]
const namePreview = previewSlug(name)
@@ -57,7 +56,7 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
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" />
+ <EntityIcon kind={o.value} 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>
@@ -73,9 +72,7 @@ export function CreateChannelDialog({ category, initial, onClose, onCreate }: {
<label className="block">
<div className="mb-2 text-xs font-semibold text-muted-foreground">Channel Name</div>
<div className="relative">
- {type === "forum"
- ? <ListChevronsUpDown className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
- : <ChannelIcon className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground" />}
+ <EntityIcon kind={type} className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={name}
onChange={(e) => setName(e.target.value)}
diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsx
index ffd8d544c..70f703cd0 100644
--- a/src/web/src/components/community/edit-profile-dialog.tsx
+++ b/src/web/src/components/community/edit-profile-dialog.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useRef, useState } from "react"
+import { useEffect, useState } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import { User, LogOut, X, Palette, Sun, Moon, Monitor, Database } from "lucide-react"
@@ -123,41 +123,47 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu
onLogout?: () => void
onUploadAvatar?: () => void
}) {
+ // Draft + saved baseline are mount-only on purpose — a WS-driven prop change
+ // (e.g. status fan-out echo) must not clobber an in-progress edit. The
+ // baseline advances only on a successful save.
const [name, setName] = useState(userName)
const [value, setValue] = useState(aboutMe)
const [status, setStatus] = useState({ emoji: statusEmoji ?? null, text: statusText ?? null })
- const [saving, setSaving] = useState(false)
+ const [baseline, setBaseline] = useState({
+ name: userName,
+ aboutMe,
+ emoji: statusEmoji ?? null,
+ text: statusText ?? null,
+ })
const [tab, setTab] = useState("profile")
- const timerRef = useRef<NodeJS.Timeout | null>(null)
- const onSaveRef = useRef(onSave)
- useEffect(() => {
- onSaveRef.current = onSave
- }, [onSave])
- const debouncedSave = useCallback((data: { name?: string; aboutMe?: string; statusEmoji?: string | null; statusText?: string | null }) => {
- if (timerRef.current) clearTimeout(timerRef.current)
- timerRef.current = setTimeout(() => {
- setSaving(true)
- onSaveRef.current(data)
- setTimeout(() => setSaving(false), 600)
- }, 800)
- }, [])
+ const dirty =
+ name !== baseline.name ||
+ value !== baseline.aboutMe ||
+ status.emoji !== baseline.emoji ||
+ status.text !== baseline.text
- useEffect(() => { return () => { if (timerRef.current) clearTimeout(timerRef.current) } }, [])
-
- const handleAboutMeChange = (text: string) => {
- setValue(text)
- debouncedSave({ aboutMe: text.trim() })
- }
-
- const handleNameChange = (text: string) => {
- setName(text)
- debouncedSave({ name: text.trim() })
+ const handleSave = () => {
+ if (!dirty) return
+ const trimmedName = name.trim()
+ const trimmedAbout = value.trim()
+ // Status is part of the unified payload so the WS-store write and
+ // server-side fanOutStatusUpdate still fire (see shell-frame wiring).
+ onSave({
+ name: trimmedName,
+ aboutMe: trimmedAbout,
+ statusEmoji: status.emoji,
+ statusText: status.text,
+ })
+ setBaseline({ name: trimmedName, aboutMe: trimmedAbout, emoji: status.emoji, text: status.text })
+ setName(trimmedName)
+ setValue(trimmedAbout)
}
- const handleStatusChange = (emoji: string | null, text: string | null) => {
- setStatus({ emoji, text })
- debouncedSave({ statusEmoji: emoji, statusText: text })
+ const handleCancel = () => {
+ setName(baseline.name)
+ setValue(baseline.aboutMe)
+ setStatus({ emoji: baseline.emoji, text: baseline.text })
}
return (
@@ -206,14 +212,14 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu
<Button variant="secondary" size="sm" className="mt-2" onClick={onUploadAvatar}>Upload Photo</Button>
</div>
</div>
- <Field label={<span>Display Name {saving && <span className="ml-2 text-xs text-muted-foreground">Saving...</span>}</span>}>
- <Input value={name} onChange={(e) => handleNameChange(e.target.value)} />
+ <Field label="Display Name">
+ <Input value={name} onChange={(e) => setName(e.target.value)} />
</Field>
<Field label="About Me">
- <Textarea className="h-24 resize-none" value={value} onChange={(e) => handleAboutMeChange(e.target.value)} />
+ <Textarea className="h-24 resize-none" value={value} onChange={(e) => setValue(e.target.value)} />
</Field>
<Field label="Status">
- <StatusEditor emoji={status.emoji} text={status.text} onChange={handleStatusChange}>
+ <StatusEditor emoji={status.emoji} text={status.text} onChange={(emoji, text) => setStatus({ emoji, text })}>
<button className="flex h-9 w-full items-center rounded-md border border-input bg-transparent px-3 text-sm hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{hasStatus(status.emoji, status.text) ? (
<span>{status.emoji} {status.text}</span>
@@ -223,6 +229,10 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu
</button>
</StatusEditor>
</Field>
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="ghost" size="sm" onClick={handleCancel} disabled={!dirty}>Cancel</Button>
+ <Button size="sm" onClick={handleSave} disabled={!dirty}>Save changes</Button>
+ </div>
</div>
</TabsContent>
<TabsContent value="appearance">
diff --git a/src/web/src/components/community/entity-icon.test.ts b/src/web/src/components/community/entity-icon.test.ts
new file mode 100644
index 000000000..ed1d20899
--- /dev/null
+++ b/src/web/src/components/community/entity-icon.test.ts
@@ -0,0 +1,20 @@
+import { describe, it, expect } from "vitest"
+import { ListChevronsUpDown, MessagesSquare } from "lucide-react"
+import { getEntityIcon } from "./entity-icon"
+import { ChannelIcon } from "./channel-icon"
+
+describe("getEntityIcon", () => {
+ it("text and undefined → ChannelIcon (the custom slash glyph)", () => {
+ expect(getEntityIcon("text")).toBe(ChannelIcon)
+ expect(getEntityIcon(undefined)).toBe(ChannelIcon)
+ })
+
+ it("forum → ListChevronsUpDown", () => {
+ expect(getEntityIcon("forum")).toBe(ListChevronsUpDown)
+ })
+
+ it("thread and forum_post → MessagesSquare", () => {
+ expect(getEntityIcon("thread")).toBe(MessagesSquare)
+ expect(getEntityIcon("forum_post")).toBe(MessagesSquare)
+ })
+})
diff --git a/src/web/src/components/community/entity-icon.tsx b/src/web/src/components/community/entity-icon.tsx
new file mode 100644
index 000000000..42e17a61f
--- /dev/null
+++ b/src/web/src/components/community/entity-icon.tsx
@@ -0,0 +1,55 @@
+import { ListChevronsUpDown, MessagesSquare } from "lucide-react"
+import { ChannelIcon } from "./channel-icon"
+
+/**
+ * Every community entity that gets a leading glyph, keyed by its RAW stored
+ * type string. `ChannelType` is only `"text" | "forum"`, but children carry
+ * `"thread"` / `"forum_post"` — so this wider union takes the raw value
+ * straight off the row without a lossy cast.
+ */
+export type EntityKind = "text" | "forum" | "thread" | "forum_post"
+
+type IconComponent = (props: { className?: string }) => React.ReactNode
+
+/**
+ * Resolve a community entity kind → its icon component. Prefer `<EntityIcon>`
+ * in render paths (the eslint `react-hooks/static-components` rule forbids
+ * assigning a component to a variable mid-render); use this only where you
+ * genuinely need the component reference (e.g. building a static options list
+ * outside the render body).
+ */
+export function getEntityIcon(kind: EntityKind | undefined): IconComponent {
+ switch (kind) {
+ case "forum":
+ return ListChevronsUpDown
+ case "thread":
+ case "forum_post":
+ return MessagesSquare
+ default:
+ return ChannelIcon
+ }
+}
+
+/**
+ * The single source of truth mapping a community entity kind → its icon. The
+ * list/sidebar is canonical; every other surface (inbox, header, dialogs)
+ * routes through here so the same entity never shows two different glyphs.
+ *
+ * text | undefined → ChannelIcon (the custom slash glyph)
+ * forum → ListChevronsUpDown
+ * thread | forum_post → MessagesSquare
+ *
+ * Accepts `className` only — matching `ChannelIcon` — so both `size-*` and
+ * `text-*` call sites keep working.
+ */
+export function EntityIcon({ kind, className }: { kind: EntityKind | undefined; className?: string }) {
+ switch (kind) {
+ case "forum":
+ return <ListChevronsUpDown className={className} />
+ case "thread":
+ case "forum_post":
+ return <MessagesSquare className={className} />
+ default:
+ return <ChannelIcon className={className} />
+ }
+}
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsx
index ee5b27ecd..b08c7e4f9 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx
+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx
@@ -198,8 +198,7 @@ function Step2({
<span className="flex items-center gap-2">
<span className="text-[15px] font-medium text-foreground">{connectedHostname}</span>
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-1 text-[11px] font-medium text-emerald-600 dark:text-emerald-400">
- <span className="inline-block size-1.5 rounded-full bg-status-online" />
- Online
+ <span className="inline-block size-1.5 rounded-full bg-status-online" />Online
</span>
</span>
<span className="text-muted-foreground">is ready for your agent friends.</span>
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index d86b6059b..5b6839a30 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -196,7 +196,12 @@ export function MessageList({
// genuine scroll-in transition.
const topSentinelRef = useRef<HTMLDivElement>(null)
const loadOlderStateRef = useRef({ onLoadOlder, hasMore, isFetchingOlder })
- loadOlderStateRef.current = { onLoadOlder, hasMore, isFetchingOlder }
+ // Sync the latest guards into the ref after each commit — the observer
+ // callback (which reads it) only fires asynchronously, so a post-render
+ // write is behavior-identical while keeping the ref untouched during render.
+ useEffect(() => {
+ loadOlderStateRef.current = { onLoadOlder, hasMore, isFetchingOlder }
+ })
useEffect(() => {
const el = topSentinelRef.current
const root = scrollRef.current
@@ -234,7 +239,10 @@ export function MessageList({
// cascade through all newer pages).
const bottomSentinelRef = useRef<HTMLDivElement>(null)
const loadNewerStateRef = useRef({ onLoadNewer, hasMoreNewer, isFetchingNewer })
- loadNewerStateRef.current = { onLoadNewer, hasMoreNewer, isFetchingNewer }
+ // Same post-commit ref sync as the top sentinel — see comment above.
+ useEffect(() => {
+ loadNewerStateRef.current = { onLoadNewer, hasMoreNewer, isFetchingNewer }
+ })
useEffect(() => {
const el = bottomSentinelRef.current
const root = scrollRef.current
diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/profile-card.tsx
index 70169eb74..d3653cf08 100644
--- a/src/web/src/components/community/profile-card.tsx
+++ b/src/web/src/components/community/profile-card.tsx
@@ -46,7 +46,8 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
if (!text || !data.userId) return
onMessage?.(data.userId, text)
setMsg("")
- mobile ? onClose() : close()
+ if (mobile) onClose()
+ else close()
}
const gradient = generateGradient(data.userId ?? data.name)
const card = (
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index 1ea26d0b5..aa7981dd9 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -128,10 +128,19 @@ 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 ?? "")
+ // Saved baseline is mount-only (same rationale as the draft above): a WS
+ // rename must not reset it mid-edit. Advances only on a successful save.
+ const [baseline, setBaseline] = useState({ name: serverName, desc: serverDescription ?? "" })
const namePreview = previewSlug(name)
+ const dirty = name !== baseline.name || desc !== baseline.desc
const save = () => {
- if (namePreview.invalid) return
+ if (namePreview.invalid || !dirty) return
onUpdateServer?.(name, desc)
+ setBaseline({ name, desc })
+ }
+ const cancel = () => {
+ setName(baseline.name)
+ setDesc(baseline.desc)
}
return (
<div className="mx-auto max-w-md space-y-10">
@@ -150,10 +159,14 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadI
</div>
</div>
<Field label="Server name">
- <Input value={name} onChange={(e) => setName(e.target.value)} onBlur={save} />
+ <Input value={name} onChange={(e) => setName(e.target.value)} />
<SlugHint {...namePreview} />
</Field>
- <Field label="Description"><Textarea className="h-20 resize-none" value={desc} onChange={(e) => setDesc(e.target.value)} onBlur={save} /></Field>
+ <Field label="Description"><Textarea className="h-20 resize-none" value={desc} onChange={(e) => setDesc(e.target.value)} /></Field>
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="ghost" size="sm" onClick={cancel} disabled={!dirty}>Cancel</Button>
+ <Button size="sm" onClick={save} disabled={!dirty || namePreview.invalid}>Save changes</Button>
+ </div>
</section>
<section className="space-y-4">
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 41d417669..f7bff9fd8 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -456,10 +456,9 @@ export function ShellFrame({
const openServerChannel = useCallback(
(sid: string, cid: string) => {
- // #3: no eager mark-read on inbox → channel navigation. The channel's
- // IntersectionObserver watermark advances the pointer as the user
- // actually reads. If they open the channel and don't scroll to the
- // new messages, the pointer correctly stays put.
+ // No PUT here — the channel/thread page's `useEagerChannelRead` fires the
+ // mark-read on mount, AFTER its read-state snapshot latches, so the NEW
+ // divider still anchors to the pre-open pointer. Navigating is enough.
router.push(`/community/channels/${sid}/${cid}`)
},
[router],
@@ -467,12 +466,11 @@ export function ShellFrame({
const openInboxDm = useCallback(
(dmId: string) => {
- // Mirrors the DM sidebar's `enterDm` (see app/community/me/layout.tsx):
- // client-only optimistic clear on `communityKeys.dms()` — no eager
- // mark-read PUT. Eagerly aligning the read pointer to the tail here
- // would resolve the DM's read-state snapshot at tail on mount and
- // suppress the NEW divider. The DM page's IntersectionObserver
- // (`useDmWatermark`) is authoritative for advancing the server pointer.
+ // Optimistic clear on `communityKeys.dms()` so the sidebar updates
+ // instantly. The real mark-read is owned by the DM page's
+ // `useEagerDmRead` on mount (snapshot latches first → NEW divider stays
+ // anchored), and `useDmWatermark` continues to advance the pointer as
+ // the viewer scrolls.
queryClient.setQueryData(
communityKeys.dms(),
(prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>
diff --git a/src/web/src/components/community/sortable-channel.tsx b/src/web/src/components/community/sortable-channel.tsx
index 93799884f..42b3c542b 100644
--- a/src/web/src/components/community/sortable-channel.tsx
+++ b/src/web/src/components/community/sortable-channel.tsx
@@ -1,8 +1,8 @@
"use client"
import { useState } from "react"
-import { ListChevronsUpDown, BellOff, Pencil, Trash2, Users } from "lucide-react"
-import { ChannelIcon } from "./channel-icon"
+import { BellOff, Pencil, Trash2, Users } from "lucide-react"
+import { EntityIcon } from "./entity-icon"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
@@ -48,11 +48,7 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManag
>
{showLine && <DropLine side={lineSide} />}
<span className="grid size-5 shrink-0 place-items-center opacity-70">
- {ch.type === "forum" ? (
- <ListChevronsUpDown className="size-4" />
- ) : (
- <ChannelIcon className="size-4" />
- )}
+ <EntityIcon kind={ch.type} className="size-4" />
</span>
<span className="truncate font-semibold">{ch.name}</span>
{ch.muted ? (
diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.ts
new file mode 100644
index 000000000..350e48d71
--- /dev/null
+++ b/src/web/src/hooks/community/use-eager-channel-read.ts
@@ -0,0 +1,69 @@
+"use client"
+
+import { useEffect, useRef } from "react"
+import { useQueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+
+/**
+ * Eager "mark this channel/thread read on open."
+ *
+ * Being *inside* a channel should consume its unread — the inbox must not keep
+ * showing a channel the viewer is actively looking at. This fires ONE mass
+ * mark-read PUT (empty body → the server marks to the latest message) per
+ * mount, as soon as the read-state snapshot has latched.
+ *
+ * Ordering matters (NEW-divider preservation): the divider anchors to
+ * `useChannelReadStateSnapshot`, a once-per-mount frozen pointer. We gate this
+ * PUT on `snapshotReady` so the snapshot latches the PRE-open pointer first;
+ * the eager PUT then advances the server pointer without moving the divider.
+ *
+ * Race avoidance: we deliberately do NOT route through `scheduleMarkRead` (the
+ * debounced watermark path keyed on `channelId`). The IntersectionObserver
+ * watermark can schedule an advance to an OLDER (divider-area) message at
+ * mount; a shared debounce would collapse to whichever fires last and could
+ * under-advance. A direct PUT-to-latest, guarded server-side by the monotonic
+ * `lastReadAt < message.createdAt` rule, can never be regressed by a later
+ * older watermark PUT.
+ *
+ * `isChildChannel` picks the endpoint — threads/forum-posts read through
+ * `/threads/:id/read`, top-level channels through `/channels/:id/read`. Both
+ * accept an empty body as mass mark-read and both batch the mention clear.
+ *
+ * Note: `lastReadSeq` (the numeric bot-wake cursor) is intentionally NOT
+ * touched here — human read routes don't bump it; that divergence is a
+ * separate concern.
+ */
+export function useEagerChannelRead({
+ channelId,
+ isChildChannel,
+ snapshotReady,
+}: {
+ channelId: string | null | undefined
+ isChildChannel: boolean
+ snapshotReady: boolean
+}) {
+ const queryClient = useQueryClient()
+ // One eager PUT per (channel mount). Reset when the channel changes.
+ const firedForRef = useRef<string | null>(null)
+
+ useEffect(() => {
+ if (!channelId) return
+ if (!snapshotReady) return
+ if (firedForRef.current === channelId) return
+ firedForRef.current = channelId
+
+ const endpoint = isChildChannel
+ ? `/api/community/threads/${channelId}/read`
+ : `/api/community/channels/${channelId}/read`
+ void apiFetch(endpoint, { method: "PUT" })
+ .then(() => {
+ // Refresh the inbox feeds and the rail badge (mention rows dropped).
+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
+ })
+ .catch(() => {
+ // Silent — the watermark / WS invalidate reconciles the inbox anyway.
+ })
+ }, [channelId, isChildChannel, snapshotReady, queryClient])
+}
diff --git a/src/web/src/hooks/community/use-eager-dm-read.ts b/src/web/src/hooks/community/use-eager-dm-read.ts
new file mode 100644
index 000000000..41c83b42e
--- /dev/null
+++ b/src/web/src/hooks/community/use-eager-dm-read.ts
@@ -0,0 +1,51 @@
+"use client"
+
+import { useEffect, useRef } from "react"
+import { useQueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import type { UnreadsResponse } from "./use-inbox"
+
+/**
+ * DM sibling of `useEagerChannelRead`. Opening a DM should consume its unread:
+ * fire ONE direct mass mark-read PUT (empty body → mark to latest) per mount,
+ * gated on the read-state snapshot having latched so the "New" divider keeps
+ * the pre-open anchor.
+ *
+ * Invalidates BOTH `inbox()` and `dms()` — the top-of-app unread badge lives
+ * under `inbox()` and the sidebar DM list's `unread` flag under `dms()`. It
+ * also optimistically trims the DM out of the `inboxUnreads().dms` array so
+ * the popover updates instantly (mirrors `useMarkChannelRead`'s optimistic
+ * inbox trim for channels).
+ */
+export function useEagerDmRead({
+ dmId,
+ snapshotReady,
+}: {
+ dmId: string | null | undefined
+ snapshotReady: boolean
+}) {
+ const queryClient = useQueryClient()
+ const firedForRef = useRef<string | null>(null)
+
+ useEffect(() => {
+ if (!dmId) return
+ if (!snapshotReady) return
+ if (firedForRef.current === dmId) return
+ firedForRef.current = dmId
+
+ // Optimistic trim so the inbox popover drops this DM immediately.
+ queryClient.setQueryData<UnreadsResponse>(communityKeys.inboxUnreads(), (prev) =>
+ prev ? { ...prev, dms: prev.dms.filter((d) => d.dmConversationId !== dmId) } : prev,
+ )
+
+ void apiFetch(`/api/community/dm/${dmId}/read`, { method: "PUT" })
+ .then(() => {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })
+ })
+ .catch(() => {
+ // Silent — the watermark / WS invalidate reconciles the inbox anyway.
+ })
+ }, [dmId, snapshotReady, queryClient])
+}
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index 685e08dce..1faaae165 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -28,6 +28,9 @@ vi.mock("@alook/shared", async () => {
isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
+ communityMembersResolver: {
+ resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),
+ },
communityDm: {
getDM: (...a: unknown[]) => mockGetDM(...a),
},
@@ -60,6 +63,7 @@ const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])
const mockGetDM = vi.fn()
const mockGetCoMemberUserIds = vi.fn()
const mockGetFriendUserIds = vi.fn()
+const mockResolveScopeMemberUserIds = vi.fn(() => [] as string[])
import {
fanOutToServerMembers,
@@ -113,9 +117,8 @@ describe("fanOutToServerMembers", () => {
expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)
})
- it("fanOutToChannel resolves through channel → server → listMemberUserIds", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "srv_1" })
- mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
+ it("fanOutToChannel resolves recipients via the shared member resolver", async () => {
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel("c1", {
type: WS_EVENTS.MESSAGE_CREATE,
@@ -123,7 +126,13 @@ describe("fanOutToServerMembers", () => {
message: {} as never,
} as never)
- expect(mockListMemberUserIds).toHaveBeenCalledTimes(1)
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledTimes(1)
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
+ scope: "channel",
+ scopeId: "c1",
+ })
+ // The old inline split (getChannel + isChannelPrivate) is gone.
+ expect(mockGetChannel).not.toHaveBeenCalled()
expect(mockListMembers).not.toHaveBeenCalled()
expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)
})
@@ -195,8 +204,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("fanOutToChannel enqueues wakes using the same recipient list, minus excludeUserId", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "srv_1" })
- mockListMemberUserIds.mockResolvedValue(["u1", "u2", "u3"])
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2", "u3"])
await fanOutToChannel(
"c1",
@@ -230,8 +238,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("does not enqueue wakes when wakeMessageRow is omitted", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "srv_1" })
- mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel("c1", {
type: WS_EVENTS.MESSAGE_CREATE,
@@ -243,8 +250,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("does not enqueue wakes for non-MESSAGE_CREATE events even with a wakeMessageRow", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "srv_1" })
- mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel(
"c1",
@@ -261,8 +267,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("a failing enqueueBotWakes does not reject fanOutToChannel", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "srv_1" })
- mockListMemberUserIds.mockResolvedValue(["u1"])
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1"])
mockEnqueueBotWakes.mockRejectedValue(new Error("queue down"))
await expect(
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index c4c88d7a0..4b623819c 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -41,25 +41,15 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s
}
/**
- * Resolves the recipient set for a channel event.
- * - public / uncategorized channel (or a thread whose anchor is public) →
- * all server members (unchanged behavior).
- * - private-category channel (or a thread anchored to one) → the channel
- * audience: explicit members ∪ creator ∪ server admins.
- * `isChannelPrivate` and `getPrivateChannelAudienceUserIds` both climb
- * `parentChannelId`, so threads inherit their parent's audience automatically.
+ * Resolves the recipient set for a channel event. The public/private split
+ * (and thread/post parent-climbing) lives in the shared member resolver — this
+ * is a thin delegate so fan-out, the WS DO, and any future surface all agree.
*/
async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {
- const channel = await queries.communityChannel.getChannel(db, channelId)
- if (!channel) {
- log.warn("fanOutToChannel: channel not found", { channelId })
- return []
- }
- const isPrivate = await queries.communityChannel.isChannelPrivate(db, channelId)
- if (isPrivate) {
- return queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)
- }
- return getServerMemberUserIds(db, channel.serverId)
+ return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
+ scope: "channel",
+ scopeId: channelId,
+ })
}
/**
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index b35ac22ae..e807a8efe 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -79,6 +79,7 @@ const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<stri
const mockGetChannelForMember = vi.fn()
const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)
const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
+const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope: string; scopeId: string }) => Promise<string[]>>().mockResolvedValue([])
const mockGetDM = vi.fn()
const mockListMembers = vi.fn()
const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
@@ -189,6 +190,9 @@ vi.mock("@alook/shared", () => {
isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
+ communityMembersResolver: {
+ resolveScopeMemberUserIds: (...a: any[]) => mockResolveScopeMemberUserIds(...a),
+ },
communityDm: {
getDM: (...a: any[]) => mockGetDM(...a),
},
@@ -1363,11 +1367,9 @@ describe("WebSocketDurableObject", () => {
it("fans out to other server members when sender IS a channel member", async () => {
const { durable, env } = createDO()
mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })
- mockListMembers.mockResolvedValueOnce([
- { userId: "member-1" },
- { userId: "member-2" },
- { userId: "sender-1" },
- ])
+ // Recipient resolution now goes through the shared member resolver — a
+ // public channel resolves to every server member (sender included).
+ mockResolveScopeMemberUserIds.mockResolvedValueOnce(["member-1", "member-2", "sender-1"])
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
@@ -1379,7 +1381,10 @@ describe("WebSocketDurableObject", () => {
await flush()
expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-1", "sender-1")
- expect(mockListMembers).toHaveBeenCalledWith(expect.anything(), "server-1")
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
+ scope: "channel",
+ scopeId: "chan-1",
+ })
// Sender is excluded from recipients — only the other 2 members get a broadcast POST.
expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-2")
@@ -1390,10 +1395,9 @@ describe("WebSocketDurableObject", () => {
it("private channel: fans out to the channel audience, not all server members", async () => {
const { durable, env } = createDO()
mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-p", serverId: "server-1" })
- mockIsChannelPrivate.mockResolvedValueOnce(true)
- // Audience = creator + added member + admin (server-wide members would be
- // more than this — the assertion below proves we used the audience).
- mockGetPrivateChannelAudienceUserIds.mockResolvedValueOnce(["sender-1", "member-1"])
+ // The resolver applies the public/private split internally — a private
+ // channel resolves to its audience (creator + added member + admin).
+ mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "member-1"])
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
@@ -1404,7 +1408,10 @@ describe("WebSocketDurableObject", () => {
)
await flush()
- expect(mockGetPrivateChannelAudienceUserIds).toHaveBeenCalledWith(expect.anything(), "chan-p")
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
+ scope: "channel",
+ scopeId: "chan-p",
+ })
expect(mockListMembers).not.toHaveBeenCalled()
// Only the non-sender audience member gets a broadcast POST.
expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 7498374ae..ea4ebd360 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -933,14 +933,12 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// channel audience — never leak "X is typing" to non-members. Also
// re-gates the sender: a server member who isn't in the private
// channel won't appear in its own audience, so they broadcast to
- // nobody. Public/uncategorized channels stay server-wide.
- const isPrivate = await queries.communityChannel.isChannelPrivate(db, targetId)
- if (isPrivate) {
- recipientUserIds = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, targetId)
- } else {
- const members = await queries.communityMember.listMembers(db, membership.serverId)
- recipientUserIds = members.map((m) => m.userId)
- }
+ // nobody. Public/uncategorized channels stay server-wide. The
+ // public/private split lives in the shared member resolver.
+ recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
+ scope: "channel",
+ scopeId: targetId,
+ })
}
}