Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): requalify revoked conversation routes on re-entry (#891)

Gener9b5970f797ac
diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
index 7fda08d59..a2546a8f9 100644
--- a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
@@ -1,5 +1,5 @@
import React from "react"
-import { } from "@/test/react-dom-harness"
+import { setupUser } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { DmView } from "@/components/community/channels/dm-view"
@@ -16,7 +16,8 @@ const {
} = vi.hoisted(() => ({
mockDismissConversation: vi.fn(),
mockCommitRoute: vi.fn(),
- mockHistory: { allowed: true, denied: false, error: null as Error | null, retry: vi.fn() },
+ mockHistory: { allowed: true, denied: false, error: null as Error | null, retry: vi.fn(),
+ status: "readable", revoked: false, retryingMetadata: false, retryMetadata: vi.fn() },
mockBlocked: [] as Array<{ userId: string }>,
mockNavigationGate: { allowed: true, failed: false, retry: vi.fn() },
mockDms: {
@@ -58,7 +59,9 @@ vi.mock("@/components/community/channels/conversation-resolution-error-frame", (
ConversationResolutionErrorFrame: ({ onRetry }: { onRetry: () => void }) => React.createElement("button", { onClick: onRetry, "data-testid": "history-error" }, "Retry"),
}))
vi.mock("@/hooks/community/use-channel-metadata", () => ({
- useChannelMetadata: () => ({ canRead: mockHistory.allowed, denied: mockHistory.denied, data: { readProof: mockHistory.allowed ? {} : undefined } }),
+ useChannelMetadata: () => ({ canRead: mockHistory.allowed, denied: mockHistory.denied,
+ status: mockHistory.status, revoked: mockHistory.revoked, retry: mockHistory.retryMetadata, retrying: mockHistory.retryingMetadata,
+ data: { readProof: mockHistory.allowed ? {} : undefined } }),
}))
vi.mock("@/lib/community/conversation-navigation-proof", async (importOriginal) => ({
...await importOriginal<typeof import("@/lib/community/conversation-navigation-proof")>(),
@@ -179,6 +182,10 @@ describe("DM notification dismissal readiness", () => {
mockHistory.allowed = true
mockHistory.denied = false
mockHistory.error = null
+ mockHistory.status = "readable"
+ mockHistory.revoked = false
+ mockHistory.retryingMetadata = false
+ mockHistory.retryMetadata.mockClear()
mockHistory.retry.mockClear()
mockBlocked.length = 0
mockNavigationGate.allowed = true
@@ -215,6 +222,32 @@ describe("DM notification dismissal readiness", () => {
else expect(mockCommitRoute).not.toHaveBeenCalled()
})
+ it.each(["pending", "failed"] as const)("uses protected metadata Retry for a known revoked DM despite %s navigation and an old position error", async (navigation) => {
+ mockDms.dms = [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }]
+ mockHistory.allowed = false
+ mockHistory.revoked = true
+ mockHistory.status = "retryable-error"
+ mockHistory.error = new Error("old read failure")
+ mockDmMessages.navigationBlocked = true
+ mockNavigationGate.allowed = false
+ mockNavigationGate.failed = navigation === "failed"
+ const view = render(React.createElement(DmView, { dmId: "dm_1" }))
+ expect(view.container.querySelector('[data-testid="dm-header"]')?.textContent).toBe("Peer")
+ expect(view.container.querySelector('[data-testid="history-body"]')).toBeNull()
+ expect(view.container.querySelector('[data-testid="composer"]')).toBeNull()
+ expect(view.container.querySelector('[role="alert"]')).toBeNull()
+ expect(view.container.querySelector('[data-testid="dm-loading"]')).toBeNull()
+ await setupUser().click(view.container.querySelector<HTMLButtonElement>('[data-testid="history-error"]')!)
+ expect(mockHistory.retryMetadata).toHaveBeenCalledOnce()
+ expect(mockHistory.retry).not.toHaveBeenCalled()
+ expect(mockNavigationGate.retry).not.toHaveBeenCalled()
+ expect(mockCommitRoute).not.toHaveBeenCalled()
+ mockHistory.retryingMetadata = true
+ view.rerender(React.createElement(DmView, { dmId: "dm_1" }))
+ expect(view.container.querySelector('[data-testid="history-error"]')).not.toBeNull()
+ expect(view.container.querySelector('[data-testid="composer"]')).toBeNull()
+ })
+
it("withholds history/composer and last while read access fails, then permits the same target after retry", () => {
mockDms.dms = [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }]
mockHistory.allowed = false
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index b841612bf..a016487d7 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -10,8 +10,8 @@ describe("DM page loading ownership", () => {
expect(source).not.toContain("currentChannelMatches")
expect(source).not.toContain("readSnapshotFetching ||\n messagesLoading")
expect(source).toContain("waitForAnchor: true")
- expect(source).toContain("if (!metadata.denied && !dmBlocked && navigationBlocked)")
- expect(source).toContain("if (!metadata.denied && !dmBlocked && navigationGate.failed)")
+ expect(source).toContain("if (!metadata.revoked && !metadata.denied && !dmBlocked && navigationBlocked)")
+ expect(source).toContain("if (!metadata.revoked && !metadata.denied && !dmBlocked && navigationGate.failed)")
expect(source).toContain("if (loadingOwnership.fullFramePending)")
expect(source).toContain("<DmHeader\n")
expect(source).toContain("<Composer\n")
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 34ba634c3..9d2076036 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -135,7 +135,7 @@ export function DmView({ dmId }: { dmId: string }) {
// the "New" divider AND the initial-page mode. Mirrors the channel-view
// wiring so both surfaces open with the same anchor-window UX.
const { snapshot: readSnapshot, isFetching: readSnapshotFetching, error: readError, retry: retryRead, retrying: retryingRead } =
- useDmReadStateSnapshot(metadata.denied || dmBlocked ? null : dmId)
+ useDmReadStateSnapshot(metadata.revoked || metadata.denied || dmBlocked ? null : dmId)
// Anchor the initial page on the viewer's read pointer. Pass `undefined`
// (not `null`) while the snapshot resolves — the hook's initialPageParam
@@ -429,10 +429,10 @@ export function DmView({ dmId }: { dmId: string }) {
channelId: dmId,
}, routeReady)
- if (!metadata.denied && !dmBlocked && navigationGate.failed) {
+ if (!metadata.revoked && !metadata.denied && !dmBlocked && navigationGate.failed) {
return <ConversationResolutionErrorFrame retrying={false} onRetry={navigationGate.retry} />
}
- if (!metadata.denied && !dmBlocked && navigationBlocked) {
+ if (!metadata.revoked && !metadata.denied && !dmBlocked && navigationBlocked) {
return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />
}
@@ -461,7 +461,7 @@ export function DmView({ dmId }: { dmId: string }) {
className="flex min-h-0 flex-1 flex-col"
>
<ConversationFooterSlotProvider>
- {dmBlocked ? null : metadata.denied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : !historyAllowed && readError ? <ConversationResolutionErrorFrame as="div" onRetry={retryRead} retrying={retryingRead} /> : <MessageList
+ {dmBlocked ? null : metadata.denied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : metadata.status === "retryable-error" ? <ConversationResolutionErrorFrame as="div" onRetry={metadata.retry} retrying={metadata.retrying} /> : !historyAllowed && readError ? <ConversationResolutionErrorFrame as="div" onRetry={retryRead} retrying={retryingRead} /> : <MessageList
key={dmId}
variant="dm"
channel={dm.name}
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
index 0425bfe6b..0640fdb33 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
@@ -1,11 +1,16 @@
import "fake-indexeddb/auto"
import { createElement } from "react"
import { type QueryClient, useQueryClient, useIsRestoring } from "@tanstack/react-query"
-import { act, waitFor, render as rtlRender } from "@/test/react-dom-harness"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, waitFor, renderHook, render as rtlRender } from "@/test/react-dom-harness"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryProvider } from "@/app/c/QueryProvider"
import { communityKeys } from "@/lib/query-keys"
-import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
+import { getCanonicalCommunityChannels, retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { channelMetadataOptions, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"
+import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"
+import { getConversationNavigationProof, useConversationNavigationGate } from "@/lib/community/conversation-navigation-proof"
import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import { useShellInboxController } from "./use-shell-inbox-controller"
@@ -130,8 +135,8 @@ vi.mock("@/hooks/community/mutations", async () => {
useRejectFriendRequest: () => useRequest("reject"),
}
})
-vi.mock("@/hooks/community/use-dm-route-verification", () => ({
- startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),
+vi.mock("@/hooks/community/channel-route-verification", () => ({
+ startChannelRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),
}))
vi.mock("@/lib/community/conversation-navigation-warmup", () => ({
startConversationNavigationWarmup: (...args: unknown[]) => mocks.warmup(...args),
@@ -210,6 +215,8 @@ async function renderController(
}
}
+afterEach(() => { vi.unstubAllGlobals() })
+
describe("useShellInboxController", () => {
beforeEach(() => {
order.length = 0
@@ -377,6 +384,58 @@ describe("useShellInboxController", () => {
expect(mocks.begin).not.toHaveBeenCalled()
})
+ it("joins protected re-entry before proof capture through the real Inbox warmup, push and afterPush chain", async () => {
+ const actualWarmup = await vi.importActual<typeof import("@/lib/community/conversation-navigation-warmup")>("@/lib/community/conversation-navigation-warmup")
+ const actualVerifier = await vi.importActual<typeof import("@/hooks/community/channel-route-verification")>("@/hooks/community/channel-route-verification")
+ mocks.warmup.mockImplementation(actualWarmup.startConversationNavigationWarmup)
+ mocks.verifyDm.mockImplementation(actualVerifier.startChannelRouteVerification)
+ const metadata = { id: "dm1", serverId: null, type: "dm", name: null,
+ parentChannelId: null, parentMessageId: null, creatorId: null, archived: false,
+ lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
+ const json = (value: unknown) => new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } })
+ const requests: Array<{ path: string; signal: AbortSignal; resolve: (value: Response) => void }> = []
+ let held = false
+ vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => !held
+ ? Promise.resolve(json(metadata))
+ : new Promise<Response>((resolve) => requests.push({ path, signal: options.signal!, resolve }))))
+ const hook = await renderController()
+ const registry = getCommunityDbRegistry(hook.queryClient)!
+ await hook.queryClient.query(channelMetadataOptions(hook.queryClient, null, "dm1"))
+ const wrapper = ({ children }: React.PropsWithChildren) => createElement(CommunityTestProvider, { client: hook.queryClient, registry, retainOwner: true }, children)
+ const prior = renderHook(() => useChannelMetadata(null, "dm1"), { wrapper })
+ const oldProof = prior.result.current.data!.readProof!
+ act(() => retireCommunityChannelReading(registry, "dm1", { reason: "read-denied" }))
+ expect(prior.result.current.denied).toBe(true)
+ held = true
+ await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))
+ await waitFor(() => expect(requests).toHaveLength(3))
+ expect(hook.pushed).toEqual(["/c/me/dm1"])
+ expect(mocks.submitted).toHaveBeenCalledOnce()
+ expect(mocks.verifyDm).toHaveBeenCalledTimes(2)
+ expect(getConversationNavigationProof(hook.queryClient)?.status).toBe("warming")
+ expect(registry.runtime.ws.get().channelAccessScopes.get("dm1")).toMatchObject({ generation: 2, revoked: true })
+ expect(isChannelMetadataTokenCurrent(oldProof)).toBe(false)
+ const authority = requests.find((request) => new URL(request.path, "https://alook.test").pathname === "/api/community/channels/dm1")!
+ const resource = hook.queryClient.getQueryCache().find({ queryKey: communityKeys.channelMeta(null, "dm1"), exact: true })!
+ prior.unmount()
+ expect(resource.getObserversCount()).toBe(2)
+ expect(authority.signal.aborted).toBe(false)
+ const current = renderHook(() => ({ metadata: useChannelMetadata(null, "dm1"), gate: useConversationNavigationGate(hook.queryClient, "viewer", "dm1", 0) }), { wrapper })
+ expect(current.result.current.metadata.canRead).toBe(false)
+ expect(current.result.current.gate.allowed).toBe(false)
+ await act(async () => authority.resolve(json(metadata)))
+ await waitFor(() => expect(current.result.current.metadata.canRead).toBe(true))
+ await act(async () => {
+ requests.find((request) => request.path.includes("/read-state"))!.resolve(json({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }))
+ requests.find((request) => request.path.includes("/messages"))!.resolve(json({ messages: [], hasMore: false, surfaceReceipt: { channelId: "dm1", surfaceKind: "dm" } }))
+ })
+ await waitFor(() => expect(current.result.current.gate.allowed).toBe(true))
+ expect(registry.runtime.ws.get().channelAccessScopes.get("dm1")).toMatchObject({ generation: 2, revoked: false })
+ expect(requests).toHaveLength(3)
+ await waitFor(() => expect(resource.getObserversCount()).toBe(1))
+ current.unmount()
+ })
+
it("upserts a DM only after projection/cancel and verifies only after push", async () => {
const hook = await renderController()
order.length = 0
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index ba3240689..4e90ab44a 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -6,7 +6,7 @@ import { channelHref } from "@/lib/community/community-route"
import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import { dmSummaryFromInbox } from "@/lib/community/dm-cache"
import { useInboxAttention, useInboxMarked } from "@/hooks/community/use-inbox"
-import { startDmRouteVerification } from "@/hooks/community/use-dm-route-verification"
+import { startChannelRouteVerification } from "@/hooks/community/channel-route-verification"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
import {
inboxChannelRowTarget,
@@ -255,7 +255,7 @@ export function useShellInboxController({
publishCommunityDmSummary(queryClient, summary)
},
() => {
- void startDmRouteVerification(queryClient, dmId).catch(() => undefined)
+ void startChannelRouteVerification(queryClient, null, dmId).catch(() => undefined)
},
)
}, [pushProjected, queryClient])
diff --git a/src/web/src/hooks/community/channel-route-verification.ts b/src/web/src/hooks/community/channel-route-verification.ts
new file mode 100644
index 000000000..1fade19e1
--- /dev/null
+++ b/src/web/src/hooks/community/channel-route-verification.ts
@@ -0,0 +1,48 @@
+"use client"
+
+import { QueryObserver, type QueryClient } from "@tanstack/react-query"
+import { channelMetadataOptions, isChannelMetadataTokenCurrent, type ChannelMetadataResource } from "./channel-metadata"
+import {
+ assertCommunityLiveSnapshotTokenCurrent,
+ captureCommunityLiveSnapshotToken,
+} from "@/lib/community-db/sync"
+
+export type ChannelRouteVerification = "present" | "missing" | "denied"
+
+export async function startChannelRouteVerification(
+ queryClient: QueryClient,
+ serverId: string | null,
+ channelId: string,
+): Promise<ChannelRouteVerification> {
+ const metadata = channelMetadataOptions(queryClient, serverId, channelId)
+ const options = { ...metadata, retry: serverId === null ? false : metadata.retry }
+ let token = captureCommunityLiveSnapshotToken(queryClient, channelId)
+ const ws = token.registry?.runtime.ws
+ if (ws?.actions.isChannelAccessRevoked(channelId, serverId)
+ && queryClient.getQueryState(options.queryKey)?.fetchStatus !== "fetching") {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ ws.actions.beginChannelMembershipChange(serverId, channelId, { preserveRevocation: true })
+ token = captureCommunityLiveSnapshotToken(queryClient, channelId)
+ }
+ const owner = new QueryObserver(queryClient, { ...options, enabled: false })
+ const release = owner.subscribe(() => {})
+ try {
+ const cached = queryClient.getQueryData<ChannelMetadataResource>(options.queryKey)
+ const resource = await queryClient.query({ ...options,
+ staleTime: cached?.readProof && isChannelMetadataTokenCurrent(cached.readProof) ? Infinity : 0, select: undefined })
+ return resource.readProof && isChannelMetadataTokenCurrent(resource.readProof) ? "present" : "denied"
+ } catch (error) {
+ const status = typeof error === "object" && error !== null && "status" in error ? error.status : undefined
+ if (status === 403 || status === 404) {
+ const current = captureCommunityLiveSnapshotToken(queryClient)
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, {
+ ...token, accessEpoch: current.accessEpoch, channelScopes: current.channelScopes,
+ }, undefined)
+ return "denied"
+ }
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ throw error
+ } finally {
+ release()
+ }
+}
diff --git a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts b/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
index b46219508..437b898b1 100644
--- a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
@@ -1,5 +1,5 @@
import React from "react"
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { CancelledError, QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { getLastChannel, setLastChannel } from "@/lib/community/last-channel"
@@ -11,6 +11,8 @@ import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataT
import { useChannelMetadata } from "./use-channel-metadata"
import { useDmReadStateSnapshot } from "./use-dm-read-state"
import { startConversationNavigationWarmup } from "@/lib/community/conversation-navigation-warmup"
+import { ApiError } from "@/lib/errors"
+import { startChannelRouteVerification } from "./channel-route-verification"
const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
@@ -38,8 +40,8 @@ async function fixture(client = new QueryClient({ defaultOptions: { queries: { r
React.createElement(CommunityDbProvider, { registry }, children))
return { client, registry, wrapper }
}
-function publishDms(registry: CommunityDbRegistry) {
- publishCommunityLiveSnapshot(registry.queryClient, { snapshot: { kind: "dms", data: dms },
+function publishDms(registry: CommunityDbRegistry, data = dms) {
+ publishCommunityLiveSnapshot(registry.queryClient, { snapshot: { kind: "dms", data },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(registry.queryClient), signal: undefined } })
}
async function qualifyMetadata(client: QueryClient, value = metadata) {
@@ -58,6 +60,172 @@ afterEach(async () => {
})
describe("shared Channel resource and canonical DM publication", () => {
+ it("requalifies a blocked other document on normal re-entry without executing its unblock command", async () => {
+ const { client, registry, wrapper } = await fixture()
+ const completeDms = { conversations: [...dms.conversations, { ...dms.conversations[0], id: "dm-b", userId: "other-peer" }] }
+ ingestDms(registry, completeDms)
+ await qualifyMetadata(client)
+ await qualifyMetadata(client, { ...metadata, id: "dm-b" })
+ const sibling = captureChannelMetadataToken(client, "dm-b")
+ const mounted = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })
+ act(() => applyCommunityDmBlockAccess(registry, "peer", true))
+ expect(mounted.result.current).toMatchObject({ denied: true, canRead: false })
+ expect(apiFetch).not.toHaveBeenCalled()
+ const retired = captureChannelMetadataToken(client, metadata.id)
+ mounted.unmount()
+ publishDms(registry, completeDms)
+ const request = deferred<typeof metadata>()
+ apiFetch.mockReturnValue(request.promise)
+ const returned = renderHook(() => ({ first: useChannelMetadata(null, metadata.id), second: useChannelMetadata(null, metadata.id) }), { wrapper })
+ const inbox = startChannelRouteVerification(client, null, metadata.id)
+ const terminal = inbox.then((result) => ({ result }), (error: unknown) => ({ error }))
+ try {
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ expect(returned.result.current.first).toMatchObject({ status: "pending", denied: false, canRead: false, revoked: true })
+ expect(returned.result.current.first.data?.readProof).toBeUndefined()
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ generation: 2, revoked: true })
+ expect(isChannelMetadataTokenCurrent(retired)).toBe(false)
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ await act(async () => request.resolve(metadata))
+ await expect(inbox).resolves.toBe("present")
+ await waitFor(() => expect(returned.result.current.first.canRead).toBe(true))
+ expect(returned.result.current.second.canRead).toBe(true)
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ generation: 2, revoked: false })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ } finally {
+ await act(async () => {
+ await client.cancelQueries({ queryKey: metadataKey, exact: true })
+ const settled = await terminal
+ returned.unmount()
+ if ("error" in settled && !(settled.error instanceof CancelledError)) throw settled.error
+ })
+ }
+ })
+
+ it.each([403, 404])("keeps a new-entry %s denied without rechecking on repaint", async (status) => {
+ const { client, registry, wrapper } = await fixture()
+ ingestDms(registry, dms)
+ await qualifyMetadata(client)
+ applyCommunityDmBlockAccess(registry, "peer", true)
+ publishDms(registry)
+ apiFetch.mockRejectedValue(new ApiError("denied", status))
+ const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })
+ await waitFor(() => expect(route.result.current.error).toMatchObject({ status }))
+ expect(route.result.current).toMatchObject({ denied: true, canRead: false })
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ generation: 2, revoked: true })
+ route.rerender()
+ await act(async () => {})
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(route.result.current.data?.readProof).toBeUndefined()
+ route.unmount()
+ })
+
+ it.each([0, 502])("keeps revoked re-entry temporary %s retryable until current protected success", async (status) => {
+ const { client, registry, wrapper } = await fixture()
+ ingestDms(registry, dms)
+ await qualifyMetadata(client)
+ applyCommunityDmBlockAccess(registry, "peer", true)
+ publishDms(registry)
+ const first = deferred<typeof metadata>()
+ apiFetch.mockReturnValueOnce(first.promise)
+ const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ expect(route.result.current).toMatchObject({ status: "pending", denied: false, canRead: false, revoked: true })
+ await act(async () => first.reject(new ApiError("unavailable", status)))
+ await waitFor(() => expect(route.result.current.status).toBe("retryable-error"))
+ expect(route.result.current).toMatchObject({ denied: false, canRead: false, revoked: true })
+ const retry = deferred<typeof metadata>()
+ apiFetch.mockReturnValueOnce(retry.promise)
+ let pending!: Promise<void>
+ await act(async () => { pending = route.result.current.retry(); void route.result.current.retry() })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
+ expect(route.result.current).toMatchObject({ status: "retryable-error", retrying: true, denied: false, canRead: false, revoked: true })
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)?.generation).toBe(2)
+ await act(async () => { retry.resolve(metadata); await pending })
+ await waitFor(() => expect(route.result.current.status).toBe("readable"))
+ expect(route.result.current).toMatchObject({ canRead: true, revoked: false })
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ route.unmount()
+ })
+
+ it("rechecks a revoked target when the route target changes and preserves the sibling proof", async () => {
+ const { client, registry, wrapper } = await fixture()
+ ingestDms(registry, { conversations: [...dms.conversations, { ...dms.conversations[0], id: "dm-b", userId: "other-peer" }] })
+ await qualifyMetadata(client)
+ await qualifyMetadata(client, { ...metadata, id: "dm-b" })
+ applyCommunityDmBlockAccess(registry, "peer", true)
+ const sibling = captureChannelMetadataToken(client, "dm-b")
+ const route = renderHook(({ id }) => useChannelMetadata(null, id), { initialProps: { id: "dm-b" }, wrapper })
+ expect(route.result.current.canRead).toBe(true)
+ const request = deferred<typeof metadata>()
+ apiFetch.mockReturnValue(request.promise)
+ route.rerender({ id: metadata.id })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ expect(route.result.current).toMatchObject({ status: "pending", denied: false, canRead: false, revoked: true })
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ await act(async () => request.resolve(metadata))
+ await waitFor(() => expect(route.result.current.canRead).toBe(true))
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ route.unmount()
+ })
+
+ it.each(["success", "denial"] as const)("rejects the prior request's late %s while the new entry is qualifying", async (outcome) => {
+ const { client, registry, wrapper } = await fixture()
+ ingestDms(registry, dms)
+ await qualifyMetadata(client)
+ const old = deferred<typeof metadata>()
+ const fresh = deferred<typeof metadata>()
+ apiFetch.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise)
+ const mounted = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })
+ void client.invalidateQueries({ queryKey: metadataKey, exact: true })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ const signal = apiFetch.mock.calls[0][1].signal as AbortSignal
+ act(() => applyCommunityDmBlockAccess(registry, "peer", true))
+ expect(signal.aborted).toBe(true)
+ mounted.unmount()
+ publishDms(registry)
+ const returned = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
+ await act(async () => {
+ if (outcome === "success") old.resolve(metadata)
+ else old.reject(new ApiError("old denied", 403))
+ })
+ expect(returned.result.current).toMatchObject({ status: "pending", denied: false, canRead: false, revoked: true })
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ generation: 2, revoked: true })
+ await act(async () => fresh.resolve(metadata))
+ await waitFor(() => expect(returned.result.current.canRead).toBe(true))
+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ generation: 2, revoked: false })
+ returned.unmount()
+ })
+
+ it.each([true, false])("keeps parent revocation until protected child metadata returns canRead=%s", async (canRead) => {
+ const { client, registry, wrapper } = await fixture()
+ const child = { ...metadata, id: "child", serverId: "server", type: "thread", name: "Child", parentChannelId: "parent", parentMessageId: "opener" }
+ apiFetch.mockResolvedValue(child)
+ await client.query(channelMetadataOptions(client, "server", child.id))
+ apiFetch.mockResolvedValue({ ...child, id: "sibling", type: "text", parentChannelId: null, parentMessageId: null })
+ await client.query(channelMetadataOptions(client, "server", "sibling"))
+ const sibling = captureChannelMetadataToken(client, "sibling")
+ registry.runtime.ws.actions.revokeChannelAccess("server", "parent")
+ const response = { ...child, accessDecision: { channelId: child.id, canRead, canSend: false, canCreateDiscussion: false } }
+ const request = deferred<typeof response>()
+ apiFetch.mockReset().mockReturnValue(request.promise)
+ const route = renderHook(() => useChannelMetadata("server", child.id), { wrapper })
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ expect(route.result.current).toMatchObject({ status: "pending", denied: false, canRead: false, revoked: true })
+ expect(registry.runtime.ws.get().channelAccessScopes.get("parent")?.revoked).toBe(true)
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ await act(async () => request.resolve(response))
+ await waitFor(() => expect(route.result.current.fetchStatus).toBe("idle"))
+ await waitFor(() => expect(route.result.current.canRead).toBe(canRead))
+ expect(registry.runtime.ws.get().channelAccessScopes.get("parent")?.revoked).toBe(!canRead)
+ expect(route.result.current.denied).toBe(!canRead)
+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ route.unmount()
+ })
+
it("retires a verified DM on block and waits for fresh metadata after unblock", async () => {
const { client, registry, wrapper } = await fixture()
publishDms(registry)
diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.ts
index 7fdf35d7f..da53909af 100644
--- a/src/web/src/hooks/community/use-channel-metadata.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.ts
@@ -3,6 +3,7 @@
import { useEffect, useMemo } from "react"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { channelMetadataOptions, isChannelMetadataTokenCurrent } from "./channel-metadata"
+import { startChannelRouteVerification } from "./channel-route-verification"
import { useRouteChannelProjection } from "@/lib/community-db/projections"
import { useCommunityWsStore } from "@/stores/community/ws"
import { communityKeys } from "@/lib/query-keys"
@@ -25,6 +26,15 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
const query = useQuery({ ...options, enabled: !!channelId && !revoked,
retry: serverId === null ? false : options.retry, retryOnMount: false,
refetchOnReconnect: false, refetchOnWindowFocus: false })
+ const entry = useMemo(() => {
+ const resource = queryClient.getQueryCache().find({ queryKey: communityKeys.channelMeta(serverId, channelId ?? "__none__"), exact: true })!
+ return { resource, revoked: !!channelId && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId) && !runtime.ws.get().revokedServerIds.has(serverId ?? ""),
+ errors: resource.state.errorUpdateCount, updates: resource.state.dataUpdateCount }
+ }, [channelId, queryClient, runtime, serverId])
+ useEffect(() => {
+ if (!channelId || !entry.revoked) return
+ void startChannelRouteVerification(queryClient, serverId, channelId).catch(() => undefined)
+ }, [channelId, entry, queryClient, serverId])
useEffect(() => {
if (!channelId || revoked || query.data === undefined
|| query.data.identityProof && isChannelMetadataTokenCurrent(query.data.identityProof) && query.data.readProof && isChannelMetadataTokenCurrent(query.data.readProof)) return
@@ -33,14 +43,18 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
}, [accessEpoch, accountEpoch, viewerId, generation, channelId, revoked, query.data, queryClient, serverId])
const retry = useConversationReadRetry(query, queryClient, [serverId, channelId, viewerId, accountEpoch, accessEpoch, generation])
const identityKnown = !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending
- const denied = revoked || typeof query.error === "object" && query.error !== null && "status" in query.error
+ const resource = queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true })!
+ const replaced = resource !== entry.resource
+ const failed = query.isError && (!entry.revoked || replaced || resource.state.errorUpdateCount > entry.errors)
+ const denied = failed && typeof query.error === "object" && query.error !== null && "status" in query.error
&& (query.error.status === 403 || query.error.status === 404)
+ || revoked && (!entry.revoked || !query.isFetching && !failed && (replaced || resource.state.dataUpdateCount > entry.updates))
const isArchived = identityKnown && canonical.archived && !!query.data?.identityProof && isChannelMetadataTokenCurrent(query.data.identityProof)
- const canRead = identityKnown && !denied && !isArchived && query.data?.id === channelId
+ const canRead = identityKnown && !revoked && !denied && !isArchived && query.data?.id === channelId
&& !!query.data.readProof && isChannelMetadataTokenCurrent(query.data.readProof)
const status: ChannelReadingStatus = !channelId ? "no-target" : denied || isArchived ? "denied"
- : canRead ? "readable" : retry.failed ? "retryable-error"
- : query.fetchStatus === "fetching" ? "pending" : "unresolved"
+ : canRead ? "readable" : (failed || retry.retrying) && retry.failed ? "retryable-error"
+ : query.isFetching || entry.revoked && revoked ? "pending" : "unresolved"
const data = useMemo(() => identityKnown ? { ...canonical, serverId,
createdAt: canonical.createdAt ?? "", name: canonical.name ?? "",
@@ -49,5 +63,5 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
parentChannelId: canonical.parentChannelId ?? null, parentMessageId: canonical.parentMessageId ?? null,
creatorId: canonical.creatorId ?? null, lastMessageAt: canonical.lastMessageAt ?? null }
: undefined, [canonical, identityKnown, query.data, serverId])
- return { ...query, data, status, identityKnown, canRead, isVerified: canRead, isArchived, denied, canonical, retry: retry.retry, retrying: retry.retrying }
+ return { ...query, data, status, identityKnown, canRead, isVerified: canRead, isArchived, denied, revoked, canonical, retry: retry.retry, retrying: retry.retrying }
}
diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
index 91145c53b..4d60abf57 100644
--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
@@ -31,6 +31,8 @@ vi.mock("@/lib/community/last-community-route", () => ({
}))
import { useChannelRouteModel } from "./use-channel-route-model"
+import { channelMetadataOptions } from "./channel-metadata"
+import { retireCommunityChannelReading } from "@/lib/community-db/sync"
import { reconcileCommunityWsReconnect } from "./community-ws/reconnect"
let current!: ReturnType<typeof useChannelRouteModel>
@@ -85,6 +87,52 @@ afterEach(async () => {
})
describe("unresolved metadata terminal error and retry", () => {
+ it.each([200, 403, 404, 502])("keeps revoked route pending until current protected %s and preserves its exit/Retry branch", async (status) => {
+ mocks.apiFetch.mockResolvedValue(payload())
+ await client.query(channelMetadataOptions(client, "server-1", "post-1"))
+ const owner = getCommunityDbRegistry(client)!
+ retireCommunityChannelReading(owner, "post-1", { reason: "read-denied", serverId: "server-1" })
+ const request = deferred()
+ mocks.apiFetch.mockReset().mockReturnValue(request.promise)
+ await mount()
+ await until(() => mocks.apiFetch.mock.calls.length === 1)
+ expect(current.routeLifecycle).toBe("pending")
+ expect(current.routeHydrated).toBe(false)
+ expect(current.currentChannelMeta).toBeNull()
+ expect(current.metadataError).toBe(false)
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(owner.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(true)
+ await act(async () => {
+ if (status === 200) request.resolve(payload())
+ else request.reject(new ApiError("unavailable", status))
+ })
+ if (status === 200) {
+ await until(() => current.routeHydrated)
+ expect(current.routeLifecycle).toBe("ready")
+ expect(mocks.replace).not.toHaveBeenCalled()
+ } else if (status === 403 || status === 404) {
+ await until(() => mocks.replace.mock.calls.length === 1)
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/server-1")
+ expect(current.metadataError).toBe(false)
+ expect(current.routeHydrated).toBe(false)
+ } else {
+ await until(() => current.metadataError)
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(current.routeHydrated).toBe(false)
+ expect(owner.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(true)
+ const retry = deferred()
+ mocks.apiFetch.mockReturnValueOnce(retry.promise)
+ let pending!: Promise<void>
+ await act(async () => { pending = current.retryMetadata(); void current.retryMetadata() })
+ expect(current.retryingMetadata).toBe(true)
+ expect(current.metadataError).toBe(true)
+ await act(async () => { retry.resolve(payload()); await pending })
+ await until(() => current.routeHydrated)
+ expect(current.metadataError).toBe(false)
+ expect(mocks.replace).not.toHaveBeenCalled()
+ }
+ })
+
it("keeps a missing server dependency retryable until its own read settles", async () => {
mocks.apiFetch.mockResolvedValue(payload())
Object.assign(mocks.server, { server: null, isError: true })
diff --git a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
index 325ddcb76..2e0568a26 100644
--- a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
+++ b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
@@ -7,7 +7,7 @@ import { QueryClientProvider } from "@tanstack/react-query"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { channelMetadataOptions } from "./channel-metadata"
-import { startDmRouteVerification } from "./use-dm-route-verification"
+import { startChannelRouteVerification } from "./channel-route-verification"
import { useChannelMetadata } from "./use-channel-metadata"
const apiFetch = vi.hoisted(() => vi.fn())
@@ -41,8 +41,8 @@ describe("DM route uses the shared Channel metadata owner", () => {
client.setQueryData(communityKeys.dms(), { conversations: [] })
const request = deferred<typeof metadata>()
apiFetch.mockReturnValue(request.promise)
- const first = startDmRouteVerification(client, dm.id)
- const second = startDmRouteVerification(client, dm.id)
+ const first = startChannelRouteVerification(client, null, dm.id)
+ const second = startChannelRouteVerification(client, null, dm.id)
const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })
await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
expect(route.result.current.status).toBe("pending")
@@ -64,7 +64,7 @@ describe("DM route uses the shared Channel metadata owner", () => {
await client.query(channelMetadataOptions(client, null, dm.id))
const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })
expect(route.result.current.status).toBe("readable")
- await expect(startDmRouteVerification(client, dm.id)).resolves.toBe("present")
+ await expect(startChannelRouteVerification(client, null, dm.id)).resolves.toBe("present")
expect(apiFetch).toHaveBeenCalledOnce()
route.unmount()
client.clear()
@@ -87,9 +87,9 @@ describe("DM route uses the shared Channel metadata owner", () => {
it.each([403, 404])("keeps explicit %s terminal and rejects scope mismatches", async (status) => {
const { client, registry } = await fixture()
apiFetch.mockRejectedValueOnce(Object.assign(new Error("denied"), { status }))
- await expect(startDmRouteVerification(client, dm.id)).resolves.toBe("denied")
+ await expect(startChannelRouteVerification(client, null, dm.id)).resolves.toBe("denied")
apiFetch.mockResolvedValueOnce({ ...metadata, serverId: "server", type: "text" })
- await expect(startDmRouteVerification(client, "other")).rejects.toThrow("scope mismatch")
+ await expect(startChannelRouteVerification(client, null, "other")).rejects.toThrow("scope mismatch")
expect(client.getQueryData(communityKeys.dms())).toBeUndefined()
client.clear()
})
@@ -119,7 +119,7 @@ describe("DM route uses the shared Channel metadata owner", () => {
const { client, registry } = await fixture()
const request = deferred<typeof metadata>()
apiFetch.mockReturnValue(request.promise)
- const started = startDmRouteVerification(client, dm.id)
+ const started = startChannelRouteVerification(client, null, dm.id)
const rejection = expect(started).rejects.toBeDefined()
await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
if (race === "cancel") await client.cancelQueries({ queryKey: communityKeys.channelMeta(null, dm.id), exact: true })
diff --git a/src/web/src/hooks/community/use-dm-route-verification.ts b/src/web/src/hooks/community/use-dm-route-verification.ts
deleted file mode 100644
index 435438e42..000000000
--- a/src/web/src/hooks/community/use-dm-route-verification.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-"use client"
-
-import { QueryObserver, type QueryClient } from "@tanstack/react-query"
-import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "./channel-metadata"
-import {
- assertCommunityLiveSnapshotTokenCurrent,
- captureCommunityLiveSnapshotToken,
-} from "@/lib/community-db/sync"
-
-export type DmRouteVerification = "present" | "missing" | "denied"
-
-function classifyDmRouteAuthorityError(error: unknown): "denied" | "error" {
- const status = typeof error === "object" && error !== null && "status" in error
- ? error.status
- : undefined
- return status === 403 || status === 404 ? "denied" : "error"
-}
-
-function verificationOptions(queryClient: QueryClient, dmId: string) {
- return {
- ...channelMetadataOptions(queryClient, null, dmId),
- retry: false,
- refetchOnReconnect: false,
- refetchOnWindowFocus: false,
- retryOnMount: false,
- } as const
-}
-
-export async function startDmRouteVerification(
- queryClient: QueryClient,
- dmId: string,
-): Promise<DmRouteVerification> {
- const options = verificationOptions(queryClient, dmId)
- const owner = new QueryObserver(queryClient, { ...options, enabled: false })
- const release = owner.subscribe(() => {})
- const token = captureCommunityLiveSnapshotToken(queryClient, dmId)
- try {
- const cached = queryClient.getQueryData<{ readProof?: ReturnType<typeof captureChannelMetadataToken> }>(options.queryKey)
- const resource = await queryClient.query({ ...options,
- staleTime: cached?.readProof && isChannelMetadataTokenCurrent(cached.readProof) ? Infinity : 0, select: undefined })
- return resource.readProof && isChannelMetadataTokenCurrent(resource.readProof) ? "present" : "denied"
- } catch (error) {
- if (classifyDmRouteAuthorityError(error) === "denied") {
- assertCommunityLiveSnapshotTokenCurrent(queryClient, {
- ...token, accessEpoch: captureCommunityLiveSnapshotToken(queryClient).accessEpoch, channelScopes: captureCommunityLiveSnapshotToken(queryClient).channelScopes,
- }, undefined)
- return "denied"
- }
- assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
- throw error
- } finally {
- release()
- }
-}
diff --git a/src/web/src/lib/community/conversation-navigation-proof.ts b/src/web/src/lib/community/conversation-navigation-proof.ts
index 35541a6eb..5d04c34e1 100644
--- a/src/web/src/lib/community/conversation-navigation-proof.ts
+++ b/src/web/src/lib/community/conversation-navigation-proof.ts
@@ -80,13 +80,9 @@ export function beginConversationNavigationProof(
const ownerToken = captureCommunityLiveSnapshotToken(queryClient, target.channelId)
if (ownerToken.viewerId !== target.viewerId) throw new DOMException("Conversation viewer does not match owner", "AbortError")
if (current.activeTarget) {
- const previousKey = current.activeTarget.scopeKind === "dm"
- ? communityKeys.dmMessages(current.activeTarget.channelId)
- : communityKeys.channelMessages(current.activeTarget.channelId)
+ const previousKey = communityKeys.channelMessages(current.activeTarget.channelId)
void queryClient.cancelQueries({ queryKey: previousKey })
- const previousReadKey = current.activeTarget.scopeKind === "dm"
- ? communityKeys.dmReadStateSnapshot(current.activeTarget.channelId)
- : communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
+ const previousReadKey = communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
void queryClient.cancelQueries({ queryKey: previousReadKey })
}
current.controller?.abort()
@@ -216,9 +212,7 @@ export function failConversationNavigationProof(
if (definitive) {
current.controller?.abort()
if (current.activeTarget) {
- const readKey = current.activeTarget.scopeKind === "dm"
- ? communityKeys.dmReadStateSnapshot(current.activeTarget.channelId)
- : communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
+ const readKey = communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
void queryClient.cancelQueries({ queryKey: readKey })
}
}
@@ -250,13 +244,9 @@ export function cancelConversationNavigationProof(
const current = store.get()
if (current.activeEpoch !== epoch) return
if (current.activeTarget) {
- const queryKey = current.activeTarget.scopeKind === "dm"
- ? communityKeys.dmMessages(current.activeTarget.channelId)
- : communityKeys.channelMessages(current.activeTarget.channelId)
+ const queryKey = communityKeys.channelMessages(current.activeTarget.channelId)
void queryClient.cancelQueries({ queryKey })
- const readKey = current.activeTarget.scopeKind === "dm"
- ? communityKeys.dmReadStateSnapshot(current.activeTarget.channelId)
- : communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
+ const readKey = communityKeys.channelReadStateSnapshot(current.activeTarget.channelId)
void queryClient.cancelQueries({ queryKey: readKey })
}
current.controller?.abort()
diff --git a/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx b/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
index 90f522f32..d6715e07c 100644
--- a/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
+++ b/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
@@ -1,7 +1,7 @@
import React, { StrictMode, useLayoutEffect } from "react"
import { QueryClient, useInfiniteQuery } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
+import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityDbRegistry, registerCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { createQueryClient } from "@/lib/query-client"
@@ -11,6 +11,10 @@ import { startConversationNavigationWarmup } from "./conversation-navigation-war
import { getConversationNavigationProof, recoverConversationNavigationProof, useConversationNavigationGate } from "./conversation-navigation-proof"
import { channelMessagesQueryFn, dmMessagesQueryFn } from "@/hooks/community/use-messages"
import type { MessagesPageParam } from "@/lib/community/models/message"
+import { channelMetadataOptions, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"
+import { startChannelRouteVerification } from "@/hooks/community/channel-route-verification"
+import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"
+import { retireCommunityChannelReading } from "@/lib/community-db/sync"
vi.mock("@/lib/api/client", async (load) => {
const actual = await load<typeof import("@/lib/api/client")>()
@@ -67,6 +71,59 @@ function response(status: number) {
}
describe("warmup original owner and complete intent resources", () => {
+ it.each(["dm", "thread"] as const)("qualifies a revoked %s before warmup capture and keeps that request through prior-body unmount", async (kind) => {
+ const owner = createClient()
+ await owner.registry.preload()
+ const serverId = kind === "dm" ? null : "s1"
+ if (serverId) owner.client.setQueryData(communityKeys.server(serverId), serverId)
+ const metadata = { id: "d1", serverId, type: kind, name: kind === "dm" ? null : "Thread",
+ parentChannelId: kind === "dm" ? null : "parent", parentMessageId: kind === "dm" ? null : "opener",
+ creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
+ const json = (value: unknown) => new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } })
+ const pending: Array<{ path: string; signal: AbortSignal; resolve: (value: Response) => void }> = []
+ let held = false
+ vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => !held
+ ? Promise.resolve(json(metadata))
+ : new Promise<Response>((resolve) => pending.push({ path, signal: options.signal!, resolve }))))
+ await owner.client.query(channelMetadataOptions(owner.client, serverId, "d1"))
+ const wrapper = ({ children }: React.PropsWithChildren) => <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>{children}</CommunityTestProvider>
+ const prior = renderHook(() => useChannelMetadata(serverId, "d1"), { wrapper })
+ const oldProof = prior.result.current.data!.readProof!
+ act(() => retireCommunityChannelReading(owner.registry, "d1", { reason: "read-denied", serverId }))
+ expect(prior.result.current.canRead).toBe(false)
+ held = true
+ const navigation = { ...target, scopeKind: kind === "dm" ? "dm" as const : "channel" as const,
+ ...(serverId ? { serverId } : {}), expectedSurfaceKind: kind }
+ let epoch!: number
+ act(() => { epoch = startConversationNavigationWarmup(owner.client, navigation, 0) })
+ await waitFor(() => expect(pending).toHaveLength(3))
+ const authority = pending.find((request) => new URL(request.path, "https://alook.test").pathname === "/api/community/channels/d1")!
+ const resource = owner.client.getQueryCache().find({ queryKey: communityKeys.channelMeta(serverId, "d1"), exact: true })!
+ expect(owner.registry.runtime.ws.get().channelAccessScopes.get("d1")).toMatchObject({ generation: 2, revoked: true })
+ expect(isChannelMetadataTokenCurrent(oldProof)).toBe(false)
+ prior.unmount()
+ expect(resource.getObserversCount()).toBe(1)
+ expect(authority.signal.aborted).toBe(false)
+ const afterPush = startChannelRouteVerification(owner.client, serverId, "d1")
+ const current = renderHook(() => ({ metadata: useChannelMetadata(serverId, "d1"), gate: useConversationNavigationGate(owner.client, "viewer", "d1", 0) }), { wrapper })
+ expect(current.result.current.metadata.canRead).toBe(false)
+ expect(owner.registry.runtime.ws.get().channelAccessScopes.get("d1")?.generation).toBe(2)
+ expect(pending).toHaveLength(3)
+ await act(async () => authority.resolve(json(metadata)))
+ await expect(afterPush).resolves.toBe("present")
+ await waitFor(() => expect(current.result.current.metadata.canRead).toBe(true))
+ await act(async () => {
+ pending.find((request) => request.path.includes("/read-state"))!.resolve(response(200))
+ pending.find((request) => request.path.includes("/messages"))!.resolve(json({ messages: [], hasMore: false, surfaceReceipt: { channelId: "d1", surfaceKind: kind } }))
+ })
+ await waitFor(() => expect(current.result.current.gate.allowed).toBe(true))
+ expect(getConversationNavigationProof(owner.client)?.epoch ?? epoch).toBe(epoch)
+ expect(owner.registry.runtime.ws.get().channelAccessScopes.get("d1")).toMatchObject({ generation: 2, revoked: false })
+ expect(pending).toHaveLength(3)
+ await waitFor(() => expect(resource.getObserversCount()).toBe(1))
+ current.unmount()
+ })
+
it.each(["channel", "thread", "forum", "dm"].flatMap((kind) =>
["anchor", "older"].map((mode) => ({ kind, mode })),
))("reads the current click after retained $mode pages on $kind", async ({ kind, mode }) => {
diff --git a/src/web/src/lib/community/conversation-navigation-warmup.ts b/src/web/src/lib/community/conversation-navigation-warmup.ts
index 61d66658f..49b289eab 100644
--- a/src/web/src/lib/community/conversation-navigation-warmup.ts
+++ b/src/web/src/lib/community/conversation-navigation-warmup.ts
@@ -10,6 +10,7 @@ import type { MessagesPage, MessagesPageParam } from "@/lib/community/models/mes
import { channelMessagesQueryFn, dmMessagesQueryFn } from "@/hooks/community/use-messages"
import { channelReadStateSnapshotQueryFn } from "@/hooks/community/use-channel-read-state"
import { serverProjectedQueryFn } from "@/hooks/community/use-servers"
+import { startChannelRouteVerification } from "@/hooks/community/channel-route-verification"
import {
beginConversationNavigationProof,
commitConversationNavigationProof,
@@ -21,24 +22,12 @@ import {
type ConversationNavigationTarget,
} from "./conversation-navigation-proof"
-function isDefinitiveAccessFailure(error: unknown): boolean {
- return error instanceof ApiError && (error.status === 403 || error.status === 404)
-}
-
function clearDeniedTarget(queryClient: QueryClient, target: ConversationNavigationTarget) {
- const messagesKey = target.scopeKind === "dm"
- ? communityKeys.dmMessages(target.channelId)
- : communityKeys.channelMessages(target.channelId)
- const readKey = target.scopeKind === "dm"
- ? communityKeys.dmReadStateSnapshot(target.channelId)
- : communityKeys.channelReadStateSnapshot(target.channelId)
+ const messagesKey = communityKeys.channelMessages(target.channelId)
+ const readKey = communityKeys.channelReadStateSnapshot(target.channelId)
queryClient.removeQueries({ queryKey: messagesKey })
queryClient.removeQueries({ queryKey: readKey })
- if (target.serverId) {
- queryClient.removeQueries({ queryKey: communityKeys.channelMeta(target.serverId, target.channelId) })
- } else {
- queryClient.removeQueries({ queryKey: communityKeys.channelMeta(null, target.channelId) })
- }
+ queryClient.removeQueries({ queryKey: communityKeys.channelMeta(target.serverId ?? null, target.channelId) })
getCommunityRuntime(queryClient).messageStream.actions.removeScope(
target.scopeKind === "dm"
? { kind: "dm", id: target.channelId }
@@ -52,6 +41,9 @@ export function startConversationNavigationWarmup(
accessEpoch: number,
recoveryAttempt = 0,
) {
+ if (getCommunityRuntime(queryClient).ws.actions.isChannelAccessRevoked(target.channelId, target.serverId ?? null)) {
+ void startChannelRouteVerification(queryClient, target.serverId ?? null, target.channelId).catch(() => undefined)
+ }
const { epoch, signal } = beginConversationNavigationProof(
queryClient,
target,
@@ -64,9 +56,7 @@ export function startConversationNavigationWarmup(
const pageParam: MessagesPageParam = target.anchorMessageId
? { mode: "anchor", anchor: target.anchorMessageId }
: { mode: "newest" }
- const messagesKey = target.scopeKind === "dm"
- ? communityKeys.dmMessages(target.channelId)
- : communityKeys.channelMessages(target.channelId)
+ const messagesKey = communityKeys.channelMessages(target.channelId)
const queryFn = target.scopeKind === "dm"
? dmMessagesQueryFn(target.channelId, {
queryClient,
@@ -111,15 +101,13 @@ export function startConversationNavigationWarmup(
})
.catch((error) => {
if (signal.aborted || !isCurrentConversationNavigation(queryClient, epoch, accessEpoch)) return
- const definitive = isDefinitiveAccessFailure(error)
+ const definitive = error instanceof ApiError && (error.status === 403 || error.status === 404)
if (definitive) clearDeniedTarget(queryClient, target)
failConversationNavigationProof(queryClient, epoch, accessEpoch, definitive, true)
})
.finally(releaseMessages)
- const readKey = target.scopeKind === "dm"
- ? communityKeys.dmReadStateSnapshot(target.channelId)
- : communityKeys.channelReadStateSnapshot(target.channelId)
+ const readKey = communityKeys.channelReadStateSnapshot(target.channelId)
void queryClient.query({
queryKey: readKey,
staleTime: 0,
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 9a3fae596..00c28c632 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -15,6 +15,11 @@ import {
*/
describe("communityKeys", () => {
+ it("keeps DM navigation resources in the canonical Channel query family", () => {
+ expect(communityKeys.dmMessages("target")).toEqual(communityKeys.channelMessages("target"))
+ expect(communityKeys.dmReadStateSnapshot("target")).toEqual(communityKeys.channelReadStateSnapshot("target"))
+ })
+
it("roots every key under ['community']", () => {
expect(communityKeys.all).toEqual(["community"])
diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.ts
index 2a97a34f5..67f81fe58 100644
--- a/src/web/src/stores/community/ws-store.ts
+++ b/src/web/src/stores/community/ws-store.ts
@@ -35,7 +35,7 @@ type CommunityWsStoreState = {
accessEpoch: number
channelAccessScopes: Map<string, ChannelAccessScope>
revokedServerIds: Set<string>
- beginChannelMembershipChange: (serverId: string | null, channelId: string) => number
+ beginChannelMembershipChange: (serverId: string | null, channelId: string, options?: { preserveRevocation: boolean }) => number
observeChannelScope: (serverId: string, channelId: string, parentChannelId?: string | null) => void
rememberChannelAccess: (serverId: string | null, channelId: string, parentChannelId?: string | null) => void
revokeChannelAccess: (serverId: string | null, channelId: string) => string[]
@@ -216,11 +216,11 @@ export function createCommunityWsStore(viewerId: string | null) {
return true
},
- beginChannelMembershipChange: (serverId, channelId) => {
+ beginChannelMembershipChange: (serverId, channelId, options) => {
const scopes = new Map(get().channelAccessScopes)
const previous = scopes.get(channelId)
const generation = (previous?.generation ?? 0) + 1
- scopes.set(channelId, { ...previous, serverId, revoked: false, generation })
+ scopes.set(channelId, { ...previous, serverId, revoked: !!options?.preserveRevocation && !!previous?.revoked, generation })
setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))
return generation
},