Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): make forum archive transitions immediate (#713)

Gener48b0c811ed24
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
index 55d9332fb..9b42ef6bf 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
@@ -7,10 +7,8 @@ import { clearLastChannel } from "@/lib/community/last-channel"
import { channelHref } from "@/lib/community/community-route"
import type { PageCache } from "./cache"
import { removeThreadFromCache } from "./cache"
-import {
- removeForumPostFromFeed,
- type ForumFeedPage,
-} from "@/hooks/community/use-forum-feed"
+import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"
+import { removeForumPostFromFeed } from "@/hooks/community/forum-feed-tag-transition"
import type { InfiniteData } from "@tanstack/react-query"
import {
isKnownNonForumSidebarChannel,
diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
index 652b6c1b2..10aeb042b 100644
--- a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
+++ b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest"
-import { notifyManager, QueryClient } from "@tanstack/react-query"
+import { notifyManager, QueryClient, QueryObserver } from "@tanstack/react-query"
import {
getCommunityWsProjectionFlushError,
runCommunityWsProjectionTransaction,
@@ -70,7 +70,7 @@ describe("community WS projection transaction", () => {
expect(cancel).toHaveBeenCalledTimes(1)
expect(invalidate).toHaveBeenCalledWith({ ...filters, refetchType: "none" })
- expect(refetch).toHaveBeenCalledWith({ ...filters, type: "all" })
+ expect(refetch).toHaveBeenCalledWith({ ...filters, type: "active" })
}
})
@@ -103,6 +103,89 @@ describe("community WS projection transaction", () => {
expect(order).toEqual(["cancel", "project", "invalidate", "refetch"])
})
+ it("upgrades one owner/filter entry and replaces each active query exactly once", async () => {
+ const queryClient = new QueryClient()
+ const prefix = ["community", "channel", "forum_1", "threads"] as const
+ const allQuery = vi.fn(async () => ({ page: "all" }))
+ const archivedQuery = vi.fn(async () => ({ page: "archived" }))
+ const allObserver = new QueryObserver(queryClient, {
+ queryKey: [...prefix, "feed", null],
+ queryFn: allQuery,
+ initialData: { page: "all" },
+ staleTime: Infinity,
+ })
+ const archivedObserver = new QueryObserver(queryClient, {
+ queryKey: [...prefix, "feed", "archived"],
+ queryFn: archivedQuery,
+ initialData: { page: "archived" },
+ staleTime: Infinity,
+ })
+ const unsubscribeAll = allObserver.subscribe(() => {})
+ const unsubscribeArchived = archivedObserver.subscribe(() => {})
+ const cancel = vi.spyOn(queryClient, "cancelQueries")
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+
+ try {
+ runCommunityWsProjectionTransaction(queryClient, (transaction) => {
+ transaction.invalidate("threads", { queryKey: prefix })
+ transaction.fence("threads", { queryKey: prefix })
+ })
+
+ await vi.waitFor(() => {
+ expect(allQuery).toHaveBeenCalledTimes(1)
+ expect(archivedQuery).toHaveBeenCalledTimes(1)
+ })
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(invalidate).toHaveBeenCalledTimes(1)
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: prefix, refetchType: "none" })
+ } finally {
+ unsubscribeAll()
+ unsubscribeArchived()
+ }
+ })
+
+ it("absorbs a rejected active replacement while preserving its query error state", async () => {
+ const queryClient = new QueryClient()
+ const prefix = ["community", "channel", "forum_1", "threads"] as const
+ const failure = new Error("probe-refetch-failed")
+ const queryFn = vi.fn().mockRejectedValue(failure)
+ const observer = new QueryObserver(queryClient, {
+ queryKey: [...prefix, "feed", null],
+ queryFn,
+ initialData: { page: "all" },
+ staleTime: Infinity,
+ retry: false,
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ const cancel = vi.spyOn(queryClient, "cancelQueries")
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+ const unhandled = vi.fn()
+ process.on("unhandledRejection", unhandled)
+
+ try {
+ runCommunityWsProjectionTransaction(queryClient, (transaction) => {
+ transaction.fence("threads", { queryKey: prefix })
+ })
+
+ await vi.waitFor(() => {
+ expect(queryFn).toHaveBeenCalledOnce()
+ expect(observer.getCurrentResult()).toMatchObject({
+ status: "error",
+ error: failure,
+ })
+ })
+ await new Promise<void>((resolve) => setImmediate(resolve))
+
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(invalidate).toHaveBeenCalledOnce()
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: prefix, refetchType: "none" })
+ expect(unhandled).not.toHaveBeenCalled()
+ } finally {
+ process.off("unhandledRejection", unhandled)
+ unsubscribe()
+ }
+ })
+
it("flushes queued invalidations when projection fails", () => {
const queryClient = new QueryClient()
const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()
diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.ts b/src/web/src/hooks/community/community-ws/projection-transaction.ts
index 44bc78147..93cdceaa9 100644
--- a/src/web/src/hooks/community/community-ws/projection-transaction.ts
+++ b/src/web/src/hooks/community/community-ws/projection-transaction.ts
@@ -25,7 +25,7 @@ export type CommunityWsProjectionTransaction = {
type PendingInvalidation = {
filters: InvalidateQueryFilters
cancellation?: Promise<void>
- replacementOptions?: FetchQueryOptions
+ replacementOptions?: FetchQueryOptions[]
}
function createProjectionTransaction(
@@ -46,10 +46,9 @@ function createProjectionTransaction(
const identity = hashKey([owner, filters])
const current = pending.get(identity)
if (current?.cancellation) return
- const query = queryClient.getQueryCache().findAll(filters)[0]
- const replacementOptions = query
- ? { ...query.options, staleTime: 0 } as FetchQueryOptions
- : undefined
+ const replacementOptions = queryClient.getQueryCache().findAll(filters)
+ .filter((query) => query.isActive() && query.options.queryFn)
+ .map((query) => ({ ...query.options, staleTime: 0 } as FetchQueryOptions))
const cancellation = queryClient.cancelQueries(filters)
if (current) {
current.cancellation = cancellation
@@ -68,15 +67,15 @@ function createProjectionTransaction(
...filters,
refetchType: "none",
})
- if (replacementOptions) {
- await queryClient.fetchQuery(replacementOptions)
+ if (replacementOptions?.length) {
+ await Promise.all(replacementOptions.map((options) => queryClient.fetchQuery(options)))
} else {
await queryClient.refetchQueries({
...filters,
- type: "all",
+ type: "active",
})
}
- })
+ }).catch(() => {})
} else {
void queryClient.invalidateQueries(filters)
}
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.ts
index adfd1f252..bf22a22c5 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
@@ -23,6 +23,60 @@ import {
resetHookMemoization,
} from "./test-harness"
+function forumFeedFixture(rows: Array<{ id: string; opener: string; tags: string[] }>) {
+ return {
+ pages: [{
+ serverId: "s1",
+ parentType: "forum",
+ threads: rows.map((row) => ({
+ id: row.id,
+ name: row.id,
+ creatorId: `author_${row.id}`,
+ messageCount: 1,
+ parentMessageId: row.opener,
+ lastMessageAt: "2026-09-05T00:00:00.000Z",
+ createdAt: "2026-09-05T00:00:00.000Z",
+ activityAt: "2026-09-05T00:00:00.000Z",
+ })),
+ included: {
+ parentMessages: rows.map((row, index) => ({
+ id: row.opener,
+ channelId: "forum_1",
+ seq: index + 1,
+ content: row.id,
+ authorId: `author_${row.id}`,
+ authorName: row.id,
+ authorImage: null,
+ authorAvatarVersion: 0,
+ })),
+ firstMessages: rows.map((row) => ({
+ channelId: row.id,
+ content: `body ${row.id}`,
+ })),
+ tags: rows.flatMap((row) => row.tags.map((tag) => ({
+ messageId: row.opener,
+ tag,
+ }))),
+ participants: rows.map((row) => ({
+ channelId: row.id,
+ userId: `author_${row.id}`,
+ userName: row.id,
+ userImage: null,
+ userAvatarVersion: 0,
+ })),
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ }
+}
+
+function forumFeedIds(filter: string | null) {
+ return capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(
+ communityKeys.forumFeed("forum_1", filter),
+ )?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) ?? []
+}
+
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
@@ -493,9 +547,86 @@ describe("useCommunityWs — child_create patches parent thread badge with count
changes: { tags: ["archived"] },
} satisfies CommunityChildChannelUpdate)
- for (const key of [allFeed, archivedFeed, tags, messages]) {
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- }
+ await vi.waitFor(() => {
+ for (const key of [allFeed, archivedFeed, tags, messages]) {
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ }
+ })
+ })
+
+ it("projects remote Archive out of warm All and ordinary feeds synchronously", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", null),
+ forumFeedFixture([{ id: "post_1", opener: "opener_1", tags: ["bug"] }]),
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", "bug"),
+ forumFeedFixture([{ id: "post_1", opener: "opener_1", tags: ["bug"] }]),
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", "archived"),
+ forumFeedFixture([]),
+ )
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "post_1",
+ changes: { tags: ["bug", "archived"] },
+ } satisfies CommunityChildChannelUpdate)
+
+ expect(forumFeedIds(null)).toEqual([])
+ expect(forumFeedIds("bug")).toEqual([])
+ expect(forumFeedIds("archived")).toEqual([])
+ })
+
+ it("projects remote Unarchive out of Archived without inventing an All rank", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", "archived"),
+ forumFeedFixture([{
+ id: "post_1",
+ opener: "opener_1",
+ tags: ["bug", "archived"],
+ }]),
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", null),
+ forumFeedFixture([]),
+ )
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "post_1",
+ changes: { tags: ["bug"] },
+ } satisfies CommunityChildChannelUpdate)
+
+ expect(forumFeedIds("archived")).toEqual([])
+ expect(forumFeedIds(null)).toEqual([])
+ })
+
+ it("leaves warm feeds untouched when parent and child resolve conflicting openers", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", null),
+ forumFeedFixture([{ id: "post_1", opener: "opener_one", tags: ["bug"] }]),
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumFeed("forum_1", "bug"),
+ forumFeedFixture([{ id: "post_1", opener: "opener_two", tags: ["bug"] }]),
+ )
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "post_1",
+ changes: { tags: ["bug", "archived"] },
+ } satisfies CommunityChildChannelUpdate)
+
+ expect(forumFeedIds(null)).toEqual(["post_1"])
+ expect(forumFeedIds("bug")).toEqual(["post_1"])
})
it("archive-tag updates evict only the sidebar projection and keep the active route", async () => {
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.ts
index ef817d747..d88d9d70a 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
@@ -47,6 +47,7 @@ import {
invalidateThreads,
} from "./invalidation-projections"
import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
+import { projectForumFeedWsTags } from "@/hooks/community/forum-feed-tag-transition"
export function handleChildChannelCreate(
event: CommunityChildChannelCreate,
@@ -134,6 +135,14 @@ export function handleChildChannelUpdate(
// indicator if the update carries them.
const changes = event.changes
if (changes.tags !== undefined) {
+ projection.fence("threads", {
+ queryKey: communityKeys.threads(event.parentChannelId),
+ })
+ projection.project(() => projectForumFeedWsTags(queryClient, {
+ forumChannelId: event.parentChannelId,
+ threadId: event.channelId,
+ tags: changes.tags ?? [],
+ }))
invalidateChannelMessages(projection, event.parentChannelId)
projection.invalidate("forum-post-tags", {
queryKey: communityKeys.forumTags(event.parentChannelId),
diff --git a/src/web/src/hooks/community/forum-feed-tag-transition.test.ts b/src/web/src/hooks/community/forum-feed-tag-transition.test.ts
new file mode 100644
index 000000000..d34e79434
--- /dev/null
+++ b/src/web/src/hooks/community/forum-feed-tag-transition.test.ts
@@ -0,0 +1,464 @@
+import { describe, expect, it, vi } from "vitest"
+import { QueryClient, QueryObserver, type InfiniteData } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { mapForumFeedPages, type ForumFeedPage } from "./use-forum-feed"
+import {
+ beginForumFeedTagTransition,
+ commitForumFeedTagTransition,
+ forumFeedMatchesTags,
+ hasForumFeedTagTransition,
+ projectForumFeedWsTags,
+ projectForumThreadsThroughActiveTagTransitions,
+ rollbackForumFeedTagTransition,
+} from "./forum-feed-tag-transition"
+
+type FeedData = InfiniteData<ForumFeedPage, string | null>
+
+function thread(id: string, openerMessageId = `opener_${id}`) {
+ return {
+ id,
+ name: id,
+ creatorId: `author_${id}`,
+ messageCount: 1,
+ parentMessageId: openerMessageId,
+ lastMessageAt: "2026-09-05T00:00:00.000Z",
+ createdAt: "2026-09-05T00:00:00.000Z",
+ activityAt: "2026-09-05T00:00:00.000Z",
+ }
+}
+
+function feed(
+ rows: Array<{ id: string; opener?: string; tags?: string[] }>,
+ pageParam: string | null = null,
+): FeedData {
+ return {
+ pages: [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: rows.map((row) => thread(row.id, row.opener)),
+ included: {
+ parentMessages: rows.map((row, index) => ({
+ id: row.opener ?? `opener_${row.id}`,
+ channelId: "forum_1",
+ seq: index + 1,
+ content: row.id,
+ authorId: `author_${row.id}`,
+ authorName: row.id,
+ authorImage: null,
+ authorAvatarVersion: 0,
+ })),
+ firstMessages: rows.map((row) => ({ channelId: row.id, content: `body ${row.id}` })),
+ tags: rows.flatMap((row) => (row.tags ?? []).map((tag) => ({
+ messageId: row.opener ?? `opener_${row.id}`,
+ tag,
+ }))),
+ participants: rows.map((row) => ({
+ channelId: row.id,
+ userId: `author_${row.id}`,
+ userName: row.id,
+ userImage: null,
+ userAvatarVersion: 0,
+ })),
+ },
+ hasMore: false,
+ }],
+ pageParams: [pageParam],
+ }
+}
+
+function ids(queryClient: QueryClient, filter: string | null) {
+ return queryClient.getQueryData<FeedData>(communityKeys.forumFeed("forum_1", filter))
+ ?.pages.flatMap((page) => page.threads.map((row) => row.id)) ?? []
+}
+
+function start(
+ queryClient: QueryClient,
+ previousTags: string[],
+ tags: string[],
+ openerMessageId = "opener_target",
+) {
+ return beginForumFeedTagTransition(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ openerMessageId,
+ previousTags,
+ tags,
+ })!
+}
+
+describe("forum feed tag transition owner", () => {
+ it("matches the authoritative All, ordinary, and Archived partitions", () => {
+ expect(forumFeedMatchesTags(null, ["bug"])).toBe(true)
+ expect(forumFeedMatchesTags("bug", ["bug"])).toBe(true)
+ expect(forumFeedMatchesTags("help", ["bug"])).toBe(false)
+ expect(forumFeedMatchesTags(null, ["bug", "archived"])).toBe(false)
+ expect(forumFeedMatchesTags("bug", ["bug", "archived"])).toBe(false)
+ expect(forumFeedMatchesTags("archived", ["bug", "archived"])).toBe(true)
+ })
+
+ it("removes Archive and Unarchive source rows without inserting a destination rank", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "archived"), feed([]))
+
+ const archive = start(queryClient, ["bug"], ["bug", "archived"])
+ expect(ids(queryClient, null)).toEqual([])
+ expect(ids(queryClient, "bug")).toEqual([])
+ expect(ids(queryClient, "archived")).toEqual([])
+ commitForumFeedTagTransition(queryClient, archive, ["bug", "archived"])
+ expect(ids(queryClient, "archived")).toEqual([])
+
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "archived"), feed([
+ { id: "target", tags: ["bug", "archived"] },
+ ]))
+ const unarchive = start(queryClient, ["bug", "archived"], ["bug"])
+ expect(ids(queryClient, "archived")).toEqual([])
+ commitForumFeedTagTransition(queryClient, unarchive, ["bug"])
+ expect(ids(queryClient, null)).toEqual([])
+ expect(ids(queryClient, "bug")).toEqual([])
+ })
+
+ it("patches authoritative tags on an already warm destination row", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "archived"), feed([
+ { id: "target", tags: ["archived"] },
+ ]))
+
+ const token = start(queryClient, ["bug"], ["bug", "archived"])
+ commitForumFeedTagTransition(queryClient, token, [" BUG ", "archived", "bug"])
+
+ const archived = queryClient.getQueryData<FeedData>(
+ communityKeys.forumFeed("forum_1", "archived"),
+ )!
+ expect(archived.pages[0]!.included.tags).toEqual([
+ { messageId: "opener_target", tag: "bug" },
+ { messageId: "opener_target", tag: "archived" },
+ ])
+ })
+
+ it("merges only the removed exact slice and preserves concurrent siblings", () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ queryClient.setQueryData(key, feed([
+ { id: "target", tags: ["bug"] },
+ { id: "sibling", tags: ["keep"] },
+ ]))
+ const token = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(key, feed([
+ { id: "sibling", tags: ["keep"] },
+ { id: "concurrent", tags: ["new"] },
+ ]))
+
+ expect(rollbackForumFeedTagTransition(queryClient, token)).toBe(true)
+ expect(ids(queryClient, null)).toEqual(["target", "sibling", "concurrent"])
+ const restored = queryClient.getQueryData<FeedData>(key)!.pages[0].included
+ expect(restored.parentMessages.map((row) => row.id)).toEqual([
+ "opener_target",
+ "opener_sibling",
+ "opener_concurrent",
+ ])
+ expect(restored.tags).toContainEqual({ messageId: "opener_target", tag: "bug" })
+ })
+
+ it("prevents an older generation from rolling back a newer exact intent", () => {
+ const queryClient = new QueryClient()
+ const archivedKey = communityKeys.forumFeed("forum_1", "archived")
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ const older = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(archivedKey, feed([
+ { id: "target", tags: ["bug", "archived"] },
+ ]))
+ const newer = start(queryClient, ["bug", "archived"], ["bug"])
+
+ expect(rollbackForumFeedTagTransition(queryClient, older)).toBe(false)
+ expect(hasForumFeedTagTransition(queryClient, newer)).toBe(true)
+ expect(ids(queryClient, "archived")).toEqual([])
+ expect(rollbackForumFeedTagTransition(queryClient, newer)).toBe(true)
+ expect(ids(queryClient, "archived")).toEqual(["target"])
+ })
+
+ it("carries the exact rollback slice into a repeated programmatic intent", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ const older = start(queryClient, ["bug"], ["bug", "archived"])
+ const newer = start(queryClient, ["bug"], ["bug", "archived"])
+
+ expect(rollbackForumFeedTagTransition(queryClient, older)).toBe(false)
+ expect(rollbackForumFeedTagTransition(queryClient, newer)).toBe(true)
+ expect(ids(queryClient, null)).toEqual(["target"])
+ })
+
+ it("restores an authoritative non-archive response into its moved cursor page", () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ const other = feed([{ id: "other", tags: ["keep"] }], "other_cursor")
+ const target = feed([{ id: "target", tags: ["bug"] }], "target_cursor")
+ queryClient.setQueryData<FeedData>(key, {
+ pages: [other.pages[0]!, target.pages[0]!],
+ pageParams: ["other_cursor", "target_cursor"],
+ })
+
+ const token = start(queryClient, ["bug"], ["bug", "archived"])
+ const movedTargetPage = feed([], "target_cursor")
+ queryClient.setQueryData<FeedData>(key, {
+ pages: [movedTargetPage.pages[0]!, other.pages[0]!],
+ pageParams: ["target_cursor", "other_cursor"],
+ })
+
+ commitForumFeedTagTransition(queryClient, token, [" BUG ", "bug"])
+
+ const restored = queryClient.getQueryData<FeedData>(key)!
+ expect(restored.pages[0]!.threads.map((row) => row.id)).toEqual(["target"])
+ expect(restored.pages[0]!.included.tags).toEqual([
+ { messageId: "opener_target", tag: "bug" },
+ ])
+ expect(ids(queryClient, null)).toEqual(["target", "other"])
+ expect(hasForumFeedTagTransition(queryClient, token)).toBe(false)
+ })
+
+ it("ignores non-partition cache keys and skips restore after cursor replacement", () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ queryClient.setQueryData(communityKeys.forumFeeds("forum_1"), feed([
+ { id: "unscoped", tags: ["bug"] },
+ ]))
+ queryClient.setQueryData(key, feed([
+ { id: "target", tags: ["bug"] },
+ ], "target_cursor"))
+
+ const token = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(key, feed([], "replacement_cursor"))
+
+ expect(rollbackForumFeedTagTransition(queryClient, token)).toBe(true)
+ expect(ids(queryClient, null)).toEqual([])
+ })
+
+ it("ignores an older success while a newer exact generation is active", () => {
+ const queryClient = new QueryClient()
+ const archivedKey = communityKeys.forumFeed("forum_1", "archived")
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", tags: ["bug"] },
+ ]))
+ const older = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(archivedKey, feed([
+ { id: "target", tags: ["bug", "archived"] },
+ ]))
+ const newer = start(queryClient, ["bug", "archived"], ["bug"])
+
+ commitForumFeedTagTransition(queryClient, older, ["bug", "archived"])
+
+ expect(hasForumFeedTagTransition(queryClient, newer)).toBe(true)
+ expect(ids(queryClient, "archived")).toEqual([])
+ })
+
+ it("settles different posts independently", () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ queryClient.setQueryData(key, feed([
+ { id: "target", tags: ["bug"] },
+ { id: "other", tags: ["help"] },
+ ]))
+ const target = start(queryClient, ["bug"], ["bug", "archived"])
+ const other = beginForumFeedTagTransition(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "other",
+ openerMessageId: "opener_other",
+ previousTags: ["help"],
+ tags: ["help", "archived"],
+ })!
+
+ expect(ids(queryClient, null)).toEqual([])
+ rollbackForumFeedTagTransition(queryClient, target)
+ expect(ids(queryClient, null)).toEqual(["target"])
+ expect(hasForumFeedTagTransition(queryClient, other)).toBe(true)
+ commitForumFeedTagTransition(queryClient, other, ["help", "archived"])
+ expect(ids(queryClient, null)).toEqual(["target"])
+ })
+
+ it("requires the local cached opener and never hides a reused child identity", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([
+ { id: "target", opener: "opener_new", tags: ["bug"] },
+ ]))
+ const token = start(queryClient, ["bug"], ["bug", "archived"], "opener_old")
+
+ expect(ids(queryClient, null)).toEqual(["target"])
+ const projected = projectForumThreadsThroughActiveTagTransitions(
+ queryClient,
+ "forum_1",
+ null,
+ mapForumFeedPages(queryClient.getQueryData<FeedData>(
+ communityKeys.forumFeed("forum_1", null),
+ )!.pages),
+ )
+ expect(projected.map((post) => post.id)).toEqual(["target"])
+ expect(rollbackForumFeedTagTransition(queryClient, token)).toBe(true)
+ })
+
+ it("projects WS membership only with one consistent cached opener", () => {
+ const queryClient = new QueryClient()
+ const allKey = communityKeys.forumFeed("forum_1", null)
+ queryClient.setQueryData(allKey, feed([{ id: "target", tags: ["bug"] }]))
+ expect(projectForumFeedWsTags(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ tags: ["bug", "archived"],
+ })).toBe(true)
+ expect(ids(queryClient, null)).toEqual([])
+
+ queryClient.setQueryData(allKey, feed([
+ { id: "target", opener: "opener_one", tags: ["bug"] },
+ ]))
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), feed([
+ { id: "target", opener: "opener_two", tags: ["bug"] },
+ ]))
+ expect(projectForumFeedWsTags(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ tags: ["bug", "archived"],
+ })).toBe(false)
+ expect(ids(queryClient, null)).toEqual(["target"])
+ expect(ids(queryClient, "bug")).toEqual(["target"])
+ })
+
+ it("falls back to refetch when a cached child has no valid opener evidence", () => {
+ const queryClient = new QueryClient()
+ const invalid = feed([{ id: "target", tags: ["bug"] }])
+ invalid.pages[0]!.threads[0]!.parentMessageId = null
+ invalid.pages[0]!.included.parentMessages = []
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), invalid)
+
+ expect(projectForumFeedWsTags(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ tags: ["bug", "archived"],
+ })).toBe(false)
+ expect(ids(queryClient, null)).toEqual(["target"])
+ })
+
+ it("keeps a newer local intent visually dominant over an intervening WS frame", () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ const stale = feed([{ id: "target", tags: ["bug"] }])
+ queryClient.setQueryData(key, stale)
+ const token = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(key, stale)
+
+ expect(projectForumFeedWsTags(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ tags: ["bug"],
+ })).toBe(true)
+ const projected = projectForumThreadsThroughActiveTagTransitions(
+ queryClient,
+ "forum_1",
+ null,
+ mapForumFeedPages(stale.pages),
+ )
+ expect(projected).toEqual([])
+ expect(hasForumFeedTagTransition(queryClient, token)).toBe(true)
+ })
+
+ it("removes a WS Unarchive from Archived without inserting into All", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", "archived"), feed([
+ { id: "target", tags: ["archived"] },
+ ]))
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), feed([]))
+
+ expect(projectForumFeedWsTags(queryClient, {
+ forumChannelId: "forum_1",
+ threadId: "target",
+ tags: [],
+ })).toBe(true)
+ expect(ids(queryClient, "archived")).toEqual([])
+ expect(ids(queryClient, null)).toEqual([])
+ })
+
+ it("keeps every success notification frame removed across generation clear", async () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ const initial = feed([{ id: "target", tags: ["bug"] }])
+ queryClient.setQueryData(key, initial)
+ let token: ReturnType<typeof start> | null = null
+ const frames: Array<{ active: boolean; ids: string[] }> = []
+ const observer = new QueryObserver<FeedData>(queryClient, {
+ queryKey: key,
+ enabled: false,
+ select: (data) => ({
+ ...data,
+ pages: [{
+ ...data.pages[0]!,
+ threads: projectForumThreadsThroughActiveTagTransitions(
+ queryClient,
+ "forum_1",
+ null,
+ mapForumFeedPages(data.pages),
+ ).map((post) => thread(post.id, post.openerMessageId)),
+ }],
+ }),
+ })
+ const unsubscribe = observer.subscribe((result) => {
+ frames.push({
+ active: token ? hasForumFeedTagTransition(queryClient, token) : false,
+ ids: result.data?.pages.flatMap((page) => page.threads.map((row) => row.id)) ?? [],
+ })
+ })
+ token = start(queryClient, ["bug"], ["bug", "archived"])
+ queryClient.setQueryData(key, initial)
+ commitForumFeedTagTransition(queryClient, token, ["bug", "archived"])
+ await vi.waitFor(() => expect(hasForumFeedTagTransition(queryClient, token!)).toBe(false))
+ unsubscribe()
+
+ const afterRemoval = frames.slice(frames.findIndex((frame) => frame.ids.length === 0))
+ expect(afterRemoval.length).toBeGreaterThan(0)
+ expect(afterRemoval.every((frame) => !frame.ids.includes("target"))).toBe(true)
+ expect(ids(queryClient, null)).toEqual([])
+ })
+
+ it("publishes rollback membership and generation clear in the same terminal frame", async () => {
+ const queryClient = new QueryClient()
+ const key = communityKeys.forumFeed("forum_1", null)
+ queryClient.setQueryData(key, feed([{ id: "target", tags: ["bug"] }]))
+ let token: ReturnType<typeof start> | null = null
+ const frames: Array<{ active: boolean; ids: string[] }> = []
+ const observer = new QueryObserver<FeedData, Error, string[]>(queryClient, {
+ queryKey: key,
+ enabled: false,
+ select: (data) => projectForumThreadsThroughActiveTagTransitions(
+ queryClient,
+ "forum_1",
+ null,
+ mapForumFeedPages(data.pages),
+ ).map((post) => post.id),
+ })
+ const unsubscribe = observer.subscribe((result) => {
+ frames.push({
+ active: token ? hasForumFeedTagTransition(queryClient, token) : false,
+ ids: result.data ?? [],
+ })
+ })
+ token = start(queryClient, ["bug"], ["bug", "archived"])
+ const rollbackFrameIndex = frames.length
+ rollbackForumFeedTagTransition(queryClient, token)
+ unsubscribe()
+
+ expect(frames.slice(rollbackFrameIndex).every((frame) => (
+ frame.ids.includes("target")
+ ))).toBe(true)
+ expect(hasForumFeedTagTransition(queryClient, token)).toBe(false)
+ expect(ids(queryClient, null)).toEqual(["target"])
+ })
+})
diff --git a/src/web/src/hooks/community/forum-feed-tag-transition.ts b/src/web/src/hooks/community/forum-feed-tag-transition.ts
new file mode 100644
index 000000000..8ae5f6197
--- /dev/null
+++ b/src/web/src/hooks/community/forum-feed-tag-transition.ts
@@ -0,0 +1,610 @@
+import { FORUM_ARCHIVE_TAG } from "@alook/shared"
+import {
+ hashKey,
+ notifyManager,
+ type InfiniteData,
+ type QueryClient,
+ type QueryKey,
+} from "@tanstack/react-query"
+import type { ForumThread } from "@/lib/community/models/message"
+import { communityKeys } from "@/lib/query-keys"
+
+type ForumFeedThread = {
+ id: string
+ name: string | null
+ creatorId: string | null
+ messageCount: number | null
+ parentMessageId: string | null
+ lastMessageAt: string | null
+ createdAt: string
+ activityAt: string
+}
+
+type ForumIncludedMessage = {
+ id: string
+ channelId: string
+ seq: number
+ createdAt?: string
+ content: string
+ authorId: string
+ authorName: string
+ authorImage: string | null
+ authorAvatarVersion: number
+}
+
+type ForumIncludedFirstMessage = { channelId: string; content: string }
+type ForumIncludedTag = { messageId: string; tag: string }
+type ForumIncludedParticipant = {
+ channelId: string
+ userId: string
+ userName: string | null
+ userImage: string | null
+ userAvatarVersion: number
+ participantCount?: number
+}
+
+export type ForumFeedPage = {
+ serverId: string
+ parentType: string
+ threads: ForumFeedThread[]
+ included: {
+ parentMessages: ForumIncludedMessage[]
+ firstMessages: ForumIncludedFirstMessage[]
+ tags: ForumIncludedTag[]
+ participants: ForumIncludedParticipant[]
+ }
+ hasMore: boolean
+ nextCursor?: string
+}
+
+type FeedData = InfiniteData<ForumFeedPage>
+type FeedThread = ForumFeedPage["threads"][number]
+type ParentMessage = ForumFeedPage["included"]["parentMessages"][number]
+type FirstMessage = ForumFeedPage["included"]["firstMessages"][number]
+type IncludedTag = ForumFeedPage["included"]["tags"][number]
+type Participant = ForumFeedPage["included"]["participants"][number]
+
+type Indexed<T> = { index: number; value: T }
+
+type PageSlice = {
+ pageIndex: number
+ pageParam: unknown
+ thread: Indexed<FeedThread>
+ parentMessages: Indexed<ParentMessage>[]
+ firstMessages: Indexed<FirstMessage>[]
+ tags: Indexed<IncludedTag>[]
+ participants: Indexed<Participant>[]
+}
+
+type QuerySlice = {
+ queryKey: QueryKey
+ pages: PageSlice[]
+}
+
+type TransitionRecord = {
+ generation: number
+ forumChannelId: string
+ threadId: string
+ openerMessageId: string
+ previousTags: string[]
+ tags: string[]
+ slices: QuerySlice[]
+}
+
+type TransitionOwner = {
+ nextGeneration: number
+ current: Map<string, TransitionRecord>
+}
+
+export type ForumFeedTagTransitionToken = Pick<
+ TransitionRecord,
+ "generation" | "forumChannelId" | "threadId" | "openerMessageId"
+>
+
+const owners = new WeakMap<QueryClient, TransitionOwner>()
+
+function transitionKey(forumChannelId: string, threadId: string) {
+ return hashKey([forumChannelId, threadId])
+}
+
+function getOwner(queryClient: QueryClient) {
+ let owner = owners.get(queryClient)
+ if (!owner) {
+ owner = { nextGeneration: 0, current: new Map() }
+ owners.set(queryClient, owner)
+ }
+ return owner
+}
+
+function getCurrent(
+ queryClient: QueryClient,
+ forumChannelId: string,
+ threadId: string,
+) {
+ return owners.get(queryClient)?.current.get(transitionKey(forumChannelId, threadId))
+}
+
+function normalizedTags(tags: readonly string[]) {
+ return [...new Set(tags.map((tag) => tag.trim().toLowerCase()).filter(Boolean))]
+}
+
+function includesArchived(tags: readonly string[]) {
+ return tags.includes(FORUM_ARCHIVE_TAG)
+}
+
+function sameTags(a: readonly string[], b: readonly string[]) {
+ return a.length === b.length && a.every((tag) => b.includes(tag))
+}
+
+export function forumFeedMatchesTags(filter: string | null, tags: readonly string[]) {
+ const archived = includesArchived(tags)
+ if (filter === FORUM_ARCHIVE_TAG) return archived
+ if (archived) return false
+ return filter === null || tags.includes(filter)
+}
+
+function startsWithQueryKey(queryKey: QueryKey, prefix: QueryKey) {
+ return prefix.length <= queryKey.length
+ && hashKey(queryKey.slice(0, prefix.length)) === hashKey(prefix)
+}
+
+function forumFeedFilter(queryKey: QueryKey, forumChannelId: string) {
+ const prefix = communityKeys.forumFeeds(forumChannelId)
+ if (!startsWithQueryKey(queryKey, prefix) || queryKey.length !== prefix.length + 1) {
+ return undefined
+ }
+ const filter = queryKey[prefix.length]
+ return filter === null || typeof filter === "string" ? filter : undefined
+}
+
+function indexed<T>(values: readonly T[], predicate: (value: T) => boolean) {
+ const result: Indexed<T>[] = []
+ values.forEach((value, index) => {
+ if (predicate(value)) result.push({ index, value })
+ })
+ return result
+}
+
+function validThreadOpener(page: ForumFeedPage, thread: FeedThread, openerMessageId: string) {
+ return thread.parentMessageId === openerMessageId
+ && page.included.parentMessages.some((message) => message.id === openerMessageId)
+}
+
+function extractPageSlice(
+ page: ForumFeedPage,
+ pageIndex: number,
+ pageParam: unknown,
+ threadId: string,
+ openerMessageId: string,
+): PageSlice | null {
+ const threadIndex = page.threads.findIndex((thread) => thread.id === threadId)
+ if (threadIndex < 0) return null
+ const thread = page.threads[threadIndex]!
+ if (!validThreadOpener(page, thread, openerMessageId)) return null
+ return {
+ pageIndex,
+ pageParam,
+ thread: { index: threadIndex, value: thread },
+ parentMessages: indexed(
+ page.included.parentMessages,
+ (message) => message.id === openerMessageId,
+ ),
+ firstMessages: indexed(
+ page.included.firstMessages,
+ (message) => message.channelId === threadId,
+ ),
+ tags: indexed(
+ page.included.tags,
+ (tag) => tag.messageId === openerMessageId,
+ ),
+ participants: indexed(
+ page.included.participants,
+ (participant) => participant.channelId === threadId,
+ ),
+ }
+}
+
+function extractQuerySlice(
+ queryKey: QueryKey,
+ data: FeedData,
+ threadId: string,
+ openerMessageId: string,
+) {
+ const pages = data.pages.flatMap((page, pageIndex) => {
+ const slice = extractPageSlice(
+ page,
+ pageIndex,
+ data.pageParams[pageIndex] ?? null,
+ threadId,
+ openerMessageId,
+ )
+ return slice ? [slice] : []
+ })
+ return pages.length > 0 ? { queryKey, pages } : null
+}
+
+function removeForumPostFromFeedByIdentity(
+ data: FeedData | undefined,
+ childChannelId: string,
+ openerMessageId: string,
+ matches: (thread: FeedThread) => boolean,
+): FeedData | undefined {
+ if (!data) return data
+ let touched = false
+ const pages = data.pages.map((page) => {
+ if (!page.threads.some(matches)) return page
+ touched = true
+ return {
+ ...page,
+ threads: page.threads.filter((thread) => !matches(thread)),
+ included: {
+ parentMessages: page.included.parentMessages.filter(
+ (message) => message.id !== openerMessageId,
+ ),
+ firstMessages: page.included.firstMessages.filter(
+ (message) => message.channelId !== childChannelId,
+ ),
+ tags: page.included.tags.filter(
+ (tag) => tag.messageId !== openerMessageId,
+ ),
+ participants: page.included.participants.filter(
+ (participant) => participant.channelId !== childChannelId,
+ ),
+ },
+ }
+ })
+ return touched ? { ...data, pages } : data
+}
+
+/** Remove a post unit by either canonical identity for the delete path. */
+export function removeForumPostFromFeed(
+ data: FeedData | undefined,
+ childChannelId: string,
+ openerMessageId: string,
+): FeedData | undefined {
+ return removeForumPostFromFeedByIdentity(
+ data,
+ childChannelId,
+ openerMessageId,
+ (thread) => thread.id === childChannelId || thread.parentMessageId === openerMessageId,
+ )
+}
+
+function removeExactForumPostFromFeed(
+ data: FeedData | undefined,
+ childChannelId: string,
+ openerMessageId: string,
+) {
+ return removeForumPostFromFeedByIdentity(
+ data,
+ childChannelId,
+ openerMessageId,
+ (thread) => thread.id === childChannelId && thread.parentMessageId === openerMessageId,
+ )
+}
+
+function insertAt<T>(values: readonly T[], additions: readonly Indexed<T>[]) {
+ const result = [...values]
+ for (const addition of [...additions].sort((a, b) => a.index - b.index)) {
+ result.splice(Math.min(addition.index, result.length), 0, addition.value)
+ }
+ return result
+}
+
+function mergeUniqueAt<T>(
+ values: readonly T[],
+ additions: readonly Indexed<T>[],
+ identity: (value: T) => string,
+) {
+ const existing = new Set(values.map(identity))
+ return insertAt(values, additions.filter(({ value }) => !existing.has(identity(value))))
+}
+
+function matchingPageIndex(data: FeedData, slice: PageSlice) {
+ if (hashKey([data.pageParams[slice.pageIndex] ?? null]) === hashKey([slice.pageParam])) {
+ return slice.pageIndex
+ }
+ return data.pageParams.findIndex((pageParam) => (
+ hashKey([pageParam ?? null]) === hashKey([slice.pageParam])
+ ))
+}
+
+function mergePageSlice(
+ data: FeedData | undefined,
+ slice: PageSlice,
+ threadId: string,
+ openerMessageId: string,
+) {
+ if (!data) return data
+ const existing = data.pages.flatMap((page) => page.threads)
+ .find((thread) => thread.id === threadId || thread.parentMessageId === openerMessageId)
+ if (existing) return data
+ const pageIndex = matchingPageIndex(data, slice)
+ if (pageIndex < 0 || !slice.parentMessages.some(({ value }) => value.id === openerMessageId)) {
+ return data
+ }
+ const page = data.pages[pageIndex]!
+ const pages = [...data.pages]
+ pages[pageIndex] = {
+ ...page,
+ threads: insertAt(page.threads, [slice.thread]),
+ included: {
+ parentMessages: mergeUniqueAt(
+ page.included.parentMessages,
+ slice.parentMessages,
+ (message) => message.id,
+ ),
+ firstMessages: mergeUniqueAt(
+ page.included.firstMessages,
+ slice.firstMessages,
+ (message) => message.channelId,
+ ),
+ tags: mergeUniqueAt(
+ page.included.tags,
+ slice.tags,
+ (tag) => `${tag.messageId}\u0000${tag.tag}`,
+ ),
+ participants: mergeUniqueAt(
+ page.included.participants,
+ slice.participants,
+ (participant) => `${participant.channelId}\u0000${participant.userId}`,
+ ),
+ },
+ }
+ return { ...data, pages }
+}
+
+function patchTagsForExistingPost(
+ data: FeedData | undefined,
+ threadId: string,
+ openerMessageId: string,
+ tags: readonly string[],
+) {
+ if (!data) return data
+ let touched = false
+ const pages = data.pages.map((page) => {
+ const thread = page.threads.find((candidate) => candidate.id === threadId)
+ if (!thread || !validThreadOpener(page, thread, openerMessageId)) return page
+ touched = true
+ const priorIndexes = page.included.tags.flatMap((tag, index) => (
+ tag.messageId === openerMessageId ? [index] : []
+ ))
+ const insertionIndex = priorIndexes[0] ?? page.included.tags.length
+ const withoutTarget = page.included.tags.filter((tag) => tag.messageId !== openerMessageId)
+ const nextRows = tags.map((tag, index) => ({
+ index: insertionIndex + index,
+ value: { messageId: openerMessageId, tag },
+ }))
+ return {
+ ...page,
+ included: {
+ ...page.included,
+ tags: insertAt(withoutTarget, nextRows),
+ },
+ }
+ })
+ return touched ? { ...data, pages } : data
+}
+
+function cachedTags(page: ForumFeedPage, openerMessageId: string) {
+ return page.included.tags
+ .filter((tag) => tag.messageId === openerMessageId)
+ .map((tag) => tag.tag)
+}
+
+function resolveWsOpener(
+ queryClient: QueryClient,
+ forumChannelId: string,
+ threadId: string,
+) {
+ const active = getCurrent(queryClient, forumChannelId, threadId)
+ const openers = new Set<string>()
+ let invalid = false
+ for (const [, data] of queryClient.getQueriesData<FeedData>({
+ queryKey: communityKeys.forumFeeds(forumChannelId),
+ })) {
+ for (const page of data?.pages ?? []) {
+ const thread = page.threads.find((candidate) => candidate.id === threadId)
+ if (!thread) continue
+ const opener = thread.parentMessageId
+ if (!opener || !validThreadOpener(page, thread, opener)) {
+ invalid = true
+ continue
+ }
+ openers.add(opener)
+ }
+ }
+ if (active) {
+ if (invalid || [...openers].some((opener) => opener !== active.openerMessageId)) return null
+ return active.openerMessageId
+ }
+ if (invalid || openers.size !== 1) return null
+ return [...openers][0]!
+}
+
+function projectTags(
+ queryClient: QueryClient,
+ input: {
+ forumChannelId: string
+ threadId: string
+ openerMessageId: string
+ tags: readonly string[]
+ },
+ source: "local" | "ws",
+) {
+ const tags = normalizedTags(input.tags)
+ for (const [queryKey, data] of queryClient.getQueriesData<FeedData>({
+ queryKey: communityKeys.forumFeeds(input.forumChannelId),
+ })) {
+ const filter = forumFeedFilter(queryKey, input.forumChannelId)
+ if (filter === undefined || !data) continue
+ const page = data.pages.find((candidate) => candidate.threads.some((thread) => (
+ thread.id === input.threadId && thread.parentMessageId === input.openerMessageId
+ )))
+ if (!page) continue
+ if (source === "ws" && includesArchived(cachedTags(page, input.openerMessageId)) === includesArchived(tags)) {
+ continue
+ }
+ queryClient.setQueryData<FeedData>(queryKey, (current) => (
+ forumFeedMatchesTags(filter, tags)
+ ? patchTagsForExistingPost(current, input.threadId, input.openerMessageId, tags)
+ : removeExactForumPostFromFeed(current, input.threadId, input.openerMessageId)
+ ))
+ }
+ return tags
+}
+
+export function beginForumFeedTagTransition(
+ queryClient: QueryClient,
+ input: {
+ forumChannelId: string
+ threadId: string
+ openerMessageId: string
+ previousTags: readonly string[]
+ tags: readonly string[]
+ },
+): ForumFeedTagTransitionToken | null {
+ const previousTags = normalizedTags(input.previousTags)
+ const tags = normalizedTags(input.tags)
+ if (includesArchived(previousTags) === includesArchived(tags)) return null
+ const owner = getOwner(queryClient)
+ const key = transitionKey(input.forumChannelId, input.threadId)
+ const prior = owner.current.get(key)
+ const inheritedSlices = prior
+ && prior.openerMessageId === input.openerMessageId
+ && sameTags(prior.previousTags, previousTags)
+ && sameTags(prior.tags, tags)
+ ? prior.slices
+ : []
+ const record: TransitionRecord = {
+ generation: ++owner.nextGeneration,
+ forumChannelId: input.forumChannelId,
+ threadId: input.threadId,
+ openerMessageId: input.openerMessageId,
+ previousTags,
+ tags,
+ slices: [...inheritedSlices],
+ }
+ owner.current.set(key, record)
+ for (const [queryKey, data] of queryClient.getQueriesData<FeedData>({
+ queryKey: communityKeys.forumFeeds(input.forumChannelId),
+ })) {
+ const filter = forumFeedFilter(queryKey, input.forumChannelId)
+ if (filter === undefined || !data || forumFeedMatchesTags(filter, tags)) continue
+ const slice = extractQuerySlice(queryKey, data, input.threadId, input.openerMessageId)
+ if (!slice) continue
+ if (!record.slices.some((saved) => hashKey(saved.queryKey) === hashKey(queryKey))) {
+ record.slices.push(slice)
+ }
+ queryClient.setQueryData<FeedData>(queryKey, (current) => removeExactForumPostFromFeed(
+ current,
+ input.threadId,
+ input.openerMessageId,
+ ))
+ }
+ return {
+ generation: record.generation,
+ forumChannelId: record.forumChannelId,
+ threadId: record.threadId,
+ openerMessageId: record.openerMessageId,
+ }
+}
+
+function isCurrent(record: TransitionRecord | undefined, token: ForumFeedTagTransitionToken) {
+ return record?.generation === token.generation
+ && record.openerMessageId === token.openerMessageId
+}
+
+export function commitForumFeedTagTransition(
+ queryClient: QueryClient,
+ token: ForumFeedTagTransitionToken,
+ tags: readonly string[],
+) {
+ const owner = getOwner(queryClient)
+ const key = transitionKey(token.forumChannelId, token.threadId)
+ const record = owner.current.get(key)
+ if (!record || !isCurrent(record, token)) return
+ notifyManager.batch(() => {
+ record.tags = normalizedTags(tags)
+ const authoritativeTags = projectTags(queryClient, {
+ forumChannelId: token.forumChannelId,
+ threadId: token.threadId,
+ openerMessageId: token.openerMessageId,
+ tags: record.tags,
+ }, "local")
+ for (const querySlice of record.slices) {
+ const filter = forumFeedFilter(querySlice.queryKey, token.forumChannelId)
+ if (filter === undefined || !forumFeedMatchesTags(filter, authoritativeTags)) continue
+ queryClient.setQueryData<FeedData>(querySlice.queryKey, (current) => {
+ let next = current
+ for (const slice of querySlice.pages) {
+ next = mergePageSlice(next, slice, token.threadId, token.openerMessageId)
+ }
+ return patchTagsForExistingPost(
+ next,
+ token.threadId,
+ token.openerMessageId,
+ authoritativeTags,
+ )
+ })
+ }
+ owner.current.delete(key)
+ })
+}
+
+export function rollbackForumFeedTagTransition(
+ queryClient: QueryClient,
+ token: ForumFeedTagTransitionToken,
+) {
+ const owner = getOwner(queryClient)
+ const key = transitionKey(token.forumChannelId, token.threadId)
+ const record = owner.current.get(key)
+ if (!record || !isCurrent(record, token)) return false
+ notifyManager.batch(() => {
+ record.tags = record.previousTags
+ for (const querySlice of record.slices) {
+ queryClient.setQueryData<FeedData>(querySlice.queryKey, (current) => {
+ let next = current
+ for (const slice of querySlice.pages) {
+ next = mergePageSlice(next, slice, token.threadId, token.openerMessageId)
+ }
+ return next
+ })
+ }
+ owner.current.delete(key)
+ })
+ return true
+}
+
+export function projectForumFeedWsTags(
+ queryClient: QueryClient,
+ input: { forumChannelId: string; threadId: string; tags: readonly string[] },
+) {
+ const openerMessageId = resolveWsOpener(queryClient, input.forumChannelId, input.threadId)
+ if (!openerMessageId) return false
+ projectTags(queryClient, { ...input, openerMessageId }, "ws")
+ return true
+}
+
+export function projectForumThreadsThroughActiveTagTransitions(
+ queryClient: QueryClient,
+ forumChannelId: string,
+ filter: string | null,
+ posts: readonly ForumThread[],
+) {
+ return posts.filter((post) => {
+ const record = getCurrent(queryClient, forumChannelId, post.id)
+ if (!record || record.openerMessageId !== post.openerMessageId) return true
+ return forumFeedMatchesTags(filter, record.tags)
+ })
+}
+
+export function hasForumFeedTagTransition(
+ queryClient: QueryClient,
+ token: ForumFeedTagTransitionToken,
+) {
+ return isCurrent(
+ getCurrent(queryClient, token.forumChannelId, token.threadId),
+ token,
+ )
+}
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index 1e2a1ea8b..6b66d88a0 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -51,8 +51,8 @@ async function runMutation<Args>(args: Args) {
const cfg = capturedConfig as MutConfig<Args>
const context = cfg.onMutate ? await cfg.onMutate(args) : undefined
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
- cfg.onSuccess?.(data, args, context)
- cfg.onSettled?.(data, null, args, context)
+ await cfg.onSuccess?.(data, args, context)
+ await cfg.onSettled?.(data, null, args, context)
return data
}
@@ -61,12 +61,12 @@ async function runMutationExpectError<Args>(args: Args) {
const context = cfg.onMutate ? await cfg.onMutate(args) : undefined
try {
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
- cfg.onSuccess?.(data, args, context)
- cfg.onSettled?.(data, null, args, context)
+ await cfg.onSuccess?.(data, args, context)
+ await cfg.onSettled?.(data, null, args, context)
throw new Error("expected mutationFn to reject")
} catch (err) {
- cfg.onError?.(err, args, context)
- cfg.onSettled?.(undefined, err, args, context)
+ await cfg.onError?.(err, args, context)
+ await cfg.onSettled?.(undefined, err, args, context)
return err
}
}
@@ -155,6 +155,59 @@ describe("useCreateForumThread", () => {
})
describe("useUpdatePostTags", () => {
+ const forumFeed = (
+ rows: Array<{ id: string; opener?: string; tags?: string[] }>,
+ ) => ({
+ pages: [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: rows.map((row) => ({
+ id: row.id,
+ name: row.id,
+ creatorId: `author_${row.id}`,
+ messageCount: 1,
+ parentMessageId: row.opener ?? `opener_${row.id}`,
+ lastMessageAt: "2026-09-05T00:00:00.000Z",
+ createdAt: "2026-09-05T00:00:00.000Z",
+ activityAt: "2026-09-05T00:00:00.000Z",
+ })),
+ included: {
+ parentMessages: rows.map((row, index) => ({
+ id: row.opener ?? `opener_${row.id}`,
+ channelId: "forum_1",
+ seq: index + 1,
+ content: row.id,
+ authorId: `author_${row.id}`,
+ authorName: row.id,
+ authorImage: null,
+ authorAvatarVersion: 0,
+ })),
+ firstMessages: rows.map((row) => ({
+ channelId: row.id,
+ content: `body ${row.id}`,
+ })),
+ tags: rows.flatMap((row) => (row.tags ?? []).map((tag) => ({
+ messageId: row.opener ?? `opener_${row.id}`,
+ tag,
+ }))),
+ participants: rows.map((row) => ({
+ channelId: row.id,
+ userId: `author_${row.id}`,
+ userName: row.id,
+ userImage: null,
+ userAvatarVersion: 0,
+ })),
+ },
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ const forumFeedIds = (key: ReturnType<typeof communityKeys.forumFeed>) => (
+ capturedQc.getQueryData<ReturnType<typeof forumFeed>>(key)
+ ?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) ?? []
+ )
+
const sidebar = (ids: string[]) => ({
threads: ids.map((id) => ({
id,
@@ -203,6 +256,113 @@ describe("useUpdatePostTags", () => {
expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(true)
})
+ it("removes the exact row before the archive PUT settles", async () => {
+ const { useUpdatePostTags } = await load()
+ useUpdatePostTags()
+ const key = communityKeys.forumFeed("forum_1", null)
+ capturedQc.setQueryData(key, forumFeed([
+ { id: "before", tags: ["bug"] },
+ { id: "p2", tags: ["bug"] },
+ { id: "after", tags: ["bug"] },
+ ]))
+ let release!: (value: { tags: string[] }) => void
+ apiFetchMock.mockReturnValueOnce(new Promise((resolve) => {
+ release = resolve
+ }))
+ const args = {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "opener_p2",
+ previousTags: ["bug"],
+ tags: ["bug", "archived"],
+ }
+ const cfg = capturedConfig as MutConfig<typeof args>
+ const context = await cfg.onMutate!(args)
+ const request = cfg.mutationFn!(args)
+
+ expect(forumFeedIds(key)).toEqual(["before", "after"])
+ release({ tags: ["bug", "archived"] })
+ const data = await request
+ await cfg.onSuccess!(data, args, context)
+ expect(forumFeedIds(key)).toEqual(["before", "after"])
+ })
+
+ it("restores only the failed generation slice while preserving concurrent siblings", async () => {
+ const { useUpdatePostTags } = await load()
+ useUpdatePostTags()
+ const key = communityKeys.forumFeed("forum_1", null)
+ capturedQc.setQueryData(key, forumFeed([
+ { id: "before", tags: ["bug"] },
+ { id: "p2", tags: ["bug"] },
+ { id: "after", tags: ["bug"] },
+ ]))
+ const args = {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "opener_p2",
+ previousTags: ["bug"],
+ tags: ["bug", "archived"],
+ }
+ const cfg = capturedConfig as MutConfig<typeof args>
+ const context = await cfg.onMutate!(args)
+ capturedQc.setQueryData(key, forumFeed([
+ { id: "before", tags: ["updated"] },
+ { id: "after", tags: ["bug"] },
+ { id: "concurrent", tags: ["new"] },
+ ]))
+
+ await cfg.onError!(new Error("403"), args, context)
+
+ expect(forumFeedIds(key)).toEqual(["before", "p2", "after", "concurrent"])
+ const tags = capturedQc.getQueryData<ReturnType<typeof forumFeed>>(key)!
+ .pages[0].included.tags
+ expect(tags).toContainEqual({ messageId: "opener_before", tag: "updated" })
+ expect(tags).toContainEqual({ messageId: "opener_p2", tag: "bug" })
+ })
+
+ it("does not let an older failure undo a newer archive intent", async () => {
+ const { useUpdatePostTags } = await load()
+ useUpdatePostTags()
+ const allKey = communityKeys.forumFeed("forum_1", null)
+ const archivedKey = communityKeys.forumFeed("forum_1", "archived")
+ capturedQc.setQueryData(allKey, forumFeed([{ id: "p2", tags: ["bug"] }]))
+ const cfg = capturedConfig as MutConfig<{
+ serverId: string
+ forumChannelId: string
+ threadId: string
+ openerMessageId: string
+ previousTags: string[]
+ tags: string[]
+ }>
+ const olderArgs = {
+ serverId: "server_1",
+ forumChannelId: "forum_1",
+ threadId: "p2",
+ openerMessageId: "opener_p2",
+ previousTags: ["bug"],
+ tags: ["bug", "archived"],
+ }
+ const older = await cfg.onMutate!(olderArgs)
+ capturedQc.setQueryData(archivedKey, forumFeed([
+ { id: "p2", tags: ["bug", "archived"] },
+ ]))
+ const newerArgs = {
+ ...olderArgs,
+ previousTags: ["bug", "archived"],
+ tags: ["bug"],
+ }
+ const newer = await cfg.onMutate!(newerArgs)
+
+ await cfg.onError!(new Error("older failed"), olderArgs, older)
+ expect(forumFeedIds(allKey)).toEqual([])
+ expect(forumFeedIds(archivedKey)).toEqual([])
+
+ await cfg.onError!(new Error("newer failed"), newerArgs, newer)
+ expect(forumFeedIds(archivedKey)).toEqual(["p2"])
+ })
+
it("evicts only the archived sidebar projection after the successful PUT", async () => {
const { useUpdatePostTags } = await load()
useUpdatePostTags()
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 7de9d259a..e63ecba02 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -21,6 +21,12 @@ import {
evictForumPostUnitQueryCaches,
type ForumPostUnitIdentity,
} from "@/hooks/community/community-ws/channel-scope-projection"
+import {
+ beginForumFeedTagTransition,
+ commitForumFeedTagTransition,
+ rollbackForumFeedTagTransition,
+ type ForumFeedTagTransitionToken,
+} from "@/hooks/community/forum-feed-tag-transition"
export type CreateForumThreadArgs = {
nonce: string
@@ -78,6 +84,14 @@ export type UpdatePostTagsArgs = {
tags: string[]
}
+type UpdatePostTagsContext = {
+ transition: ForumFeedTagTransitionToken | null
+}
+
+function hasArchiveTag(tags: readonly string[]) {
+ return tags.some((tag) => tag.trim().toLowerCase() === FORUM_ARCHIVE_TAG)
+}
+
/**
* Edit a single forum post's tags. PUTs the opener-message tag resource (author or manager
* gated server-side), then patches the post's row in the forum's cached list so
@@ -85,7 +99,7 @@ export type UpdatePostTagsArgs = {
*/
export function useUpdatePostTags() {
const queryClient = useQueryClient()
- return useMutation<{ tags: string[] }, Error, UpdatePostTagsArgs>({
+ return useMutation<{ tags: string[] }, Error, UpdatePostTagsArgs, UpdatePostTagsContext>({
mutationFn: async ({ openerMessageId, tags }) => {
const normalized = [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))]
const result = await apiFetch<{ tags: string[] }>(`/api/community/messages/${openerMessageId}/tags`, {
@@ -96,9 +110,37 @@ export function useUpdatePostTags() {
tags: [...new Set(result.tags.map((tag) => tag.trim().toLowerCase()).filter(Boolean))],
}
},
- onSuccess: (data, args) => {
- const wasArchived = args.previousTags.includes(FORUM_ARCHIVE_TAG)
- const isArchived = data.tags.includes(FORUM_ARCHIVE_TAG)
+ onMutate: async (args) => {
+ if (hasArchiveTag(args.previousTags) === hasArchiveTag(args.tags)) {
+ return { transition: null }
+ }
+ const cancellation = queryClient.cancelQueries({
+ queryKey: communityKeys.forumFeeds(args.forumChannelId),
+ })
+ const transition = beginForumFeedTagTransition(queryClient, args)
+ await cancellation
+ return { transition }
+ },
+ onError: async (_error, args, context) => {
+ if (!context?.transition) return
+ await queryClient.cancelQueries({
+ queryKey: communityKeys.forumFeeds(args.forumChannelId),
+ })
+ if (rollbackForumFeedTagTransition(queryClient, context.transition)) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.forumFeeds(args.forumChannelId),
+ })
+ }
+ },
+ onSuccess: async (data, args, context) => {
+ if (context?.transition) {
+ await queryClient.cancelQueries({
+ queryKey: communityKeys.forumFeeds(args.forumChannelId),
+ })
+ commitForumFeedTagTransition(queryClient, context.transition, data.tags)
+ }
+ const wasArchived = hasArchiveTag(args.previousTags)
+ const isArchived = hasArchiveTag(data.tags)
if (wasArchived !== isArchived) {
void reconcileForumSidebarArchiveTag(
queryClient,
diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.ts
index 9c33ee7ae..9c3432de3 100644
--- a/src/web/src/hooks/community/use-forum-feed.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.test.ts
@@ -1,15 +1,27 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { communityKeys } from "@/lib/query-keys"
const apiFetchMock = vi.fn()
+const useForumTagsMock = vi.fn(() => ({
+ data: { tags: ["bug"] },
+ isSuccess: true,
+}))
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+vi.mock("./use-channel-panels", () => ({
+ useForumTags: (...args: unknown[]) => useForumTagsMock(...args),
+}))
import {
forumFeedPageQueryFn,
mapForumFeedPages,
removeForumPostFromFeed,
+ useForumFeed,
type ForumFeedPage,
} from "./use-forum-feed"
@@ -48,6 +60,21 @@ describe("forumFeedPageQueryFn", () => {
expect(new URL(url, "http://localhost").searchParams.get("tag")).toBe("archived")
})
+ it("passes the query abort signal through to the request", async () => {
+ apiFetchMock.mockResolvedValue({ threads: [], included: emptyIncluded, hasMore: false })
+ const controller = new AbortController()
+
+ await forumFeedPageQueryFn("forum_one", null)({
+ pageParam: null,
+ signal: controller.signal,
+ })
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ expect.stringContaining("/api/community/channels/forum_one/threads?"),
+ { signal: controller.signal },
+ )
+ })
+
it("seeds opener and participant profiles while returning the raw page", async () => {
const page = {
threads: [],
@@ -261,3 +288,42 @@ describe("mapForumFeedPages", () => {
expect(mapForumFeedPages(pages).map((thread) => thread.id)).toEqual(expectedIds)
})
})
+
+describe("useForumFeed", () => {
+ it("projects the cached page through the owning query client", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ })
+ queryClient.setQueryData(communityKeys.forumFeed("forum_one", null), {
+ pages: [{
+ serverId: "server_one",
+ parentType: "forum",
+ threads: [],
+ included: emptyIncluded,
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+ let result: ReturnType<typeof useForumFeed> | undefined
+ function Probe() {
+ result = useForumFeed("server_one", "forum_one")
+ return null
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe),
+ ),
+ )
+ })
+
+ expect(useForumTagsMock).toHaveBeenCalledWith("forum_one", true)
+ expect(result?.tag).toBe("All")
+ expect(result?.posts).toEqual([])
+ act(() => renderer.unmount())
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index a6b30ac7a..e9abcf7e2 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -1,7 +1,7 @@
"use client"
import { useCallback, useEffect, useMemo, useState } from "react"
-import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"
+import { useInfiniteQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query"
import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"
import { apiFetchProfiles } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
@@ -10,94 +10,16 @@ import { canonicalUserImage } from "@/lib/community/storage"
import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
import type { ForumThread } from "@/lib/community/models/message"
import { useForumTags } from "./use-channel-panels"
+import {
+ projectForumThreadsThroughActiveTagTransitions,
+ type ForumFeedPage,
+} from "./forum-feed-tag-transition"
-type FeedThread = {
- 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
- seq: number
- createdAt?: string
- content: string
- authorId: string
- authorName: string
- authorImage: string | null
- authorAvatarVersion: number
-}
-
-type IncludedFirstMessage = { channelId: string; content: string }
-type IncludedTag = { messageId: string; tag: string }
-type IncludedParticipant = {
- channelId: string
- userId: string
- userName: string | null
- userImage: string | null
- userAvatarVersion: number
- participantCount?: number
-}
-
-export type ForumFeedPage = {
- serverId: string
- parentType: string
- threads: FeedThread[]
- included: {
- parentMessages: IncludedMessage[]
- firstMessages: IncludedFirstMessage[]
- tags: IncludedTag[]
- participants: IncludedParticipant[]
- }
- hasMore: boolean
- nextCursor?: string
-}
-
-/** Remove one canonical forum post and every included row owned by its unit. */
-export function removeForumPostFromFeed(
- data: InfiniteData<ForumFeedPage> | undefined,
- childChannelId: string,
- openerMessageId: string,
-): InfiniteData<ForumFeedPage> | undefined {
- if (!data) return data
- let touched = false
- const pages = data.pages.map((page) => {
- if (!page.threads.some((thread) => (
- thread.id === childChannelId || thread.parentMessageId === openerMessageId
- ))) return page
- touched = true
- return {
- ...page,
- threads: page.threads.filter((thread) => (
- thread.id !== childChannelId && thread.parentMessageId !== openerMessageId
- )),
- included: {
- parentMessages: page.included.parentMessages.filter(
- (message) => message.id !== openerMessageId,
- ),
- firstMessages: page.included.firstMessages.filter(
- (message) => message.channelId !== childChannelId,
- ),
- tags: page.included.tags.filter(
- (tag) => tag.messageId !== openerMessageId,
- ),
- participants: page.included.participants.filter(
- (participant) => participant.channelId !== childChannelId,
- ),
- },
- }
- })
- return touched ? { ...data, pages } : data
-}
+export { removeForumPostFromFeed } from "./forum-feed-tag-transition"
+export type { ForumFeedPage } from "./forum-feed-tag-transition"
export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
- return ({ pageParam }: { pageParam: string | null }) => {
+ return ({ pageParam, signal }: { pageParam: string | null; signal?: AbortSignal }) => {
const params = new URLSearchParams({
order: "createdAt",
limit: String(DEFAULT_MESSAGE_PAGE_SIZE),
@@ -135,6 +57,7 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
},
})),
],
+ signal ? { signal } : undefined,
)
}
}
@@ -203,6 +126,7 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
}
export function useForumFeed(_serverId: string, channelId: string) {
+ const queryClient = useQueryClient()
const [tag, setTag] = useState(() => {
if (typeof window === "undefined") return "All"
try { return readForumTagSelection(window.localStorage, channelId) }
@@ -234,8 +158,13 @@ export function useForumFeed(_serverId: string, channelId: string) {
getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
})
const posts = useMemo(
- () => mapForumFeedPages(query.data?.pages ?? []),
- [query.data?.pages],
+ () => projectForumThreadsThroughActiveTagTransitions(
+ queryClient,
+ channelId,
+ selectedTag,
+ mapForumFeedPages(query.data?.pages ?? []),
+ ),
+ [channelId, query.data?.pages, queryClient, selectedTag],
)
return {
diff --git a/src/web/src/lib/community/forum-tag-operations.test.ts b/src/web/src/lib/community/forum-tag-operations.test.ts
index c50625c5d..aeb999e9a 100644
--- a/src/web/src/lib/community/forum-tag-operations.test.ts
+++ b/src/web/src/lib/community/forum-tag-operations.test.ts
@@ -205,6 +205,40 @@ describe("forum tag operations", () => {
}))
})
+ it("returns after the D1 write without waiting for background fanout", async () => {
+ mockListTags.mockResolvedValue(["keep"])
+ let releaseFanout!: () => void
+ mockFanOut.mockReturnValueOnce(new Promise<void>((resolve) => {
+ releaseFanout = resolve
+ }))
+
+ const result = await Promise.race([
+ replaceForumTagsForActor({} as any, {
+ messageId: "m1",
+ userId: "bot1",
+ tags: ["keep", "new"],
+ }),
+ new Promise<"timed-out">((resolve) => setTimeout(() => resolve("timed-out"), 50)),
+ ])
+ releaseFanout()
+
+ expect(result).toEqual({ ok: true, value: { tags: ["keep", "new"], changed: true } })
+ expect(mockReplaceTags).toHaveBeenCalledOnce()
+ expect(mockFanOut).toHaveBeenCalledOnce()
+ })
+
+ it("does not schedule fanout when the authoritative D1 write fails", async () => {
+ mockListTags.mockResolvedValue(["keep"])
+ mockReplaceTags.mockRejectedValueOnce(new Error("D1 unavailable"))
+
+ await expect(replaceForumTagsForActor({} as any, {
+ messageId: "m1",
+ userId: "bot1",
+ tags: ["keep", "new"],
+ })).rejects.toThrow("D1 unavailable")
+ expect(mockFanOut).not.toHaveBeenCalled()
+ })
+
it("publishes a real removal and lists the caller-visible tags in stable order", async () => {
mockListTags
.mockResolvedValueOnce(["keep", "old"])
diff --git a/src/web/src/lib/community/forum-tag-operations.ts b/src/web/src/lib/community/forum-tag-operations.ts
index f62163f46..12e89c394 100644
--- a/src/web/src/lib/community/forum-tag-operations.ts
+++ b/src/web/src/lib/community/forum-tag-operations.ts
@@ -85,7 +85,7 @@ async function replaceAuthorizedTags(
messageId: target.message.id,
tags,
})
- await fanOutToChannel(target.message.channelId, {
+ void fanOutToChannel(target.message.channelId, {
type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
parentChannelId: target.message.channelId,
channelId: target.threadId,
@@ -149,7 +149,7 @@ export async function mutateForumTagsForActor(
}
const tags = (await queries.communityMessageTag.listTagsForMessage(db, input.messageId)).sort()
- await fanOutToChannel(target.value.message.channelId, {
+ void fanOutToChannel(target.value.message.channelId, {
type: WS_EVENTS.CHILD_CHANNEL_UPDATE,
parentChannelId: target.value.message.channelId,
channelId: target.value.threadId,
diff --git a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
index 5a99e1263..26f0d335a 100644
--- a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
+++ b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
@@ -13,6 +13,47 @@ function observeTagPuts(page: Page): string[] {
return writes
}
+async function gateNextTagPut(page: Page) {
+ let release!: () => void
+ let sawRequest!: () => void
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const requested = new Promise<void>((resolve) => {
+ sawRequest = resolve
+ })
+ await page.route("**/api/community/messages/*/tags", async (routeRequest) => {
+ const response = await routeRequest.fetch()
+ sawRequest()
+ await gate
+ await routeRequest.fulfill({ response })
+ }, { times: 1 })
+ return { release, requested }
+}
+
+async function gateNextForumFeedResponse(page: Page) {
+ let release!: () => void
+ let sawResponse!: () => void
+ let finished!: () => void
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const captured = new Promise<void>((resolve) => {
+ sawResponse = resolve
+ })
+ const delivered = new Promise<void>((resolve) => {
+ finished = resolve
+ })
+ await page.route(/\/api\/community\/channels\/[^/]+\/threads\?/, async (routeRequest) => {
+ const response = await routeRequest.fetch()
+ sawResponse()
+ await gate
+ await routeRequest.fulfill({ response }).catch(() => undefined)
+ finished()
+ }, { times: 1 })
+ return { release, captured, delivered }
+}
+
async function seedForum(label: string) {
const serverId = await seedServer("alice", `${label} ${Date.now()}`)
const forumId = await seedChannel("alice", serverId, "tag-editor", "forum")
@@ -64,6 +105,8 @@ test.describe.serial("forum tag editor", () => {
const card = page.getByTestId(tid.forumThreadCard(threadId))
await expect(card.getByText("#kept", { exact: true })).toBeVisible()
+ await page.getByTestId(tid.forumTagChip("kept")).click()
+ await expect(card).toBeVisible()
await card.hover()
const archiveButton = page.getByTestId(tid.forumThreadArchiveBtn(threadId))
await expect(archiveButton).toHaveAttribute("aria-label", "Archive post")
@@ -72,11 +115,15 @@ test.describe.serial("forum tag editor", () => {
body: await page.screenshot(),
contentType: "image/png",
})
+ const archiveGate = await gateNextTagPut(page)
const archivedSave = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname.endsWith("/tags")
))
await archiveButton.click()
+ await archiveGate.requested
+ await expect(card).toHaveCount(0)
+ archiveGate.release()
const archivedResponse = await archivedSave
expect(archivedResponse.status()).toBe(200)
expect((archivedResponse.request().postDataJSON() as { tags: string[] }).tags)
@@ -115,11 +162,15 @@ test.describe.serial("forum tag editor", () => {
contentType: "image/png",
})
await page.emulateMedia({ colorScheme: "light" })
+ const unarchiveGate = await gateNextTagPut(page)
const restoredSave = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname.endsWith("/tags")
))
await unarchiveButton.click()
+ await unarchiveGate.requested
+ await expect(card).toHaveCount(0)
+ unarchiveGate.release()
const restoredResponse = await restoredSave
expect(restoredResponse.status()).toBe(200)
expect([...(restoredResponse.request().postDataJSON() as { tags: string[] }).tags].sort())
@@ -132,6 +183,84 @@ test.describe.serial("forum tag editor", () => {
expect(writes).toHaveLength(4)
})
+ test("keeps a cancelled stale feed response behind the active archive generation", async ({ asUser }) => {
+ const { route, threadId } = await seedForum("Archive stale feed fence")
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 1280, height: 900 })
+ await gotoAfterUserWsAuth(page, route)
+ const card = page.getByTestId(tid.forumThreadCard(threadId))
+ await expect(card).toBeVisible()
+
+ const staleFeed = await gateNextForumFeedResponse(page)
+ await openEditor(page, threadId)
+ await addDraft(page, "stale-source")
+ const ordinarySave = page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname.endsWith("/tags")
+ ))
+ await page.keyboard.press("Escape")
+ expect((await ordinarySave).status()).toBe(200)
+ await staleFeed.captured
+
+ await card.hover()
+ const archiveResponse = page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname.endsWith("/tags")
+ ))
+ await page.getByTestId(tid.forumThreadArchiveBtn(threadId)).click()
+ await expect(card).toHaveCount(0)
+
+ staleFeed.release()
+ await staleFeed.delivered
+ await expect(card).toHaveCount(0)
+
+ expect((await archiveResponse).status()).toBe(200)
+ await expect(card).toHaveCount(0)
+ })
+
+ test("converges Archive and Unarchive across two tabs", async ({ asUser }) => {
+ const { route, threadId } = await seedForum("Archive cross tab")
+ const tabA = await asUser("alice")
+ const tabB = await asUser("alice")
+ await Promise.all([
+ gotoAfterUserWsAuth(tabA.page, route),
+ gotoAfterUserWsAuth(tabB.page, route),
+ ])
+ const cardA = tabA.page.getByTestId(tid.forumThreadCard(threadId))
+ const cardB = tabB.page.getByTestId(tid.forumThreadCard(threadId))
+ await expect(cardA).toBeVisible()
+ await expect(cardB).toBeVisible()
+
+ await cardA.hover()
+ const archived = tabA.page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname.endsWith("/tags")
+ ))
+ await tabA.page.getByTestId(tid.forumThreadArchiveBtn(threadId)).click()
+ expect((await archived).status()).toBe(200)
+ await expect(cardB).toHaveCount(0)
+
+ await expect(tabA.page.getByTestId(tid.forumTagChip("archived"))).toBeVisible()
+ await expect(tabB.page.getByTestId(tid.forumTagChip("archived"))).toBeVisible()
+ await tabA.page.getByTestId(tid.forumTagChip("archived")).click()
+ await tabB.page.getByTestId(tid.forumTagChip("archived")).click()
+ await expect(cardA).toBeVisible()
+ await expect(cardB).toBeVisible()
+
+ await cardB.hover()
+ const unarchived = tabB.page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname.endsWith("/tags")
+ ))
+ await tabB.page.getByTestId(tid.forumThreadArchiveBtn(threadId)).click()
+ expect((await unarchived).status()).toBe(200)
+ await expect(cardA).toHaveCount(0)
+
+ await tabA.page.getByTestId(tid.forumTagAll).click()
+ await expect(cardA).toBeVisible()
+ await expect(tabA.page.getByTestId(tid.forumThreadCard(threadId))).toHaveCount(1)
+ })
+
test("discards implicit close and commits only explicit Save", async ({ asUser }) => {
const { route, threadId } = await seedForum("Mobile explicit save")
const { page } = await asUser("alice")
@@ -187,12 +316,17 @@ test.describe.serial("forum tag editor", () => {
const writes = observeTagPuts(page)
let rejectNext = true
let releaseFailure!: () => void
+ let sawFailureRequest!: () => void
const failureGate = new Promise<void>((resolve) => {
releaseFailure = resolve
})
+ const failureRequested = new Promise<void>((resolve) => {
+ sawFailureRequest = resolve
+ })
await page.route("**/api/community/messages/*/tags", async (routeRequest) => {
if (rejectNext) {
rejectNext = false
+ sawFailureRequest()
await failureGate
await routeRequest.fulfill({
status: 500,
@@ -212,22 +346,25 @@ test.describe.serial("forum tag editor", () => {
&& new URL(response.url()).pathname.endsWith("/tags")
))
await archiveButton.click()
- await expect(archiveButton).toBeDisabled()
- expect(writes).toHaveLength(1)
- await archiveButton.evaluate((button: HTMLButtonElement) => button.click())
+ await failureRequested
+ await expect(page.getByTestId(tid.forumThreadCard(threadId))).toHaveCount(0)
expect(writes).toHaveLength(1)
releaseFailure()
expect((await failed).status()).toBe(500)
await expect(page.getByText("archive retry", { exact: true })).toBeVisible()
- await expect(archiveButton).toBeEnabled()
- await expect(archiveButton).toHaveAttribute("aria-pressed", "false")
+ const restoredCard = page.getByTestId(tid.forumThreadCard(threadId))
+ await expect(restoredCard).toBeVisible()
+ await restoredCard.hover()
+ const restoredArchiveButton = page.getByTestId(tid.forumThreadArchiveBtn(threadId))
+ await expect(restoredArchiveButton).toBeEnabled()
+ await expect(restoredArchiveButton).toHaveAttribute("aria-pressed", "false")
const retried = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname.endsWith("/tags")
&& response.status() === 200
))
- await archiveButton.click()
+ await restoredArchiveButton.click()
const retriedResponse = await retried
expect((retriedResponse.request().postDataJSON() as { tags: string[] }).tags)
.toEqual(["archived"])