Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): exclude archived forum openers from sidebar (#606)
Gener4ed1ca832f67
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex fac696c7b..2cbdd211c 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -292,6 +292,11 @@ export async function listParticipatingThreadIds(export type ForumCreatedAtCursor = { createdAt: string; id: string };+export type ForumSidebarRetainedDisposition =+ | "eligible"+ | "opener-archived"+ | "genuine-negative";+export async function listForumThreadsByCreatedAt(db: Database,params: {@@ -388,7 +393,11 @@ export async function listParticipatingForumThreads() {const parentChannelIds = [...new Set(params.parentChannelIds)];if (parentChannelIds.length === 0 || params.limitPerParent < 1) {- return { canonical: [], retained: null };+ return {+ canonical: [],+ retained: null,+ retainedDisposition: params.retainId ? "genuine-negative" as const : null,+ };}const activityAt = sql<string>`coalesce(${communityChannel.lastMessageAt}, ${communityChannel.createdAt})`;@@ -410,6 +419,14 @@ export async function listParticipatingForumThreads(activityAt: activityAt.as("activity_at"),} as const;+ const archiveTagQuery = db+ .select({ messageId: communityMessageTag.messageId })+ .from(communityMessageTag)+ .where(and(+ eq(communityMessageTag.messageId, communityChannel.parentMessageId),+ eq(communityMessageTag.tag, FORUM_ARCHIVE_TAG)+ ));+const batches = await Promise.all(chunk(parentChannelIds, D1_MAX_IN_PARAMS).map((parentIds) => {const ranked = db@@ -431,6 +448,7 @@ export async function listParticipatingForumThreads(eq(communityChannel.type, "thread"),eq(communityChannel.archived, 0),isNotNull(communityChannel.parentMessageId),+ notExists(archiveTagQuery),gt(activityAt, params.activeAfter),)).as("ranked_sidebar_threads");@@ -460,12 +478,15 @@ export async function listParticipatingForumThreads();const rows = batches.flat();let retained: (typeof rows)[number] | null = null;+ let retainedDisposition: ForumSidebarRetainedDisposition | null = params.retainId+ ? "genuine-negative"+ : null;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.- retained = (await Promise.all(+ const retainedCandidate = (await Promise.all(chunk(parentChannelIds, D1_MAX_IN_PARAMS).map((parentIds) => db.select(select).from(communityChannel)@@ -486,6 +507,22 @@ export async function listParticipatingForumThreads()).limit(1)),)).flat()[0] ?? null;+ if (retainedCandidate?.parentMessageId) {+ const archived = (await db+ .select({ messageId: communityMessageTag.messageId })+ .from(communityMessageTag)+ .where(and(+ eq(communityMessageTag.messageId, retainedCandidate.parentMessageId),+ eq(communityMessageTag.tag, FORUM_ARCHIVE_TAG)+ ))+ .limit(1))[0];+ if (archived) {+ retainedDisposition = "opener-archived";+ } else {+ retained = retainedCandidate;+ retainedDisposition = "eligible";+ }+ }}return {@@ -495,5 +532,6 @@ export async function listParticipatingForumThreads(compareAsciiSqliteBinary(b.id, a.id)),retained,+ retainedDisposition,};}diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex 415234b29..a4c1da120 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -181,9 +181,12 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {(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"]) {+ for (const id of ["t_new", "t_tie_b", "t_tie_a", "t_created", "t_tag_archived", "t_archived", "foreign"]) {insertMember.run(`member_${id}`, id);}+ sqlite.prepare(+ "INSERT INTO community_message_tag (id, message_id, tag) VALUES (?, ?, ?)",+ ).run("tag_channel_archive", "m_archived", FORUM_ARCHIVE_TAG);const recent = await threadQueries.listParticipatingForumThreads(db as never, {parentChannelIds: ["forum_1", "forum_2"],@@ -193,6 +196,7 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {});expect(recent.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);expect(recent.retained).toBeNull();+ expect(recent.retainedDisposition).toBeNull();const retained = await threadQueries.listParticipatingForumThreads(db as never, {parentChannelIds: ["forum_1", "forum_2"],@@ -203,6 +207,38 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {});expect(retained.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);expect(retained.retained?.id).toBe("t_created");+ expect(retained.retainedDisposition).toBe("eligible");++ const openerArchived = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "viewer",+ activeAfter: "2026-08-08T03:00:00.000Z",+ limitPerParent: 2,+ retainId: "t_tag_archived",+ });+ expect(openerArchived.retained).toBeNull();+ expect(openerArchived.retainedDisposition).toBe("opener-archived");++ const channelArchived = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "viewer",+ activeAfter: "2026-08-08T03:00:00.000Z",+ limitPerParent: 2,+ retainId: "t_archived",+ });+ expect(channelArchived.retained).toBeNull();+ expect(channelArchived.retainedDisposition).toBe("genuine-negative");++ sqlite.prepare("INSERT INTO user (id, name) VALUES (?, ?)").run("outsider", "Outsider");+ const nonparticipantArchived = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "outsider",+ activeAfter: "2026-08-08T03:00:00.000Z",+ limitPerParent: 2,+ retainId: "t_tag_archived",+ });+ expect(nonparticipantArchived.retained).toBeNull();+ expect(nonparticipantArchived.retainedDisposition).toBe("genuine-negative");const outOfScopeRetained = await threadQueries.listParticipatingForumThreads(db as never, {parentChannelIds: ["forum_1"],@@ -213,6 +249,75 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {});expect(outOfScopeRetained.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);expect(outOfScopeRetained.retained).toBeNull();+ expect(outOfScopeRetained.retainedDisposition).toBe("genuine-negative");+ });++ it("filters archived openers before top-five ranking and refills from the sixth active post", async () => {+ sqlite.prepare("INSERT INTO user (id, name) VALUES (?, ?)").run("viewer", "Viewer");+ const insertChannel = sqlite.prepare(`+ INSERT INTO community_channel+ (id, name, type, parent_channel_id, parent_message_id, archived, last_message_at, created_at)+ VALUES (?, ?, 'thread', 'forum_1', ?, 0, ?, '2026-01-01T00:00:00.000Z')+ `);+ insertChannel.run("t_fifth", "fifth", "m_fifth", "2026-08-08T03:30:00.000Z");+ insertChannel.run("t_sixth", "sixth", "m_sixth", "2026-08-08T03:00:00.000Z");+ 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_tag_archived",+ "t_new",+ "t_tie_b",+ "t_tie_a",+ "t_fifth",+ "t_sixth",+ "t_created",+ ]) {+ insertMember.run(`member_${id}`, id);+ }+ sqlite.prepare("DELETE FROM community_message_tag WHERE id = 'tag_archive'").run();++ const before = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "viewer",+ activeAfter: "2026-08-08T00:00:00.000Z",+ limitPerParent: 5,+ });+ expect(before.canonical.map((row) => row.id)).toEqual([+ "t_tag_archived",+ "t_new",+ "t_tie_b",+ "t_tie_a",+ "t_fifth",+ ]);++ sqlite.prepare(+ "INSERT INTO community_message_tag (id, message_id, tag) VALUES (?, ?, ?)",+ ).run("tag_archive_again", "m_tag_archived", FORUM_ARCHIVE_TAG);+ const archived = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "viewer",+ activeAfter: "2026-08-08T00:00:00.000Z",+ limitPerParent: 5,+ });+ expect(archived.canonical.map((row) => row.id)).toEqual([+ "t_new",+ "t_tie_b",+ "t_tie_a",+ "t_fifth",+ "t_sixth",+ ]);++ sqlite.prepare("DELETE FROM community_message_tag WHERE id = 'tag_archive_again'").run();+ const unarchived = await threadQueries.listParticipatingForumThreads(db as never, {+ parentChannelIds: ["forum_1"],+ userId: "viewer",+ activeAfter: "2026-08-08T00:00:00.000Z",+ limitPerParent: 5,+ });+ expect(unarchived.canonical.map((row) => row.id)).toEqual(before.canonical.map((row) => row.id));});});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.tsindex 9f0ce8caa..32505ce24 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@@ -78,7 +78,11 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {type: "thread",activityAt: "2026-08-08T11:00:00.000Z",}- mockListParticipatingForumThreads.mockResolvedValue({ canonical: [thread], retained: thread })+ mockListParticipatingForumThreads.mockResolvedValue({+ canonical: [thread],+ retained: thread,+ retainedDisposition: "eligible",+ })mockGetMessagesByIds.mockResolvedValue([{ id: "message_1", content: "Current title" }])mockListEligibleUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])@@ -111,6 +115,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {expiresAt: "2026-08-11T11:00:00.000Z",unread: true,}),+ retainedDisposition: "eligible",included: { parentMessages: [{ id: "message_1", content: "Current title" }] },serverNow: "2026-08-08T12:00:00.000Z",})@@ -139,6 +144,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {mockListParticipatingForumThreads.mockResolvedValue({canonical: [row("z"), row("a")],retained: row("ä"),+ retainedDisposition: "eligible",})mockGetMessagesByIds.mockResolvedValue([{ id: "message_z", content: "Z" },@@ -162,6 +168,34 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {}})+ it("serializes an archived-opener retained negative without returning the child", async () => {+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })+ mockListServerChannelsForViewer.mockResolvedValue([+ { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },+ ])+ mockListParticipatingForumThreads.mockResolvedValue({+ canonical: [],+ retained: null,+ retainedDisposition: "opener-archived",+ })+ mockGetMessagesByIds.mockResolvedValue([])++ 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_archived&include=parentMessage"),+ { params: { id: "server_1" } } as never,+ )++ expect(response.status).toBe(200)+ expect(await response.json()).toMatchObject({+ channels: [],+ canonicalChannels: [],+ retainedChannel: null,+ retainedDisposition: "opener-archived",+ included: { parentMessages: [] },+ })+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), [])+ })+it("rejects a partial or oversized sidebar query without reading child threads", async () => {mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })mockListServerChannelsForViewer.mockResolvedValue([])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.tsindex 87dc3f543..a235d72c0 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@@ -107,6 +107,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {channels,canonicalChannels,retainedChannel,+ retainedDisposition: projection.retainedDisposition,included: { parentMessages },serverNow,})diff --git a/src/web/src/components/community/channels/forum-channel-surface.test.ts b/src/web/src/components/community/channels/forum-channel-surface.test.tsindex 38a418fed..3f04eaa00 100644--- a/src/web/src/components/community/channels/forum-channel-surface.test.ts+++ b/src/web/src/components/community/channels/forum-channel-surface.test.ts@@ -105,6 +105,7 @@ describe("ForumChannelSurface ownership", () => {id: "post_1",authorId: "viewer_1",openerMessageId: "opener_1",+ tags: ["bug"],} as Parameters<NonNullable<typeof forumProps.canEditPostTags>>[0]const otherPost = { ...ownPost, authorId: "other_1" }expect(forumProps.canEditPostTags?.(ownPost)).toBe(true)@@ -134,9 +135,11 @@ describe("ForumChannelSurface ownership", () => {forumProps.onDeletePost?.(ownPost)})expect(mocks.updatePostTags).toHaveBeenCalledWith({+ serverId: "srv_1",forumChannelId: "forum_1",threadId: "post_1",openerMessageId: "opener_1",+ previousTags: ["bug"],tags: ["shipped"],}, expect.any(Object))expect(mocks.deleteForumThread).toHaveBeenCalledWith({diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsxindex c25a9d12c..80925dec9 100644--- a/src/web/src/components/community/channels/forum-channel-surface.tsx+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx@@ -116,7 +116,14 @@ export function ForumChannelSurface({savingTagsFor={updatePostTagsMut.isPending ? updatePostTagsMut.variables?.threadId ?? null : null}onEditPostTags={(post, tags) => {updatePostTagsMut.mutate(- { forumChannelId: channelId, threadId: post.id, openerMessageId: post.openerMessageId, tags },+ {+ serverId,+ forumChannelId: channelId,+ threadId: post.id,+ openerMessageId: post.openerMessageId,+ previousTags: post.tags ?? [],+ tags,+ },{ onError: (error) => toastApiError(error, "Failed to update tags") },)}}diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.tsindex ea4d4e581..626808063 100644--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts@@ -96,6 +96,61 @@ function invalidationCount(queryKey: readonly unknown[]): number {}describe("useCommunityWs — operation bundles", () => {+ it("applies archive and null-tag sidebar semantics inside committed batches", async () => {+ await mountHook()+ const baseKey = communityKeys.forumSidebarThreads("s1")+ const metaKey = communityKeys.channelMeta("s1", "post_1")+ const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {+ id: "s1",+ categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],+ })+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture(["post_1", "post_2"]))+ capturedQueryClient.setQueryData(metaKey, {+ id: "post_1",+ parentChannelId: "forum_1",+ parentMessageId: "opener-post_1",+ })+ capturedQueryClient.setQueryData(hintKey, {+ id: "opener-post_1",+ content: "Post one",+ })++ capturedOnMessage!(await batchFor("forum-archive", [{+ type: "community:channel.child_update",+ parentChannelId: "forum_1",+ channelId: "post_1",+ changes: { tags: ["archived"] },+ }]))++ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)+ ?.threads.map(({ id }) => id)).toEqual(["post_2"])+ expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })+ expect(capturedQueryClient.getQueryData(hintKey)).toEqual({+ id: "opener-post_1",+ content: "Post one",+ })+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })++ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture(["post_2"]))+ capturedOnMessage!(await batchFor("forum-unarchive", [{+ type: "community:channel.child_update",+ parentChannelId: "forum_1",+ channelId: "post_1",+ changes: { tags: null },+ }]))++ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)+ ?.threads.map(({ id }) => id)).toEqual(["post_2"])+ expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })+ expect(capturedQueryClient.getQueryData(hintKey)).toEqual({+ id: "opener-post_1",+ content: "Post one",+ })+ })+it("merges multiple requests into one queued successor generation", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.tsindex ba6f731f5..1116ef5dd 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts@@ -483,6 +483,120 @@ describe("useCommunityWs — child_create patches parent thread badge with count}})+ it("archive-tag updates evict only the sidebar projection and keep the active route", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ const baseKey = communityKeys.forumSidebarThreads("s1")+ const retainedKey = communityKeys.forumSidebarRetained("s1", "post_1")+ const metaKey = communityKeys.channelMeta("s1", "post_1")+ const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")+ const fallbackKey = communityKeys.forumSidebarUnreadFallbacks("s1")+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {+ id: "s1",+ categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],+ })+ const base = forumSidebarFixture(["post_1", "post_2"])+ capturedQueryClient.setQueryData(baseKey, base)+ capturedQueryClient.setQueryData(retainedKey, base.threads[0])+ capturedQueryClient.setQueryData(metaKey, {+ id: "post_1",+ parentChannelId: "forum_1",+ parentMessageId: "opener-post_1",+ })+ capturedQueryClient.setQueryData(hintKey, {+ id: "opener-post_1",+ content: "Post one",+ })+ capturedQueryClient.setQueryData(fallbackKey, {+ forum_1: { baseUnread: false, childIds: ["post_1"] },+ })+ useCommunityStore.getState().setCurrentChannelId("post_1")+ useCommunityStore.getState().setCurrentChannelMeta({+ name: "Post one",+ parentChannelId: "forum_1",+ parentMessageId: "opener-post_1",+ })++ capturedOnMessage!({+ type: "community:channel.child_update",+ parentChannelId: "forum_1",+ channelId: "post_1",+ changes: { tags: ["bug", "archived"] },+ } satisfies CommunityChildChannelUpdate)++ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)+ ?.threads.map(({ id }) => id)).toEqual(["post_2"])+ expect(capturedQueryClient.getQueryState(retainedKey)).toBeUndefined()+ expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })+ expect(capturedQueryClient.getQueryData(hintKey)).toEqual({+ id: "opener-post_1",+ content: "Post one",+ })+ expect(capturedQueryClient.getQueryData(fallbackKey)).toEqual({+ forum_1: { baseUnread: false, childIds: ["post_1"] },+ })+ expect(useCommunityStore.getState().currentChannelId).toBe("post_1")+ expect(useCommunityStore.getState().currentChannelMeta).toMatchObject({+ parentMessageId: "opener-post_1",+ })+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })+ })++ it.each([+ ["ordinary tags", ["bug"]],+ ["null tags", null],+ ] as const)("%s keeps the warm projection until the exact-base response", async (_label, tags) => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ const baseKey = communityKeys.forumSidebarThreads("s1")+ const retainedKey = communityKeys.forumSidebarRetained("s1", "post_1")+ const metaKey = communityKeys.channelMeta("s1", "post_1")+ const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {+ id: "s1",+ categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],+ })+ const base = forumSidebarFixture(["post_1", "post_2"])+ capturedQueryClient.setQueryData(baseKey, base)+ capturedQueryClient.setQueryData(retainedKey, base.threads[0])+ capturedQueryClient.setQueryData(metaKey, {+ id: "post_1",+ parentChannelId: "forum_1",+ parentMessageId: "opener-post_1",+ })+ capturedQueryClient.setQueryData(hintKey, {+ id: "opener-post_1",+ content: "Post one",+ })+ useCommunityStore.getState().setCurrentChannelId("post_1")+ useCommunityStore.getState().setCurrentChannelMeta({+ name: "Post one",+ parentChannelId: "forum_1",+ parentMessageId: "opener-post_1",+ })++ capturedOnMessage!({+ type: "community:channel.child_update",+ parentChannelId: "forum_1",+ channelId: "post_1",+ changes: { tags },+ } satisfies CommunityChildChannelUpdate)++ expect(capturedQueryClient.getQueryData(baseKey)).toEqual(base)+ expect(capturedQueryClient.getQueryData(retainedKey)).toEqual(base.threads[0])+ expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })+ expect(capturedQueryClient.getQueryData(hintKey)).toEqual({+ id: "opener-post_1",+ content: "Post one",+ })+ expect(useCommunityStore.getState().currentChannelId).toBe("post_1")+ await vi.waitFor(() => {+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })+ })+it("child_update rename patches focused child metadata and its cached channel meta", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")@@ -532,7 +646,7 @@ describe("useCommunityWs — child_create patches parent thread badge with counttype: "community:channel.child_update",parentChannelId: "forum_1",channelId: "ch_thread",- changes: { archived: true },+ changes: { archived: true, tags: ["bug"] },} satisfies CommunityChildChannelUpdate)expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])expect(useCommunityStore.getState().currentChannelMeta).toBeNull()diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.tsindex 0b41eff9d..6497108e6 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts@@ -13,6 +13,7 @@ import type {CommunityServerDelete,CommunityServerUpdate,} from "@alook/shared"+import { FORUM_ARCHIVE_TAG } from "@alook/shared"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import type { CanonicalMessage } from "@/lib/community/message-stream"@@ -23,6 +24,7 @@ import {grantForumSidebarChild,isForumSidebarParent,patchForumSidebarActivityExact,+ reconcileForumSidebarArchiveTag,removeForumSidebarThreadExact,removeForumSidebarUnreadChild,} from "@/hooks/community/use-forum-sidebar-threads"@@ -160,6 +162,13 @@ export function handleChildChannelUpdate(removeForumSidebarThreadExact(queryClient, sidebarServerId, event.channelId)} else if (changes.archived === false) {void grantForumSidebarChild(queryClient, sidebarServerId, event.channelId)+ } else if (changes.tags !== undefined) {+ void reconcileForumSidebarArchiveTag(+ queryClient,+ sidebarServerId,+ event.channelId,+ (changes.tags ?? []).includes(FORUM_ARCHIVE_TAG),+ )} else if (changes.lastMessageAt) {patchForumSidebarActivityExact(queryClient,diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex 0781ca64f..d43ad4130 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -155,6 +155,21 @@ describe("useCreateForumThread", () => {})describe("useUpdatePostTags", () => {+ const sidebar = (ids: string[]) => ({+ threads: ids.map((id) => ({+ id,+ parentChannelId: "forum_1",+ parentMessageId: `opener_${id}`,+ title: id,+ activityAt: "2026-08-28T00:00:00.000Z",+ expiresAt: "2026-08-31T00:00:00.000Z",+ unread: id === "p2",+ })),+ verifiedEpoch: 1,+ serverNow: "2026-08-28T00:00:00.000Z",+ serverClockOffsetMs: 0,+ })+it("PUTs normalized tags and invalidates every message-feed variant plus the forum tag list", async () => {const { useUpdatePostTags } = await load()useUpdatePostTags()@@ -169,9 +184,11 @@ describe("useUpdatePostTags", () => {apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "p0"] })await runMutation({+ serverId: "server_1",forumChannelId: "forum_1",threadId: "p2",openerMessageId: "m_p2",+ previousTags: ["bug"],tags: [" Bug ", "P0", "bug"],})@@ -186,6 +203,85 @@ describe("useUpdatePostTags", () => {expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(true)})+ it("evicts only the archived sidebar projection after the successful PUT", async () => {+ const { useUpdatePostTags } = await load()+ useUpdatePostTags()+ const baseKey = communityKeys.forumSidebarThreads("server_1")+ const retainedKey = communityKeys.forumSidebarRetained("server_1", "p2")+ const metaKey = communityKeys.channelMeta("server_1", "p2")+ const hintKey = communityKeys.forumOpenerHint("server_1", "opener_p2")+ capturedQc.setQueryData(baseKey, sidebar(["p1", "p2", "p3"]))+ capturedQc.setQueryData(retainedKey, sidebar(["p2"]).threads[0])+ capturedQc.setQueryData(metaKey, { id: "p2", parentMessageId: "opener_p2" })+ capturedQc.setQueryData(hintKey, { id: "opener_p2", content: "p2" })+ apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "archived"] })++ await runMutation({+ serverId: "server_1",+ forumChannelId: "forum_1",+ threadId: "p2",+ openerMessageId: "opener_p2",+ previousTags: ["bug"],+ tags: ["bug", "archived"],+ })++ expect(capturedQc.getQueryData<ReturnType<typeof sidebar>>(baseKey)?.threads.map(({ id }) => id))+ .toEqual(["p1", "p3"])+ expect(capturedQc.getQueryState(retainedKey)).toBeUndefined()+ expect(capturedQc.getQueryData(metaKey)).toEqual({ id: "p2", parentMessageId: "opener_p2" })+ expect(capturedQc.getQueryData(hintKey)).toEqual({ id: "opener_p2", content: "p2" })+ await vi.waitFor(() => {+ expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })+ })++ it("waits for authoritative ranking on unarchive without speculative insertion", async () => {+ const { useUpdatePostTags } = await load()+ useUpdatePostTags()+ const baseKey = communityKeys.forumSidebarThreads("server_1")+ const retainedKey = communityKeys.forumSidebarRetained("server_1", "p2")+ capturedQc.setQueryData(baseKey, sidebar(["p1", "p3"]))+ capturedQc.setQueryData(retainedKey, null)+ apiFetchMock.mockResolvedValueOnce({ tags: ["bug"] })++ await runMutation({+ serverId: "server_1",+ forumChannelId: "forum_1",+ threadId: "p2",+ openerMessageId: "opener_p2",+ previousTags: ["archived", "bug"],+ tags: ["bug"],+ })+ expect(capturedQc.getQueryData<ReturnType<typeof sidebar>>(baseKey)?.threads.map(({ id }) => id))+ .toEqual(["p1", "p3"])+ await vi.waitFor(() => {+ expect(capturedQc.getQueryState(retainedKey)).toBeUndefined()+ expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })+ })++ it("uses normalized returned tags and leaves the sidebar neutral without a transition", async () => {+ const { useUpdatePostTags } = await load()+ useUpdatePostTags()+ const baseKey = communityKeys.forumSidebarThreads("server_1")+ const before = sidebar(["p1", "p2"])+ capturedQc.setQueryData(baseKey, before)+ apiFetchMock.mockResolvedValueOnce({ tags: [" BUG "] })++ const result = await runMutation({+ serverId: "server_1",+ forumChannelId: "forum_1",+ threadId: "p2",+ openerMessageId: "opener_p2",+ previousTags: ["bug"],+ tags: ["archived"],+ })++ expect(result).toEqual({ tags: ["bug"] })+ expect(capturedQc.getQueryData(baseKey)).toEqual(before)+ expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(false)+ })+it("leaves both the message feeds and forum tag list untouched when the PUT fails", async () => {const { useUpdatePostTags } = await load()useUpdatePostTags()@@ -194,12 +290,15 @@ describe("useUpdatePostTags", () => {capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), feedBefore)capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), feedBefore)capturedQc.setQueryData(communityKeys.forumTags("forum_1"), tagsBefore)+ capturedQc.setQueryData(communityKeys.forumSidebarThreads("server_1"), sidebar(["p2"]))apiFetchMock.mockRejectedValueOnce(new Error("500"))await runMutationExpectError({+ serverId: "server_1",forumChannelId: "forum_1",threadId: "p2",openerMessageId: "m_p2",+ previousTags: ["bug"],tags: [],})@@ -208,6 +307,9 @@ describe("useUpdatePostTags", () => {expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(false)expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(false)expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(false)+ expect(capturedQc.getQueryData<ReturnType<typeof sidebar>>(+ communityKeys.forumSidebarThreads("server_1"),+ )?.threads.map(({ id }) => id)).toEqual(["p2"])})})diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex a935c0b97..7de9d259a 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -11,7 +11,9 @@ 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 { FORUM_ARCHIVE_TAG } from "@alook/shared"import {+ reconcileForumSidebarArchiveTag,restoreForumSidebarThreadInflight,} from "@/hooks/community/use-forum-sidebar-threads"import {@@ -65,12 +67,14 @@ export function useCreateForumThread() {}export type UpdatePostTagsArgs = {+ serverId: string// The parent forum channel — the cache key the post list lives under.forumChannelId: string// The post/thread card being patched in cache.threadId: string// Tags are a resource of the forum opener message, never of the child thread.openerMessageId: string+ previousTags: string[]tags: string[]}@@ -84,14 +88,25 @@ export function useUpdatePostTags() {return useMutation<{ tags: string[] }, Error, UpdatePostTagsArgs>({mutationFn: async ({ openerMessageId, tags }) => {const normalized = [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))]- await apiFetch(`/api/community/messages/${openerMessageId}/tags`, {+ const result = await apiFetch<{ tags: string[] }>(`/api/community/messages/${openerMessageId}/tags`, {method: "PUT",body: JSON.stringify({ tags: normalized }),})- return { tags: normalized }+ return {+ tags: [...new Set(result.tags.map((tag) => tag.trim().toLowerCase()).filter(Boolean))],+ }},onSuccess: (data, args) => {- void data+ const wasArchived = args.previousTags.includes(FORUM_ARCHIVE_TAG)+ const isArchived = data.tags.includes(FORUM_ARCHIVE_TAG)+ if (wasArchived !== isArchived) {+ void reconcileForumSidebarArchiveTag(+ queryClient,+ args.serverId,+ args.threadId,+ isArchived,+ )+ }// Prefix invalidation covers the unfiltered list and every tag variant.// This is required when the edited// post loses the currently-selected tag and must leave that result set.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.tsindex 34f41bcdf..6bbb57776 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts@@ -15,6 +15,7 @@ import {patchForumSidebarActivity,patchForumSidebarUnread,projectForumSidebarThreads,+ reconcileForumSidebarArchiveTag,reconcileForumSidebarUnreadFallbacks,recordForumSidebarChildUnread,removeForumSidebarThread,@@ -1085,11 +1086,146 @@ describe("forum sidebar Stage B resources", () => {)).toEqual({ id: "post-2" })})+ it("archive-tag eviction preserves route resources and hidden unread ownership", async () => {+ const queryClient = new QueryClient()+ const source = envelope(["post-1", "post-2"])+ const normalized = normalizeForumSidebarEnvelope({+ ...source,+ canonicalChannels: source.channels,+ retainedChannel: source.channels[0],+ retainedDisposition: "eligible",+ }, "post-1", 0)+ const baseKey = communityKeys.forumSidebarThreads("server-1")+ const retainedKey = communityKeys.forumSidebarRetained("server-1", "post-1")+ const metaKey = communityKeys.channelMeta("server-1", "post-1")+ const hintKey = communityKeys.forumOpenerHint("server-1", "opener-post-1")+ const fallbackKey = communityKeys.forumSidebarUnreadFallbacks("server-1")+ queryClient.setQueryData(baseKey, normalized.base)+ queryClient.setQueryData(retainedKey, normalized.retained)+ queryClient.setQueryData(metaKey, normalized.channelMetas["post-1"])+ queryClient.setQueryData(hintKey, normalized.openerHints["opener-post-1"])+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(fallbackKey, {+ "forum-1": { baseUnread: false, childIds: ["post-1"] },+ })++ await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)++ expect(queryClient.getQueryData<ForumSidebarQueryData>(baseKey)?.threads.map(({ id }) => id))+ .toEqual(["post-2"])+ expect(queryClient.getQueryState(retainedKey)).toBeUndefined()+ expect(queryClient.getQueryData(metaKey)).toEqual(normalized.channelMetas["post-1"])+ expect(queryClient.getQueryData(hintKey)).toEqual(normalized.openerHints["opener-post-1"])+ expect(queryClient.getQueryData(fallbackKey)).toEqual({+ "forum-1": { baseUnread: false, childIds: ["post-1"] },+ })+ expect(queryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })++ it("tag-only unarchive clears retained null and waits for authoritative ranking", async () => {+ const queryClient = new QueryClient()+ const source = envelope(["post-2"])+ const normalized = normalizeForumSidebarEnvelope({+ ...source,+ canonicalChannels: source.channels,+ retainedChannel: null,+ }, null, 0)+ const baseKey = communityKeys.forumSidebarThreads("server-1")+ const retainedKey = communityKeys.forumSidebarRetained("server-1", "post-1")+ const metaKey = communityKeys.channelMeta("server-1", "post-1")+ const hintKey = communityKeys.forumOpenerHint("server-1", "opener-post-1")+ queryClient.setQueryData(baseKey, normalized.base)+ queryClient.setQueryData(retainedKey, null)+ queryClient.setQueryData(metaKey, { id: "post-1", parentMessageId: "opener-post-1" })+ queryClient.setQueryData(hintKey, { id: "opener-post-1", content: "Post one" })++ await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", false)++ expect(queryClient.getQueryData<ForumSidebarQueryData>(baseKey)?.threads.map(({ id }) => id))+ .toEqual(["post-2"])+ expect(queryClient.getQueryState(retainedKey)).toBeUndefined()+ expect(queryClient.getQueryData(metaKey)).toEqual({+ id: "post-1",+ parentMessageId: "opener-post-1",+ })+ expect(queryClient.getQueryData(hintKey)).toEqual({+ id: "opener-post-1",+ content: "Post one",+ })+ expect(queryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)+ })++ it("preserves hidden unread ownership for an authoritative archived-opener negative", async () => {+ apiFetchMock.mockResolvedValue({+ ...envelope([]),+ canonicalChannels: [],+ retainedChannel: null,+ retainedDisposition: "opener-archived",+ })+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ queryClient.setQueryData(communityKeys.server("server-1"), {+ ...serverDetail(true),+ forumUnreadState: {+ "forum-1": { baseUnread: false, childIds: ["private-post"] },+ },+ })+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(+ communityKeys.forumSidebarUnreadFallbacks("server-1"),+ { "forum-1": { baseUnread: false, childIds: ["private-post"] } },+ )+ queryClient.setQueryData(communityKeys.channelMeta("server-1", "private-post"), {+ id: "private-post",+ serverId: "server-1",+ name: "Private post",+ type: "thread",+ parentChannelId: "forum-1",+ parentMessageId: "private-opener",+ creatorId: "user-1",+ archived: false,+ activityAt: "2026-08-08T00:00:00.000Z",+ verifiedEpoch: 0,+ })+ queryClient.setQueryData(+ communityKeys.forumOpenerHint("server-1", "private-opener"),+ { id: "private-opener", content: "Private title" },+ )+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, { retainId: "private-post", onRender: () => undefined }),+ ),+ )+ })+ await waitFor(() => queryClient.getQueryState(+ communityKeys.forumSidebarRetained("server-1", "private-post"),+ )?.status === "success")++ expect(queryClient.getQueryData<ServerDetail>(+ communityKeys.server("server-1"),+ )?.forumUnreadState?.["forum-1"]).toEqual({+ baseUnread: false,+ childIds: ["private-post"],+ })+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(+ communityKeys.forumSidebarUnreadFallbacks("server-1"),+ )).toEqual({ "forum-1": { baseUnread: false, childIds: ["private-post"] } })+ expect(queryClient.getQueryData(+ communityKeys.channelMeta("server-1", "private-post"),+ )).toMatchObject({ id: "private-post" })+ expect(queryClient.getQueryData(+ communityKeys.forumOpenerHint("server-1", "private-opener"),+ )).toEqual({ id: "private-opener", content: "Private title" })+ renderer!.unmount()+ })+it("clears a negative retained projection without deleting exact route metadata", async () => {apiFetchMock.mockResolvedValue({...envelope([]),canonicalChannels: [],retainedChannel: null,+ retainedDisposition: "genuine-negative",})const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })queryClient.setQueryData(communityKeys.server("server-1"), {@@ -1166,6 +1302,7 @@ describe("forum sidebar Stage B resources", () => {...envelope([]),canonicalChannels: [],retainedChannel: null,+ retainedDisposition: "genuine-negative",})const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })const accessEpoch = useCommunityWsStore.getState().accessEpochdiff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex cd4068d4f..fd2148275 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -18,6 +18,11 @@ export type ForumSidebarThread = {unread: boolean}+type ForumSidebarRetainedDisposition =+ | "eligible"+ | "opener-archived"+ | "genuine-negative"+export type SidebarThreadEnvelope = {channels: Array<{id: string@@ -36,6 +41,7 @@ export type SidebarThreadEnvelope = {}>canonicalChannels?: SidebarThreadEnvelope["channels"]retainedChannel?: SidebarThreadEnvelope["channels"][number] | null+ retainedDisposition?: ForumSidebarRetainedDisposition | nullincluded: {parentMessages: Array<{ id: string; content: string; seq?: number; channelId?: string }>}@@ -72,6 +78,7 @@ export type ForumOpenerHint = {export type NormalizedForumSidebarEnvelope = {base: ForumSidebarQueryDataretained: ForumSidebarThread | null+ retainedDisposition: ForumSidebarRetainedDisposition | nullchannelMetas: Record<string, ChildChannelMeta>openerHints: Record<string, ForumOpenerHint>}@@ -90,18 +97,21 @@ type InflightDelta = {titles: Map<string, string>unread: Map<string, boolean>removed: Set<string>+ archiveRemovals: Map<string, number>}type InflightRecord = {promise: Promise<NormalizedForumSidebarEnvelope>delta: InflightDeltacandidate: string | null+ generation: numbercontroller: AbortControllersignals: Set<AbortSignal>abortTimer: ReturnType<typeof setTimeout> | null}const inflight = new Map<string, InflightRecord>()+let nextInflightGeneration = 0function recordInflightDelta(serverId: string,@@ -419,6 +429,9 @@ export function normalizeForumSidebarEnvelope(const retained = retainedChannel? projectChannels([retainedChannel], envelope.included.parentMessages)[0] ?? null: null+ const retainedDisposition = retainId+ ? envelope.retainedDisposition ?? (retained ? "eligible" : "genuine-negative")+ : nullconst channelMetas: Record<string, ChildChannelMeta> = {}for (const channel of retainedChannel? [...canonicalChannels, retainedChannel]@@ -432,7 +445,7 @@ export function normalizeForumSidebarEnvelope({ id, content, ...(seq === undefined ? {} : { seq }), ...(channelId ? { channelId } : {}) },]),)- return { base, retained, channelMetas, openerHints }+ return { base, retained, retainedDisposition, channelMetas, openerHints }}export function deriveForumSidebarProjection(@@ -664,7 +677,7 @@ export function removeForumSidebarProjectionExact(serverId: string,childId: string,) {- removeForumSidebarBaseProjectionExact(queryClient, serverId, childId)+ removeForumSidebarBaseProjectionExact(queryClient, serverId, childId, "genuine")queryClient.removeQueries({queryKey: communityKeys.forumSidebarRetained(serverId, childId),exact: true,@@ -675,10 +688,17 @@ function removeForumSidebarBaseProjectionExact(queryClient: QueryClient,serverId: string,childId: string,+ cause: "genuine" | "archive-tag" = "genuine",) {- recordInflightDelta(serverId, (delta) => {- delta.removed.add(childId)- })+ const record = inflight.get(serverId)+ if (record) {+ record.delta.removed.add(childId)+ if (cause === "archive-tag") {+ record.delta.archiveRemovals.set(childId, record.generation)+ } else {+ record.delta.archiveRemovals.delete(childId)+ }+ }queryClient.setQueryData<ForumSidebarQueryData | undefined>(communityKeys.forumSidebarThreads(serverId),(data) => removeForumSidebarThread(data, childId),@@ -691,7 +711,7 @@ export function restoreForumSidebarThreadInflight(childId: string,) {recordInflightDelta(serverId, (delta) => {- delta.removed.delete(childId)+ if (!delta.archiveRemovals.has(childId)) delta.removed.delete(childId)})}@@ -760,6 +780,39 @@ export function grantForumSidebarChild(return invalidateForumSidebarBaseExact(queryClient, serverId)}+export function reconcileForumSidebarArchiveTag(+ queryClient: QueryClient,+ serverId: string,+ childId: string,+ archived: boolean,+) {+ const retainedKey = communityKeys.forumSidebarRetained(serverId, childId)+ if (archived) {+ removeForumSidebarBaseProjectionExact(+ queryClient,+ serverId,+ childId,+ "archive-tag",+ )+ queryClient.removeQueries({ queryKey: retainedKey, exact: true })+ return invalidateForumSidebarBaseExact(queryClient, serverId)+ }+ const record = inflight.get(serverId)+ if (record && record.delta.archiveRemovals.get(childId) === record.generation) {+ record.delta.archiveRemovals.delete(childId)+ record.delta.removed.delete(childId)+ }+ const retainedState = queryClient.getQueryState<ForumSidebarThread | null>(retainedKey)+ const resetRetained = retainedState?.data === null || retainedState?.fetchStatus === "fetching"+ ? queryClient.cancelQueries({ queryKey: retainedKey, exact: true }).then(() => {+ queryClient.removeQueries({ queryKey: retainedKey, exact: true })+ })+ : Promise.resolve()+ return resetRetained.then(() => {+ return invalidateForumSidebarBaseExact(queryClient, serverId)+ })+}+function sidebarUrl(serverId: string, retainId: string | null) {const params = new URLSearchParams({type: "thread",@@ -810,11 +863,13 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: Ainflight.delete(serverId)}const controller = new AbortController()+ const generation = ++nextInflightGenerationconst delta: InflightDelta = {activity: new Map(),titles: new Map(),unread: new Map(),removed: new Set(),+ archiveRemovals: new Map(),}const request = apiFetch<SidebarThreadEnvelope>(sidebarUrl(serverId, retainId), {signal: controller.signal,@@ -823,6 +878,7 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: A.then((normalized) => {let base: ForumSidebarQueryData | undefined = normalized.baselet retained = normalized.retained+ let retainedDisposition = normalized.retainedDispositionconst channelMetas = { ...normalized.channelMetas }const openerHints = { ...normalized.openerHints }for (const [childId, update] of delta.activity) {@@ -868,12 +924,22 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: Aif (meta) delete openerHints[meta.parentMessageId]delete channelMetas[childId]base = removeForumSidebarThread(base, childId)- if (retained?.id === childId) retained = null+ if (retained?.id === childId) {+ if (+ retainedDisposition === "eligible"+ && retainId === childId+ && delta.archiveRemovals.get(childId) === generation+ ) {+ retainedDisposition = "opener-archived"+ }+ retained = null+ }}return {...normalized,base: base ?? normalized.base,retained,+ retainedDisposition,channelMetas,openerHints,}@@ -888,6 +954,7 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: Apromise: request,delta,candidate: retainId,+ generation,controller,signals: new Set(),abortTimer: null,@@ -910,10 +977,19 @@ function seedForumSidebarResources(!hasForumSidebarThread(normalized.base, retainId) &&hasForumSidebarOwnershipEvidence(queryClient, serverId, retainId)) {- removeForumSidebarUnreadChild(queryClient, serverId, retainId)+ if (normalized.retainedDisposition !== "opener-archived") {+ removeForumSidebarUnreadChild(queryClient, serverId, retainId)+ }// The retained query owns its negative result. Removing that active query// here makes `retained=null` immediately eligible to refetch in a loop.- removeForumSidebarBaseProjectionExact(queryClient, serverId, retainId)+ removeForumSidebarBaseProjectionExact(+ queryClient,+ serverId,+ retainId,+ normalized.retainedDisposition === "opener-archived"+ ? "archive-tag"+ : "genuine",+ )}for (const meta of Object.values(normalized.channelMetas)) {queryClient.setQueryData(diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 9e49a6e9f..384c2da29 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -67,6 +67,58 @@ async function participantUserIds(page: Page, channelId: string): Promise<stringreturn payload.members.map((member) => member.userId)}+async function strictSidebar(page: Page, serverId: string, retainId?: string) {+ const params = new URLSearchParams({+ type: "thread",+ parentType: "forum",+ participating: "true",+ activeWithin: "72h",+ limitPerParent: "5",+ include: "parentMessage",+ })+ if (retainId) params.set("retainId", retainId)+ const response = await page.request.get(+ `/api/community/servers/${serverId}/channels?${params.toString()}`,+ )+ expect(response.status()).toBe(200)+ return await response.json() as {+ canonicalChannels: Array<{ id: string }>+ retainedChannel: { id: string } | null+ retainedDisposition: "eligible" | "opener-archived" | "genuine-negative" | null+ }+}++async function setForumPostArchived(+ page: Page,+ serverId: string,+ forumId: string,+ threadId: string,+ currentlyArchived: boolean,+) {+ await page.goto(`/c/channels/${serverId}/${forumId}`)+ await expect(page.getByTestId(tid.forumPostList)).toBeVisible({ timeout: 20_000 })+ if (currentlyArchived) {+ await expect(page.getByTestId(tid.forumTagChip("archived"))).toBeVisible({ timeout: 20_000 })+ await page.getByTestId(tid.forumTagChip("archived")).click()+ }+ const card = page.getByTestId(tid.forumThreadCard(threadId))+ await expect(card).toBeVisible({ timeout: 20_000 })+ await card.hover()+ await page.getByTestId(tid.forumThreadTagBtn(threadId)).click()+ await expect(page.getByTestId(tid.forumTagDialog)).toBeVisible({ timeout: 10_000 })+ await page.getByTestId(tid.forumTagDialogChip("archived")).click()+ const put = page.waitForResponse((response) =>+ response.request().method() === "PUT"+ && new URL(response.url()).pathname.endsWith("/tags"),+ )+ const sidebar = page.waitForResponse((response) =>+ response.ok() && isSidebarRequest(response.url(), serverId),+ )+ await page.keyboard.press("Escape")+ expect((await put).status()).toBe(200)+ await sidebar+}+test.describe.serial("forum sidebar Stage B request shape", () => {let serverId: stringlet forumId: string@@ -391,3 +443,90 @@ test.describe.serial("forum sidebar Stage B request shape", () => {)})})++test.describe.serial("forum sidebar archived opener projection", () => {+ test("local, remote, retained, and hard-refresh paths converge on a filled top five", async ({ asUser }) => {+ test.setTimeout(180_000)+ const serverId = await seedServer("alice", `Archived sidebar ${Date.now()}`)+ const categoryId = await seedCategory("alice", serverId, "Forum group")+ const forumId = await seedChannel("alice", serverId, "archive-ranking", "forum", categoryId)+ const textId = await seedChannel("alice", serverId, "side-view", undefined, categoryId)+ const titles = new Map<string, string>()+ const bodies = new Map<string, string>()+ const threadIds: string[] = []+ for (let index = 0; index < 6; index++) {+ const title = `Ranked post ${index + 1} ${Date.now()}`+ const body = `ranked body ${index + 1}`+ const threadId = await seedForumThread("alice", forumId, title, body)+ threadIds.push(threadId)+ titles.set(threadId, title)+ bodies.set(threadId, body)+ }++ const viewer = await asUser("alice")+ await viewer.page.goto(`/c/channels/${serverId}/${textId}`)+ const initial = await strictSidebar(viewer.page, serverId)+ const initialIds = initial.canonicalChannels.map(({ id }) => id)+ expect(initialIds).toHaveLength(5)+ const archivedId = initialIds[0]!+ const refillId = threadIds.find((id) => !initialIds.includes(id))!+ for (const id of initialIds) {+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(id))).toBeVisible({+ timeout: 20_000,+ })+ }+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(refillId))).toHaveCount(0)++ await setForumPostArchived(viewer.page, serverId, forumId, archivedId, false)+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toHaveCount(0)+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(refillId))).toBeVisible({+ timeout: 20_000,+ })+ const archivedProjection = await strictSidebar(viewer.page, serverId, archivedId)+ expect(archivedProjection.retainedChannel).toBeNull()+ expect(archivedProjection.retainedDisposition).toBe("opener-archived")+ expect(archivedProjection.canonicalChannels.map(({ id }) => id)).toEqual(+ initialIds.filter((id) => id !== archivedId).concat(refillId),+ )+ const exact = await viewer.page.request.get(`/api/community/channels/${archivedId}`)+ expect(exact.status()).toBe(200)+ expect((await exact.json() as { archived: boolean | number }).archived).toBeFalsy()++ await viewer.page.goto(`/c/channels/${serverId}/${archivedId}`)+ await expect(viewer.page.getByRole("heading", { name: titles.get(archivedId)! })).toBeVisible({+ timeout: 20_000,+ })+ await expect(viewer.page.getByText(bodies.get(archivedId)!, { exact: true })).toBeVisible()+ await expect(viewer.page.getByTestId(tid.channelComposerShell)).toBeVisible()+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toHaveCount(0)++ await viewer.page.goto(`/c/channels/${serverId}/${forumId}`)+ await viewer.page.getByTestId(tid.forumTagChip("archived")).click()+ await expect(viewer.page.getByTestId(tid.forumThreadCard(archivedId))).toBeVisible({+ timeout: 20_000,+ })++ await viewer.page.goto(`/c/channels/${serverId}/${textId}`)+ const editor = await asUser("alice")+ await setForumPostArchived(editor.page, serverId, forumId, archivedId, true)+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toBeVisible({+ timeout: 20_000,+ })+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(refillId))).toHaveCount(0)+ expect((await strictSidebar(viewer.page, serverId)).canonicalChannels.map(({ id }) => id))+ .toEqual(initialIds)++ await setForumPostArchived(editor.page, serverId, forumId, archivedId, false)+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toHaveCount(0)+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(refillId))).toBeVisible({+ timeout: 20_000,+ })+ await viewer.page.reload({ waitUntil: "commit" })+ for (const id of initialIds.filter((id) => id !== archivedId).concat(refillId)) {+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(id))).toBeVisible({+ timeout: 20_000,+ })+ }+ await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toHaveCount(0)+ })+})