Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): add activity-ranked forum threads to sidebar (#430)

Gener9f131587e516
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 91e0bb1bb..2ff1d91bc 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -14,6 +14,10 @@ import type { MentionType } from "./utils/community-mentions"
export type CommunityMessageCreate = {
type: "community:message.create"
channelId: string
+ /** Present for server-channel messages; lets server-scoped collections react without unread state. */
+ serverId?: string
+ /** Present when channelId is a child thread/post. */
+ parentChannelId?: string
message: {
id: string
seq: number
@@ -429,7 +433,8 @@ export type CommunityUnreadBump = {
type: "community:unread.bump"
userId: string
/** The channel the message actually landed in (a thread bump = the thread's
- * id). Use `railChannelId` to locate the sidebar row; this is the true scope. */
+ * id). Clients with a loaded child row may badge it directly; otherwise use
+ * `railChannelId` as the locatable fallback. */
channelId: string
/**
* The server whose tree/rail badge to patch (inbox-dot-ws-driven plan). Lets
@@ -440,9 +445,9 @@ export type CommunityUnreadBump = {
*/
serverId?: string
/**
- * The sidebar-locatable channel row = `parentChannelId ?? channelId`, computed
- * server-side. A child-thread message has no independent sidebar row, so
- * its dot must light the PARENT channel's row; a plain channel is its own row.
+ * The always-locatable fallback row = `parentChannelId ?? channelId`, computed
+ * server-side. A participating forum thread may now have its own nested row;
+ * when it does not, this parent fallback keeps the unread signal visible.
* Absent → client falls back to `channelId`.
*/
railChannelId?: string
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.ts
index c940ed572..3602e19b7 100644
--- a/src/shared/src/db/queries/community/thread.ts
+++ b/src/shared/src/db/queries/community/thread.ts
@@ -1,10 +1,17 @@
-import { and, asc, eq, inArray, lte, sql } from "drizzle-orm";
-import { communityChannel, communityChannelMember } from "../../community-schema";
+import { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte, or, sql } from "drizzle-orm";
+import { communityChannel, communityChannelMember, communityMessageTag } from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";
import { type ParticipantSource } from "../../../constants/community";
+// SQLite's default TEXT ordering is BINARY. These values are ASCII ids / ISO
+// timestamps, so JS code-unit comparison matches the database byte order while
+// localeCompare does not (notably for case-sensitive nanoids such as A vs a).
+function compareSqliteBinary(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
// The NOTIFICATION set for a child thread — relation='notify' rows
// on `community_channel_member` (formerly the standalone
// community_thread_participant table). A thread/post is not an access unit —
@@ -127,38 +134,50 @@ export async function listParticipantsForChannels(
limitPerChannel?: number
) {
if (channelIds.length === 0) return [];
+ // D1 caps each statement at 100 bind parameters. Both variants below bind
+ // every channel id plus fixed predicates (and the ranked variant also binds
+ // the per-channel limit), so hydrate in safe chunks. De-duplicate first so
+ // an id repeated across chunk boundaries cannot duplicate participant rows.
+ const channelIdChunks = chunk([...new Set(channelIds)], D1_MAX_IN_PARAMS);
if (limitPerChannel !== undefined) {
- const ranked = db
- .select({
- channelId: communityChannelMember.channelId,
- userId: communityChannelMember.userId,
- addedAt: communityChannelMember.addedAt,
- userName: user.name,
- userImage: user.image,
- participantCount: sql<number>`count(*) over (partition by ${communityChannelMember.channelId})`.as("participant_count"),
- rank: sql<number>`row_number() over (partition by ${communityChannelMember.channelId} order by ${communityChannelMember.addedAt}, ${communityChannelMember.userId})`.as("participant_rank"),
- })
- .from(communityChannelMember)
- .innerJoin(user, eq(user.id, communityChannelMember.userId))
- .where(and(
- inArray(communityChannelMember.channelId, channelIds),
- eq(communityChannelMember.relation, "notify")
- ))
- .as("ranked_participants");
- return db
- .select({
- channelId: ranked.channelId,
- userId: ranked.userId,
- addedAt: ranked.addedAt,
- userName: ranked.userName,
- userImage: ranked.userImage,
- participantCount: ranked.participantCount,
- })
- .from(ranked)
- .where(lte(ranked.rank, limitPerChannel))
- .orderBy(asc(ranked.channelId), asc(ranked.addedAt), asc(ranked.userId));
+ const batches = await Promise.all(channelIdChunks.map((ids) => {
+ const ranked = db
+ .select({
+ channelId: communityChannelMember.channelId,
+ userId: communityChannelMember.userId,
+ addedAt: communityChannelMember.addedAt,
+ userName: user.name,
+ userImage: user.image,
+ participantCount: sql<number>`count(*) over (partition by ${communityChannelMember.channelId})`.as("participant_count"),
+ rank: sql<number>`row_number() over (partition by ${communityChannelMember.channelId} order by ${communityChannelMember.addedAt}, ${communityChannelMember.userId})`.as("participant_rank"),
+ })
+ .from(communityChannelMember)
+ .innerJoin(user, eq(user.id, communityChannelMember.userId))
+ .where(and(
+ inArray(communityChannelMember.channelId, ids),
+ eq(communityChannelMember.relation, "notify")
+ ))
+ .as("ranked_participants");
+ return db
+ .select({
+ channelId: ranked.channelId,
+ userId: ranked.userId,
+ addedAt: ranked.addedAt,
+ userName: ranked.userName,
+ userImage: ranked.userImage,
+ participantCount: ranked.participantCount,
+ })
+ .from(ranked)
+ .where(lte(ranked.rank, limitPerChannel))
+ .orderBy(asc(ranked.channelId), asc(ranked.addedAt), asc(ranked.userId));
+ }));
+ return batches.flat().sort((a, b) =>
+ compareSqliteBinary(a.channelId, b.channelId) ||
+ compareSqliteBinary(a.addedAt, b.addedAt) ||
+ compareSqliteBinary(a.userId, b.userId)
+ );
}
- return db
+ const batches = await Promise.all(channelIdChunks.map((ids) => db
.select({
channelId: communityChannelMember.channelId,
userId: communityChannelMember.userId,
@@ -170,10 +189,11 @@ export async function listParticipantsForChannels(
.innerJoin(user, eq(user.id, communityChannelMember.userId))
.where(
and(
- inArray(communityChannelMember.channelId, channelIds),
+ inArray(communityChannelMember.channelId, ids),
eq(communityChannelMember.relation, "notify")
)
- );
+ )));
+ return batches.flat();
}
export async function isThreadParticipant(
@@ -271,3 +291,211 @@ export async function listParticipatingThreadIds(
).flat();
return rows.map((r) => r.channelId);
}
+
+export type ForumActivityCursor = { activityAt: string; id: string };
+
+export async function listForumThreadsByActivity(
+ db: Database,
+ params: {
+ parentChannelId: string;
+ tag?: string;
+ cursor?: ForumActivityCursor;
+ limit: number;
+ }
+) {
+ const activityAt = sql<string>`coalesce(${communityChannel.lastMessageAt}, ${communityChannel.createdAt})`;
+ const conditions = [
+ eq(communityChannel.parentChannelId, params.parentChannelId),
+ eq(communityChannel.type, "thread"),
+ eq(communityChannel.archived, 0),
+ isNotNull(communityChannel.parentMessageId),
+ ];
+ if (params.cursor) {
+ conditions.push(or(
+ lt(activityAt, params.cursor.activityAt),
+ and(
+ eq(activityAt, params.cursor.activityAt),
+ lt(communityChannel.id, params.cursor.id)
+ )
+ )!);
+ }
+
+ const select = {
+ id: communityChannel.id,
+ serverId: communityChannel.serverId,
+ categoryId: communityChannel.categoryId,
+ name: communityChannel.name,
+ type: communityChannel.type,
+ topic: communityChannel.topic,
+ position: communityChannel.position,
+ parentChannelId: communityChannel.parentChannelId,
+ creatorId: communityChannel.creatorId,
+ messageCount: communityChannel.messageCount,
+ archived: communityChannel.archived,
+ parentMessageId: communityChannel.parentMessageId,
+ lastMessageAt: communityChannel.lastMessageAt,
+ createdAt: communityChannel.createdAt,
+ activityAt: activityAt.as("activity_at"),
+ } as const;
+
+ if (params.tag) {
+ return db
+ .select(select)
+ .from(communityChannel)
+ .innerJoin(
+ communityMessageTag,
+ and(
+ eq(communityMessageTag.messageId, communityChannel.parentMessageId),
+ eq(communityMessageTag.tag, params.tag)
+ )
+ )
+ .where(and(...conditions))
+ .orderBy(desc(activityAt), desc(communityChannel.id))
+ .limit(params.limit);
+ }
+
+ return db
+ .select(select)
+ .from(communityChannel)
+ .where(and(...conditions))
+ .orderBy(desc(activityAt), desc(communityChannel.id))
+ .limit(params.limit);
+}
+
+/**
+ * Viewer-participating forum posts for the nested server sidebar. The caller
+ * supplies only forum ids that already passed the viewer's top-level visibility
+ * gate; notify membership narrows that trusted set to posts the viewer follows.
+ * The rolling activity window and row_number limit are applied per forum in SQL.
+ *
+ * `retainId` is the currently open post. If it is a valid participating post
+ * under one of the visible forums, keep it even outside the rolling window or
+ * top-N and let it displace that forum's final ordinary row.
+ */
+export async function listParticipatingForumThreads(
+ db: Database,
+ params: {
+ parentChannelIds: string[];
+ userId: string;
+ activeAfter: string;
+ limitPerParent: number;
+ retainId?: string;
+ }
+) {
+ const parentChannelIds = [...new Set(params.parentChannelIds)];
+ if (parentChannelIds.length === 0 || params.limitPerParent < 1) return [];
+
+ const activityAt = sql<string>`coalesce(${communityChannel.lastMessageAt}, ${communityChannel.createdAt})`;
+ const select = {
+ id: communityChannel.id,
+ serverId: communityChannel.serverId,
+ categoryId: communityChannel.categoryId,
+ name: communityChannel.name,
+ type: communityChannel.type,
+ topic: communityChannel.topic,
+ position: communityChannel.position,
+ parentChannelId: communityChannel.parentChannelId,
+ creatorId: communityChannel.creatorId,
+ messageCount: communityChannel.messageCount,
+ archived: communityChannel.archived,
+ parentMessageId: communityChannel.parentMessageId,
+ lastMessageAt: communityChannel.lastMessageAt,
+ createdAt: communityChannel.createdAt,
+ activityAt: activityAt.as("activity_at"),
+ } as const;
+
+ const batches = await Promise.all(
+ chunk(parentChannelIds, D1_MAX_IN_PARAMS).map((parentIds) => {
+ const ranked = db
+ .select({
+ ...select,
+ rank: sql<number>`row_number() over (partition by ${communityChannel.parentChannelId} order by ${activityAt} desc, ${communityChannel.id} desc)`.as("sidebar_rank"),
+ })
+ .from(communityChannel)
+ .innerJoin(
+ communityChannelMember,
+ and(
+ eq(communityChannelMember.channelId, communityChannel.id),
+ eq(communityChannelMember.userId, params.userId),
+ eq(communityChannelMember.relation, "notify"),
+ ),
+ )
+ .where(and(
+ inArray(communityChannel.parentChannelId, parentIds),
+ eq(communityChannel.type, "thread"),
+ eq(communityChannel.archived, 0),
+ isNotNull(communityChannel.parentMessageId),
+ gt(activityAt, params.activeAfter),
+ ))
+ .as("ranked_sidebar_threads");
+
+ return db
+ .select({
+ id: ranked.id,
+ serverId: ranked.serverId,
+ categoryId: ranked.categoryId,
+ name: ranked.name,
+ type: ranked.type,
+ topic: ranked.topic,
+ position: ranked.position,
+ parentChannelId: ranked.parentChannelId,
+ creatorId: ranked.creatorId,
+ messageCount: ranked.messageCount,
+ archived: ranked.archived,
+ parentMessageId: ranked.parentMessageId,
+ lastMessageAt: ranked.lastMessageAt,
+ createdAt: ranked.createdAt,
+ activityAt: ranked.activityAt,
+ })
+ .from(ranked)
+ .where(lte(ranked.rank, params.limitPerParent))
+ .orderBy(asc(ranked.parentChannelId), desc(ranked.activityAt), desc(ranked.id));
+ }),
+ );
+ let rows = batches.flat();
+
+ if (params.retainId) {
+ // Scope the retained lookup inside the same caller-authorized parent set,
+ // rather than fetching an arbitrary id first and masking it in JS. Chunking
+ // preserves that structural scope without exceeding D1's bind ceiling.
+ const retained = (await Promise.all(
+ chunk(parentChannelIds, D1_MAX_IN_PARAMS).map((parentIds) => db
+ .select(select)
+ .from(communityChannel)
+ .innerJoin(
+ communityChannelMember,
+ and(
+ eq(communityChannelMember.channelId, communityChannel.id),
+ eq(communityChannelMember.userId, params.userId),
+ eq(communityChannelMember.relation, "notify"),
+ ),
+ )
+ .where(and(
+ eq(communityChannel.id, params.retainId!),
+ inArray(communityChannel.parentChannelId, parentIds),
+ eq(communityChannel.type, "thread"),
+ eq(communityChannel.archived, 0),
+ isNotNull(communityChannel.parentMessageId),
+ ))
+ .limit(1)),
+ )).flat()[0];
+
+ if (
+ retained?.parentChannelId &&
+ !rows.some((row) => row.id === retained.id)
+ ) {
+ const parentId = retained.parentChannelId;
+ const otherParents = rows.filter((row) => row.parentChannelId !== parentId);
+ const ordinary = rows
+ .filter((row) => row.parentChannelId === parentId)
+ .slice(0, params.limitPerParent - 1);
+ rows = [...otherParents, ...ordinary, retained];
+ }
+ }
+
+ return rows.sort((a, b) =>
+ compareSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
+ compareSqliteBinary(b.activityAt, a.activityAt) ||
+ compareSqliteBinary(b.id, a.id)
+ );
+}
diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.ts
index 0af4148fd..892797a5d 100644
--- a/src/shared/test/queries/community-thread.test.ts
+++ b/src/shared/test/queries/community-thread.test.ts
@@ -1,5 +1,9 @@
-import { describe, it, expect, vi } from "vitest";
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { drizzle as drizzleProxy } from "drizzle-orm/sqlite-proxy";
+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import * as threadQueries from "../../src/db/queries/community/thread";
+import { D1_MAX_BIND_PARAMS } from "../../src/db/queries/_chunk";
describe("community/thread exports", () => {
it("exports the participant CRUD", () => {
@@ -11,6 +15,158 @@ describe("community/thread exports", () => {
});
});
+describe("listForumThreadsByActivity against real SQLite", () => {
+ let sqlite: Sqlite.Database;
+ let db: ReturnType<typeof drizzle>;
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.exec(`
+ CREATE TABLE community_channel (
+ id TEXT PRIMARY KEY,
+ server_id TEXT,
+ category_id TEXT,
+ name TEXT,
+ type TEXT NOT NULL DEFAULT 'text',
+ topic TEXT DEFAULT '',
+ position INTEGER DEFAULT 0,
+ parent_channel_id TEXT,
+ creator_id TEXT,
+ message_count INTEGER DEFAULT 0,
+ archived INTEGER DEFAULT 0,
+ parent_message_id TEXT,
+ last_message_at TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_message_tag (
+ id TEXT PRIMARY KEY,
+ message_id TEXT NOT NULL,
+ tag TEXT NOT NULL,
+ UNIQUE(message_id, tag)
+ );
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ image TEXT
+ );
+ 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 NOT NULL,
+ added_by TEXT,
+ added_at TEXT NOT NULL
+ );
+ `);
+ const insertChannel = sqlite.prepare(`
+ INSERT INTO community_channel
+ (id, name, type, parent_channel_id, parent_message_id, archived, last_message_at, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ `);
+ insertChannel.run("t_new", "new activity", "thread", "forum_1", "m_new", 0, "2026-08-08T05:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ insertChannel.run("t_tie_b", "tie b", "thread", "forum_1", "m_tie_b", 0, "2026-08-08T04:00:00.000Z", "2026-01-02T00:00:00.000Z");
+ insertChannel.run("t_tie_a", "tie a", "thread", "forum_1", "m_tie_a", 0, "2026-08-08T04:00:00.000Z", "2026-01-03T00:00:00.000Z");
+ insertChannel.run("t_created", "created fallback", "thread", "forum_1", "m_created", 0, null, "2026-08-08T02:00:00.000Z");
+ insertChannel.run("t_archived", "archived", "thread", "forum_1", "m_archived", 1, "2026-08-09T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ insertChannel.run("t_rootless", "rootless", "thread", "forum_1", null, 0, "2026-08-09T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ insertChannel.run("not_thread", "text child", "text", "forum_1", "m_text", 0, "2026-08-09T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ insertChannel.run("foreign", "foreign", "thread", "forum_2", "m_foreign", 0, "2026-08-10T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ const insertTag = sqlite.prepare("INSERT INTO community_message_tag (id, message_id, tag) VALUES (?, ?, ?)");
+ insertTag.run("tag_tie", "m_tie_a", "bug");
+ insertTag.run("tag_created", "m_created", "bug");
+ insertTag.run("tag_foreign", "m_foreign", "bug");
+ db = drizzle(sqlite);
+ });
+
+ afterEach(() => sqlite.close());
+
+ it("orders by activity and pages stable timestamp ties without overlap", async () => {
+ const first = await threadQueries.listForumThreadsByActivity(db as never, {
+ parentChannelId: "forum_1",
+ limit: 2,
+ });
+ const second = await threadQueries.listForumThreadsByActivity(db as never, {
+ parentChannelId: "forum_1",
+ cursor: { activityAt: first[1]!.activityAt, id: first[1]!.id },
+ limit: 3,
+ });
+
+ expect(first.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);
+ expect(second.map((row) => row.id)).toEqual(["t_tie_a", "t_created"]);
+ expect(second[1]!.activityAt).toBe("2026-08-08T02:00:00.000Z");
+ expect(new Set([...first, ...second].map((row) => row.id)).size).toBe(4);
+ });
+
+ it("applies the tag and forum scope before the activity limit", async () => {
+ const rows = await threadQueries.listForumThreadsByActivity(db as never, {
+ parentChannelId: "forum_1",
+ tag: "bug",
+ limit: 5,
+ });
+ expect(rows.map((row) => row.id)).toEqual(["t_tie_a", "t_created"]);
+ });
+
+ it("preserves SQLite BINARY participant tie ordering for case-sensitive ids", async () => {
+ sqlite.prepare("INSERT INTO user (id, name) VALUES (?, ?)").run("A", "upper");
+ sqlite.prepare("INSERT INTO user (id, name) VALUES (?, ?)").run("a", "lower");
+ const insertMember = sqlite.prepare(`
+ INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, source, added_at)
+ VALUES (?, ?, ?, 'notify', 'added', ?)
+ `);
+ const tiedAt = "2026-08-08T06:00:00.000Z";
+ insertMember.run("member_a", "t_new", "a", tiedAt);
+ insertMember.run("member_A", "t_new", "A", tiedAt);
+
+ const rows = await threadQueries.listParticipantsForChannels(
+ db as never,
+ ["t_new"],
+ 5,
+ );
+
+ expect(rows.map((row) => row.userId)).toEqual(["A", "a"]);
+ });
+
+ it("returns per-forum recent notify rows and retains an older open post", async () => {
+ sqlite.prepare("INSERT INTO user (id, name) VALUES (?, ?)").run("viewer", "Viewer");
+ const insertMember = sqlite.prepare(`
+ INSERT INTO community_channel_member
+ (id, channel_id, user_id, relation, source, added_at)
+ VALUES (?, ?, 'viewer', 'notify', 'spoke', '2026-08-08T00:00:00.000Z')
+ `);
+ for (const id of ["t_new", "t_tie_b", "t_tie_a", "t_created", "t_archived", "foreign"]) {
+ insertMember.run(`member_${id}`, id);
+ }
+
+ const recent = await threadQueries.listParticipatingForumThreads(db as never, {
+ parentChannelIds: ["forum_1", "forum_2"],
+ userId: "viewer",
+ activeAfter: "2026-08-08T03:00:00.000Z",
+ limitPerParent: 2,
+ });
+ expect(recent.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);
+
+ const retained = await threadQueries.listParticipatingForumThreads(db as never, {
+ parentChannelIds: ["forum_1", "forum_2"],
+ userId: "viewer",
+ activeAfter: "2026-08-08T03:00:00.000Z",
+ limitPerParent: 2,
+ retainId: "t_created",
+ });
+ expect(retained.map((row) => row.id)).toEqual(["t_new", "t_created", "foreign"]);
+
+ const outOfScopeRetained = await threadQueries.listParticipatingForumThreads(db as never, {
+ parentChannelIds: ["forum_1"],
+ userId: "viewer",
+ activeAfter: "2026-08-08T03:00:00.000Z",
+ limitPerParent: 2,
+ retainId: "foreign",
+ });
+ expect(outOfScopeRetained.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);
+ });
+});
+
describe("addThreadParticipant", () => {
function insertMock(returned: any[]) {
const chain: any = {};
@@ -80,6 +236,46 @@ describe("listThreadParticipantUserIds — notify set", () => {
});
});
+describe("listParticipantsForChannels — D1 bind cap", () => {
+ it("chunks 100 channel ids so every ranked statement stays within 100 binds", async () => {
+ const paramCounts: number[] = [];
+ const db = drizzleProxy(async (_sql, params) => {
+ paramCounts.push(params.length);
+ return { rows: [] };
+ });
+
+ await threadQueries.listParticipantsForChannels(
+ db as never,
+ Array.from({ length: 100 }, (_, i) => `thread_${i}`),
+ 5,
+ );
+
+ expect(paramCounts).toHaveLength(2);
+ expect(Math.max(...paramCounts)).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);
+ });
+});
+
+describe("listParticipatingForumThreads — D1 bind cap", () => {
+ it("chunks 100 visible forum ids so ranked and retained statements stay within 100 binds", async () => {
+ const paramCounts: number[] = [];
+ const db = drizzleProxy(async (_sql, params) => {
+ paramCounts.push(params.length);
+ return { rows: [] };
+ });
+
+ await threadQueries.listParticipatingForumThreads(db as never, {
+ parentChannelIds: Array.from({ length: 100 }, (_, i) => `forum_${i}`),
+ userId: "viewer_1",
+ activeAfter: "2026-08-05T00:00:00.000Z",
+ limitPerParent: 5,
+ retainId: "thread_1",
+ });
+
+ expect(paramCounts).toHaveLength(4);
+ expect(Math.max(...paramCounts)).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);
+ });
+});
+
describe("listParticipatingThreadIds", () => {
function whereMock(rows: any[]) {
const chain: any = {};
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
index dbbddfad3..da68c6603 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
@@ -7,8 +7,12 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockResolveChannelAccessContext = vi.fn()
const mockRemoveThreadParticipant = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
+}))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -69,6 +73,12 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {
const res = await DELETE(delReq(), { params: { id: "t1", userId: "u1" } } as any)
expect(res.status).toBe(204)
expect(mockRemoveThreadParticipant).toHaveBeenCalledWith(expect.anything(), "t1", "u1")
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {
+ type: "community:channel.member_remove",
+ serverId: "s1",
+ channelId: "t1",
+ userId: "u1",
+ })
})
it("thread creator can remove another participant", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
index c096372b5..0d78d3f5f 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
@@ -2,7 +2,8 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, isThread } from "@alook/shared"
+import { queries, WS_EVENTS, isThread } from "@alook/shared"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireChannelAccess } from "@/lib/community/permissions"
/**
@@ -36,5 +37,11 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const removed = await queries.communityThread.removeThreadParticipant(db, channelId, targetUserId)
if (!removed) return writeError("participant not found", 404)
+ await broadcastToUserSafe(targetUserId, {
+ type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,
+ serverId: access.value.channel.serverId,
+ channelId,
+ userId: targetUserId,
+ })
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
index 92e940997..b405d2539 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
@@ -16,6 +16,9 @@ const mockGetMessage = vi.fn()
const mockGetUser = vi.fn()
const mockListMessages = vi.fn()
const mockFilterMessageIdsByTag = vi.fn()
+const mockListTagsForMessages = vi.fn()
+const mockListForumThreadsByActivity = vi.fn()
+const mockListParticipantsForChannels = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -40,6 +43,11 @@ vi.mock("@alook/shared", async () => {
},
communityMessageTag: {
filterMessageIdsByTag: (...a: unknown[]) => mockFilterMessageIdsByTag(...a),
+ listTagsForMessages: (...a: unknown[]) => mockListTagsForMessages(...a),
+ },
+ communityThread: {
+ listForumThreadsByActivity: (...a: unknown[]) => mockListForumThreadsByActivity(...a),
+ listParticipantsForChannels: (...a: unknown[]) => mockListParticipantsForChannels(...a),
},
user: {
getUser: (...a: unknown[]) => mockGetUser(...a),
@@ -80,8 +88,8 @@ describe("GET /api/community/channels/[id]/threads", () => {
// requireChannelAccess resolves through resolveChannelAccessContext — a
// public channel the caller is a member of.
mockResolveChannelAccessContext.mockResolvedValue({
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null },
- anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null },
+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" },
+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" },
role: "member",
isPrivate: false,
isChannelMember: false,
@@ -164,4 +172,110 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(res.status).toBe(400)
expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()
})
+
+ it("returns an activity page with scoped included resources and an opaque next cursor", async () => {
+ mockListForumThreadsByActivity.mockResolvedValue([
+ { id: "t3", parentMessageId: "m3", activityAt: "2026-08-08T03:00:00.000Z" },
+ { id: "t2", parentMessageId: "m2", activityAt: "2026-08-08T02:00:00.000Z" },
+ { id: "t1", parentMessageId: "m1", activityAt: "2026-08-08T01:00:00.000Z" },
+ ])
+ mockGetMessagesByIds.mockResolvedValue([{ id: "m3" }, { id: "m2" }])
+ mockGetFirstMessageByChannelIds.mockResolvedValue([{ channelId: "t3", content: "preview" }])
+ mockListTagsForMessages.mockResolvedValue([{ messageId: "m3", tag: "bug" }])
+ mockListParticipantsForChannels.mockResolvedValue([{ channelId: "t3", userId: "u1" }])
+
+ const res = await GET(req(
+ "http://localhost/api/community/channels/c1/threads?order=activity&limit=2&include=parentMessage,firstMessage,tags,participants",
+ ), ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.threads.map((thread: { id: string }) => thread.id)).toEqual(["t3", "t2"])
+ expect(body).toMatchObject({
+ hasMore: true,
+ included: {
+ parentMessages: [{ id: "m3" }, { id: "m2" }],
+ firstMessages: [{ channelId: "t3", content: "preview" }],
+ tags: [{ messageId: "m3", tag: "bug" }],
+ participants: [{ channelId: "t3", userId: "u1" }],
+ },
+ })
+ expect(body.nextCursor).toEqual(expect.any(String))
+ expect(mockListForumThreadsByActivity).toHaveBeenCalledWith(expect.anything(), {
+ parentChannelId: "c1",
+ limit: 3,
+ })
+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["m3", "m2"])
+ expect(mockGetFirstMessageByChannelIds).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"])
+ expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"], 5)
+
+ mockListForumThreadsByActivity.mockResolvedValue([])
+ const next = await GET(req(
+ `http://localhost/api/community/channels/c1/threads?order=activity&limit=2&cursor=${encodeURIComponent(body.nextCursor)}`,
+ ), ctx)
+ expect(next.status).toBe(200)
+ expect(mockListForumThreadsByActivity).toHaveBeenLastCalledWith(expect.anything(), {
+ parentChannelId: "c1",
+ cursor: { activityAt: "2026-08-08T02:00:00.000Z", id: "t2" },
+ limit: 3,
+ })
+ })
+
+ it("applies a normalized tag before activity pagination", async () => {
+ mockListForumThreadsByActivity.mockResolvedValue([])
+ const res = await GET(req(
+ "http://localhost/api/community/channels/c1/threads?order=activity&tag=%20BUG%20&limit=5",
+ ), ctx)
+ expect(res.status).toBe(200)
+ expect(mockListForumThreadsByActivity).toHaveBeenCalledWith(expect.anything(), {
+ parentChannelId: "c1",
+ tag: "bug",
+ limit: 6,
+ })
+ expect(mockListChildChannels).not.toHaveBeenCalled()
+ expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()
+ })
+
+ it("rejects malformed and cross-forum activity cursors without querying children", async () => {
+ const malformed = await GET(req(
+ "http://localhost/api/community/channels/c1/threads?order=activity&cursor=not-a-cursor",
+ ), ctx)
+ expect(malformed.status).toBe(400)
+
+ const foreignPayload = btoa(encodeURIComponent(JSON.stringify({
+ parentChannelId: "another-forum",
+ activityAt: "2026-08-08T02:00:00.000Z",
+ id: "t2",
+ tag: null,
+ }))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")
+ const foreign = await GET(req(
+ `http://localhost/api/community/channels/c1/threads?order=activity&cursor=${foreignPayload}`,
+ ), ctx)
+ expect(foreign.status).toBe(400)
+ expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ })
+
+ it("rejects unknown included resources before querying children", async () => {
+ const res = await GET(req(
+ "http://localhost/api/community/channels/c1/threads?order=activity&include=parentMessage,secrets",
+ ), ctx)
+ expect(res.status).toBe(400)
+ expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ })
+
+ it("does not query activity children when the forum access gate rejects the viewer", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue({
+ channel: { id: "c1", serverId: "s1", type: "forum" },
+ anchor: { id: "c1", serverId: "s1", type: "forum" },
+ role: "member",
+ isPrivate: true,
+ isCreator: false,
+ isChannelMember: false,
+ })
+ const res = await GET(req(
+ "http://localhost/api/community/channels/c1/threads?order=activity",
+ ), ctx)
+ expect(res.status).toBe(403)
+ expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ expect(mockGetMessagesByIds).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.ts
index 6ac1b46a3..885fab6b6 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts
@@ -2,8 +2,10 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, MAX_FORUM_TAG_LENGTH } from "@alook/shared"
+import { isForum, queries, MAX_FORUM_TAG_LENGTH } from "@alook/shared"
import { requireChannelAccess } from "@/lib/community/permissions"
+import { parseBoundedInt } from "@/lib/community/messages"
+import { encodeForumActivityCursor, parseForumActivityCursor } from "@/lib/community/forum-activity"
export const GET = withAuth(async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -20,18 +22,84 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const archivedParam = req.nextUrl.searchParams.get("archived")
const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined
+ const rawTag = req.nextUrl.searchParams.get("tag")
+ const tag = rawTag?.trim().toLowerCase()
+ if (rawTag !== null && !tag) return writeError("tag is required", 400)
+ if (tag && tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)
+
+ if (req.nextUrl.searchParams.get("order") === "activity") {
+ if (!isForum(access.value.channel.type)) return writeError("not a forum", 400)
+ if (archived === true) return writeError("activity order only supports active threads", 400)
+ const includes = new Set(
+ (req.nextUrl.searchParams.get("include") ?? "")
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean),
+ )
+ const allowedIncludes = new Set(["parentMessage", "firstMessage", "tags", "participants"])
+ if ([...includes].some((value) => !allowedIncludes.has(value))) {
+ return writeError("invalid include", 400)
+ }
+ const pageSize = parseBoundedInt(req.nextUrl.searchParams.get("limit"), 50, 100)
+ const cursor = parseForumActivityCursor(req.nextUrl.searchParams.get("cursor"), {
+ parentChannelId: channelId,
+ tag: tag ?? null,
+ })
+ if (cursor === null) return writeError("invalid cursor", 400)
+
+ const rows = await queries.communityThread.listForumThreadsByActivity(db, {
+ parentChannelId: channelId,
+ ...(tag ? { tag } : {}),
+ ...(cursor ? { cursor } : {}),
+ limit: pageSize + 1,
+ })
+ const hasMore = rows.length > pageSize
+ const threads = hasMore ? rows.slice(0, pageSize) : rows
+ const last = threads.at(-1)
+ const nextCursor = hasMore && last
+ ? encodeForumActivityCursor({
+ parentChannelId: channelId,
+ activityAt: last.activityAt,
+ id: last.id,
+ tag: tag ?? null,
+ })
+ : undefined
+
+ const parentMessageIds = threads
+ .map((thread) => thread.parentMessageId)
+ .filter((id): id is string => !!id)
+ const threadIds = threads.map((thread) => thread.id)
+ const [parentMessages, firstMessages, tags, participants] = await Promise.all([
+ includes.has("parentMessage")
+ ? queries.communityMessage.getMessagesByIds(db, parentMessageIds)
+ : Promise.resolve([]),
+ includes.has("firstMessage")
+ ? queries.communityMessage.getFirstMessageByChannelIds(db, threadIds)
+ : Promise.resolve([]),
+ includes.has("tags")
+ ? queries.communityMessageTag.listTagsForMessages(db, parentMessageIds)
+ : Promise.resolve([]),
+ includes.has("participants")
+ ? queries.communityThread.listParticipantsForChannels(db, threadIds, 5)
+ : Promise.resolve([]),
+ ])
+
+ return writeJSON({
+ threads,
+ included: { parentMessages, firstMessages, tags, participants },
+ hasMore,
+ ...(nextCursor ? { nextCursor } : {}),
+ })
+ }
+
let childChannels = await queries.communityChannel.listChildChannels(db, channelId, {
archived,
type: "thread",
})
- const rawTag = req.nextUrl.searchParams.get("tag")
if (rawTag !== null) {
- const tag = rawTag.trim().toLowerCase()
- if (!tag) return writeError("tag is required", 400)
- if (tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)
const openerIds = childChannels.map((child) => child.parentMessageId).filter((id): id is string => !!id)
- const matching = new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, tag))
+ const matching = new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, tag!))
childChannels = childChannels.filter((child) => !!child.parentMessageId && matching.has(child.parentMessageId))
}
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
index 166011d6e..427489ae4 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
@@ -1,8 +1,11 @@
-import { describe, expect, it, vi } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
const mockGetMember = vi.fn()
const mockListServerChannelsForViewer = vi.fn()
+const mockListParticipatingForumThreads = vi.fn()
+const mockGetMessagesByIds = vi.fn()
+const mockListUnreadChannels = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
@@ -16,6 +19,18 @@ vi.mock("@alook/shared", async () => {
...actual.queries.communityChannel,
listServerChannelsForViewer: (...args: unknown[]) => mockListServerChannelsForViewer(...args),
},
+ communityThread: {
+ ...actual.queries.communityThread,
+ listParticipatingForumThreads: (...args: unknown[]) => mockListParticipatingForumThreads(...args),
+ },
+ communityMessage: {
+ ...actual.queries.communityMessage,
+ getMessagesByIds: (...args: unknown[]) => mockGetMessagesByIds(...args),
+ },
+ communityInbox: {
+ ...actual.queries.communityInbox,
+ listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),
+ },
},
}
})
@@ -30,6 +45,11 @@ vi.mock("@/lib/middleware/community-actor", () => ({
import { GET } from "./route"
describe("GET /api/community/servers/[id]/channels — human resource", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockListUnreadChannels.mockResolvedValue([])
+ })
+
it("returns only viewer-visible channel rows after one server membership gate", async () => {
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
mockListServerChannelsForViewer.mockResolvedValue([{ id: "channel_1", serverId: "server_1", name: "general" }])
@@ -41,4 +61,62 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
expect(await response.json()).toEqual({ channels: [{ id: "channel_1", serverId: "server_1", name: "general" }] })
expect(mockListServerChannelsForViewer).toHaveBeenCalledWith(expect.anything(), "server_1", "user_1")
})
+
+ it("returns recent participating forum threads with opener messages and server-relative expiry", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-08-08T12:00:00.000Z"))
+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
+ mockListServerChannelsForViewer.mockResolvedValue([
+ { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
+ { id: "text_visible", serverId: "server_1", name: "General", type: "text" },
+ ])
+ mockListParticipatingForumThreads.mockResolvedValue([{
+ id: "thread_1",
+ serverId: "server_1",
+ parentChannelId: "forum_visible",
+ parentMessageId: "message_1",
+ type: "thread",
+ activityAt: "2026-08-08T11:00:00.000Z",
+ }])
+ mockGetMessagesByIds.mockResolvedValue([{ id: "message_1", content: "Current title" }])
+ mockListUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])
+
+ try {
+ const response = await GET(
+ new NextRequest("http://localhost/api/community/servers/server_1/channels?type=thread&parentType=forum&participating=true&activeWithin=72h&limitPerParent=5&retainId=thread_1&include=parentMessage"),
+ { params: { id: "server_1" } } as never,
+ )
+ expect(response.status).toBe(200)
+ expect(mockListParticipatingForumThreads).toHaveBeenCalledWith(expect.anything(), {
+ parentChannelIds: ["forum_visible"],
+ userId: "user_1",
+ activeAfter: "2026-08-05T12:00:00.000Z",
+ limitPerParent: 5,
+ retainId: "thread_1",
+ })
+ expect(await response.json()).toEqual({
+ channels: [expect.objectContaining({
+ id: "thread_1",
+ expiresAt: "2026-08-11T11:00:00.000Z",
+ unread: true,
+ })],
+ included: { parentMessages: [{ id: "message_1", content: "Current title" }] },
+ serverNow: "2026-08-08T12:00:00.000Z",
+ })
+ expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("rejects a partial or oversized sidebar query without reading child threads", async () => {
+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
+ mockListServerChannelsForViewer.mockResolvedValue([])
+ const response = await GET(
+ new NextRequest("http://localhost/api/community/servers/server_1/channels?type=thread&limitPerParent=6"),
+ { params: { id: "server_1" } } as never,
+ )
+ expect(response.status).toBe(400)
+ expect(mockListParticipatingForumThreads).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index 27b29d54e..5a01c33a7 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -1,19 +1,19 @@
import { NextResponse, NextRequest } from "next/server"
import { getDb } from "@/lib/db"
-import { parseNameAndTag, queries } from "@alook/shared"
+import { isForum, parseNameAndTag, queries } from "@alook/shared"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { buildServerChannelGroups } from "@/lib/community/list-channels"
import { requireServerMember } from "@/lib/community/permissions"
/**
- * GET /api/community/servers/[id]/channels — single-server channel list, bot
- * arm of the folded `listChannels` verb (route/disc trunk, 接口树统一 轴3). The
+ * GET /api/community/servers/[id]/channels — single-server channel list. Human
+ * callers receive the visible top-level tree, with one strict participating
+ * forum-thread projection used by the nested sidebar. The bot arm implements
+ * the folded `listChannels` verb (route/disc trunk, 接口树统一 轴3). The
* bot addresses by `?server=<name#discriminator>`; the all-servers mode
* (bot omitting `server`) lives at the servers-collection route `GET
* servers/channels` instead — a cross-server aggregate has no single-`[id]`
- * home. Human web reads the channel tree via the server bootstrap, so this GET
- * is bot-only today; a human actor gets a lean 404 (no human channel-list DTO
- * to project — the human read simply isn't this door).
+ * home.
*
* ①-C existence mask: `resolveServerByNameForMember` is member-scoped, so a
* server the bot isn't in returns zero matches → 404 (indistinguishable from a
@@ -28,8 +28,56 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
if (!serverId) return NextResponse.json({ error: "missing server id" }, { status: 400 })
const auth = await requireServerMember(db, serverId, ctx.actor.userId)
if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status })
- const channels = await queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.actor.userId)
- return NextResponse.json({ channels })
+ const visibleChannels = await queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.actor.userId)
+ const search = req.nextUrl.searchParams
+ const sidebarKeys = ["type", "parentType", "participating", "activeWithin", "limitPerParent", "retainId", "include"]
+ const wantsSidebarThreads = sidebarKeys.some((key) => search.has(key))
+ if (!wantsSidebarThreads) return NextResponse.json({ channels: visibleChannels })
+
+ if (
+ search.get("type") !== "thread" ||
+ search.get("parentType") !== "forum" ||
+ search.get("participating") !== "true" ||
+ search.get("activeWithin") !== "72h" ||
+ search.get("include") !== "parentMessage"
+ ) {
+ return NextResponse.json({ error: "invalid forum sidebar query" }, { status: 400 })
+ }
+ const rawLimit = search.get("limitPerParent")
+ const limitPerParent = rawLimit && /^\d+$/.test(rawLimit) ? Number(rawLimit) : NaN
+ if (!Number.isInteger(limitPerParent) || limitPerParent < 1 || limitPerParent > 5) {
+ return NextResponse.json({ error: "limitPerParent must be between 1 and 5" }, { status: 400 })
+ }
+ const retainId = search.get("retainId")?.trim()
+ if (search.has("retainId") && !retainId) {
+ return NextResponse.json({ error: "retainId is required" }, { status: 400 })
+ }
+
+ const forumIds = visibleChannels.filter((channel) => isForum(channel.type)).map((channel) => channel.id)
+ const serverNow = new Date().toISOString()
+ const windowMs = 72 * 60 * 60 * 1000
+ const activeAfter = new Date(Date.parse(serverNow) - windowMs).toISOString()
+ const rows = await queries.communityThread.listParticipatingForumThreads(db, {
+ parentChannelIds: forumIds,
+ userId: ctx.actor.userId,
+ activeAfter,
+ limitPerParent,
+ ...(retainId ? { retainId } : {}),
+ })
+ const parentMessageIds = rows
+ .map((channel) => channel.parentMessageId)
+ .filter((id): id is string => !!id)
+ const [parentMessages, unreadRows] = await Promise.all([
+ queries.communityMessage.getMessagesByIds(db, parentMessageIds),
+ queries.communityInbox.listUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),
+ ])
+ const unreadIds = new Set(unreadRows.map((row) => row.channelId))
+ const channels = rows.map((channel) => ({
+ ...channel,
+ expiresAt: new Date(Date.parse(channel.activityAt) + windowMs).toISOString(),
+ unread: unreadIds.has(channel.id),
+ }))
+ return NextResponse.json({ channels, included: { parentMessages }, serverNow })
}
const botUserId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
index 7b93ed8af..ec5d45094 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
@@ -41,7 +41,7 @@ describe("GET /api/community/servers/[id]/unreads", () => {
mockListVisibleChannelIds.mockResolvedValue(["channel_1", "channel_2", "other_1"])
mockListUnreadChannels.mockResolvedValue([
{ serverId: "server_1", channelId: "channel_1" },
- { serverId: "server_1", channelId: "channel_2" },
+ { serverId: "server_1", channelId: "channel_2", parentChannelId: "channel_1" },
{ serverId: "server_2", channelId: "other_1" },
])
})
@@ -53,7 +53,11 @@ describe("GET /api/community/servers/[id]/unreads", () => {
)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ channelIds: ["channel_1", "channel_2"], stale: false })
+ expect(await response.json()).toEqual({
+ channelIds: ["channel_1", "channel_2"],
+ childChannels: [{ id: "channel_2", parentChannelId: "channel_1" }],
+ stale: false,
+ })
expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["channel_1", "channel_2", "other_1"])
})
@@ -87,6 +91,6 @@ describe("GET /api/community/servers/[id]/unreads", () => {
)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ channelIds: [], stale: true })
+ expect(await response.json()).toEqual({ channelIds: [], childChannels: [], stale: true })
})
})
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
index 9fbcd8b41..f98be1719 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
@@ -20,12 +20,28 @@ export const GET = withAuth(async (_req, ctx) => {
const { value, stale } = await readOrStale(
async () => {
const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
- const unread = await queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds)
- return { channelIds: unread.filter((row) => row.serverId === serverId).map((row) => row.channelId) }
+ const unread = (await queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds))
+ .filter((row) => row.serverId === serverId)
+ return {
+ channelIds: unread.map((row) => row.channelId),
+ // Preserve the canonical child → parent attribution. The client needs
+ // this even when a participating forum post is outside the sidebar's
+ // 72h / top-five projection, otherwise a cold boot loses its unread
+ // signal entirely. `listUnreadChannels` has already applied access,
+ // archive, and participant filtering, so these are safe candidates;
+ // the client narrows them to parents whose canonical type is `forum`.
+ childChannels: unread.flatMap((row) => row.parentChannelId
+ ? [{ id: row.channelId, parentChannelId: row.parentChannelId }]
+ : []),
+ }
},
- { channelIds: [] as string[] },
+ { channelIds: [] as string[], childChannels: [] as Array<{ id: string; parentChannelId: string }> },
{ route: "community/servers/:id/unreads" },
)
- return NextResponse.json({ channelIds: value.channelIds, stale })
+ return NextResponse.json({
+ channelIds: value.channelIds,
+ childChannels: value.childChannels,
+ stale,
+ })
})
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 12478d67c..885948fe1 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -18,7 +18,7 @@ import { ServerSettings } from "@/components/community/server-settings"
import { ImageCropDialog } from "@/components/community/image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { MobileZone, SettingsSection } from "@/components/community/_types"
-import { canManageServer, notifLevelDisplay, type ChannelType } from "@alook/shared"
+import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"
import { resolveRowPresence } from "@/lib/community/presence"
import {
useCommunityStore,
@@ -34,6 +34,14 @@ import {
} from "@/components/community/eject-server"
import { clearLastChannel } from "@/lib/community/last-channel"
import { usePresence } from "@/hooks/community/use-server-panels"
+import {
+ patchForumSidebarUnread,
+ removeForumSidebarUnreadChild,
+ setForumSidebarParentUnreadBase,
+ useForumSidebarThreads,
+ type ForumSidebarThread,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import {
@@ -97,6 +105,23 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const channelNotif = notifs.channel
const currentChannelId = useCurrentChannelId()
const currentChannelMeta = useCurrentChannelMeta()
+ const activeForumThreadId = useMemo(() => {
+ if (!currentChannelId || !currentChannelMeta?.parentChannelId) return null
+ const parent = currentServer?.categories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id === currentChannelMeta.parentChannelId)
+ return isForum(parent?.type) ? currentChannelId : null
+ }, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer])
+ const forumSidebar = useForumSidebarThreads(serverId, activeForumThreadId)
+ const forumThreadsByParent = useMemo(() => {
+ const grouped: Record<string, ForumSidebarThread[]> = {}
+ for (const thread of forumSidebar.threads) {
+ const siblings = grouped[thread.parentChannelId] ?? []
+ siblings.push(thread)
+ grouped[thread.parentChannelId] = siblings
+ }
+ return grouped
+ }, [forumSidebar.threads])
// Mutations
const createChannelMut = useCreateChannel()
@@ -265,13 +290,32 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
markSwitch("channel", id)
router.push(`/c/channels/${serverId}/${id}`)
channelTree.markRead(id)
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(serverId),
- (cache) => patchChannelUnread(cache, id, false),
+ const hasChildFallback = setForumSidebarParentUnreadBase(
+ queryClient,
+ serverId,
+ id,
+ false,
)
+ if (!hasChildFallback) {
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(serverId),
+ (cache) => patchChannelUnread(cache, id, false),
+ )
+ }
if (bp === "mobile") setMobileZone("messages")
}, [router, serverId, channelTree, bp, queryClient])
+ const setActiveForumThread = useCallback((id: string) => {
+ markSwitch("channel", id)
+ router.push(`/c/channels/${serverId}/${id}`)
+ removeForumSidebarUnreadChild(queryClient, serverId, id)
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(serverId) },
+ (data) => patchForumSidebarUnread(data, id, false),
+ )
+ if (bp === "mobile") setMobileZone("messages")
+ }, [bp, queryClient, router, serverId])
+
const onSidebarOpenSettings = useCallback((section?: SettingsSection) => {
if (section) setSettingsSection(section)
setServerSettingsOpen(true)
@@ -348,6 +392,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
currentUserId: currentUser.id,
loading: !currentServer,
setActiveChannel,
+ forumThreadsByParent,
+ activeThreadId: activeForumThreadId,
+ onSelectForumThread: setActiveForumThread,
onOpenSettings: isAdmin ? onSidebarOpenSettings : undefined,
onBlockedCreate,
mutedChannels,
@@ -367,6 +414,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}), [
channelTree, currentServer, currentChannelMeta?.parentChannelId,
currentChannelId, isAdmin, currentUser.id, setActiveChannel,
+ forumThreadsByParent, activeForumThreadId, setActiveForumThread,
onSidebarOpenSettings, onBlockedCreate, mutedChannels,
onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel,
onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar,
diff --git a/src/web/src/components/community/attachment-layout.ts b/src/web/src/components/community/attachment-layout.ts
new file mode 100644
index 000000000..5bc1dc597
--- /dev/null
+++ b/src/web/src/components/community/attachment-layout.ts
@@ -0,0 +1,6 @@
+export function attachmentAspectRatio(
+ width: number | undefined,
+ height: number | undefined,
+): string {
+ return width && height ? `${width}/${height}` : "auto"
+}
diff --git a/src/web/src/components/community/channel-member-view-model.tsx b/src/web/src/components/community/channel-member-view-model.tsx
index a17b7ffae..176e8b93a 100644
--- a/src/web/src/components/community/channel-member-view-model.tsx
+++ b/src/web/src/components/community/channel-member-view-model.tsx
@@ -136,7 +136,7 @@ export function useChannelMemberViewModel({
const addChannelMemberMut = useAddChannelMember(channelId)
const removeChannelMemberMut = useRemoveChannelMember(channelId)
const addThreadParticipantMut = useAddThreadParticipant(channelId)
- const removeThreadParticipantMut = useRemoveThreadParticipant(channelId)
+ const removeThreadParticipantMut = useRemoveThreadParticipant(channelId, serverId, currentUser.id)
const setMemberRoleMut = useSetMemberRole()
const kickMemberMut = useKickMember()
diff --git a/src/web/src/components/community/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channel-sidebar.crumb.test.ts
index e01df6c83..09e605507 100644
--- a/src/web/src/components/community/channel-sidebar.crumb.test.ts
+++ b/src/web/src/components/community/channel-sidebar.crumb.test.ts
@@ -35,10 +35,77 @@ const render = () =>
}),
)
+const forumTree = {
+ ...emptyTree,
+ catOrder: ["cat_1"],
+ order: {
+ cat_1: [{
+ id: "forum_1",
+ name: "Forum",
+ type: "forum",
+ active: false,
+ unread: false,
+ muted: false,
+ }],
+ },
+ catNames: { cat_1: "Channels" },
+ catPrivate: { cat_1: false },
+ catPending: { cat_1: false },
+} as unknown as ChannelTree
+
+const renderForum = (muted = false) => renderToStaticMarkup(
+ createElement(ChannelSidebar, {
+ tree: forumTree,
+ serverName: "Alpha",
+ activeChannel: "forum_1",
+ setActiveChannel: vi.fn(),
+ mutedChannels: muted ? { forum_1: true } : {},
+ forumThreadsByParent: {
+ forum_1: [
+ {
+ id: "post_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ title: "First post",
+ activityAt: "2026-08-08T00:00:00.000Z",
+ expiresAt: "2026-08-11T00:00:00.000Z",
+ unread: true,
+ },
+ {
+ id: "post_2",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_2",
+ title: "Second post",
+ activityAt: "2026-08-07T00:00:00.000Z",
+ expiresAt: "2026-08-10T00:00:00.000Z",
+ unread: false,
+ },
+ ],
+ },
+ activeThreadId: "post_2",
+ onSelectForumThread: vi.fn(),
+ }),
+)
+
describe("ChannelSidebar header", () => {
it("renders the server name as the sole header identity marker (no duplicate ServerCrumb icon)", () => {
const html = render()
expect(html).toContain("Alpha")
expect(html).not.toContain('aria-label="Alpha"')
})
+
+ it("renders forum children as non-sortable nested rows with one solid 2px connector", () => {
+ const html = renderForum()
+ expect(html).toContain('data-testid="community-forum-sidebar-thread-post_1"')
+ expect(html).toContain('data-testid="community-forum-sidebar-thread-post_2"')
+ expect(html).toContain('aria-current="page"')
+ expect(html).toContain('stroke-width="2"')
+ expect(html).toContain("First post")
+ expect(html).toContain("Second post")
+ expect(html).toContain("bg-primary")
+ })
+
+ it("suppresses the child unread dot when its parent forum is muted", () => {
+ expect(renderForum(true)).not.toContain("bg-primary")
+ })
})
diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsx
index 96c0607d4..c4a508e35 100644
--- a/src/web/src/components/community/channel-sidebar.tsx
+++ b/src/web/src/components/community/channel-sidebar.tsx
@@ -1,6 +1,6 @@
"use client"
-import { memo, useRef, useState } from "react"
+import { Fragment, memo, useRef, useState } from "react"
import { Settings, Users, Link2, Bell, ScrollText, ChevronDown, UserPlus } from "lucide-react"
import {
DndContext, closestCenter, PointerSensor, useSensor, useSensors,
@@ -19,6 +19,8 @@ import { InviteDialog } from "./invite-dialog"
import { ChannelAddMembersDialog } from "./channel-add-members-dialog"
import type { Channel, SettingsSection } from "./_types"
import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
+import { tid } from "@/lib/community/testids"
+import type { ForumSidebarThread } from "@/hooks/community/use-forum-sidebar-threads"
type Dialog =
@@ -40,6 +42,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,
onMoveChannel, onBlockedMove,
serverId, invitePopoverOpen, onInvitePopoverOpenChange,
+ forumThreadsByParent = {}, activeThreadId, onSelectForumThread,
}: {
tree: ChannelTree
serverName: string
@@ -66,6 +69,9 @@ export const ChannelSidebar = memo(function ChannelSidebar({
serverId?: string
invitePopoverOpen?: boolean
onInvitePopoverOpenChange?: (open: boolean) => void
+ forumThreadsByParent?: Record<string, ForumSidebarThread[]>
+ activeThreadId?: string | null
+ onSelectForumThread?: (id: string) => void
}) {
const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, removeChannel, renameChannel, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree
// Category the dragged channel started in — captured at drag start, because
@@ -136,6 +142,49 @@ export const ChannelSidebar = memo(function ChannelSidebar({
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
const [dialog, setDialog] = useState<Dialog>(null)
const withMute = (ch: Channel): Channel => mutedChannels && ch.id in mutedChannels ? { ...ch, muted: mutedChannels[ch.id] } : ch
+ const hasActiveSidebarThread = !!activeThreadId && Object.values(forumThreadsByParent)
+ .some((threads) => threads.some((thread) => thread.id === activeThreadId))
+ const childRows = (parentId: string) => {
+ const threads = forumThreadsByParent[parentId] ?? []
+ if (threads.length === 0) return null
+ const rowHeight = 28
+ const branchY = (index: number) => index * rowHeight + rowHeight / 2
+ const lastY = branchY(threads.length - 1)
+ const connectorPath = [
+ `M 1 0 V ${lastY - 6} Q 1 ${lastY} 7 ${lastY} H 16`,
+ ...threads.slice(0, -1).map((_, index) => `M 1 ${branchY(index)} H 16`),
+ ].join(" ")
+ return (
+ <div className="relative mt-0! ml-5">
+ <svg
+ aria-hidden="true"
+ viewBox={`0 0 16 ${threads.length * rowHeight}`}
+ preserveAspectRatio="none"
+ className="pointer-events-none absolute top-0 left-0 w-4 text-muted-foreground/60"
+ style={{ height: threads.length * rowHeight }}
+ >
+ <path
+ d={connectorPath}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ {threads.map((thread) => (
+ <ForumSidebarThreadRow
+ key={thread.id}
+ thread={thread}
+ active={thread.id === activeThreadId}
+ muted={!!mutedChannels?.[parentId]}
+ onClick={() => onSelectForumThread?.(thread.id)}
+ />
+ ))}
+ </div>
+ )
+ }
// Find the "none" category ID (empty name) — only if one explicitly exists
const noneCatId = Object.keys(catNames).find((id) => catNames[id] === "") ?? ""
@@ -175,15 +224,17 @@ export const ChannelSidebar = memo(function ChannelSidebar({
{order[noneCatId].map((ch) => ch.pending ? (
<PendingChannelRow key={ch.id} ch={ch} />
) : (
- <SortableChannel
- key={ch.id}
- ch={withMute(ch)}
- active={ch.id === activeChannel}
- canReorder={isAdmin}
- onClick={() => setActiveChannel(ch.id)}
- onEdit={isAdmin ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}
- onDelete={isAdmin ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}
- />
+ <Fragment key={ch.id}>
+ <SortableChannel
+ ch={withMute(ch)}
+ active={ch.id === activeChannel && !hasActiveSidebarThread}
+ canReorder={isAdmin}
+ onClick={() => setActiveChannel(ch.id)}
+ onEdit={isAdmin ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}
+ onDelete={isAdmin ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}
+ />
+ {childRows(ch.id)}
+ </Fragment>
))}
</div>
</SortableContext>
@@ -213,16 +264,18 @@ export const ChannelSidebar = memo(function ChannelSidebar({
// Public-category channels are admin-managed only.
const canManageChannel = isAdmin || (!!catPrivate[id] && ch.creatorId === currentUserId)
return (
- <SortableChannel
- key={ch.id}
- ch={withMute(ch)}
- active={ch.id === activeChannel}
- canReorder={isAdmin}
- onClick={() => setActiveChannel(ch.id)}
- onEdit={canManageChannel ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}
- onDelete={canManageChannel ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}
- onManageMembers={(catPrivate[id] && canManageChannel) ? () => setDialog({ kind: "manage-members", channelId: ch.id, channelName: ch.name }) : undefined}
- />
+ <Fragment key={ch.id}>
+ <SortableChannel
+ ch={withMute(ch)}
+ active={ch.id === activeChannel && !hasActiveSidebarThread}
+ canReorder={isAdmin}
+ onClick={() => setActiveChannel(ch.id)}
+ onEdit={canManageChannel ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}
+ onDelete={canManageChannel ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}
+ onManageMembers={(catPrivate[id] && canManageChannel) ? () => setDialog({ kind: "manage-members", channelId: ch.id, channelName: ch.name }) : undefined}
+ />
+ {childRows(ch.id)}
+ </Fragment>
)
})}
</div>
@@ -339,6 +392,48 @@ export const ChannelSidebar = memo(function ChannelSidebar({
)
})
+function ForumSidebarThreadRow({
+ thread,
+ active,
+ muted,
+ onClick,
+}: {
+ thread: ForumSidebarThread
+ active: boolean
+ muted: boolean
+ onClick: () => void
+}) {
+ return (
+ <div className="relative h-7">
+ <button
+ type="button"
+ data-testid={tid.forumSidebarThread(thread.id)}
+ aria-current={active ? "page" : undefined}
+ onClick={onClick}
+ onContextMenu={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ className={[
+ "ml-4 flex h-7 w-[calc(100%-1rem)] min-w-0 items-center rounded-md px-2 text-left text-xs",
+ active
+ ? "bg-sidebar-accent text-foreground"
+ : muted
+ ? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
+ : thread.unread
+ ? "font-semibold text-foreground hover:bg-sidebar-accent/60"
+ : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
+ ].join(" ")}
+ >
+ <span className="truncate">{thread.title}</span>
+ {!muted && thread.unread && !active ? (
+ <span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />
+ ) : null}
+ </button>
+ </div>
+ )
+}
+
// Loading placeholder for the channel sidebar. Kept colocated so changes to
// row density or header height stay in sync with the live sidebar above.
function ChannelSidebarSkeleton({ noHeader }: { noHeader?: boolean }) {
diff --git a/src/web/src/components/community/entity-icon.test.ts b/src/web/src/components/community/entity-icon.test.ts
index 25ce312ef..48f7a0bce 100644
--- a/src/web/src/components/community/entity-icon.test.ts
+++ b/src/web/src/components/community/entity-icon.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest"
-import { ListChevronsUpDown, MessagesSquare } from "lucide-react"
+import { Hash, ListChevronsUpDown } from "lucide-react"
import { getEntityIcon } from "./entity-icon"
import { ChannelIcon } from "./channel-icon"
@@ -13,7 +13,7 @@ describe("getEntityIcon", () => {
expect(getEntityIcon("forum")).toBe(ListChevronsUpDown)
})
- it("thread → MessagesSquare", () => {
- expect(getEntityIcon("thread")).toBe(MessagesSquare)
+ it("thread → Hash", () => {
+ expect(getEntityIcon("thread")).toBe(Hash)
})
})
diff --git a/src/web/src/components/community/entity-icon.tsx b/src/web/src/components/community/entity-icon.tsx
index df9ce58f2..9c9c14dbb 100644
--- a/src/web/src/components/community/entity-icon.tsx
+++ b/src/web/src/components/community/entity-icon.tsx
@@ -1,4 +1,4 @@
-import { ListChevronsUpDown, MessagesSquare } from "lucide-react"
+import { Hash, ListChevronsUpDown } from "lucide-react"
import { ChannelIcon } from "./channel-icon"
/**
@@ -23,7 +23,7 @@ export function getEntityIcon(kind: EntityKind | undefined): IconComponent {
case "forum":
return ListChevronsUpDown
case "thread":
- return MessagesSquare
+ return Hash
default:
return ChannelIcon
}
@@ -36,7 +36,7 @@ export function getEntityIcon(kind: EntityKind | undefined): IconComponent {
*
* text | undefined → ChannelIcon (the custom slash glyph)
* forum → ListChevronsUpDown
- * thread → MessagesSquare
+ * thread → Hash
*
* Accepts `className` only — matching `ChannelIcon` — so both `size-*` and
* `text-*` call sites keep working.
@@ -46,7 +46,7 @@ export function EntityIcon({ kind, className }: { kind: EntityKind | undefined;
case "forum":
return <ListChevronsUpDown className={className} />
case "thread":
- return <MessagesSquare className={className} />
+ return <Hash className={className} />
default:
return <ChannelIcon className={className} />
}
diff --git a/src/web/src/components/community/forum-channel-surface.test.ts b/src/web/src/components/community/forum-channel-surface.test.ts
index 0cfd812c0..c34e286f4 100644
--- a/src/web/src/components/community/forum-channel-surface.test.ts
+++ b/src/web/src/components/community/forum-channel-surface.test.ts
@@ -150,6 +150,7 @@ describe("ForumChannelSurface ownership", () => {
}, expect.any(Object))
expect(mocks.deleteForumThread).toHaveBeenCalledWith({
forumChannelId: "forum_1",
+ serverId: "srv_1",
threadId: "post_1",
}, expect.any(Object))
expect(renderer!.root.findByProps({ "data-manage-dialog": true })).toBeTruthy()
diff --git a/src/web/src/components/community/forum-channel-surface.tsx b/src/web/src/components/community/forum-channel-surface.tsx
index 882ce4cd6..2b75bf6c9 100644
--- a/src/web/src/components/community/forum-channel-surface.tsx
+++ b/src/web/src/components/community/forum-channel-surface.tsx
@@ -130,7 +130,7 @@ export function ForumChannelSurface({
deletingPost={deleteForumThreadMut.isPending ? deleteForumThreadMut.variables?.threadId ?? null : null}
onDeletePost={(post) => {
deleteForumThreadMut.mutate(
- { forumChannelId: channelId, threadId: post.id },
+ { serverId, forumChannelId: channelId, threadId: post.id },
{ onError: (error) => toastApiError(error, "Failed to delete post") },
)
}}
diff --git a/src/web/src/components/community/forum-view.scroll.test.ts b/src/web/src/components/community/forum-view.scroll.test.ts
index 29c67495a..a1e1f04b1 100644
--- a/src/web/src/components/community/forum-view.scroll.test.ts
+++ b/src/web/src/components/community/forum-view.scroll.test.ts
@@ -5,6 +5,7 @@ import type { ForumThread } from "./_types"
const scrollToIndex = vi.fn()
let requestOlder: (() => void) | undefined
+let sentinelEdge: string | undefined
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
options: { scrollMargin: 0 },
@@ -15,8 +16,9 @@ vi.mock("@tanstack/react-virtual", () => ({
}),
}))
vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({
- useVirtualCursorSentinel: ({ onLoad }: { onLoad?: () => void }) => {
+ useVirtualCursorSentinel: ({ onLoad, edge }: { onLoad?: () => void; edge: string }) => {
requestOlder = onLoad
+ sentinelEdge = edge
return () => {}
},
}))
@@ -54,35 +56,39 @@ describe("ForumView scroll anchoring", () => {
vi.resetModules()
scrollToIndex.mockReset()
requestOlder = undefined
+ sentinelEdge = undefined
root.scrollHeight = 300
root.scrollTop = 20
ForumView = (await import("./forum-view")).ForumView
})
- it("aligns the newest post to the end on first load and again after a tag switch", async () => {
+ it("aligns the newest post to the top on first load and again after a tag switch", async () => {
let view: ReactTestRenderer
await act(async () => {
view = create(createElement(ForumView, props([post("p1"), post("p2")])), {
createNodeMock: (element) => element.props.role === "main" ? root : {},
})
})
- expect(scrollToIndex).toHaveBeenLastCalledWith(1, { align: "end" })
+ expect(scrollToIndex).toHaveBeenLastCalledWith(0, { align: "start" })
scrollToIndex.mockClear()
await act(async () => { view!.update(createElement(ForumView, props([post("p3")], "bug"))) })
- expect(scrollToIndex).toHaveBeenCalledWith(0, { align: "end" })
+ expect(scrollToIndex).toHaveBeenCalledWith(0, { align: "start" })
})
- it("preserves the visible rows by applying the scroll-height delta after older posts prepend", async () => {
+ it("loads older activity pages from the bottom sentinel without scroll-height compensation", async () => {
+ const onLoadMore = vi.fn()
let view: ReactTestRenderer
await act(async () => {
- view = create(createElement(ForumView, props([post("p2"), post("p3")])), {
+ view = create(createElement(ForumView, { ...props([post("p3"), post("p2")]), onLoadMore }), {
createNodeMock: (element) => element.props.role === "main" ? root : {},
})
})
act(() => requestOlder?.())
- await act(async () => { view!.update(createElement(ForumView, props([post("p2"), post("p3")], "All", true))) })
+ expect(sentinelEdge).toBe("end")
+ expect(onLoadMore).toHaveBeenCalledTimes(1)
+ await act(async () => { view!.update(createElement(ForumView, { ...props([post("p3"), post("p2")], "All", true), onLoadMore })) })
root.scrollHeight = 500
- await act(async () => { view!.update(createElement(ForumView, props([post("p1"), post("p2"), post("p3")]))) })
- expect(root.scrollTop).toBe(220)
+ await act(async () => { view!.update(createElement(ForumView, { ...props([post("p3"), post("p2"), post("p1")]), onLoadMore })) })
+ expect(root.scrollTop).toBe(20)
})
})
diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsx
index 4e04f03eb..ca25bb11c 100644
--- a/src/web/src/components/community/forum-view.tsx
+++ b/src/web/src/components/community/forum-view.tsx
@@ -71,8 +71,6 @@ export function ForumView({
const newPostTriggerRef = useRef<HTMLButtonElement>(null)
const scrollRef = useRef<HTMLDivElement>(null)
const alignedTagRef = useRef<string | null>(null)
- const prependSnapshotRef = useRef<{ height: number; top: number } | null>(null)
- const wasLoadingMoreRef = useRef(loadingMore)
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
@@ -89,30 +87,14 @@ export function ForumView({
useLayoutEffect(() => {
if (posts.length === 0 || alignedTagRef.current === tag) return
alignedTagRef.current = tag
- virtualizer.scrollToIndex(posts.length - 1, { align: "end" })
+ virtualizer.scrollToIndex(0, { align: "start" })
}, [posts.length, tag, virtualizer])
- useLayoutEffect(() => {
- const wasLoading = wasLoadingMoreRef.current
- wasLoadingMoreRef.current = loadingMore
- const snapshot = prependSnapshotRef.current
- const root = scrollRef.current
- if (!wasLoading || loadingMore || !snapshot || !root) return
- root.scrollTop = snapshot.top + (root.scrollHeight - snapshot.height)
- prependSnapshotRef.current = null
- }, [loadingMore, posts.length])
- const loadOlder = () => {
- const root = scrollRef.current
- if (root && !prependSnapshotRef.current) {
- prependSnapshotRef.current = { height: root.scrollHeight, top: root.scrollTop }
- }
- onLoadMore?.()
- }
const olderSentinelRef = useVirtualCursorSentinel({
scrollRef,
hasMore,
isFetching: loadingMore,
- onLoad: loadOlder,
- edge: "start",
+ onLoad: onLoadMore,
+ edge: "end",
})
const closeCompose = () => {
@@ -172,7 +154,6 @@ export function ForumView({
<EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." />
) : (
<>
- <div ref={olderSentinelRef} className="h-px" aria-hidden />
<VirtualRows
items={posts}
virtualizer={virtualizer}
@@ -246,6 +227,7 @@ export function ForumView({
)
}}
/>
+ <div ref={olderSentinelRef} className="h-px" aria-hidden />
</>
)}
</div>
diff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsx
index 7664e2ee3..c4efe6636 100644
--- a/src/web/src/components/community/message-channel-controller.tsx
+++ b/src/web/src/components/community/message-channel-controller.tsx
@@ -54,6 +54,7 @@ export function MessageChannelController({
serverId,
serverParam,
channelName,
+ forumParentChannelId,
viewer,
anchorMessageId,
feed,
@@ -67,6 +68,7 @@ export function MessageChannelController({
serverId: string
serverParam: string
channelName: string
+ forumParentChannelId?: string
viewer: Viewer
anchorMessageId: string | null
feed: MessageFeed
@@ -275,6 +277,7 @@ export function MessageChannelController({
await sendMessageAsync({
serverId,
channelId,
+ forumParentChannelId,
content: payload.message.content ?? "",
replyToId: payload.message.replyTo?.id,
mentionType: payload.mentionType,
@@ -290,7 +293,7 @@ export function MessageChannelController({
return
}
},
- [messageScope, uploadFileAsync, channelId, sendMessageAsync, serverId, viewer.id, viewer.name, viewer.avatar],
+ [messageScope, uploadFileAsync, channelId, forumParentChannelId, sendMessageAsync, serverId, viewer.id, viewer.name, viewer.avatar],
)
const messageActions = useMemo(() => ({
diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/components/community/message-list-items.ts
index 4c2fd6fa1..f3d3f9921 100644
--- a/src/web/src/components/community/message-list-items.ts
+++ b/src/web/src/components/community/message-list-items.ts
@@ -104,11 +104,9 @@ const MESSAGE_BASE_ESTIMATE_PX = 24
const CHARS_PER_LINE_ESTIMATE = 55
const LINE_HEIGHT_ESTIMATE_PX = 20
const MAX_TEXT_ESTIMATE_PX = 400
-// Attachment images render inside a max-width box (see message.tsx's
-// `max-w-[320px]`) — an aspect-ratio estimate is clamped against that width
-// so a very tall/narrow image doesn't produce an absurd height guess.
-const ATTACHMENT_MAX_WIDTH_PX = 320
const ATTACHMENT_FALLBACK_ESTIMATE_PX = 200
+const ATTACHMENT_MAX_HEIGHT_ESTIMATE_PX = 300
+const ATTACHMENT_TYPICAL_WIDTH_ESTIMATE_PX = 320
const EMBED_ESTIMATE_PX = 120
const REACTIONS_ESTIMATE_PX = 32
const THREAD_PREVIEW_ESTIMATE_PX = 36
@@ -125,11 +123,12 @@ function estimateAttachmentsHeight(m: Msg): number {
let total = 0
for (const a of m.attachments) {
if (a.kind !== "image") continue
- if (a.width && a.height) {
- total += Math.round((ATTACHMENT_MAX_WIDTH_PX * a.height) / a.width)
- } else {
- total += ATTACHMENT_FALLBACK_ESTIMATE_PX
- }
+ total += a.width && a.height
+ ? Math.min(
+ ATTACHMENT_MAX_HEIGHT_ESTIMATE_PX,
+ Math.round((ATTACHMENT_TYPICAL_WIDTH_ESTIMATE_PX * a.height) / a.width),
+ )
+ : ATTACHMENT_FALLBACK_ESTIMATE_PX
}
return total
}
diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.ts
index f9041415c..d138acb48 100644
--- a/src/web/src/components/community/message.render.test.ts
+++ b/src/web/src/components/community/message.render.test.ts
@@ -122,6 +122,38 @@ describe("Message memo comparator", () => {
})
})
+describe("Message image attachment layout", () => {
+ it("keeps a known portrait image intrinsic and constrains it by message width + max height", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ makeTree({
+ m: baseMsg({
+ attachments: [{
+ kind: "image",
+ name: "portrait.png",
+ url: "/portrait.png",
+ width: 396,
+ height: 702,
+ }],
+ }),
+ onOpenThread: vi.fn(),
+ }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+
+ const image = renderer!.root.findByType("img")
+ expect(image.props).toMatchObject({ width: 396, height: 702 })
+ expect(image.props.className).toContain("h-auto")
+ expect(image.props.className).toContain("w-auto")
+ expect(image.props.className).toContain("max-h-75")
+ expect(image.props.className).toContain("max-w-full")
+ expect(image.parent?.props.className).toContain("w-fit")
+ expect(image.parent?.props.className).toContain("max-w-full")
+ })
+})
+
describe("Message lazy overlays", () => {
it("does not mount the ContextMenu root until the row is activated", () => {
const onOpenThread = vi.fn()
diff --git a/src/web/src/components/community/message.test.ts b/src/web/src/components/community/message.test.ts
index 20bc24de0..1498744d4 100644
--- a/src/web/src/components/community/message.test.ts
+++ b/src/web/src/components/community/message.test.ts
@@ -1,24 +1,24 @@
import { describe, it, expect } from "vitest"
-import { attachmentAspectRatio } from "./message"
+import { attachmentAspectRatio } from "./attachment-layout"
// Reserves the correct CSS aspect-ratio box for an image attachment before
// it decodes, mirroring the pattern the embed-image `<img>` already uses.
-// Falls back to a neutral "4/3" when a dimension is missing — pre-feature
+// Falls back to intrinsic sizing when a dimension is missing — pre-feature
// attachment rows (sent before width/height were tracked) have neither.
describe("attachmentAspectRatio", () => {
it("returns 'width/height' when both dimensions are present", () => {
expect(attachmentAspectRatio(1920, 1080)).toBe("1920/1080")
})
- it("falls back to '4/3' when width is missing", () => {
- expect(attachmentAspectRatio(undefined, 1080)).toBe("4/3")
+ it("falls back to 'auto' when width is missing", () => {
+ expect(attachmentAspectRatio(undefined, 1080)).toBe("auto")
})
- it("falls back to '4/3' when height is missing", () => {
- expect(attachmentAspectRatio(1920, undefined)).toBe("4/3")
+ it("falls back to 'auto' when height is missing", () => {
+ expect(attachmentAspectRatio(1920, undefined)).toBe("auto")
})
- it("falls back to '4/3' when both dimensions are missing", () => {
- expect(attachmentAspectRatio(undefined, undefined)).toBe("4/3")
+ it("falls back to 'auto' when both dimensions are missing", () => {
+ expect(attachmentAspectRatio(undefined, undefined)).toBe("auto")
})
})
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index 6fc22e15e..b5041fb51 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -22,16 +22,7 @@ import { avatarInitial } from "@/lib/community/avatar"
import { displayName } from "@/lib/community/display-name"
import { stripInlineMarkup } from "@alook/shared"
import type { RenderMsg, OpenProfile } from "./_types"
-
-// Fallback ratio for an attachment image with no known dimensions
-// (pre-feature rows sent before width/height were tracked). A more neutral
-// default than the embed-image branch's "40/21" wide-banner ratio — plain
-// attachments are typically screenshots/photos, not link-preview banners.
-const ATTACHMENT_FALLBACK_ASPECT_RATIO = "4/3"
-
-export function attachmentAspectRatio(width: number | undefined, height: number | undefined): string {
- return width && height ? `${width}/${height}` : ATTACHMENT_FALLBACK_ASPECT_RATIO
-}
+import { attachmentAspectRatio } from "./attachment-layout"
// Whether the "Share as Image" action is offered for a message. Share is
// computed inside `Message` from the message alone (no handler is threaded in),
@@ -256,16 +247,25 @@ function MessageImpl({
{m.attachments && (
<div className="mt-2 flex flex-col gap-2 pb-2">
- {m.attachments.map((a, i) =>
- a.kind === "image" ? (
+ {m.attachments.map((a, i) => {
+ if (a.kind === "image") return (
<button
key={i}
onClick={() => onPreviewImage?.(a.url)}
- className="block w-fit max-w-[320px] overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
+ className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} width={a.width} height={a.height} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} onLoad={onImageLoad} />
+ <img
+ src={a.url}
+ alt={a.name}
+ width={a.width}
+ height={a.height}
+ className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"
+ style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}
+ onLoad={onImageLoad}
+ />
</button>
- ) : (
+ )
+ return (
<button
key={i}
onClick={() => onDownloadFile?.(a.url)}
@@ -278,8 +278,8 @@ function MessageImpl({
</div>
<Download className="size-4 shrink-0 text-muted-foreground" />
</button>
- ),
- )}
+ )
+ })}
</div>
)}
diff --git a/src/web/src/components/community/thread-channel-surface.test.ts b/src/web/src/components/community/thread-channel-surface.test.ts
index 1a34cdd9c..ce99ad889 100644
--- a/src/web/src/components/community/thread-channel-surface.test.ts
+++ b/src/web/src/components/community/thread-channel-surface.test.ts
@@ -346,6 +346,7 @@ describe("ThreadChannelSurface ownership", () => {
messageId: "opener_1",
content: "Renamed post",
forumChannelId: "parent_1",
+ forumThreadId: "thread_1",
})
act(() => {
diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/thread-channel-surface.tsx
index fd016fe58..c709ce968 100644
--- a/src/web/src/components/community/thread-channel-surface.tsx
+++ b/src/web/src/components/community/thread-channel-surface.tsx
@@ -116,6 +116,7 @@ export function ThreadChannelSurface({
messageId: parentMessageId,
content: name,
forumChannelId: parentChannelId,
+ forumThreadId: channelId,
})
} catch (error) {
toastApiError(error, "Failed to edit post")
@@ -172,6 +173,7 @@ export function ThreadChannelSurface({
serverId={serverId}
serverParam={serverParam}
channelName={displayName}
+ forumParentChannelId={parentIsForum ? parentChannelId ?? undefined : undefined}
viewer={viewer}
anchorMessageId={anchorMessageId}
feed={feed}
diff --git a/src/web/src/components/community/thread-opener.test.ts b/src/web/src/components/community/thread-opener.test.ts
new file mode 100644
index 000000000..3e1c0e0de
--- /dev/null
+++ b/src/web/src/components/community/thread-opener.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+
+const useMessageMock = vi.fn()
+vi.mock("@/hooks/community/use-message", () => ({
+ useMessage: (...args: unknown[]) => useMessageMock(...args),
+}))
+
+import { ThreadOpener } from "./thread-opener"
+
+const genericMock = {
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
+}
+
+describe("ThreadOpener image attachment layout", () => {
+ it("keeps a known portrait image intrinsic and constrains it by message width + max height", () => {
+ useMessageMock.mockReturnValue({
+ isLoading: false,
+ isError: false,
+ message: {
+ id: "opener_1",
+ type: "chat",
+ authorId: "user_1",
+ authorName: "Alice",
+ content: "Portrait",
+ createdAt: "2026-08-08T00:00:00.000Z",
+ attachments: [{
+ kind: "image",
+ name: "portrait.png",
+ url: "/portrait.png",
+ width: 396,
+ height: 702,
+ }],
+ },
+ })
+
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(ThreadOpener, { parentMessageId: "opener_1" }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+
+ const image = renderer!.root.findByType("img")
+ expect(image.props).toMatchObject({ width: 396, height: 702 })
+ expect(image.props.className).toContain("h-auto")
+ expect(image.props.className).toContain("w-auto")
+ expect(image.props.className).toContain("max-h-75")
+ expect(image.props.className).toContain("max-w-full")
+ expect(image.parent?.props.className).toContain("w-fit")
+ expect(image.parent?.props.className).toContain("max-w-full")
+ })
+})
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index 5ca46ae14..0ed5dbab2 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -3,7 +3,7 @@
import { MessagesSquare, FileText, Download, ArrowUpRight } from "lucide-react"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
-import { attachmentAspectRatio } from "./message"
+import { attachmentAspectRatio } from "./attachment-layout"
import { formatMessageTime } from "./format-time"
import { Skeleton } from "@/components/ui/skeleton"
import { NumberTicker } from "@/components/ui/number-ticker"
@@ -105,16 +105,24 @@ export function ThreadOpener({
{msg.attachments && msg.attachments.length > 0 && (
<div className="mt-2 flex flex-col gap-2 pb-2">
- {msg.attachments.map((a, i) =>
- a.kind === "image" ? (
+ {msg.attachments.map((a, i) => {
+ if (a.kind === "image") return (
<button
key={i}
onClick={() => onPreviewImage?.(a.url)}
- className="block w-fit max-w-[320px] overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
+ className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
>
- <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />
+ <img
+ src={a.url}
+ alt={a.name}
+ width={a.width}
+ height={a.height}
+ className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"
+ style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}
+ />
</button>
- ) : (
+ )
+ return (
<button
key={i}
onClick={() => onDownloadFile?.(a.url)}
@@ -129,8 +137,8 @@ export function ThreadOpener({
</div>
<Download className="size-4 shrink-0 text-muted-foreground" />
</button>
- ),
- )}
+ )
+ })}
</div>
)}
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index 339a4c9ca..0bfe7d333 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -126,11 +126,13 @@ describe("useCreateForumThread", () => {
const { useCreateForumThread } = await load()
useCreateForumThread()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
+ capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), { pages: [], pageParams: [] })
apiFetchMock.mockResolvedValueOnce({ threadId: "p_new" })
await runMutation({ nonce: "command_1", channelId: "forum_1", name: "n", content: "c" })
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(true)
})
})
@@ -140,7 +142,11 @@ describe("useUpdatePostTags", () => {
useUpdatePostTags()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
const bugKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as const
+ const activityAllKey = communityKeys.forumActivityFeed("forum_1", null)
+ const activityBugKey = communityKeys.forumActivityFeed("forum_1", "bug")
capturedQc.setQueryData(bugKey, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(activityAllKey, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(activityBugKey, { pages: [], pageParams: [] })
capturedQc.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug", "p0"] })
apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "p0"] })
@@ -157,6 +163,8 @@ describe("useUpdatePostTags", () => {
})
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(bugKey)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(activityAllKey)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(activityBugKey)?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(true)
})
@@ -166,6 +174,7 @@ describe("useUpdatePostTags", () => {
const feedBefore = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }
const tagsBefore = { tags: ["bug"] }
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), feedBefore)
+ capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), feedBefore)
capturedQc.setQueryData(communityKeys.forumTags("forum_1"), tagsBefore)
apiFetchMock.mockRejectedValueOnce(new Error("500"))
@@ -179,6 +188,7 @@ describe("useUpdatePostTags", () => {
expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(feedBefore)
expect(capturedQc.getQueryData(communityKeys.forumTags("forum_1"))).toEqual(tagsBefore)
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(false)
+ expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(false)
expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(false)
})
})
@@ -189,12 +199,21 @@ describe("useDeleteForumThread", () => {
useDeleteForumThread()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
+ capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), { pages: [], pageParams: [] })
+ const sidebarKey = communityKeys.forumSidebarThreadsView("server_1", "p2")
+ capturedQc.setQueryData(sidebarKey, {
+ channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: [{ id: "p2", parentChannelId: "forum_1" }],
+ })
apiFetchMock.mockResolvedValueOnce(undefined)
- await runMutation({ forumChannelId: "forum_1", threadId: "p2" })
+ await runMutation({ serverId: "server_1", forumChannelId: "forum_1", threadId: "p2" })
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/p2", { method: "DELETE" })
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryData<{ threads: unknown[] }>(sidebarKey)?.threads).toEqual([])
})
it("leaves the cache untouched when the DELETE fails", async () => {
@@ -203,10 +222,12 @@ describe("useDeleteForumThread", () => {
const before = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), before)
+ capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), before)
apiFetchMock.mockRejectedValueOnce(new Error("500"))
- await runMutationExpectError({ forumChannelId: "forum_1", threadId: "p2" })
+ await runMutationExpectError({ serverId: "server_1", forumChannelId: "forum_1", threadId: "p2" })
expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(before)
+ expect(capturedQc.getQueryData(communityKeys.forumActivityFeed("forum_1", null))).toEqual(before)
})
})
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 49f10233d..f6b83c5a1 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -5,6 +5,11 @@ import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"
import type { MentionType } from "@alook/shared"
+import {
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
export type CreateForumThreadArgs = {
nonce: string
@@ -45,6 +50,7 @@ export function useCreateForumThread() {
onSuccess: (data, args) => {
void data
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.channelId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.channelId) })
},
})
}
@@ -81,12 +87,14 @@ export function useUpdatePostTags() {
// This is required when the edited
// post loses the currently-selected tag and must leave that result set.
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.forumChannelId) })
void queryClient.invalidateQueries({ queryKey: communityKeys.forumTags(args.forumChannelId) })
},
})
}
export type DeleteForumThreadArgs = {
+ serverId: string
// The parent forum channel — the cache key the post list lives under.
forumChannelId: string
// The post channel being deleted.
@@ -107,6 +115,12 @@ export function useDeleteForumThread() {
},
onSuccess: (_data, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.forumChannelId) })
+ removeForumSidebarUnreadChild(queryClient, args.serverId, args.threadId)
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(args.serverId) },
+ (data) => removeForumSidebarThread(data, args.threadId),
+ )
},
})
}
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index fd8eced37..932898967 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -119,6 +119,24 @@ function postedMessage(id: string, seq: number) {
}
}
+function sidebarData(threadId = "post_1") {
+ return {
+ channels: [],
+ included: { parentMessages: [] },
+ serverNow: "2026-08-07T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: [{
+ id: threadId,
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ title: "Old title",
+ activityAt: "2026-08-06T00:00:00.000Z",
+ expiresAt: "2026-08-09T00:00:00.000Z",
+ unread: false,
+ }],
+ }
+}
+
beforeEach(() => {
apiFetchMock.mockReset()
toastMock.mockReset()
@@ -182,6 +200,26 @@ describe("useEditMessage", () => {
expect(capturedQc.getQueryState(root)?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(bug)?.isInvalidated).toBe(true)
})
+
+ it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
+ const sidebarKey = communityKeys.forumSidebarThreadsView("s1", "post_1")
+ capturedQc.setQueryData(sidebarKey, sidebarData())
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await loadMod()
+ mod.useEditMessage()
+
+ await runMutation({
+ serverId: "s1",
+ channelId: "forum_1",
+ messageId: "opener_1",
+ content: "New title",
+ forumChannelId: "forum_1",
+ forumThreadId: "post_1",
+ })
+
+ expect(capturedQc.getQueryData<ReturnType<typeof sidebarData>>(sidebarKey)?.threads[0].title)
+ .toBe("New title")
+ })
})
// ── useSendMessage ────────────────────────────────────────────────────────
@@ -223,6 +261,47 @@ describe("useSendMessage — happy path", () => {
}),
)
})
+
+ it("re-ranks a loaded participating forum thread from the canonical send timestamp", async () => {
+ const sidebarKey = communityKeys.forumSidebarThreadsView("s1", "post_1")
+ capturedQc.setQueryData(sidebarKey, sidebarData())
+ apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ const mod = await loadMod()
+ mod.useSendMessage()
+
+ await runMutation({
+ serverId: "s1",
+ channelId: "post_1",
+ forumParentChannelId: "forum_1",
+ content: "hi",
+ author: { id: "u_me", name: "me", avatar: "M" },
+ })
+
+ expect(capturedQc.getQueryData<ReturnType<typeof sidebarData>>(sidebarKey)?.threads[0])
+ .toMatchObject({
+ activityAt: "2026-08-07T10:00:00.000Z",
+ expiresAt: "2026-08-10T10:00:00.000Z",
+ })
+ })
+
+ it("invalidates the sidebar collection when a just-enrolled thread is not loaded", async () => {
+ const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
+ const empty = { ...sidebarData(), threads: [] }
+ capturedQc.setQueryData(sidebarKey, empty)
+ apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ const mod = await loadMod()
+ mod.useSendMessage()
+
+ await runMutation({
+ serverId: "s1",
+ channelId: "post_new",
+ forumParentChannelId: "forum_1",
+ content: "hi",
+ author: { id: "u_me", name: "me", avatar: "M" },
+ })
+
+ expect(capturedQc.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
+ })
})
describe("useSendMessage — rollback", () => {
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index dfb322f93..37617348e 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -27,6 +27,12 @@ import type { Msg, Attachment } from "@/components/community/_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
import type { PinsResponse } from "@/hooks/community/use-channel-panels"
import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"
+import {
+ hasForumSidebarThread,
+ patchForumSidebarActivity,
+ patchForumSidebarTitle,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
import { isBlocked, type MentionType } from "@alook/shared"
/**
@@ -70,6 +76,7 @@ type EditMessageArgs = {
messageId: string
content: string
forumChannelId?: string
+ forumThreadId?: string
}
type EditMessageContext = {
@@ -125,6 +132,12 @@ export function useEditMessage() {
},
onSuccess: (_data, variables) => {
if (variables.forumChannelId) void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(variables.forumChannelId) })
+ if (variables.forumThreadId) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(variables.serverId) },
+ (data) => patchForumSidebarTitle(data, variables.forumThreadId!, variables.content),
+ )
+ }
},
})
}
@@ -177,6 +190,7 @@ export function sendNonce(): string {
export type SendMessageArgs = {
serverId: string
channelId: string
+ forumParentChannelId?: string
content: string
replyToId?: string
replyTo?: Msg["replyTo"]
@@ -205,6 +219,7 @@ export type SendMessageResult = { message: PostedMessage; deduped?: boolean }
* `/channels/:id/messages`.
*/
export function useSendMessage() {
+ const queryClient = useQueryClient()
return useMutation<
SendMessageResult,
Error,
@@ -251,6 +266,24 @@ export function useSendMessage() {
}
},
onSuccess: (data, args) => {
+ if (args.forumParentChannelId) {
+ const key = communityKeys.forumSidebarThreads(args.serverId)
+ const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
+ const loaded = cached.some(([, value]) => hasForumSidebarThread(value, args.channelId))
+ if (loaded) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: key },
+ (value) => patchForumSidebarActivity(
+ value,
+ args.channelId,
+ args.forumParentChannelId!,
+ data.message.createdAt,
+ ),
+ )
+ } else {
+ void queryClient.invalidateQueries({ queryKey: key })
+ }
+ }
if (!args.nonce) return
useMessageStreamStore.getState().dispatch(
{ kind: "channel", id: args.channelId, serverId: args.serverId },
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 77279b444..5f0b74160 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -31,6 +31,13 @@ import type {
} from "@alook/shared"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
+import type { ServerDetail } from "./use-servers"
+import {
+ patchForumSidebarUnread,
+ reconcileForumSidebarUnreadFallbacks,
+ type ForumSidebarQueryData,
+ type ForumSidebarUnreadFallbackState,
+} from "./use-forum-sidebar-threads"
// ── React shim ───────────────────────────────────────────────────────────
let refs: Map<string, { current: unknown }> = new Map()
@@ -168,7 +175,69 @@ function unreadBump(
return { type: "community:unread.bump" as const, userId, channelId, ...extra }
}
+function forumSidebarFixture(ids = ["post_1"]) {
+ return {
+ channels: ids.map((id) => ({
+ id,
+ name: `fallback-${id}`,
+ parentChannelId: "forum_1",
+ parentMessageId: `opener-${id}`,
+ activityAt: "2026-08-01T00:00:00.000Z",
+ expiresAt: "2026-08-04T00:00:00.000Z",
+ unread: false,
+ })),
+ included: { parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })) },
+ serverNow: "2026-08-01T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: ids.map((id) => ({
+ id,
+ parentChannelId: "forum_1",
+ parentMessageId: `opener-${id}`,
+ title: `title-${id}`,
+ activityAt: "2026-08-01T00:00:00.000Z",
+ expiresAt: "2026-08-04T00:00:00.000Z",
+ unread: false,
+ })),
+ }
+}
+
describe("useCommunityWs — message.create", () => {
+ it("patches a loaded forum-sidebar child activity without a refetch", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture())
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event = {
+ ...messageCreate("post_1"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate
+
+ capturedOnMessage!(event)
+
+ const data = capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
+ expect(data?.threads[0]).toMatchObject({
+ id: "post_1",
+ activityAt: "2026-07-03T00:00:00.000Z",
+ expiresAt: "2026-07-06T00:00:00.000Z",
+ })
+ expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: communityKeys.forumSidebarThreads("srv_1") })
+ })
+
+ it("invalidates the forum-sidebar collection when the active child is not loaded", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
+
+ capturedOnMessage!({
+ ...messageCreate("post_missing"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+
it("writes the channel overlay and leaves the base cache untouched when focused", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
@@ -534,6 +603,91 @@ describe("useCommunityWs — message.create patches channel unread in the open s
expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })
})
+ it("routes a child unread.bump to its loaded forum-sidebar row instead of the parent forum", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
+
+ capturedOnMessage!(unreadBump("post_1", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].unread)
+ .toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ communityKeys.server("srv_open"),
+ )?.categories[0].channels[0].unread).toBe(false)
+ expect(capturedQueryClient.getQueryData<ServerDetail>(
+ communityKeys.server("srv_open"),
+ )?.forumUnreadState?.forum_1?.childIds).toEqual(["post_1"])
+ })
+
+ it("falls back to the parent forum dot when the child has no locatable sidebar row", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarThreadsView("srv_open", null),
+ forumSidebarFixture([]),
+ )
+
+ capturedOnMessage!(unreadBump("post_missing", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ communityKeys.server("srv_open"),
+ )?.categories[0].channels[0].unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("srv_open"),
+ )).toEqual({
+ forum_1: { baseUnread: false, childIds: ["post_missing"] },
+ })
+ })
+
+ it("moves message.create → unread.bump fallback ownership to the refetched child", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const serverKey = communityKeys.server("srv_open")
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
+ capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1"))
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture([]))
+
+ capturedOnMessage!({
+ ...messageCreate("post_new"),
+ serverId: "srv_open",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+ expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
+
+ capturedOnMessage!(unreadBump("post_new", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(true)
+
+ const refetched = forumSidebarFixture(["post_new"])
+ refetched.threads[0]!.unread = true
+ capturedQueryClient.setQueryData(sidebarKey, refetched)
+ reconcileForumSidebarUnreadFallbacks(capturedQueryClient, "srv_open", ["post_new"])
+
+ expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(false)
+
+ capturedQueryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
+ patchForumSidebarUnread(data, "post_new", false),
+ )
+ expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(false)
+ })
+
it("message.create alone does NOT flip the sidebar unread (mute-gated bump is the only trigger now)", async () => {
// Regression pin: mute ≠ blindness. The message.create still arrives (and
// content syncs), but the unread dot is flipped ONLY by the server's
@@ -987,6 +1141,29 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
),
).toBe(true)
})
+
+ it("adds/removes the viewer's participating child in the forum sidebar", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture())
+
+ capturedOnMessage!({
+ type: "community:channel.member_remove",
+ serverId: "srv_1",
+ channelId: "post_1",
+ userId: "u_me",
+ })
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+
+ capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
+ capturedOnMessage!({
+ type: "community:channel.member_add",
+ serverId: "srv_1",
+ channelId: "post_2",
+ userId: "u_me",
+ })
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
})
describe("useCommunityWs — friend + mention → invalidate", () => {
@@ -1337,6 +1514,8 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
})
capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })
capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["ch_dead"]))
const event: CommunityChannelDelete = {
type: "community:channel.delete",
@@ -1348,6 +1527,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads).toEqual([])
})
})
@@ -1473,6 +1653,28 @@ describe("useCommunityWs — child_create patches parent thread badge with count
expect(cache?.pages[0].messages[0].thread?.messageCount).toBe(5)
})
+ it("child_update removes archived sidebar rows and invalidates on reopen", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("s1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture(["ch_thread"]))
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "ch_thread",
+ changes: { archived: true },
+ } satisfies CommunityChildChannelUpdate)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "ch_thread",
+ changes: { archived: false },
+ } satisfies CommunityChildChannelUpdate)
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+
it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
@@ -1762,6 +1964,8 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
const forumPage = { pages: [{ messages: [{ id: "opener_1", content: "old title" }] }], pageParams: [null] }
capturedQueryClient.setQueryData(allKey, forumPage)
capturedQueryClient.setQueryData(bugKey, forumPage)
+ const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
capturedOnMessage!(opener)
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })
expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(true)
@@ -1769,6 +1973,8 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("new title")
expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("new title")
expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener_1"))?.content).toBe("new title")
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].title)
+ .toBe("new title")
invalidateSpy.mockClear()
capturedOnMessage!({
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 160b62981..b0ad3c3ad 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -58,6 +58,17 @@ import type { CanonicalMessage } from "@/lib/community/message-stream"
import type { MachinesResponse } from "@/hooks/community/use-machines"
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
+import {
+ hasForumSidebarThread,
+ patchForumSidebarActivity,
+ patchForumSidebarTitle,
+ patchForumSidebarUnread,
+ recordForumSidebarChildUnread,
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ setForumSidebarParentUnreadBase,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
/**
* Community WebSocket handler.
@@ -420,6 +431,29 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// regular channel (`ch:`) so the pill clears in the right bucket.
clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)
+ // Participation, not unread state, is the sidebar truth. A child
+ // message reaches every notify member even when muted; use its
+ // explicit server/parent metadata to re-rank a loaded row without a
+ // GET, or refetch when the active post is currently absent/expired.
+ if (event.serverId && event.parentChannelId) {
+ const key = communityKeys.forumSidebarThreads(event.serverId)
+ const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
+ const loaded = cached.some(([, data]) => hasForumSidebarThread(data, event.channelId))
+ if (loaded) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: key },
+ (data) => patchForumSidebarActivity(
+ data,
+ event.channelId,
+ event.parentChannelId!,
+ event.message.createdAt,
+ ),
+ )
+ } else {
+ void queryClient.invalidateQueries({ queryKey: key })
+ }
+ }
+
// 1) A child channel enrolls its sender and mentioned users in its
// member set server-side, so refresh an open child roster live.
if (
@@ -469,27 +503,62 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// defensively).
case "community:unread.bump": {
const viewerId = viewerUserIdRef.current
- // The sidebar row to light: a child-thread message has no
- // independent tree row, so its dot lights the PARENT channel
- // (`railChannelId`); a plain channel is its own row. Fall back to
- // `channelId` for older frames that predate `railChannelId`.
+ // `railChannelId` is the always-locatable fallback. A participating
+ // forum child now has its own nested row, so prefer that row when it
+ // is loaded; ordinary/expired children continue to light the parent.
const railChannelId = event.railChannelId ?? event.channelId
+ const targetServerId =
+ event.serverId ?? useCommunityStore.getState().currentServerId
+ const sidebarKey = targetServerId
+ ? communityKeys.forumSidebarThreads(targetServerId)
+ : null
+ const hasChildSidebarRow = !!sidebarKey && event.channelId !== railChannelId &&
+ queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: sidebarKey })
+ .some(([, data]) => hasForumSidebarThread(data, event.channelId))
+ const sidebarChannelId = hasChildSidebarRow ? event.channelId : railChannelId
// Suppress the dot for the channel the viewer is actually looking at
// (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 && railChannelId !== sub.channelId) {
+ if (event.userId === viewerId && sidebarChannelId !== sub.channelId) {
// 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
// bumps never lit. Absent serverId (DM bump / older frame) → fall
// back to the currently-open server (backward-compatible).
- const targetServerId =
- event.serverId ?? useCommunityStore.getState().currentServerId
- if (targetServerId) {
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(targetServerId),
- (cache) => patchChannelUnread(cache, railChannelId, true),
+ if (hasChildSidebarRow && sidebarKey) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => patchForumSidebarUnread(data, event.channelId, true),
+ )
+ recordForumSidebarChildUnread(
+ queryClient,
+ targetServerId!,
+ railChannelId,
+ event.channelId,
+ true,
)
+ } else if (targetServerId) {
+ if (event.channelId !== railChannelId) {
+ recordForumSidebarChildUnread(
+ queryClient,
+ targetServerId,
+ railChannelId,
+ event.channelId,
+ )
+ } else {
+ const hasChildFallback = setForumSidebarParentUnreadBase(
+ queryClient,
+ targetServerId,
+ railChannelId,
+ true,
+ )
+ if (!hasChildFallback) {
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(targetServerId),
+ (cache) => patchChannelUnread(cache, railChannelId, true),
+ )
+ }
+ }
}
// Rail mention badge: the rail row carries only a `mentions` count
// (no separate unread dot — plain unread lives on the tree dot
@@ -682,6 +751,29 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// child_update — sync counts/name on the parent message's thread
// indicator if the update carries them.
const changes = event.changes
+ const sidebarServerId = useCommunityStore.getState().currentServerId
+ if (sidebarServerId) {
+ const sidebarKey = communityKeys.forumSidebarThreads(sidebarServerId)
+ if (changes.archived === true) {
+ removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
+ } else if (changes.archived === false) {
+ void queryClient.invalidateQueries({ queryKey: sidebarKey })
+ } else if (changes.lastMessageAt) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => patchForumSidebarActivity(
+ data,
+ event.channelId,
+ event.parentChannelId,
+ changes.lastMessageAt!,
+ ),
+ )
+ }
+ }
if (changes.messageCount !== undefined || changes.name !== undefined) {
queryClient.setQueriesData<PageCache>(
{ queryKey: communityKeys.channelMessages(event.parentChannelId) },
@@ -819,6 +911,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// subsequent same-id revive (rare, but the server can reuse ids)
// would surface stale rows.
if (event.type === "community:channel.delete") {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
useMessageStreamStore.getState().removeScope({
kind: "channel",
id: event.channelId,
@@ -833,6 +926,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
queryClient.removeQueries({
queryKey: communityKeys.threads(event.channelId),
})
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
// When a child thread is deleted, refresh the
// PARENT's list so the deleted card disappears from the feed on
// every client. Absent on older events / top-level channels.
@@ -871,6 +968,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
event.type === "community:channel.member_remove" &&
event.userId === viewerUserIdRef.current
) {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
useMessageStreamStore.getState().removeScope({
kind: "channel",
id: event.channelId,
@@ -879,6 +977,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })
queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })
queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
+ } else if (
+ event.type === "community:channel.member_add" &&
+ event.userId === viewerUserIdRef.current
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.forumSidebarThreads(event.serverId),
+ })
}
void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
// Refetch the channel roster so an open private-channel Members drawer
@@ -1062,6 +1171,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
void queryClient.invalidateQueries({
queryKey: communityKeys.channelMessages(event.parentChannelId),
})
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(serverId) },
+ (data) => patchForumSidebarTitle(data, event.channelId, event.content),
+ )
+ }
}
return
}
diff --git a/src/web/src/hooks/community/use-eager-channel-read.test.ts b/src/web/src/hooks/community/use-eager-channel-read.test.ts
index 91e444aa9..90c333dc5 100644
--- a/src/web/src/hooks/community/use-eager-channel-read.test.ts
+++ b/src/web/src/hooks/community/use-eager-channel-read.test.ts
@@ -50,8 +50,15 @@ vi.mock("@/lib/api/client", () => ({
let serversCache: ServersResponse | undefined
const invalidateQueries = vi.fn()
const getQueryData = vi.fn((_key: unknown) => serversCache)
+const setQueryData = vi.fn()
+const setQueriesData = vi.fn()
vi.mock("@tanstack/react-query", () => ({
- useQueryClient: () => ({ invalidateQueries, getQueryData }),
+ useQueryClient: () => ({
+ invalidateQueries,
+ getQueryData,
+ setQueryData,
+ setQueriesData,
+ }),
}))
function resetHarness() {
@@ -62,6 +69,8 @@ function resetHarness() {
apiFetchMock.mockClear()
invalidateQueries.mockClear()
getQueryData.mockClear()
+ setQueryData.mockClear()
+ setQueriesData.mockClear()
}
async function loadHook() {
diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.ts
index 6c1395b61..ab8b87a02 100644
--- a/src/web/src/hooks/community/use-eager-channel-read.ts
+++ b/src/web/src/hooks/community/use-eager-channel-read.ts
@@ -5,6 +5,12 @@ import { useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { ServersResponse } from "@/hooks/community/use-servers"
+import {
+ patchForumSidebarUnread,
+ removeForumSidebarUnreadChild,
+ setForumSidebarParentUnreadBase,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
/**
* Eager "mark this channel/thread read on open."
@@ -63,6 +69,20 @@ export function useEagerChannelRead({
// Always refresh the inbox feeds — the mass mark-read cleared them.
void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
+ // Keep the local canonical attribution in step with the successful
+ // read even on a direct/deep-link mount (where no sidebar click ran).
+ // Otherwise a loaded child that later expires from the projection
+ // could incorrectly re-light its parent from stale local ownership.
+ if (serverId && isChildChannel) {
+ removeForumSidebarUnreadChild(queryClient, serverId, channelId)
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(serverId) },
+ (data) => patchForumSidebarUnread(data, channelId, false),
+ )
+ } else if (serverId) {
+ setForumSidebarParentUnreadBase(queryClient, serverId, channelId, false)
+ }
+
// The rail mention badge (`server.mentions`) only needs refreshing when
// this server actually carries mentions the PUT may have cleared. Read
// it from the `servers()` cache and gate on it: the common case (no
diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.ts
new file mode 100644
index 000000000..c0880eb23
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-feed.test.ts
@@ -0,0 +1,119 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+import {
+ forumActivityPageQueryFn,
+ mapForumActivityPages,
+ type ForumActivityPage,
+} from "./use-forum-feed"
+
+const emptyIncluded = {
+ parentMessages: [],
+ firstMessages: [],
+ tags: [],
+ participants: [],
+}
+
+describe("forumActivityPageQueryFn", () => {
+ beforeEach(() => apiFetchMock.mockReset())
+
+ it("requests the canonical activity collection with includes, tag, and cursor", async () => {
+ apiFetchMock.mockResolvedValue({ threads: [], included: emptyIncluded, hasMore: false })
+ await forumActivityPageQueryFn("forum_one", "bug")({ pageParam: "opaque cursor" })
+
+ const url = apiFetchMock.mock.calls[0]![0] as string
+ expect(url).toContain("/api/community/channels/forum_one/threads?")
+ const params = new URL(url, "http://localhost").searchParams
+ expect(params.get("order")).toBe("activity")
+ expect(params.get("include")).toBe("parentMessage,firstMessage,tags,participants")
+ expect(params.get("tag")).toBe("bug")
+ expect(params.get("cursor")).toBe("opaque cursor")
+ })
+})
+
+describe("mapForumActivityPages", () => {
+ it("joins included resources, deduplicates pages, and keeps latest activity first", () => {
+ const pages: ForumActivityPage[] = [
+ {
+ threads: [
+ {
+ id: "t2",
+ name: "fallback two",
+ creatorId: "creator_2",
+ messageCount: 2,
+ parentMessageId: "m2",
+ lastMessageAt: "2026-08-08T02:00:00.000Z",
+ createdAt: "2026-08-08T00:00:00.000Z",
+ activityAt: "2026-08-08T02:00:00.000Z",
+ },
+ {
+ id: "t1",
+ name: "fallback one",
+ creatorId: "creator_1",
+ messageCount: 1,
+ parentMessageId: "m1",
+ lastMessageAt: null,
+ createdAt: "2026-08-08T01:00:00.000Z",
+ activityAt: "2026-08-08T01:00:00.000Z",
+ },
+ ],
+ included: {
+ parentMessages: [
+ { id: "m2", channelId: "forum_1", content: "Opener title", authorId: "u2", authorName: "Alice", authorImage: null },
+ ],
+ firstMessages: [{ channelId: "t2", content: "First reply preview" }],
+ tags: [{ messageId: "m2", tag: "bug" }, { messageId: "m2", tag: "help" }],
+ participants: [
+ { channelId: "t2", userId: "u2", userName: "Alice", userImage: null, participantCount: 7 },
+ { channelId: "t2", userId: "u3", userName: "Bob", userImage: "bob.png", participantCount: 7 },
+ ],
+ },
+ hasMore: true,
+ nextCursor: "next",
+ },
+ {
+ threads: [
+ {
+ id: "t2",
+ name: "duplicate",
+ creatorId: "duplicate",
+ messageCount: 99,
+ parentMessageId: "m2",
+ lastMessageAt: null,
+ createdAt: "2026-08-07T00:00:00.000Z",
+ activityAt: "2026-08-07T00:00:00.000Z",
+ },
+ ],
+ included: emptyIncluded,
+ hasMore: false,
+ },
+ ]
+
+ const result = mapForumActivityPages(pages)
+ expect(result.map((thread) => thread.id)).toEqual(["t2", "t1"])
+ expect(result[0]).toMatchObject({
+ name: "Opener title",
+ authorId: "u2",
+ authorAvatar: "A",
+ preview: "First reply preview",
+ parent: { authorName: "Alice", text: "First reply preview" },
+ tags: ["bug", "help"],
+ participantCount: 7,
+ participants: [
+ { id: "u2", name: "Alice", avatar: "A" },
+ { id: "u3", name: "Bob", avatar: "bob.png" },
+ ],
+ })
+ expect(result[1]).toMatchObject({
+ name: "fallback one",
+ authorId: "creator_1",
+ preview: "",
+ tags: [],
+ participantCount: 0,
+ })
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 03c0f9786..afa7f5e08 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -1,12 +1,125 @@
"use client"
import { useCallback, useEffect, useMemo, useState } from "react"
+import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"
+import { DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
+import type { ForumThread } from "@/components/community/_types"
import { useForumTags } from "./use-channel-panels"
-import { useMessages } from "./use-messages"
-export function useForumFeed(serverId: string, channelId: string) {
+type ActivityThread = {
+ id: string
+ name: string | null
+ creatorId: string | null
+ messageCount: number | null
+ parentMessageId: string | null
+ lastMessageAt: string | null
+ createdAt: string
+ activityAt: string
+}
+
+type IncludedMessage = {
+ id: string
+ channelId: string
+ content: string
+ authorId: string
+ authorName: string
+ authorImage: string | null
+}
+
+type IncludedFirstMessage = { channelId: string; content: string }
+type IncludedTag = { messageId: string; tag: string }
+type IncludedParticipant = {
+ channelId: string
+ userId: string
+ userName: string | null
+ userImage: string | null
+ participantCount?: number
+}
+
+export type ForumActivityPage = {
+ threads: ActivityThread[]
+ included: {
+ parentMessages: IncludedMessage[]
+ firstMessages: IncludedFirstMessage[]
+ tags: IncludedTag[]
+ participants: IncludedParticipant[]
+ }
+ hasMore: boolean
+ nextCursor?: string
+}
+
+export function forumActivityPageQueryFn(channelId: string, tag: string | null) {
+ return ({ pageParam }: { pageParam: string | null }) => {
+ const params = new URLSearchParams({
+ order: "activity",
+ limit: String(DEFAULT_MESSAGE_PAGE_SIZE),
+ include: "parentMessage,firstMessage,tags,participants",
+ })
+ if (tag) params.set("tag", tag)
+ if (pageParam) params.set("cursor", pageParam)
+ return apiFetch<ForumActivityPage>(
+ `/api/community/channels/${channelId}/threads?${params.toString()}`,
+ )
+ }
+}
+
+export function mapForumActivityPages(pages: ForumActivityPage[]): ForumThread[] {
+ const byId = new Map<string, ForumThread>()
+ for (const page of pages) {
+ const openerById = new Map(page.included.parentMessages.map((message) => [message.id, message]))
+ const firstByChannel = new Map(page.included.firstMessages.map((message) => [message.channelId, message]))
+ const tagsByMessage = new Map<string, string[]>()
+ for (const row of page.included.tags) {
+ tagsByMessage.set(row.messageId, [...(tagsByMessage.get(row.messageId) ?? []), row.tag])
+ }
+ const participantsByChannel = new Map<string, ForumThread["participants"]>()
+ const participantCountByChannel = new Map<string, number>()
+ for (const row of page.included.participants) {
+ participantsByChannel.set(row.channelId, [
+ ...(participantsByChannel.get(row.channelId) ?? []),
+ {
+ id: row.userId,
+ name: row.userName ?? "",
+ avatar: row.userImage ?? avatarInitial(row.userName ?? ""),
+ },
+ ])
+ participantCountByChannel.set(row.channelId, Number(row.participantCount ?? 0))
+ }
+
+ for (const thread of page.threads) {
+ if (byId.has(thread.id)) continue
+ const opener = thread.parentMessageId ? openerById.get(thread.parentMessageId) : undefined
+ const first = firstByChannel.get(thread.id)
+ byId.set(thread.id, {
+ id: thread.id,
+ name: opener?.content.trim() || thread.name?.trim() || "Post",
+ messageCount: thread.messageCount ?? 0,
+ lastMessageAt: thread.activityAt,
+ parent: {
+ authorName: opener?.authorName ?? "",
+ text: (first?.content ?? "").slice(0, 100),
+ },
+ authorId: opener?.authorId ?? thread.creatorId ?? "",
+ authorAvatar: opener?.authorImage ?? avatarInitial(opener?.authorName ?? ""),
+ openerMessageId: thread.parentMessageId ?? "",
+ tags: thread.parentMessageId ? tagsByMessage.get(thread.parentMessageId) ?? [] : [],
+ preview: (first?.content ?? "").slice(0, 100),
+ participants: participantsByChannel.get(thread.id) ?? [],
+ participantCount: participantCountByChannel.get(thread.id) ?? 0,
+ })
+ }
+ }
+ return [...byId.values()].sort((a, b) => {
+ const activity = b.lastMessageAt.localeCompare(a.lastMessageAt)
+ return activity || b.id.localeCompare(a.id)
+ })
+}
+
+export function useForumFeed(_serverId: string, channelId: string) {
const [tag, setTag] = useState(() => {
if (typeof window === "undefined") return "All"
try { return readForumTagSelection(window.localStorage, channelId) }
@@ -23,30 +136,33 @@ export function useForumFeed(serverId: string, channelId: string) {
setTag(next)
try { writeForumTagSelection(window.localStorage, channelId, next) } catch { }
}, [channelId])
- const feed = useMessages(channelId, {
- serverId,
- lastReadMessageId: null,
- anchorMessageId: null,
- tag: tag === "All" ? null : tag,
+ const selectedTag = tag === "All" ? null : tag
+ const queryKey = communityKeys.forumActivityFeed(channelId, selectedTag)
+ const query = useInfiniteQuery<
+ ForumActivityPage,
+ Error,
+ InfiniteData<ForumActivityPage, string | null>,
+ typeof queryKey,
+ string | null
+ >({
+ queryKey,
+ queryFn: forumActivityPageQueryFn(channelId, selectedTag),
+ initialPageParam: null,
+ getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
})
- const posts = useMemo(() => feed.messages.flatMap((message) => {
- const thread = message.thread
- if (!thread) return []
- return [{
- id: thread.id,
- name: message.content ?? thread.name,
- messageCount: thread.messageCount,
- lastMessageAt: thread.lastReplyAt ?? message.createdAt ?? "",
- parent: { authorName: message.authorName ?? "", text: thread.preview ?? "" },
- authorId: message.authorId ?? "",
- authorAvatar: message.authorAvatar ?? avatarInitial(message.authorName ?? ""),
- openerMessageId: message.id,
- tags: thread.tags ?? [],
- preview: thread.preview ?? "",
- participants: thread.participants ?? [],
- participantCount: thread.participantCount ?? 0,
- }]
- }), [feed.messages])
-
- return { ...feed, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [] }
+ const posts = useMemo(
+ () => mapForumActivityPages(query.data?.pages ?? []),
+ [query.data?.pages],
+ )
+
+ return {
+ ...query,
+ posts,
+ tag,
+ selectTag,
+ availableTags: tagsQuery.data?.tags ?? [],
+ hasMoreOlder: query.hasNextPage,
+ isFetchingOlder: query.isFetchingNextPage,
+ fetchOlder: () => { void query.fetchNextPage() },
+ }
}
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
new file mode 100644
index 000000000..fb538b3db
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
@@ -0,0 +1,422 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ patchForumSidebarActivity,
+ patchForumSidebarUnread,
+ projectForumSidebarThreads,
+ reconcileForumSidebarUnreadFallbacks,
+ recordForumSidebarChildUnread,
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ setForumSidebarParentUnreadBase,
+ type ForumSidebarQueryData,
+ type ForumSidebarUnreadFallbackState,
+ type SidebarThreadEnvelope,
+ useForumSidebarThreads,
+} from "./use-forum-sidebar-threads"
+import type { ServerDetail } from "./use-servers"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+const envelope = (ids: string[]): SidebarThreadEnvelope => ({
+ channels: ids.map((id, index) => ({
+ id,
+ name: `fallback-${id}`,
+ parentChannelId: "forum-1",
+ parentMessageId: `opener-${id}`,
+ activityAt: `2026-08-08T0${index}:00:00.000Z`,
+ expiresAt: `2026-08-11T0${index}:00:00.000Z`,
+ unread: index === 0,
+ })),
+ included: {
+ parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })),
+ },
+ serverNow: "2026-08-08T00:00:00.000Z",
+})
+
+function Capture({ retainId, onRender }: {
+ retainId: string | null
+ onRender: (ids: string[]) => void
+}) {
+ const result = useForumSidebarThreads("server-1", retainId)
+ onRender(result.threads.map((thread) => thread.id))
+ return null
+}
+
+async function waitFor(predicate: () => boolean) {
+ for (let i = 0; i < 40 && !predicate(); i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+function serverDetail(parentUnread: boolean): ServerDetail {
+ return {
+ id: "server-1",
+ name: "Server",
+ description: "",
+ icon: null,
+ ownerId: "owner-1",
+ categories: [{
+ id: "category-1",
+ name: "Channels",
+ private: 0,
+ channels: [{
+ id: "forum-1",
+ name: "Forum",
+ type: "forum",
+ active: false,
+ unread: parentUnread,
+ muted: false,
+ }],
+ }],
+ }
+}
+
+function parentUnread(queryClient: QueryClient): boolean {
+ return !!queryClient.getQueryData<ServerDetail>(communityKeys.server("server-1"))
+ ?.categories[0]?.channels[0]?.unread
+}
+
+describe("useForumSidebarThreads", () => {
+ it("preserves a genuine parent unread when a child fallback becomes locatable", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(true))
+ recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
+
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+
+ expect(parentUnread(queryClient)).toBe(true)
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )).toEqual({})
+ })
+
+ it("preserves a parent unread that arrives while a child fallback is pending", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
+ recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
+ expect(setForumSidebarParentUnreadBase(queryClient, "server-1", "forum-1", true)).toBe(true)
+
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+
+ expect(parentUnread(queryClient)).toBe(true)
+ })
+
+ it("keeps the parent fallback while another unread child is still unlisted", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
+ recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
+ recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-2")
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )?.["forum-1"]?.childIds).toEqual(["post-1", "post-2"])
+
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+ expect(parentUnread(queryClient)).toBe(true)
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )?.["forum-1"]?.childIds).toEqual(["post-2"])
+
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1", "post-2"])
+ expect(parentUnread(queryClient)).toBe(false)
+ })
+
+ it("transfers a loaded unread child back to its parent when top-five/expiry hides it", async () => {
+ apiFetchMock
+ .mockResolvedValueOnce(envelope(["post-1"]))
+ .mockResolvedValueOnce(envelope([]))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(true),
+ forumUnreadState: {
+ "forum-1": { baseUnread: false, childIds: ["post-1"] },
+ },
+ })
+
+ let renderer: TestRenderer.ReactTestRenderer
+ const renders: string[][] = []
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: null,
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ })
+ await waitFor(() => renders.at(-1)?.[0] === "post-1")
+ await waitFor(() => Object.keys(
+ queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ ) ?? {},
+ ).length === 0)
+
+ expect(parentUnread(queryClient)).toBe(false)
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: communityKeys.forumSidebarThreads("server-1"),
+ })
+ })
+ await waitFor(() => renders.at(-1)?.length === 0)
+ await waitFor(() => parentUnread(queryClient))
+
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )).toEqual({
+ "forum-1": { baseUnread: false, childIds: ["post-1"] },
+ })
+ renderer!.unmount()
+ })
+
+ it("does not create a fallback after an explicit leave/delete/archive removal", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(false),
+ forumUnreadState: {
+ "forum-1": { baseUnread: false, childIds: ["post-1"] },
+ },
+ })
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+
+ removeForumSidebarUnreadChild(queryClient, "server-1", "post-1")
+ reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", [])
+
+ expect(parentUnread(queryClient)).toBe(false)
+ expect(queryClient.getQueryData<ServerDetail>(
+ communityKeys.server("server-1"),
+ )?.forumUnreadState?.["forum-1"]?.childIds).toEqual([])
+ })
+
+ it("clears a hidden fallback when a canonical refetch removes access or participation", async () => {
+ apiFetchMock.mockResolvedValue(envelope([]))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(true),
+ forumUnreadState: {
+ "forum-1": { baseUnread: false, childIds: ["post-inaccessible"] },
+ },
+ })
+
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )?.["forum-1"]?.childIds[0] === "post-inaccessible")
+
+ await act(async () => {
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(false),
+ forumUnreadState: {
+ "forum-1": { baseUnread: false, childIds: [] },
+ },
+ })
+ })
+ await waitFor(() => Object.keys(
+ queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ ) ?? {},
+ ).length === 0)
+
+ expect(parentUnread(queryClient)).toBe(false)
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )).toEqual({})
+ renderer!.unmount()
+ })
+
+ it("migrates a missing-child fallback dot to the child after the sidebar refetch", async () => {
+ apiFetchMock.mockResolvedValue(envelope(["post-missing"]))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const sidebarKey = communityKeys.forumSidebarThreadsView("server-1", null)
+ queryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, {
+ ...envelope([]),
+ threads: [],
+ serverClockOffsetMs: 0,
+ })
+ queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
+
+ // message.create invalidates the missing row; unread.bump temporarily owns
+ // the parent fallback while that refetch is outstanding.
+ await queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads("server-1") })
+ recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-missing")
+ expect(parentUnread(queryClient)).toBe(true)
+
+ let renderer: TestRenderer.ReactTestRenderer
+ const renders: string[][] = []
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: null,
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ })
+ await waitFor(() => renders.at(-1)?.[0] === "post-missing")
+ await waitFor(() => !parentUnread(queryClient))
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
+ expect(parentUnread(queryClient)).toBe(false)
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )).toEqual({})
+
+ queryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
+ patchForumSidebarUnread(data, "post-missing", false),
+ )
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
+ expect(parentUnread(queryClient)).toBe(false)
+ renderer!.unmount()
+ })
+
+ it("expires live activity 72h after the event instead of reusing the old serverNow", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-08-08T00:00:00.000Z"))
+ apiFetchMock.mockResolvedValue(envelope(["thread-1"]))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries")
+ let renderer: TestRenderer.ReactTestRenderer
+ const renders: string[][] = []
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: null,
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(renders.at(-1)).toEqual(["thread-1"])
+ invalidateSpy.mockClear()
+
+ act(() => vi.advanceTimersByTime(10 * 60 * 60 * 1000))
+ const key = communityKeys.forumSidebarThreadsView("server-1", null)
+ await act(async () => {
+ queryClient.setQueryData<ForumSidebarQueryData>(key, (data) =>
+ patchForumSidebarActivity(
+ data,
+ "thread-1",
+ "forum-1",
+ "2026-08-08T10:00:00.000Z",
+ ),
+ )
+ await vi.advanceTimersByTimeAsync(0)
+ })
+
+ act(() => vi.advanceTimersByTime((72 * 60 * 60 * 1000) + 24))
+ expect(invalidateSpy).not.toHaveBeenCalled()
+ act(() => vi.advanceTimersByTime(1))
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: communityKeys.forumSidebarThreads("server-1"),
+ })
+ renderer!.unmount()
+ })
+
+ it("keeps the cached list painted while a retainId-specific view is loading", async () => {
+ let resolveRetained: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock
+ .mockResolvedValueOnce(envelope(["thread-1"]))
+ .mockImplementationOnce(() => new Promise((resolve) => {
+ resolveRetained = resolve
+ }))
+
+ const renders: string[][] = []
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: null,
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ })
+ await waitFor(() => renders.at(-1)?.[0] === "thread-1")
+ const switchRenderStart = renders.length
+
+ await act(async () => {
+ renderer!.update(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: "thread-2",
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ })
+
+ expect(renders.slice(switchRenderStart)).not.toContainEqual([])
+ expect(renders.at(-1)).toEqual(["thread-1"])
+ expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=thread-2")
+
+ await act(async () => {
+ resolveRetained?.(envelope(["thread-2"]))
+ })
+ await waitFor(() => renders.at(-1)?.[0] === "thread-2")
+ expect(renders.at(-1)).toEqual(["thread-2"])
+ expect(renders.slice(switchRenderStart)).not.toContainEqual([])
+ renderer!.unmount()
+ })
+
+ it("projects opener titles and patches activity/removal without mutating the source", () => {
+ const source = envelope(["thread-1", "thread-2"])
+ const threads = projectForumSidebarThreads(source)
+ const data = { ...source, threads, serverClockOffsetMs: 0 }
+
+ expect(threads.map((thread) => thread.title)).toEqual(["title-thread-1", "title-thread-2"])
+ const patched = patchForumSidebarActivity(
+ data,
+ "thread-1",
+ "forum-1",
+ "2026-08-09T00:00:00.000Z",
+ )
+ expect(patched?.threads[0]?.id).toBe("thread-1")
+ expect(patched?.threads[0]?.expiresAt).toBe("2026-08-12T00:00:00.000Z")
+ expect(data.threads[0]?.activityAt).toBe("2026-08-08T00:00:00.000Z")
+ expect(removeForumSidebarThread(patched, "thread-1")?.threads.map((thread) => thread.id))
+ .toEqual(["thread-2"])
+ expect(patchForumSidebarUnread(data, "thread-1", false)?.threads[0]?.unread).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
new file mode 100644
index 000000000..54aff3a13
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -0,0 +1,369 @@
+"use client"
+
+import { useEffect } from "react"
+import { keepPreviousData, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
+import type { ServerDetail } from "@/hooks/community/use-servers"
+
+export type ForumSidebarThread = {
+ id: string
+ parentChannelId: string
+ parentMessageId: string
+ title: string
+ activityAt: string
+ expiresAt: string
+ unread: boolean
+}
+
+export type SidebarThreadEnvelope = {
+ channels: Array<{
+ id: string
+ name: string
+ parentChannelId: string | null
+ parentMessageId: string | null
+ activityAt: string
+ expiresAt: string
+ unread: boolean
+ }>
+ included: {
+ parentMessages: Array<{ id: string; content: string }>
+ }
+ serverNow: string
+}
+
+export type ForumSidebarQueryData = SidebarThreadEnvelope & {
+ threads: ForumSidebarThread[]
+ /** Server clock minus client clock, captured when this envelope arrived. */
+ serverClockOffsetMs: number
+}
+
+export type ForumSidebarUnreadFallbackState = Record<string, {
+ baseUnread: boolean
+ childIds: string[]
+}>
+
+const SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000
+
+function parentUnread(cache: ServerDetail | undefined, parentChannelId: string): boolean {
+ return !!cache?.categories.some((category) =>
+ category.channels.some((channel) => channel.id === parentChannelId && channel.unread),
+ )
+}
+
+/** Record canonical child unread ownership and project it to the loaded row or parent fallback. */
+export function recordForumSidebarChildUnread(
+ queryClient: QueryClient,
+ serverId: string,
+ parentChannelId: string,
+ childChannelId: string,
+ loaded = false,
+) {
+ const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
+ const serverKey = communityKeys.server(serverId)
+ const cachedServer = queryClient.getQueryData<ServerDetail>(serverKey)
+ const canonicalBaseUnread = cachedServer?.forumUnreadState?.[parentChannelId]?.baseUnread
+ ?? parentUnread(cachedServer, parentChannelId)
+ queryClient.setQueryData<ServerDetail | undefined>(serverKey, (cache) => {
+ if (!cache) return cache
+ const current = cache.forumUnreadState?.[parentChannelId]
+ const baseUnread = current?.baseUnread ?? canonicalBaseUnread
+ const childIds = current?.childIds.includes(childChannelId)
+ ? current.childIds
+ : [...(current?.childIds ?? []), childChannelId]
+ const next = {
+ ...cache,
+ forumUnreadState: {
+ ...cache.forumUnreadState,
+ [parentChannelId]: { baseUnread, childIds },
+ },
+ }
+ const hidden = (queryClient.getQueryData<ForumSidebarUnreadFallbackState>(key)
+ ?.[parentChannelId]?.childIds ?? [])
+ .filter((id) => !loaded || id !== childChannelId)
+ return patchChannelUnread(
+ next,
+ parentChannelId,
+ baseUnread || !loaded || hidden.length > 0,
+ )
+ })
+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, (state = {}) => {
+ const current = state[parentChannelId]
+ const baseUnread = current?.baseUnread ?? canonicalBaseUnread
+ const childIds = loaded
+ ? (current?.childIds ?? []).filter((id) => id !== childChannelId)
+ : current?.childIds.includes(childChannelId)
+ ? current.childIds
+ : [...(current?.childIds ?? []), childChannelId]
+ if (childIds.length === 0) {
+ if (!current) return state
+ const next = { ...state }
+ delete next[parentChannelId]
+ return next
+ }
+ return {
+ ...state,
+ [parentChannelId]: { baseUnread, childIds },
+ }
+ })
+}
+
+/** Update the genuine parent contribution while preserving missing children. */
+export function setForumSidebarParentUnreadBase(
+ queryClient: QueryClient,
+ serverId: string,
+ parentChannelId: string,
+ unread: boolean,
+): boolean {
+ const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
+ const state = queryClient.getQueryData<ForumSidebarUnreadFallbackState>(key)
+ const current = state?.[parentChannelId]
+ let handled = false
+ queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
+ if (!cache?.forumUnreadState?.[parentChannelId]) return cache
+ handled = true
+ const entry = cache.forumUnreadState[parentChannelId]!
+ return patchChannelUnread({
+ ...cache,
+ forumUnreadState: {
+ ...cache.forumUnreadState,
+ [parentChannelId]: { ...entry, baseUnread: unread },
+ },
+ }, parentChannelId, unread || (current?.childIds.length ?? 0) > 0)
+ })
+ if (current) {
+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, {
+ ...state,
+ [parentChannelId]: { ...current, baseUnread: unread },
+ })
+ handled = true
+ }
+ return handled
+}
+
+/**
+ * Re-project fallback ownership from the canonical unread child set. Loaded
+ * children own their own dots; only unread children omitted by the sidebar's
+ * 72h / top-five projection light the parent. Re-deriving (rather than merely
+ * removing loaded ids) is what preserves visible → hidden transitions.
+ */
+export function reconcileForumSidebarUnreadFallbacks(
+ queryClient: QueryClient,
+ serverId: string,
+ loadedChildIds: Iterable<string>,
+) {
+ const loaded = new Set(loadedChildIds)
+ const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
+ let fallbackState: ForumSidebarUnreadFallbackState = {}
+ queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
+ if (!cache?.forumUnreadState) return cache
+ let next: ServerDetail | undefined = cache
+ for (const [parentChannelId, entry] of Object.entries(cache.forumUnreadState)) {
+ const childIds = entry.childIds.filter((id) => !loaded.has(id))
+ if (childIds.length > 0) {
+ fallbackState = {
+ ...fallbackState,
+ [parentChannelId]: { baseUnread: entry.baseUnread, childIds },
+ }
+ }
+ next = patchChannelUnread(
+ next,
+ parentChannelId,
+ entry.baseUnread || childIds.length > 0,
+ )
+ }
+ return next
+ })
+ queryClient.setQueryData(key, fallbackState)
+}
+
+/** Remove a child's canonical unread ownership after read/leave/delete/archive. */
+export function removeForumSidebarUnreadChild(
+ queryClient: QueryClient,
+ serverId: string,
+ childChannelId: string,
+) {
+ const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, (state = {}) => {
+ let next = state
+ for (const [parentChannelId, entry] of Object.entries(state)) {
+ if (!entry.childIds.includes(childChannelId)) continue
+ const childIds = entry.childIds.filter((id) => id !== childChannelId)
+ next = { ...state }
+ if (childIds.length === 0) delete next[parentChannelId]
+ else next[parentChannelId] = { ...entry, childIds }
+ break
+ }
+ return next
+ })
+ queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
+ if (!cache?.forumUnreadState) return cache
+ const found = Object.entries(cache.forumUnreadState)
+ .find(([, entry]) => entry.childIds.includes(childChannelId))
+ if (!found) return cache
+ const [parentChannelId, entry] = found
+ const childIds = entry.childIds.filter((id) => id !== childChannelId)
+ const next = {
+ ...cache,
+ forumUnreadState: {
+ ...cache.forumUnreadState,
+ [parentChannelId]: { ...entry, childIds },
+ },
+ }
+ const hiddenChildIds = queryClient
+ .getQueryData<ForumSidebarUnreadFallbackState>(key)
+ ?.[parentChannelId]?.childIds ?? []
+ const unread = entry.baseUnread || hiddenChildIds.length > 0
+ return patchChannelUnread(next, parentChannelId, unread)
+ })
+}
+
+export function hasForumSidebarThread(data: ForumSidebarQueryData | undefined, threadId: string) {
+ return !!data?.threads.some((thread) => thread.id === threadId)
+}
+
+export function patchForumSidebarActivity(
+ data: ForumSidebarQueryData | undefined,
+ threadId: string,
+ parentChannelId: string,
+ activityAt: string,
+): ForumSidebarQueryData | undefined {
+ if (!data || !hasForumSidebarThread(data, threadId)) return data
+ const expiresAt = new Date(Date.parse(activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
+ const threads = data.threads
+ .map((thread) => thread.id === threadId ? { ...thread, activityAt, expiresAt } : thread)
+ .sort((a, b) => {
+ if (a.parentChannelId !== b.parentChannelId) return a.parentChannelId < b.parentChannelId ? -1 : 1
+ if (a.activityAt !== b.activityAt) return a.activityAt > b.activityAt ? -1 : 1
+ return a.id === b.id ? 0 : a.id > b.id ? -1 : 1
+ })
+ // Ignore metadata from a malformed/mismatched event rather than moving the
+ // loaded row under a different forum. The event's parent id is still checked
+ // by callers before deciding whether a missing row requires a refetch.
+ if (!threads.some((thread) => thread.id === threadId && thread.parentChannelId === parentChannelId)) return data
+ return { ...data, threads }
+}
+
+export function patchForumSidebarTitle(
+ data: ForumSidebarQueryData | undefined,
+ threadId: string,
+ title: string,
+): ForumSidebarQueryData | undefined {
+ if (!data) return data
+ return {
+ ...data,
+ threads: data.threads.map((thread) => thread.id === threadId ? { ...thread, title } : thread),
+ }
+}
+
+export function patchForumSidebarUnread(
+ data: ForumSidebarQueryData | undefined,
+ threadId: string,
+ unread: boolean,
+): ForumSidebarQueryData | undefined {
+ if (!data || !hasForumSidebarThread(data, threadId)) return data
+ return {
+ ...data,
+ threads: data.threads.map((thread) => thread.id === threadId ? { ...thread, unread } : thread),
+ }
+}
+
+export function removeForumSidebarThread(
+ data: ForumSidebarQueryData | undefined,
+ threadId: string,
+): ForumSidebarQueryData | undefined {
+ if (!data) return data
+ return { ...data, threads: data.threads.filter((thread) => thread.id !== threadId) }
+}
+
+export function projectForumSidebarThreads(data: SidebarThreadEnvelope): ForumSidebarThread[] {
+ const openerById = new Map(data.included.parentMessages.map((message) => [message.id, message]))
+ return data.channels.flatMap((channel) => {
+ if (!channel.parentChannelId || !channel.parentMessageId) return []
+ return [{
+ id: channel.id,
+ parentChannelId: channel.parentChannelId,
+ parentMessageId: channel.parentMessageId,
+ title: openerById.get(channel.parentMessageId)?.content || channel.name,
+ activityAt: channel.activityAt,
+ expiresAt: channel.expiresAt,
+ unread: channel.unread,
+ }]
+ })
+}
+
+export function useForumSidebarThreads(serverId: string, retainId: string | null) {
+ const queryClient = useQueryClient()
+ // Observe (without fetching) the already-canonical ServerDetail cache so a
+ // fresh `/unreads` result re-runs attribution even when the sidebar rows did
+ // not change. This is essential for access/archive/participation removal:
+ // those must clear a prior fallback instead of being mistaken for expiry.
+ const serverDetailQuery = useQuery<ServerDetail>({
+ queryKey: communityKeys.server(serverId),
+ queryFn: () => Promise.reject(new Error("server detail observer only")),
+ enabled: false,
+ })
+ const query = useQuery({
+ queryKey: communityKeys.forumSidebarThreadsView(serverId, retainId),
+ enabled: !!serverId,
+ // `retainId` is part of the key because the server may return an otherwise
+ // expired/non-top-five active thread. Keep the prior projection visible
+ // while that neighboring view loads so route changes never collapse the
+ // sidebar to an empty list for a frame.
+ placeholderData: keepPreviousData,
+ queryFn: async () => {
+ const params = new URLSearchParams({
+ type: "thread",
+ parentType: "forum",
+ participating: "true",
+ activeWithin: "72h",
+ limitPerParent: "5",
+ include: "parentMessage",
+ })
+ if (retainId) params.set("retainId", retainId)
+ const envelope = await apiFetch<SidebarThreadEnvelope>(
+ `/api/community/servers/${serverId}/channels?${params.toString()}`,
+ )
+ const serverNowMs = Date.parse(envelope.serverNow)
+ return {
+ ...envelope,
+ threads: projectForumSidebarThreads(envelope),
+ serverClockOffsetMs: Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0,
+ } satisfies ForumSidebarQueryData
+ },
+ })
+
+ useEffect(() => {
+ if (!query.data) return
+ reconcileForumSidebarUnreadFallbacks(
+ queryClient,
+ serverId,
+ query.data.threads.map((thread) => thread.id),
+ )
+ }, [query.data, queryClient, serverDetailQuery.data?.forumUnreadState, serverId])
+
+ // Expire rows against the server's clock without polling. The currently
+ // retained route is deliberately excluded: it remains visible until the
+ // viewer leaves it, even when its ordinary 72h expiry is already past.
+ useEffect(() => {
+ const data = query.data
+ if (!data) return
+ const serverNowMs = Date.now() + data.serverClockOffsetMs
+ const nextExpiry = data.threads
+ .filter((thread) => thread.id !== retainId)
+ .map((thread) => Date.parse(thread.expiresAt))
+ .filter((expiresAt) => Number.isFinite(expiresAt))
+ .sort((a, b) => a - b)[0]
+ if (nextExpiry === undefined) return
+ const timeout = globalThis.setTimeout(() => {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads(serverId) })
+ }, Math.max(0, nextExpiry - serverNowMs) + 25)
+ return () => globalThis.clearTimeout(timeout)
+ }, [query.data, queryClient, retainId, serverId])
+
+ return {
+ ...query,
+ threads: query.data?.threads ?? [],
+ }
+}
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index 91e854cf2..27cade9e3 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -80,7 +80,32 @@ describe("useServer / serverQueryFn", () => {
expect(data).toEqual({ ...detail, categories: [
{ id: "cat_1", name: "Main", private: 0, channels: [{ id: "ch_1", name: "general", categoryId: "cat_1", active: false, unread: true }] },
{ id: "__uncategorized__", name: "", private: 0, channels: [{ id: "ch_2", name: "loose", categoryId: null, active: false, unread: false }] },
- ] })
+ ], forumUnreadState: {} })
+ })
+
+ it("cold-boots a forum fallback from a canonical unread child outside the sidebar projection", async () => {
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url === "/api/community/servers") return { servers: [{
+ id: "srv_1", name: "Alook", discriminator: "0001", icon: null, ownerId: "u_1",
+ }] }
+ if (url.endsWith("/categories")) return { categories: [{ id: "cat_1", name: "Main", private: 0 }] }
+ if (url.endsWith("/channels")) return { channels: [{
+ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1",
+ }] }
+ if (url.endsWith("/unreads")) return {
+ channelIds: ["post_hidden"],
+ childChannels: [{ id: "post_hidden", parentChannelId: "forum_1" }],
+ }
+ throw new Error(`unexpected ${url}`)
+ })
+
+ const { serverQueryFn } = await import("./use-servers")
+ const data = await serverQueryFn("srv_1")()
+
+ expect(data.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(data.forumUnreadState).toEqual({
+ forum_1: { baseUnread: false, childIds: ["post_hidden"] },
+ })
})
it("nests the server(id) key under servers() so prefix invalidation cascades", async () => {
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 491b4f41b..8c4e886c9 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -85,12 +85,22 @@ export type ServerDetail = {
icon: string | null
ownerId: string
categories: Category[]
+ /** Canonical unread ownership for participating children of forum channels. */
+ forumUnreadState?: ForumUnreadState
}
+type ForumUnreadState = Record<string, {
+ /** The forum channel's own unread contribution, excluding child posts. */
+ baseUnread: boolean
+ /** Every canonically unread participating child, loaded in the sidebar or not. */
+ childIds: string[]
+}>
+
type RawChannel = Channel & { categoryId: string | null }
type UnreadResponse = {
stale?: boolean
channelIds: string[]
+ childChannels?: Array<{ id: string; parentChannelId: string }>
}
export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetail> => {
@@ -104,7 +114,30 @@ export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetai
const server = serverData.servers.find((row) => row.id === serverId)
if (!server) throw new Error("server not found")
const unreadIds = new Set(unreadData.channelIds)
- const channels = channelData.channels.map((channel) => ({ ...channel, active: false, unread: unreadIds.has(channel.id) }))
+ const forumParentIds = new Set(
+ channelData.channels.filter((channel) => channel.type === "forum").map((channel) => channel.id),
+ )
+ const forumUnreadState: ForumUnreadState = Object.fromEntries(
+ [...forumParentIds].map((parentChannelId) => [parentChannelId, {
+ baseUnread: unreadIds.has(parentChannelId),
+ childIds: (unreadData.childChannels ?? [])
+ .filter((child) => child.parentChannelId === parentChannelId)
+ .map((child) => child.id),
+ }]),
+ )
+ const channels = channelData.channels.map((channel) => {
+ const forumUnread = forumUnreadState[channel.id]
+ return {
+ ...channel,
+ active: false,
+ // Until the sidebar projection arrives, every canonical unread child is
+ // necessarily hidden. Its parent owns the cold-boot fallback dot; the
+ // sidebar hook migrates loaded children to their own rows immediately.
+ unread: forumUnread
+ ? forumUnread.baseUnread || forumUnread.childIds.length > 0
+ : unreadIds.has(channel.id),
+ }
+ })
const categories: Category[] = categoryData.categories.map((category) => ({
...category,
channels: channels.filter((channel) => channel.categoryId === category.id),
@@ -120,6 +153,7 @@ export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetai
icon: server.icon,
ownerId: server.ownerId,
categories,
+ forumUnreadState,
}
}
diff --git a/src/web/src/hooks/community/use-thread-participants.test.ts b/src/web/src/hooks/community/use-thread-participants.test.ts
new file mode 100644
index 000000000..b5a4255ca
--- /dev/null
+++ b/src/web/src/hooks/community/use-thread-participants.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+type MutationConfig = {
+ mutationFn: (userId: string) => Promise<unknown>
+ onSuccess?: (data: unknown, userId: string) => void
+}
+
+let config: MutationConfig
+let queryClient: QueryClient
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return {
+ ...actual,
+ useQueryClient: () => queryClient,
+ useMutation: (next: MutationConfig) => {
+ config = next
+ return {}
+ },
+ }
+})
+
+function sidebarData() {
+ return {
+ channels: [],
+ included: { parentMessages: [] },
+ serverNow: "2026-08-08T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: [{
+ id: "post_1",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_1",
+ title: "Post",
+ activityAt: "2026-08-08T00:00:00.000Z",
+ expiresAt: "2026-08-11T00:00:00.000Z",
+ unread: false,
+ }],
+ }
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ apiFetchMock.mockResolvedValue(undefined)
+ queryClient = new QueryClient()
+})
+
+describe("useRemoveThreadParticipant", () => {
+ it("removes the child from every sidebar view when the viewer leaves", async () => {
+ const key = communityKeys.forumSidebarThreadsView("server_1", "post_1")
+ queryClient.setQueryData(key, sidebarData())
+ const { useRemoveThreadParticipant } = await import("./use-thread-participants")
+ useRemoveThreadParticipant("post_1", "server_1", "viewer_1")
+
+ const result = await config.mutationFn("viewer_1")
+ config.onSuccess?.(result, "viewer_1")
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/post_1/participants/viewer_1",
+ { method: "DELETE" },
+ )
+ expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toEqual([])
+ })
+
+ it("keeps the viewer's sidebar row when the creator removes someone else", async () => {
+ const key = communityKeys.forumSidebarThreadsView("server_1", null)
+ queryClient.setQueryData(key, sidebarData())
+ const { useRemoveThreadParticipant } = await import("./use-thread-participants")
+ useRemoveThreadParticipant("post_1", "server_1", "viewer_1")
+
+ const result = await config.mutationFn("other_1")
+ config.onSuccess?.(result, "other_1")
+
+ expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toHaveLength(1)
+ })
+})
diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.ts
index f180b499f..779636696 100644
--- a/src/web/src/hooks/community/use-thread-participants.ts
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -3,6 +3,11 @@
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
+import {
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
// The participant READ hook was retired: the post/thread member panel now reads
// the unified `/members` endpoint (via `useChannelMembers`), which returns the
@@ -26,7 +31,7 @@ export function useAddThreadParticipant(channelId: string) {
}
/** Leave a thread/post (remove your own participation, or the creator removes someone). */
-export function useRemoveThreadParticipant(channelId: string) {
+export function useRemoveThreadParticipant(channelId: string, serverId?: string, viewerUserId?: string) {
const qc = useQueryClient()
return useMutation({
mutationFn: (userId: string) =>
@@ -34,8 +39,15 @@ export function useRemoveThreadParticipant(channelId: string) {
`/api/community/channels/${encodeURIComponent(channelId)}/participants/${encodeURIComponent(userId)}`,
{ method: "DELETE" },
),
- onSuccess: () => {
+ onSuccess: (_data, userId) => {
void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })
+ if (serverId && userId === viewerUserId) {
+ removeForumSidebarUnreadChild(qc, serverId, channelId)
+ qc.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(serverId) },
+ (data) => removeForumSidebarThread(data, channelId),
+ )
+ }
},
})
}
diff --git a/src/web/src/lib/community/forum-activity.test.ts b/src/web/src/lib/community/forum-activity.test.ts
new file mode 100644
index 000000000..4e8806f66
--- /dev/null
+++ b/src/web/src/lib/community/forum-activity.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest"
+import { encodeForumActivityCursor, parseForumActivityCursor } from "./forum-activity"
+
+describe("forum activity cursor", () => {
+ const value = {
+ parentChannelId: "forum_1",
+ activityAt: "2026-08-08T02:00:00.123Z",
+ id: "thread_2",
+ tag: "产品",
+ }
+
+ it("round-trips an opaque cursor within the same forum and tag scope", () => {
+ const encoded = encodeForumActivityCursor(value)
+ expect(encoded).not.toContain("forum_1")
+ expect(parseForumActivityCursor(encoded, {
+ parentChannelId: "forum_1",
+ tag: "产品",
+ })).toEqual({
+ activityAt: "2026-08-08T02:00:00.123Z",
+ id: "thread_2",
+ })
+ })
+
+ it("rejects malformed, cross-forum, and cross-tag cursors", () => {
+ const encoded = encodeForumActivityCursor(value)
+ expect(parseForumActivityCursor("invalid", { parentChannelId: "forum_1", tag: "产品" })).toBeNull()
+ expect(parseForumActivityCursor(encoded, { parentChannelId: "forum_2", tag: "产品" })).toBeNull()
+ expect(parseForumActivityCursor(encoded, { parentChannelId: "forum_1", tag: "bug" })).toBeNull()
+ })
+
+ it("treats an absent cursor as the first page", () => {
+ expect(parseForumActivityCursor(null, { parentChannelId: "forum_1", tag: null })).toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/community/forum-activity.ts b/src/web/src/lib/community/forum-activity.ts
new file mode 100644
index 000000000..cdaf4b8ed
--- /dev/null
+++ b/src/web/src/lib/community/forum-activity.ts
@@ -0,0 +1,35 @@
+export type ForumActivityCursor = {
+ parentChannelId: string
+ activityAt: string
+ id: string
+ tag: string | null
+}
+
+export function encodeForumActivityCursor(cursor: ForumActivityCursor): string {
+ const ascii = encodeURIComponent(JSON.stringify(cursor))
+ return btoa(ascii).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")
+}
+
+export function parseForumActivityCursor(
+ raw: string | null,
+ scope: { parentChannelId: string; tag: string | null },
+): { activityAt: string; id: string } | null | undefined {
+ if (!raw) return undefined
+ try {
+ const base64 = raw.replaceAll("-", "+").replaceAll("_", "/")
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
+ const value = JSON.parse(decodeURIComponent(atob(padded))) as Partial<ForumActivityCursor>
+ if (
+ value.parentChannelId !== scope.parentChannelId
+ || value.tag !== scope.tag
+ || typeof value.activityAt !== "string"
+ || !Number.isFinite(Date.parse(value.activityAt))
+ || new Date(value.activityAt).toISOString() !== value.activityAt
+ || typeof value.id !== "string"
+ || value.id.length === 0
+ ) return null
+ return { activityAt: value.activityAt, id: value.id }
+ } catch {
+ return null
+ }
+}
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 18bbf4fd7..8fe165d7d 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -483,10 +483,35 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
expect(mockFanOutToChannel).toHaveBeenCalledTimes(1)
const [, event] = mockFanOutToChannel.mock.calls[0]!
+ expect(event).toMatchObject({ serverId: "srv_1" })
expect(event.message.attachments).toEqual([
expect.objectContaining({ width: 1920, height: 1080 }),
])
})
+
+ it("includes server + parent metadata for a child message so server-scoped sidebars can patch", async () => {
+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })
+ mockGetMessage.mockResolvedValue(messageRow())
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: {
+ kind: "thread",
+ channelId: "post_1",
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ },
+ body: { content: "reply" },
+ })
+
+ expect(mockFanOutToChannel.mock.calls[0]?.[1]).toMatchObject({
+ type: "community:message.create",
+ channelId: "post_1",
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ })
+ })
})
describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index a3ae6624e..869009b58 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -784,6 +784,12 @@ export async function createCommunityMessage(params: {
{
type: WS_EVENTS.MESSAGE_CREATE,
channelId: target.channelId,
+ ...(isDmTarget(target)
+ ? {}
+ : {
+ serverId: target.serverId,
+ ...(hasParentChannel(target) ? { parentChannelId: target.parentChannelId } : {}),
+ }),
message: messagePayload,
},
{
@@ -806,8 +812,8 @@ export async function createCommunityMessage(params: {
{
mentionedUserIds: [...liveMentions, ...liveReplies],
// serverId + railChannelId ride the UNREAD_BUMP so the client patches
- // the right server tree + (parent, for threads) sidebar row without a
- // query — straight off the resolved `target` (DM has neither). See
+ // the right server tree + a parent fallback for unlisted child threads
+ // without a query — straight off the resolved `target` (DM has neither). See
// inbox-dot-ws-driven plan.
...(isDmTarget(target)
? {}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 76fea1912..dc3791841 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -35,6 +35,7 @@ export const tid = {
// is the hover-revealed delete icon; `forumThreadAvatars` wraps the participant
// AvatarGroup; `forumTagChip` is a filter-bar tag chip.
forumThreadCard: (id: string) => `community-forum-post-${id}`,
+ forumSidebarThread: (id: string) => `community-forum-sidebar-thread-${id}`,
forumThreadTagBtn: (id: string) => `community-forum-post-tag-btn-${id}`,
forumThreadDeleteBtn: (id: string) => `community-forum-post-delete-btn-${id}`,
forumThreadAvatars: (id: string) => `community-forum-post-avatars-${id}`,
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 37ca6fe71..e4171a7c8 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -31,6 +31,12 @@ describe("communityKeys", () => {
expect(communityKeys.presence("s1")).toEqual([...server, "presence"])
expect(communityKeys.auditLog("s1")).toEqual([...server, "audit-log"])
expect(communityKeys.invites("s1")).toEqual([...server, "invites"])
+ const sidebar = [...server, "forum-sidebar-threads"]
+ expect(communityKeys.forumSidebarThreads("s1")).toEqual(sidebar)
+ expect(communityKeys.forumSidebarThreadsView("s1", "post_1")).toEqual([...sidebar, "post_1"])
+ expect(communityKeys.forumSidebarUnreadFallbacks("s1")).toEqual([
+ ...server, "forum-sidebar-unread-fallbacks",
+ ])
})
it("nests channel-scoped keys under a stable channel prefix", () => {
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 569aad178..52edc1d36 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -20,6 +20,12 @@ export const communityKeys = {
servers: () => [...communityKeys.all, "servers"] as const,
server: (serverId: string) =>
[...communityKeys.servers(), serverId] as const,
+ forumSidebarThreads: (serverId: string) =>
+ [...communityKeys.server(serverId), "forum-sidebar-threads"] as const,
+ forumSidebarThreadsView: (serverId: string, retainId: string | null) =>
+ [...communityKeys.forumSidebarThreads(serverId), retainId] as const,
+ forumSidebarUnreadFallbacks: (serverId: string) =>
+ [...communityKeys.server(serverId), "forum-sidebar-unread-fallbacks"] as const,
// ── Server-scoped resources ─────────────────────────────────────────────
members: (serverId: string) =>
@@ -67,6 +73,8 @@ export const communityKeys = {
[...communityKeys.all, "channel", channelId, "pins"] as const,
threads: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "threads"] as const,
+ forumActivityFeed: (channelId: string, tag: string | null) =>
+ [...communityKeys.threads(channelId), "activity", tag] as const,
forumTags: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "forum-tags"] as const,
// #3: the viewer's `communityReadState` row for a single channel, fetched