Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(web): remove obsolete message paths (#1017)

Genere3c9fc597d66
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index e9ad8dff0..42245c583 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -1583,6 +1583,15 @@ describe("GET explicit conversation entry", () => {
expect(mockListMessages).not.toHaveBeenCalled()
})
+ it("marks a missing ordinary window anchor separately from target access denial", async () => {
+ mockGetMessageInScope.mockResolvedValue(null)
+ const response = await GET(request("window=around&anchorMessageId=gone"), ctx)
+ expect(response.status).toBe(404)
+ expect(await response.json()).toEqual({ error: "anchor not found", details: ["conversation_anchor_missing"] })
+ expect(mockListMessages).not.toHaveBeenCalled()
+ expect(mockListMessagesAround).not.toHaveBeenCalled()
+ })
+
it("honors an explicit newest window without discarding the entry pointer", async () => {
mockGetChannelReadStateSnapshot.mockResolvedValue({ revision: 5, readState: pointer })
const response = await GET(request("entry=1&window=tail"), ctx)
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index dca1f6661..2d30e6e7a 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -131,7 +131,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const result = await readCommunityMessageWindow(db, {
viewerId: userId, target: resolved.value, window, tag, contract: requestedCommunityContract(req.headers) ?? 1,
})
- if (!result.ok) return writeError(result.error, result.status)
+ if (!result.ok) return NextResponse.json({ error: result.error, details: result.details }, { status: result.status })
return writeCommunityMessagesRead(req, channelId, result.page)
})
diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
index 6468d2860..62d9cae60 100644
--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
@@ -188,12 +188,31 @@ describe("MessageContextSheet thread navigation", () => {
mocks.openThread = undefined
mocks.pin = undefined
mocks.reply = undefined
- mocks.canonicalMessages.mockReturnValue(undefined)
+ mocks.canonicalMessages.mockReturnValue(new Map([["message_1", {
+ id: "message_1", seq: 1, type: "chat", authorId: "author_1", authorName: "Author", content: "Message",
+ createdAt: "2026-08-20T00:00:00.000Z", thread: { id: "child_1", name: "Child", messageCount: 1 },
+ }]]))
mocks.toggleReaction = undefined
mocks.addReaction = undefined
mocks.noData = false
})
+ it("does not render or act on transport rows while the canonical owner is unavailable", () => {
+ mocks.canonicalMessages.mockReturnValue(undefined)
+ render(React.createElement(MessageContextSheet, { open: true, onOpenChange: mocks.close, channelId: "parent_1", targetSeq: 1 }))
+ expect(mocks.reply).toBeUndefined()
+ expect(mocks.pin).toBeUndefined()
+ expect(mocks.toggleReaction).toBeUndefined()
+ })
+
+ it("shows a missing anchor when the canonical map exists without its ID", () => {
+ mocks.canonicalMessages.mockReturnValue(new Map())
+ const view = render(React.createElement(MessageContextSheet, { open: true, onOpenChange: mocks.close, channelId: "parent_1", targetSeq: 1 }))
+ expect(view.getByText("Message not found — it may have been deleted.")).toBeTruthy()
+ expect(mocks.reply).toBeUndefined()
+ expect(mocks.pin).toBeUndefined()
+ })
+
it("carries the source author ID and complete visible body into a sheet reply", () => {
mocks.canonicalMessages.mockReturnValue(new Map([["message_1", {
id: "message_1", type: "chat", authorId: "author_1", authorName: "Author",
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index 669a5f28c..14515580e 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -237,15 +237,16 @@ export function MessageContextSheet({
const anchorId = query.data && !query.data.notFound ? (query.data.anchorId ?? null) : null
+ const canonicalPending = !!query.data && !query.data.notFound && canonicalMessages === undefined
+ const anchorMissing = canonicalMessages !== undefined && !!anchorId && !canonicalMessages.has(anchorId)
+
// ── Sheet-local actions ──────────────────────────────────────────────────
const findMessage = useCallback(
(id: string): Msg | undefined => {
- const transport = (canonicalMessages === undefined
- ? queryClient.getQueryData<SheetCache>(queryKey)?.messages
- : query.data?.messages)?.find((message) => message.id === id)
+ const transport = query.data?.messages?.find((message) => message.id === id)
return transport ? materializeCanonicalMessage(transport, canonicalMessages) : undefined
},
- [canonicalMessages, query.data, queryClient, queryKey],
+ [canonicalMessages, query.data],
)
const runReactionIntent = useCallback((
@@ -421,7 +422,7 @@ export function MessageContextSheet({
bodyRef={bodyRef}
bodyClassName="px-4 py-3"
>
- {query.isLoading && <ContextSkeleton />}
+ {(query.isLoading || canonicalPending) && <ContextSkeleton />}
{query.isError && (
<p className="py-8 text-center text-sm text-muted-foreground">
@@ -429,13 +430,13 @@ export function MessageContextSheet({
</p>
)}
- {query.data?.notFound && (
+ {(query.data?.notFound || anchorMissing) && (
<p className="py-8 text-center text-sm text-muted-foreground">
Message not found — it may have been deleted.
</p>
)}
- {!query.isLoading && !query.isError && query.data && !query.data.notFound && (
+ {!query.isLoading && !query.isError && !canonicalPending && !anchorMissing && query.data && !query.data.notFound && (
<ContextRows
rows={renderRows}
viewerUserId={currentUser.id}
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 16f8b61d1..b2e790347 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
@@ -284,7 +284,7 @@ export function useShellInboxController({
unreadDms,
mentions,
marked: inboxMarked.marked,
- markedLoading: inboxMarked.isLoading,
+ markedLoading: inboxMarked.isLoading || inboxMarked.canonicalPending,
loading,
attentionError: attention.isInitialError,
onRetryAttention: () => { void attention.refetch() },
diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
index ab6d4ff62..9576aed06 100644
--- a/src/web/src/hooks/community/community-ws/read-state-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
@@ -1,3 +1,5 @@
+import { seedCommunityReadState } from "@/test/community-query-owner"
+import { currentConversationReadState } from "@/lib/community/conversation-entry"
import { createCommunityDbRegistry } from "@/lib/community-db/collections"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -50,7 +52,7 @@ describe("same-account read-state WS events", () => {
revision: 2,
readStates: [],
})
- queryClient.setQueryData(communityKeys.dmReadStateSnapshot("dm1"), {
+ seedCommunityReadState(queryClient, "dm1", {
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -71,8 +73,7 @@ describe("same-account read-state WS events", () => {
inboxChanged: true,
}, context(queryClient))
- await vi.waitFor(() => expect(queryClient.getQueryData(
- communityKeys.dmReadStateSnapshot("dm1"),
+ await vi.waitFor(() => expect(currentConversationReadState(queryClient, "dm1",
)).toMatchObject({
lastReadMessageId: "m4",
lastReadSeq: 4,
@@ -112,7 +113,7 @@ describe("same-account read-state WS events", () => {
revision: 7,
readStates: [],
})
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 0 })
+ seedCommunityReadState(queryClient, "c1", { lastReadSeq: 0 })
apiFetch.mockResolvedValue({
revision: 8,
@@ -131,8 +132,7 @@ describe("same-account read-state WS events", () => {
reason: "read_all",
} as const
dispatchCommunityWsEvent(event, context(queryClient))
- await vi.waitFor(() => expect(queryClient.getQueryData(
- communityKeys.channelReadStateSnapshot("c1"),
+ await vi.waitFor(() => expect(currentConversationReadState(queryClient, "c1",
)).toMatchObject({
lastReadSeq: 8,
}))
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
index 35af19390..47d45a225 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
@@ -1,3 +1,5 @@
+import { seedCommunityReadState } from "@/test/community-query-owner"
+import { currentConversationReadState } from "@/lib/community/conversation-entry"
import { createCommunityDbRegistry } from "@/lib/community-db/collections"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClient, QueryObserver } from "@tanstack/react-query"
@@ -51,8 +53,8 @@ describe("account read-state reconciliation", () => {
})
it("loads the authoritative full replacement, including regression and removal", async () => {
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 1 })
- queryClient.setQueryData(communityKeys.dmReadStateSnapshot("dm1"), { lastReadSeq: 2 })
+ seedCommunityReadState(queryClient, "c1", { lastReadSeq: 1 })
+ seedCommunityReadState(queryClient, "dm1", { lastReadSeq: 2 })
apiFetch.mockResolvedValue({
revision: 10,
readStates: [{
@@ -65,11 +67,11 @@ describe("account read-state reconciliation", () => {
await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/read-state", expect.objectContaining({ signal: expect.any(AbortSignal) }))
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1"))).toMatchObject({
+ expect(currentConversationReadState(queryClient, "c1")).toMatchObject({
lastReadMessageId: "m0",
lastReadSeq: 0,
})
- expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("dm1"))).toEqual({
+ expect(currentConversationReadState(queryClient, "dm1")).toMatchObject({
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -81,7 +83,7 @@ describe("account read-state reconciliation", () => {
revision: 4,
readStates: [],
})
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ seedCommunityReadState(queryClient, "c1", {
lastReadMessageId: "m4",
lastReadAt: "2026-08-24T00:00:04.000Z",
lastReadSeq: 4,
@@ -113,7 +115,7 @@ describe("account read-state reconciliation", () => {
expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
.toMatchObject({ revision: 4 })
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ expect(currentConversationReadState(queryClient, "c1"))
.toMatchObject({ lastReadSeq: 4 })
releases[1]!({
@@ -129,7 +131,7 @@ describe("account read-state reconciliation", () => {
expect.objectContaining({ revision: 6 }),
expect.objectContaining({ revision: 6 }),
])
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ expect(currentConversationReadState(queryClient, "c1"))
.toMatchObject({ lastReadSeq: 6 })
})
@@ -159,7 +161,7 @@ describe("account read-state reconciliation", () => {
revision: 10,
readStates: [],
})
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("late"), {
+ seedCommunityReadState(queryClient, "late", {
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -176,7 +178,7 @@ describe("account read-state reconciliation", () => {
await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("late")))
+ expect(currentConversationReadState(queryClient, "late"))
.toMatchObject({ lastReadMessageId: "m3", lastReadSeq: 3 })
})
@@ -260,8 +262,8 @@ describe("account read-state reconciliation", () => {
.mockReturnValueOnce(new Promise<AccountReadStateSnapshot>((resolve) => {
releaseFresh = resolve
}))
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 0 })
- queryClient.setQueryData(communityKeys.dmReadStateSnapshot("removed"), { lastReadSeq: 4 })
+ seedCommunityReadState(queryClient, "c1", { lastReadSeq: 0 })
+ seedCommunityReadState(queryClient, "removed", { lastReadSeq: 4 })
const auth = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
expect(projectReadStateEnvelope(queryClient, {
@@ -306,11 +308,11 @@ describe("account read-state reconciliation", () => {
}],
},
])
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1"))).toMatchObject({
+ expect(currentConversationReadState(queryClient, "c1")).toMatchObject({
lastReadMessageId: "m5",
lastReadSeq: 5,
})
- expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("removed"))).toEqual({
+ expect(currentConversationReadState(queryClient, "removed")).toMatchObject({
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -339,7 +341,7 @@ describe("account read-state reconciliation", () => {
revision: 4,
readStates: [],
})
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ seedCommunityReadState(queryClient, "c1", {
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -366,7 +368,7 @@ describe("account read-state reconciliation", () => {
targetRevision: 5,
})).resolves.toMatchObject({ revision: 5 })
expect(apiFetch).toHaveBeenCalledTimes(2)
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ expect(currentConversationReadState(queryClient, "c1"))
.toMatchObject({ lastReadSeq: 5 })
})
@@ -425,7 +427,7 @@ describe("account read-state reconciliation", () => {
revision: 4,
readStates: [],
})
- queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ seedCommunityReadState(queryClient, "c1", {
lastReadMessageId: null,
lastReadAt: null,
lastReadSeq: 0,
@@ -452,7 +454,7 @@ describe("account read-state reconciliation", () => {
expect(apiFetch).toHaveBeenCalledTimes(1)
expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
.toMatchObject({ revision: 4 })
- expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ expect(currentConversationReadState(queryClient, "c1"))
.toMatchObject({ lastReadSeq: 0 })
await expect(reconcileAccountReadState(queryClient, {
targetRevision: 5,
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
index ca6ee5c66..6a7375969 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
@@ -58,40 +58,6 @@ const MAX_RETRY_DELAY_MS = 5_000
const reconciliationStates = new WeakMap<QueryClient, ReconciliationState>()
const disposedReconciliationClients = new WeakSet<QueryClient>()
-const emptyReadState = {
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
-}
-
-function cachedReadStateTarget(key: QueryKey) {
- if (
- key[0] === "community"
- && (key[1] === "channel" || key[1] === "dm")
- && typeof key[2] === "string"
- && key[3] === "read-state-snapshot"
- ) {
- return { kind: key[1], channelId: key[2] }
- }
- return null
-}
-
-function projectReadStateRows(queryClient: QueryClient, snapshot: AccountReadStateSnapshot) {
- const byChannel = new Map(snapshot.readStates.map((row) => [row.channelId, row]))
- for (const query of queryClient.getQueryCache().getAll()) {
- const target = cachedReadStateTarget(query.queryKey)
- if (!target) continue
- const row = byChannel.get(target.channelId)
- queryClient.setQueryData(query.queryKey, row
- ? {
- lastReadMessageId: row.lastReadMessageId,
- lastReadAt: row.lastReadAt,
- lastReadSeq: row.lastReadSeq,
- }
- : emptyReadState)
- }
-}
-
function applyAccountReadStateSnapshot(
queryClient: QueryClient,
snapshot: AccountReadStateSnapshot,
@@ -114,17 +80,14 @@ function applyAccountReadStateSnapshot(
if (current && snapshot.revision < current.revision) return "stale" as const
if (current?.revision === snapshot.revision) {
// Same revision is the same authoritative account snapshot by contract.
- // Re-project leaf caches in case one mounted after the first application,
// but do not trigger a second round of derived-surface refetches when
// concurrent auth/live reconciliations joined the same HTTP request.
- projectReadStateRows(queryClient, snapshot)
projectReadCoordinatorSnapshot(queryClient, snapshot)
acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
return "stale" as const
}
notifyManager.batch(() => {
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), snapshot)
- projectReadStateRows(queryClient, snapshot)
projectReadCoordinatorSnapshot(queryClient, snapshot)
acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
})
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
index a25738487..14f1f4dbe 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -1,3 +1,5 @@
+import { COMMUNITY_CONVERSATION_ANCHOR_MISSING } from "@alook/shared"
+import { ingestDms, ingestMessages, ingestServerDetail, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { messageWindowPage, type MessagesPage } from "@/lib/community/models/message"
@@ -162,7 +164,7 @@ describe("focused message reconnect catch-up", () => {
it("refreshes a completed query variant when another variant still holds the scope owner", async () => {
const { client: client } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("variants")
- const taggedKey = [...key, "tag", "selected"]
+ const taggedKey = communityKeys.channelMessagesWindow("variants", { mode: "newest" }, "selected")
const subscriptions = [seedActiveQuery(client, key), seedActiveQuery(client, taggedKey)]
let releaseTagged!: (page: unknown) => void
const tagged = new Promise((resolve) => { releaseTagged = resolve })
@@ -386,6 +388,103 @@ describe("focused message reconnect catch-up", () => {
unsubscribe()
})
+ it.each([403, 404])("retires a denied DM through its real scope and keeps the DM shell for status %s", async (status) => {
+ const { client, registry, runtime } = await createCommunityQueryOwner("a")
+ ingestDms(registry, { conversations: ["denied", "sibling"].map((id) => ({ id, userId: id + "-peer", name: id, discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "old" })) })
+ ingestMessages(registry, "denied", [{ id: "private", type: "chat", content: "remove" }])
+ ingestMessages(registry, "sibling", [{ id: "sibling-message", type: "chat", content: "keep" }])
+ const scope = { kind: "dm" as const, id: "denied" }
+ runtime.messageStream.actions.accept(scope, { nonce: "pending", tempId: "temp", message: { type: "chat", content: "pending", authorId: "a" }, localUploads: [] })
+ const key = communityKeys.dmMessages(scope.id), sibling = communityKeys.dmMessages("sibling")
+ const subscriptions = [seedActiveQuery(client, key), seedActiveQuery(client, sibling)]
+ apiFetchMock.mockRejectedValueOnce(new ApiError("denied", status))
+ try {
+ await reconcileFocusedMessageQueries(client, "dm", scope.id)
+ expect(client.getQueryData(key)).toBeUndefined()
+ expect(client.getQueryData(sibling)).toBeDefined()
+ expect(registry.collections.messages.has("private")).toBe(false)
+ expect(registry.collections.messages.get("sibling-message")?.content).toBe("keep")
+ expect(registry.collections.channels.get(scope.id)?.type).toBe("dm")
+ expect(runtime.ws.actions.isChannelAccessRevoked(scope.id, null)).toBe(true)
+ expect(runtime.messageStream.get().entries.has("dm:" + scope.id)).toBe(false)
+ } finally { for (const subscription of subscriptions) subscription.unsubscribe() }
+ })
+
+ it("retires a denied channel using its captured server and leaves the sibling readable", async () => {
+ const { client, registry, runtime } = await createCommunityQueryOwner("a")
+ ingestServerDetail(registry, { id: "server", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "a",
+ categories: [{ id: "category", name: "Chats", channels: ["denied-channel", "sibling-channel"].map((id) => ({ id, name: id, active: false, unread: false })) }] })
+ ingestMessages(registry, "denied-channel", [{ id: "private", type: "chat", content: "remove" }])
+ ingestMessages(registry, "sibling-channel", [{ id: "public", type: "chat", content: "keep" }])
+ const key = communityKeys.channelMessages("denied-channel"), sibling = communityKeys.channelMessages("sibling-channel")
+ const subscriptions = [seedActiveQuery(client, key), seedActiveQuery(client, sibling)]
+ apiFetchMock.mockRejectedValueOnce(new ApiError("forbidden", 403))
+ try {
+ await reconcileFocusedMessageQueries(client, "channel", "denied-channel", "server")
+ expect(client.getQueryData(key)).toBeUndefined()
+ expect(client.getQueryData(sibling)).toBeDefined()
+ expect(registry.collections.channels.has("denied-channel")).toBe(false)
+ expect(registry.collections.messages.has("private")).toBe(false)
+ expect(registry.collections.messages.get("public")?.content).toBe("keep")
+ expect(runtime.ws.actions.isChannelAccessRevoked("denied-channel", "server")).toBe(true)
+ expect(runtime.ws.actions.isChannelAccessRevoked("sibling-channel", "server")).toBe(false)
+ } finally { for (const subscription of subscriptions) subscription.unsubscribe() }
+ })
+
+ it.each(["account", "replacement"] as const)("ignores a late denial after %s ownership changes", async (change) => {
+ const { client, registry, runtime } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("late-denial")
+ const subscriptions = [seedActiveQuery(client, key)]
+ ingestMessages(registry, "late-denial", [{ id: "keep", type: "chat", content: "current" }])
+ let reject!: (error: Error) => void
+ apiFetchMock.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail }))
+ const repair = reconcileFocusedMessageQueries(client, "channel", "late-denial", "server")
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ if (change === "account") { runtime.ws.actions.activateProfileAccount("b"); runtime.ws.actions.activateProfileAccount("a") }
+ else { client.removeQueries({ queryKey: key, exact: true }); subscriptions.push(seedActiveQuery(client, key)) }
+ const current = client.getQueryCache().find({ queryKey: key, exact: true })
+ reject(new ApiError("forbidden", 403))
+ await repair
+ expect(client.getQueryCache().find({ queryKey: key, exact: true })).toBe(current)
+ expect(registry.collections.messages.get("keep")?.content).toBe("current")
+ expect(runtime.ws.actions.isChannelAccessRevoked("late-denial", "server")).toBe(false)
+ for (const subscription of subscriptions) subscription.unsubscribe()
+ })
+
+ it("keeps a missing anchor local to its window and retains its canonical body and pending intent", async () => {
+ const { client, registry, runtime } = await createCommunityQueryOwner("a")
+ const scope = { kind: "channel" as const, id: "anchor-scope", serverId: "server" }
+ const key = communityKeys.channelMessagesWindow(scope.id, { mode: "anchor", anchor: "gone" })
+ const { unsubscribe } = seedActiveQuery(client, key)
+ ingestMessages(registry, scope.id, [{ id: "readable", type: "chat", content: "keep" }])
+ runtime.messageStream.actions.accept(scope, { nonce: "pending", tempId: "temp", message: { type: "chat", content: "pending", authorId: "a" }, localUploads: [] })
+ const missing = new ApiError("anchor not found", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING])
+ apiFetchMock.mockRejectedValueOnce(missing)
+ try {
+ await expect(reconcileFocusedMessageQueries(client, "channel", scope.id, scope.serverId)).rejects.toBe(missing)
+ expect(client.getQueryData(key)).toBeDefined()
+ expect(registry.collections.messages.get("readable")?.content).toBe("keep")
+ expect(runtime.ws.actions.isChannelAccessRevoked(scope.id, scope.serverId)).toBe(false)
+ expect(runtime.messageStream.get().entries.get("channel:" + scope.id)?.state.outboxByNonce.has("pending")).toBe(true)
+ } finally { unsubscribe() }
+ })
+
+ it("does not turn a late denial after explicit DM deletion into read-denied retirement or restore its shell", async () => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ ingestDms(registry, { conversations: [{ id: "deleted", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "" }] })
+ const key = communityKeys.dmMessages("deleted"), { unsubscribe } = seedActiveQuery(client, key)
+ let reject!: (error: Error) => void
+ apiFetchMock.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail }))
+ const repair = reconcileFocusedMessageQueries(client, "dm", "deleted")
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ retireCommunityChannelReading(registry, "deleted", { reason: "resource-deleted", serverId: null })
+ reject(new ApiError("gone", 404))
+ await repair
+ expect(registry.collections.channels.has("deleted")).toBe(false)
+ expect(client.getQueryData(key)).toBeUndefined()
+ unsubscribe()
+ })
+
it("retains the focused scope on transient reconnect failure", async () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_offline")
@@ -1093,7 +1192,7 @@ describe("focused message reconnect catch-up", () => {
it("keeps a tag-filtered active query scoped to the same tag", async () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
- const queryKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as const
+ const queryKey = communityKeys.channelMessagesWindow("forum_1", { mode: "newest" }, "bug")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
apiFetchMock.mockResolvedValue({ messages: [], hasMoreNewer: false, latestSeq: 2 })
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
index 662d0d2a2..869b21cfe 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,7 +1,8 @@
import { CancelledError, queryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"
+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { isConversationAnchorMissingError } from "@/lib/community/conversation-read"
import { ApiError, isAbortError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { getCommunityRuntime } from "@/stores/community/runtime"
@@ -32,8 +33,11 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
return { ...cache, pages }
}
-export function messageReconcileOptions(queryClient: QueryClient, scopeId: string, key: QueryKey) {
+export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey) {
+ const scopeId = scope.scopeId
const token = captureCommunityLiveSnapshotToken(queryClient, scopeId), registry = getCommunityDbRegistry(queryClient)
+ const channel = registry?.collections.channels.get(scopeId)
+ const serverId = scope.kind === "dm" ? null : channel ? channel.serverId : scope.serverId
const originalQuery = queryClient.getQueryCache().find({ queryKey: key, exact: true })
const receipt = { token, window: originalQuery }
return queryOptions({
@@ -82,10 +86,11 @@ export function messageReconcileOptions(queryClient: QueryClient, scopeId: strin
return { latestSeq: highWater }
} catch (error) {
assert()
- if (!(error instanceof ApiError) || (error.status !== 403 && error.status !== 404)) throw error
- const kind = key[1] === "dm" ? "dm" : "channel"
- getCommunityRuntime(queryClient).messageStream.actions.removeScope(kind === "dm" ? { kind, id: scopeId } : { kind, id: scopeId, serverId: "" })
- queryClient.removeQueries({ queryKey: key, exact: true })
+ if (!(error instanceof ApiError) || (error.status !== 403 && error.status !== 404) || isConversationAnchorMissingError(error)) throw error
+ if (registry) retireCommunityChannelReading(registry, scopeId, {
+ reason: "read-denied", serverId,
+ preserveQuery: queryClient.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true }),
+ })
return { latestSeq: 0 }
} finally {
const repair = queryClient.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })
@@ -108,7 +113,7 @@ function reconcile(queryClient: QueryClient, scope: GapRepairScope, target = 0)
try { assertCommunityLiveSnapshotTokenCurrent(queryClient, receipt.token, undefined) } catch { current = false }
if (!current) queryClient.removeQueries({ queryKey: repairKey, exact: true })
}
- return queryClient.query({ ...messageReconcileOptions(queryClient, scope.scopeId, query.queryKey), select: undefined }).catch((error: unknown) => {
+ return queryClient.query({ ...messageReconcileOptions(queryClient, scope, query.queryKey), select: undefined }).catch((error: unknown) => {
if (!isAbortError(error) && !(error instanceof CancelledError)) throw error
})
})).then(() => undefined)
@@ -123,4 +128,4 @@ export function scheduleFocusedMessageGapRepair(queryClient: QueryClient, scope:
return incomingSeq > known + 1 ? reconcile(queryClient, scope, incomingSeq).catch(() => undefined) : null
}
-export function reconcileFocusedMessageQueries(queryClient: QueryClient, kind: "channel" | "dm", scopeId: string): Promise<void> { return reconcile(queryClient, { kind, scopeId }) }
+export function reconcileFocusedMessageQueries(queryClient: QueryClient, kind: "channel" | "dm", scopeId: string, serverId?: string): Promise<void> { return reconcile(queryClient, { kind, scopeId, serverId }) }
diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
index 4f06060d7..d14b79790 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
@@ -1,4 +1,7 @@
import { seedCanonicalFocusedChannel } from "./test-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { ingestMessages, ingestServerDetail } from "@/lib/community-db/sync"
+import { ApiError } from "@/lib/errors"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -41,6 +44,42 @@ async function flushMicrotasks(iterations = 12) {
}
describe("useCommunityWs — resyncs machines on WS reconnect", () => {
+ it.each(["channelId", "secondaryChannelId"] as const)("keeps a captured %s in its own server when navigation switches servers before repair", async (field) => {
+ const { reconcileCommunityWsReconnect } = await import("./reconnect")
+ const { communityWsReconnectPolicies } = await import("./registry")
+ const { client, registry, runtime } = await createCommunityQueryOwner("scope-viewer")
+ const subscriptions: Array<() => void> = []
+ for (const serverId of ["server-A", "server-B"]) {
+ const id = serverId === "server-A" ? "channel-A" : "channel-B"
+ ingestServerDetail(registry, { id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "scope-viewer",
+ categories: [{ id: "category-" + serverId, name: "Chats", channels: [{ id, name: id, active: false, unread: false }] }] })
+ ingestMessages(registry, id, [{ id: "message-" + id, seq: 1, type: "chat", content: id }])
+ const queryKey = communityKeys.channelMessages(id)
+ client.setQueryData(queryKey, { pages: [{ messages: [{ id: "message-" + id, seq: 1 }], latestSeq: 1, hasMore: false }], pageParams: [{ mode: "newest" }] })
+ subscriptions.push(new QueryObserver(client, { queryKey, queryFn: async () => null, staleTime: Infinity }).subscribe(() => {}))
+ }
+ runtime.ui.actions.setCurrentServerId("server-A")
+ if (field === "channelId") runtime.ui.actions.subscribe({ channelId: "channel-A" })
+ else runtime.ui.actions.claimSecondaryChannel(Symbol("old-pane"), "channel-A")
+ const revoke = vi.spyOn(runtime.ws.actions, "revokeChannelAccess")
+ getCommunityApiFetchMock().mockRejectedValueOnce(new ApiError("forbidden", 403))
+ try {
+ const repairing = reconcileCommunityWsReconnect(client, 0, { excludePolicies: communityWsReconnectPolicies.filter((policy) => policy !== "focused-messages") })
+ runtime.ui.actions.setCurrentServerId("server-B")
+ runtime.ui.actions.subscribe({ channelId: "channel-B" })
+ await repairing
+ expect(getCommunityApiFetchMock()).toHaveBeenCalledExactlyOnceWith("/api/community/channels/channel-A/messages", expect.anything())
+ expect(revoke).toHaveBeenCalledWith("server-A", "channel-A")
+ expect(revoke).not.toHaveBeenCalledWith("server-B", "channel-A")
+ expect(client.getQueryData(communityKeys.channelMessages("channel-A"))).toBeUndefined()
+ expect(registry.collections.messages.has("message-channel-A")).toBe(false)
+ expect(client.getQueryData(communityKeys.channelMessages("channel-B"))).toBeDefined()
+ expect(registry.collections.messages.get("message-channel-B")?.content).toBe("channel-B")
+ expect(runtime.ws.actions.isChannelAccessRevoked("channel-B", "server-B")).toBe(false)
+ expect(runtime.ui.get().subscription.channelId).toBe("channel-B")
+ } finally { revoke.mockRestore(); for (const unsubscribe of subscriptions) unsubscribe() }
+ })
+
it("re-reads the authoritative self identity after a reconnect gap", async () => {
const apiFetch = getCommunityApiFetchMock()
apiFetch.mockImplementation(async (url: unknown) => {
@@ -372,7 +411,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
)?.isInvalidated).toBe(true)
})
- it("reconciles the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
+ it("reconciles the focused DM's messages on reconnect, without invalidating its entry resource", async () => {
const { useCommunityStore } = await import("@/stores/community")
getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_focus" })
@@ -386,7 +425,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
(c) => c[0]?.queryKey as unknown[] | undefined,
)
expect(invalidatedKeys).toContainEqual(communityKeys.channelMembers("dm_focus"))
- expect(invalidatedKeys).not.toContainEqual(communityKeys.dmReadStateSnapshot("dm_focus"))
+ expect(invalidatedKeys).not.toContainEqual(communityKeys.conversationEntry("dm_focus"))
expect(
invalidatedKeys.some(
(k) =>
diff --git a/src/web/src/hooks/community/message-surface-ownership.test.ts b/src/web/src/hooks/community/message-surface-ownership.test.ts
index 6ac7b898d..fdbe0b571 100644
--- a/src/web/src/hooks/community/message-surface-ownership.test.ts
+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts
@@ -7,6 +7,7 @@ import {
type CommunityDbRegistry,
} from "@/lib/community-db/collections"
import {
+ materializeCanonicalMessage,
materializeCanonicalMessages,
} from "@/lib/community-db/projections"
import {
@@ -33,6 +34,16 @@ afterEach(async () => {
})
describe("embedded message surface ownership", () => {
+ it("never promotes raw transport text when the canonical owner is unavailable or a row is missing", () => {
+ const transport: Msg = { id: "m1", type: "chat", content: "stale transport" }
+ expect(materializeCanonicalMessage(transport, undefined)).toBeUndefined()
+ expect(materializeCanonicalMessages([transport], undefined)).toEqual([])
+ expect(materializeCanonicalMessage(transport, new Map())).toBeUndefined()
+ expect(materializeCanonicalMessages([transport], new Map())).toEqual([])
+ const canonical: Msg = { ...transport, content: "canonical" }
+ expect(materializeCanonicalMessage(transport, new Map([["m1", canonical]]))).toBe(canonical)
+ })
+
it("publishes an empty first load once and projects WS edit/delete across every surface", async () => {
const queryClient = new QueryClient()
registry = createCommunityDbRegistry(queryClient, "viewer")
diff --git a/src/web/src/hooks/community/mutations/notifications.dom.test.ts b/src/web/src/hooks/community/mutations/notifications.dom.test.ts
index f757c924b..a906934d0 100644
--- a/src/web/src/hooks/community/mutations/notifications.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/notifications.dom.test.ts
@@ -89,17 +89,17 @@ describe("notification mutation cache refresh", () => {
await waitFor(() => expect(view.rendered.result.current.settings.server).toMatchObject({ server_1: "All Messages", server_2: "Nothing" }))
})
- it("refreshes settings, inbox, and all read-state snapshots after a server change", async () => {
+ it("refreshes settings, inbox, and the account read-state resource after a server change", async () => {
const view = await setup()
- const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.channelReadStateSnapshot("parent_1"), communityKeys.channelReadStateSnapshot("child_1"), communityKeys.dmReadStateSnapshot("dm_1")]
+ const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.accountReadStateSnapshot()]
for (const key of keys) view.client.setQueryData(key, { ids: [] })
await act(async () => { await view.rendered.result.current.command.mutateAsync({ serverId: "server_1", level: "Nothing" }) })
for (const key of keys) expect(view.client.getQueryState(key)?.isInvalidated).toBe(true)
})
- it("refreshes every read-state snapshot after a parent channel change", async () => {
+ it("refreshes the account read-state resource after a parent channel change", async () => {
const view = await setup("channel")
- const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.channelReadStateSnapshot("parent_1"), communityKeys.channelReadStateSnapshot("child_1"), communityKeys.dmReadStateSnapshot("dm_1")]
+ const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.accountReadStateSnapshot()]
const unrelated = ["application", "unrelated"]
for (const key of [...keys, unrelated]) view.client.setQueryData(key, { ids: [] })
await act(async () => { await view.rendered.result.current.command.mutateAsync({ channelId: "parent_1", level: "Nothing" }) })
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index 4b575b884..9270d8761 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -75,6 +75,6 @@ export function useChannelMessageFeed({
threads: threadsQuery.threads,
threadsLoading: threadsQuery.isLoading,
pinned: pinsQuery.pins,
- pinnedLoading: pinsQuery.isLoading,
+ pinnedLoading: pinsQuery.isLoading || pinsQuery.canonicalPending,
}
}
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index f453757ec..864d5013a 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -132,6 +132,7 @@ export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>
export function usePins(channelId: string | null): UseQueryResult<PinsWindowResponse> & {
pins: Msg[]
+ canonicalPending: boolean
} {
const queryClient = useQueryClient()
const enabled = !!channelId
@@ -152,5 +153,6 @@ export function usePins(channelId: string | null): UseQueryResult<PinsWindowResp
return {
...query,
pins: materializeCanonicalMessages(ids.map((id) => ({ id })), canonicalMessages),
+ canonicalPending: enabled && !!query.data && !query.isError && canonicalMessages === undefined,
}
}
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index 20cbd52d8..56110009f 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -301,6 +301,7 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>
export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowResponse> & {
marked: Marked[]
+ canonicalPending: boolean
} {
const queryClient = useQueryClient()
const unreadProjection = useMemo(
@@ -326,7 +327,7 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowRes
return message ? [{ ...marked, m: message }] : []
})
}, [canonicalMessages, query.data?.marked, markedAccess, pendingMarks])
- return { ...query, marked }
+ return { ...query, marked, canonicalPending: enabled && !!query.data && !query.isError && canonicalMessages === undefined }
}
export type MessageMarkedResponse = { marked: boolean }
diff --git a/src/web/src/hooks/community/use-messages.dom.test.ts b/src/web/src/hooks/community/use-messages.dom.test.ts
index 752ca6829..04ec8cfd2 100644
--- a/src/web/src/hooks/community/use-messages.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.dom.test.ts
@@ -1,3 +1,4 @@
+import { messageWindowOptions } from "@/lib/community/message-window"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -177,13 +178,10 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
expect(qc.getQueryData(key)).toBeDefined()
})
- // Foundation invariant: invalidating `channelMessages(channelId)` marks
- // every `channelMessagesPage(channelId, …)` variant as invalidated too.
- it("prefix invalidation via channelMessages(id) marks channelMessagesPage(id, cursor) invalidated", async () => {
- const { channelMessagesQueryFn } = await loadHook()
+ it("prefix invalidation includes anchored message windows", async () => {
apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })
const { client: qc } = await createCommunityQueryOwner()
- const cursorKey = communityKeys.channelMessagesPage("ch_1", "cur|abc")
+ const cursorKey = communityKeys.channelMessagesWindow("ch_1", { mode: "anchor", anchor: "m1" })
await qc.query({ queryKey: cursorKey, queryFn: () => apiFetchMock() })
expect(qc.getQueryData(cursorKey)).toBeDefined()
@@ -192,9 +190,8 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
})
})
-describe("dmMessagesQueryFn", () => {
+describe("shared DM message window transport", () => {
it("strips the authoritative receipt before QueryClient storage", async () => {
- const { dmMessagesQueryFn } = await loadHook()
apiFetchMock.mockResolvedValueOnce({
messages: [],
hasMore: false,
@@ -203,23 +200,19 @@ describe("dmMessagesQueryFn", () => {
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.dmMessages("dm_1")
- await qc.infiniteQuery({
- queryKey: key,
- queryFn: dmMessagesQueryFn("dm_1"),
- initialPageParam: { mode: "newest" } as const,
- })
+ await qc.infiniteQuery({ ...messageWindowOptions(qc, "dm_1", { mode: "newest" }), select: undefined })
const data = qc.getQueryData<InfiniteData<Record<string, unknown>>>(key)
expect(data?.pages[0]).not.toHaveProperty("surfaceReceipt")
})
it("passes TanStack's AbortSignal to apiFetch", async () => {
- const { dmMessagesQueryFn } = await loadHook()
+ const { channelMessagesQueryFn } = await loadHook()
const controller = new AbortController()
apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
const { client } = await createCommunityQueryOwner()
- await dmMessagesQueryFn("dm_abort")({
+ await channelMessagesQueryFn("dm_abort")({
client,
pageParam: { mode: "newest" },
signal: controller.signal,
@@ -234,18 +227,18 @@ describe("dmMessagesQueryFn", () => {
})
it("newest → no query params", async () => {
- const { dmMessagesQueryFn } = await loadHook()
+ const { channelMessagesQueryFn } = await loadHook()
apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
const { client } = await createCommunityQueryOwner()
- await dmMessagesQueryFn("dm_1")({ client, signal: new AbortController().signal, pageParam: { mode: "newest" } })
+ await channelMessagesQueryFn("dm_1")({ client, signal: new AbortController().signal, pageParam: { mode: "newest" } })
expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/dm_1/messages", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
})
it("older cursor → ?cursor", async () => {
- const { dmMessagesQueryFn } = await loadHook()
+ const { channelMessagesQueryFn } = await loadHook()
apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
const { client } = await createCommunityQueryOwner()
- await dmMessagesQueryFn("dm_1")({
+ await channelMessagesQueryFn("dm_1")({
client,
signal: new AbortController().signal,
pageParam: { mode: "older", cursor: "cur_1" },
@@ -257,18 +250,14 @@ describe("dmMessagesQueryFn", () => {
})
it("fetchNextPage (older) produces a new page under the same infinite key", async () => {
- const { dmMessagesQueryFn } = await loadHook()
apiFetchMock
.mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: true, cursor: "cur_1", latestSeq: 1 })
.mockResolvedValueOnce({ messages: [{ id: "m_2" }], hasMore: false, latestSeq: 1 })
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.dmMessages("dm_1")
await qc.infiniteQuery({
- queryKey: key,
- queryFn: dmMessagesQueryFn("dm_1"),
- initialPageParam: { mode: "newest" } as const,
- getNextPageParam: (last: { hasMore?: boolean; cursor?: string }) =>
- last.hasMore && last.cursor ? { mode: "older" as const, cursor: last.cursor } : undefined,
+ ...messageWindowOptions(qc, "dm_1", { mode: "newest" }),
+ select: undefined,
pages: 2,
})
const data = qc.getQueryData<InfiniteData<{ messages: unknown[] }>>(key)
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 68c340257..8f0d3930e 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -17,7 +17,7 @@ import type { findConversationEntryWindow } from "@/lib/community/conversation-e
import type { Msg } from "@/lib/community/models/message"
import { messageReconcileOptions } from "./community-ws/reconnect-messages"
-export { channelMessagesQueryFn, dmMessagesQueryFn } from "@/lib/community/message-window"
+export { channelMessagesQueryFn } from "@/lib/community/message-window"
export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"
export function messageMatchesTag(message: Msg, tag?: string | null): boolean {
@@ -102,7 +102,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const options = messageWindowOptions(client, enabled ? channelId : "__none__", initial, tag, { observation })
const queryKey = selectedWindow?.key ?? options.queryKey
const query = useInfiniteQuery({ ...options, queryKey, enabled, subscribed: enabled })
- useQuery({ ...messageReconcileOptions(client, channelId ?? "__none__", queryKey), enabled: false, subscribed: enabled })
+ useQuery({ ...messageReconcileOptions(client, { kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined }, queryKey), enabled: false, subscribed: enabled })
const originalQuery = client.getQueryCache().find({ queryKey, exact: true })
const owner = useMemo(() => ({ present, query: originalQuery, enabled }), [present, originalQuery, enabled])
const committed = useRef<typeof owner | null>(null)
@@ -172,7 +172,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const error = query.error ?? entry.error
const windowAvailable = !!selectedWindow && query.data !== undefined
const initialLoadError = windowAvailable ? null : error ?? (entry.failed ? INITIAL_ENTRY_ERROR : null)
- const loading = !!channelId && (windowAvailable ? projection.messages === undefined : !initialLoadError && !entry.denied && !entry.anchorMissing)
+ const loading = !!channelId && (windowAvailable ? projection.canonicalMessages === undefined : !initialLoadError && !entry.denied && !entry.anchorMissing)
const entryWindow = entry.window, retryEntry = entry.retry, refetchWindow = query.refetch
const retryInitialLoad = useCallback(() => {
if (entryWindow) void refetchWindow({ cancelRefetch: false })
diff --git a/src/web/src/lib/cache.test.ts b/src/web/src/lib/cache.test.ts
index 7c9b27265..89dc7f2f1 100644
--- a/src/web/src/lib/cache.test.ts
+++ b/src/web/src/lib/cache.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { cached, cachedBatch, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV, throttled } from "./cache";
+import { cached, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV, throttled } from "./cache";
function createMockKV() {
const store = new Map<string, { value: string; expiration?: number }>();
@@ -108,61 +108,6 @@ describe("cache", () => {
});
});
- describe("cachedBatch()", () => {
- it("returns all from KV on full cache hit", async () => {
- mockKV._store.set("k1", { value: JSON.stringify("v1") });
- mockKV._store.set("k2", { value: JSON.stringify("v2") });
- const fetchMissing = vi.fn();
-
- const result = await cachedBatch(["k1", "k2"], 300, fetchMissing);
-
- expect(result.get("k1")).toBe("v1");
- expect(result.get("k2")).toBe("v2");
- expect(fetchMissing).not.toHaveBeenCalled();
- });
-
- it("fetches missing keys from D1 and stores in KV", async () => {
- mockKV._store.set("k1", { value: JSON.stringify("cached") });
- const fetchMissing = vi.fn(async (keys: string[]) => {
- const m = new Map<string, string>();
- for (const k of keys) m.set(k, `fetched-${k}`);
- return m;
- });
-
- const result = await cachedBatch(["k1", "k2", "k3"], 300, fetchMissing);
-
- expect(result.get("k1")).toBe("cached");
- expect(result.get("k2")).toBe("fetched-k2");
- expect(result.get("k3")).toBe("fetched-k3");
- expect(fetchMissing).toHaveBeenCalledWith(["k2", "k3"]);
- expect(mockKV.put).toHaveBeenCalledTimes(2);
- });
-
- it("falls back to full D1 fetch when KV throws", async () => {
- (mockKV.get as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("KV down"));
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const fetchMissing = vi.fn(async (keys: string[]) => {
- const m = new Map<string, string>();
- for (const k of keys) m.set(k, `db-${k}`);
- return m;
- });
-
- const result = await cachedBatch(["k1", "k2"], 300, fetchMissing);
-
- expect(result.get("k1")).toBe("db-k1");
- expect(result.get("k2")).toBe("db-k2");
- expect(fetchMissing).toHaveBeenCalledWith(["k1", "k2"]);
- warnSpy.mockRestore();
- });
-
- it("returns empty map for empty keys", async () => {
- const fetchMissing = vi.fn();
- const result = await cachedBatch([], 300, fetchMissing);
- expect(result.size).toBe(0);
- expect(fetchMissing).not.toHaveBeenCalled();
- });
- });
-
describe("invalidate()", () => {
it("deletes key from KV", async () => {
mockKV._store.set("del-key", { value: "x" });
@@ -321,15 +266,6 @@ describe("cache", () => {
const result = await cached("key", 300, async () => "db-value");
expect(result).toBe("db-value");
- // cachedBatch() should fetch all from D1
- const batchResult = await cachedBatch(
- ["k1", "k2"],
- 300,
- async (keys) => new Map(keys.map((k) => [k, `val-${k}`])),
- );
- expect(batchResult.get("k1")).toBe("val-k1");
- expect(batchResult.get("k2")).toBe("val-k2");
-
// invalidate() should not throw
await expect(invalidate("key")).resolves.toBeUndefined();
await expect(invalidateMany(["k1", "k2"])).resolves.toBeUndefined();
diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.ts
index e36ecab15..3f57d0c4c 100644
--- a/src/web/src/lib/cache.ts
+++ b/src/web/src/lib/cache.ts
@@ -21,7 +21,7 @@
* see a stale value for up to the cache TTL (~60s default).
*
* ✅ Use this module for:
- * - Pure TTL memoization / read-through cache (`cached`, `cachedBatch`)
+ * - Pure TTL memoization / read-through cache (`cached`)
* - Best-effort throttles where a double-run is safe (`throttled`)
* - Negative-cache flags with short TTLs, config, feature flags,
* whitelists, static-content indexes — the classic "write rarely,
@@ -94,55 +94,6 @@ export async function cached<T>(
return value;
}
-/**
- * Batch-get from KV. Returns { hits, misses } where hits is a Map of found entries
- * and misses is the list of keys that need to be fetched from D1.
- * On KV failure, all keys are returned as misses (graceful fallback).
- */
-export async function cachedBatch<T>(
- keys: string[],
- ttlSeconds: number,
- fetchMissing: (missingKeys: string[]) => Promise<Map<string, T>>,
-): Promise<Map<string, T>> {
- if (keys.length === 0) return new Map();
-
- const kv = getKV();
- const result = new Map<string, T>();
- let missingKeys = keys;
-
- if (kv) {
- const hits: string[] = [];
- await Promise.all(
- keys.map(async (key) => {
- try {
- const raw = await kv.get(key);
- if (raw) {
- result.set(key, JSON.parse(raw) as T);
- hits.push(key);
- }
- } catch (err) {
- log.warn("KV batch read failed", { key, err });
- }
- }),
- );
- missingKeys = keys.filter((k) => !hits.includes(k));
- }
-
- if (missingKeys.length > 0) {
- const fetched = await fetchMissing(missingKeys);
- for (const [key, value] of fetched) {
- result.set(key, value);
- if (value != null && kv) {
- kv.put(key, JSON.stringify(value), { expirationTtl: Math.max(ttlSeconds, MIN_KV_TTL) }).catch((err) => {
- log.warn("KV batch write failed", { key, err });
- });
- }
- }
- }
-
- return result;
-}
-
/**
* Timestamp-based throttle — not limited by KV's 60s minimum TTL.
* Stores last-run timestamp in KV; skips `fn` if within `intervalSeconds`.
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
index b5695bb16..277d68ea0 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -16,7 +16,7 @@ import {
getMemberReadState,
useChannelRefDirectoryProjection,
useDmProjection,
- useMessageProjection,
+ useMessageWindowProjection,
useNotificationSettingsProjection,
useRouteChannelProjection,
useServerRailProjection,
@@ -75,11 +75,11 @@ describe("community DB projections", () => {
const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children),
)
- const observations: Array<{ array: ReturnType<typeof useMessageProjection>; map: ReturnType<typeof useCanonicalMessagesById> }> = []
+ const observations: Array<{ array: ReturnType<typeof useMessageWindowProjection>["canonicalMessages"]; map: ReturnType<typeof useCanonicalMessagesById> }> = []
const rendered = renderHook(() => {
- const array = useMessageProjection("c1", ["selected"]), map = useCanonicalMessagesById(["selected"])
+ const array = useMessageWindowProjection("c1", ["selected"], []).canonicalMessages, map = useCanonicalMessagesById(["selected"])
observations.push({ array, map })
- return { array, map, nullScope: useMessageProjection(null), emptyScope: useMessageProjection("") }
+ return { array, map, nullScope: useMessageWindowProjection(null, [], []).canonicalMessages, emptyScope: useMessageWindowProjection("", [], []).canonicalMessages }
}, { wrapper })
try {
expect(observations[0]?.array).toEqual([])
@@ -186,7 +186,7 @@ describe("community DB projections", () => {
tree: useServerTreeProjection("s1"),
dms: useDmProjection(),
route: useRouteChannelProjection("c1"),
- messages: useMessageProjection("c1"),
+ messages: useMessageWindowProjection("c1", ["m1"], []).canonicalMessages,
messagesById: useCanonicalMessagesById(),
notifications: useNotificationSettingsProjection(),
directory: useChannelRefDirectoryProjection(),
@@ -452,7 +452,7 @@ describe("community DB projections", () => {
tree: useServerTreeProjection("s1"),
dms: useDmProjection(),
route: useRouteChannelProjection("c1"),
- messages: useMessageProjection("c1"),
+ messages: useMessageWindowProjection("c1", ["m1", "m2"], []).canonicalMessages,
messagesById: useCanonicalMessagesById(),
notifications: useNotificationSettingsProjection(),
profiles: useCanonicalProfilesByUserId(),
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 47faeeff1..cb60baacf 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -21,7 +21,6 @@ import type { CommunityDbRegistry } from "./collections"
import { communityCollectionQuery, communityJoinedMessagesQuery } from "./queries"
import { communityProjection } from "./live-query"
import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"
-import { MAX_PERSISTED_MESSAGES_PER_SCOPE } from "@/lib/query-persister"
import type {
CommunityCollectionName,
@@ -313,19 +312,6 @@ function useJoinedMessageQuery(channelId: string | null | undefined, ids?: reado
return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow }> | undefined }
}
-export function useMessageProjection(channelId: string | null, ids?: readonly string[]) {
- const { data } = useJoinedMessageQuery(channelId, ids)
- return useMemo(() => {
- if (!channelId || !data) return undefined
- const messages = data
- .sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0))
- .map(({ message, child }) => {
- return projectedMessage(message, child)
- })
- return messages
- }, [channelId, data])
-}
-
export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<string, Msg> | undefined {
const { registry, data } = useJoinedMessageQuery(undefined, ids)
return useMemo(() => !registry ? undefined : new Map(
@@ -335,21 +321,13 @@ export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<s
), [registry, data])
}
-export function useMessageWindowProjection(channelId: string | null, ids: readonly string[] | undefined, liveIds: readonly string[]) {
- const registry = useOptionalCommunityDbRegistry()
- const warm = useLiveQuery({ query: (q) => registry && channelId && ids === undefined
- ? q.from({ message: registry.collections.messages }).where(({ message }) => eq(message.channelId, channelId))
- .orderBy(({ message }) => message.seq, "desc").orderBy(({ message }) => message.id, "desc")
- .limit(MAX_PERSISTED_MESSAGES_PER_SCOPE).select(({ message }) => ({ id: message.id }))
- : undefined }).data as Array<{ id: string }> | undefined
- const selected = useMemo(() => ids ?? warm?.map((message) => message.id) ?? [], [ids, warm])
- const allIds = useMemo(() => [...new Set([...selected, ...liveIds])], [selected, liveIds])
+export function useMessageWindowProjection(channelId: string | null, ids: readonly string[], liveIds: readonly string[]) {
+ const allIds = useMemo(() => [...new Set([...ids, ...liveIds])], [ids, liveIds])
const { data } = useJoinedMessageQuery(channelId, allIds)
const canonicalMessages = useMemo(() => !channelId || !data ? undefined : data
.sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0))
.map(({ message, child }) => projectedCanonicalMessage(message, child)), [channelId, data])
- const messages = useMemo(() => canonicalMessages?.map(presentCanonicalMessage), [canonicalMessages])
- return { messages, canonicalMessages, windowIds: selected }
+ return { canonicalMessages, windowIds: ids }
}
function useCollectionById<N extends "channels" | "servers">(name: N) {
@@ -373,19 +351,17 @@ export function materializeCanonicalMessage(
transport: Pick<Msg, "id">,
canonical: ReadonlyMap<string, Msg> | undefined,
): Msg | undefined {
- return canonical === undefined ? transport as Msg : canonical.get(transport.id)
+ return canonical?.get(transport.id)
}
export function materializeCanonicalMessages(
transport: readonly Pick<Msg, "id">[],
canonical: ReadonlyMap<string, Msg> | undefined,
): Msg[] {
- return canonical === undefined
- ? [...transport] as Msg[]
- : transport.flatMap((message) => {
- const row = canonical.get(message.id)
- return row ? [row] : []
- })
+ return transport.flatMap((message) => {
+ const row = canonical?.get(message.id)
+ return row ? [row] : []
+ })
}
export function useNotificationSettingsProjection() {
diff --git a/src/web/src/lib/community/document-seed.server.test.ts b/src/web/src/lib/community/document-seed.server.test.ts
index ff8ed3a0a..7cce569c0 100644
--- a/src/web/src/lib/community/document-seed.server.test.ts
+++ b/src/web/src/lib/community/document-seed.server.test.ts
@@ -41,7 +41,7 @@ function Probe() {
const self = useCanonicalCommunityProfile("viewer")
const channel = useRouteChannelProjection("c1")
const messages = useMessageWindowProjection("c1", ["m1"], [])
- return createElement("span", null, `${self?.name}:${channel?.name}:${messages.messages?.[0]?.content}`)
+ return createElement("span", null, `${self?.name}:${channel?.name}:${messages.canonicalMessages?.[0]?.content}`)
}
describe("document resource handoff", () => {
diff --git a/src/web/src/lib/community/message-window.server.ts b/src/web/src/lib/community/message-window.server.ts
index 15937e8b6..f8fa2633d 100644
--- a/src/web/src/lib/community/message-window.server.ts
+++ b/src/web/src/lib/community/message-window.server.ts
@@ -1,4 +1,4 @@
-import { queries, type CommunityContract, type Database } from "@alook/shared"
+import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, queries, type CommunityContract, type Database } from "@alook/shared"
import { buildAnchorResponse, buildPaginatedResponse, buildSinceResponse, type parseCommunityMessageWindow } from "./messages"
import { enrichMessages } from "./enrich-messages"
import type { DoorTarget } from "./message-door"
@@ -10,7 +10,7 @@ export async function readCommunityMessageWindow(db: Database, input: {
window: ReturnType<typeof parseCommunityMessageWindow>
contract: CommunityContract
tag?: string
-}): Promise<{ ok: true; page: MessagePage } | { ok: false; status: 404; error: string }> {
+}): Promise<{ ok: true; page: MessagePage } | { ok: false; status: 404; error: string; details: string[] }> {
const { viewerId, target, window: { anchorId, since, cursor, pageSize }, contract, tag } = input
const channelId = target.target.channelId
const scope = { channelId, isDm: target.isDm, isForum: target.target.kind === "forum", contract }
@@ -18,7 +18,7 @@ export async function readCommunityMessageWindow(db: Database, input: {
if (anchorId) {
const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })
- if (!anchor) return { ok: false, status: 404, error: "anchor not found" }
+ if (!anchor) return { ok: false, status: 404, error: "anchor not found", details: [COMMUNITY_CONVERSATION_ANCHOR_MISSING] }
const around = await queries.communityMessage.listMessagesAround(db, {
channelId, anchor: { createdAt: anchor.createdAt, id: anchor.id }, limit: pageSize, tag,
})
diff --git a/src/web/src/lib/community/message-window.test.ts b/src/web/src/lib/community/message-window.test.ts
index 82bb2ab5d..cada9dac8 100644
--- a/src/web/src/lib/community/message-window.test.ts
+++ b/src/web/src/lib/community/message-window.test.ts
@@ -29,6 +29,7 @@ describe("native message window identity", () => {
expect(messageWindowIdentity(options.queryKey)?.channelId).toBe("c1")
}
expect(messageWindowIdentity([...specs[1].queryKey, "reconcile"])).toBeUndefined()
+ expect(messageWindowIdentity([...communityKeys.channelMessages("c1"), "tag", "old"])).toBeUndefined()
expect(messageWindowIdentity(["foreign", "channel", "c1", "messages"])).toBeUndefined()
expect(messageWindowIdentity([...communityKeys.channelMessages("c1"), "window", { mode: "anchor", anchor: "m1", tag: null, extra: true }])).toBeUndefined()
})
diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.ts
index eb69bf886..ba40e997b 100644
--- a/src/web/src/lib/community/message-window.ts
+++ b/src/web/src/lib/community/message-window.ts
@@ -93,17 +93,12 @@ export const channelMessagesQueryFn =
return messageWindowPage(page)
}
-export const dmMessagesQueryFn =
- (dmId: string, options?: MessagesTransportOptions) =>
- channelMessagesQueryFn(dmId, undefined, options)
-
export type InitialMessageWindow = Extract<MessagesPageParam, { mode: "newest" | "anchor" | "since" }>
export type MessageWindowData = InfiniteData<MessagesPage, MessagesPageParam>
export function messageWindowIdentity(key: QueryKey): { channelId: string; initial: InitialMessageWindow; tag: string | null } | undefined {
if (key[0] !== "community" || key[1] !== "channel" || typeof key[2] !== "string" || key[3] !== "messages") return
if (key.length === 4) return { channelId: key[2], initial: { mode: "newest" }, tag: null }
- if (key.length === 6 && key[4] === "tag" && typeof key[5] === "string") return { channelId: key[2], initial: { mode: "newest" }, tag: key[5] }
if (key.length !== 6 || key[4] !== "window" || !key[5] || typeof key[5] !== "object") return
const value = key[5] as Record<string, unknown>
if (value.tag !== null && typeof value.tag !== "string") return
diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.ts
index a9917395d..491aa760b 100644
--- a/src/web/src/lib/community/read-contract.test.ts
+++ b/src/web/src/lib/community/read-contract.test.ts
@@ -37,7 +37,6 @@ describe("common reading negotiation", () => {
})
it("gives DM and channel transports a single target identity", () => {
expect(communityKeys.dmMessages("channel")).toEqual(communityKeys.channelMessages("channel"))
- expect(communityKeys.dmReadStateSnapshot("channel")).toEqual(communityKeys.channelReadStateSnapshot("channel"))
expect(communityKeys.channelMeta(null, "channel")).toEqual(communityKeys.channelMeta("server", "channel"))
expect(communityKeys.channelMembers("channel", "access")).not.toEqual(communityKeys.channelMembers("channel", "notify"))
})
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 96a108c63..29c30e16f 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -17,7 +17,6 @@ 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']", () => {
@@ -85,17 +84,6 @@ describe("communityKeys", () => {
const messagesRoot = communityKeys.channelMessages("c1")
expect(messagesRoot).toEqual(["community", "channel", "c1", "messages"])
- // Cursor-page keys extend the root so invalidateQueries on the root
- // clears every page.
- expect(communityKeys.channelMessagesPage("c1", "cur-1")).toEqual([
- ...messagesRoot,
- "cur-1",
- ])
- expect(communityKeys.channelMessagesPage("c1")).toEqual([
- ...messagesRoot,
- null,
- ])
-
expect(communityKeys.pins("c1")).toEqual([
"community",
"channel",
@@ -120,11 +108,6 @@ describe("communityKeys", () => {
const dmRoot = communityKeys.dmMessages("d1")
expect(dmRoot).toEqual(["community", "channel", "d1", "messages"])
- expect(communityKeys.dmMessagesPage("d1", "cur-1")).toEqual([
- ...dmRoot,
- "cur-1",
- ])
- expect(communityKeys.dmMessagesPage("d1")).toEqual([...dmRoot, null])
})
it("nests inbox feeds under a shared inbox() prefix", () => {
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 9c0d4700d..75a1c323b 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -11,9 +11,7 @@ import type { MessagesPageParam } from "./community/models/message"
* inbox feeds under it, `invalidateQueries({ queryKey: communityKeys.server(id) })`
* invalidates every subkey of that server, and so on.
* - Parameterisation matches the underlying route params. Message list keys
- * include an optional cursor so pagination pages nest under a stable
- * channel-scoped root (useful for `useInfiniteQuery` and for invalidating
- * all pages of one channel in a single call).
+ * identify a loaded window under a stable channel-scoped root.
*/
export const communityKeys = {
all: ["community"] as const,
@@ -64,9 +62,6 @@ export const communityKeys = {
[...communityKeys.all, "invite-info", token] as const,
// ── Channel-scoped resources ────────────────────────────────────────────
- // Message list roots are keyed by channelId so paginated pages nest under
- // a stable prefix. Cursor-specific keys use `channelMessagesPage`; consumers
- // that want to invalidate every page of a channel use `channelMessages`.
channelMessages: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "messages"] as const,
channelMessagesWindow: (channelId: string, initial: Extract<MessagesPageParam, { mode: "newest" | "anchor" | "since" }>, tag?: string | null) =>
@@ -77,14 +72,8 @@ export const communityKeys = {
[...communityKeys.conversationEntries(channelId), {
serverId: intent.serverId ?? null, anchorMessageId: intent.anchorMessageId ?? null, tag: intent.tag ?? null, preferTail: intent.preferTail === true,
}, ...(qualification ? [qualification] : [])] as const,
- channelMessagesPage: (channelId: string, cursor?: string | null) =>
- [...communityKeys.channelMessages(channelId), cursor ?? null] as const,
-
dmMessages: (dmId: string) =>
communityKeys.channelMessages(dmId),
- dmMessagesPage: (dmId: string, cursor?: string | null) =>
- [...communityKeys.dmMessages(dmId), cursor ?? null] as const,
-
// Explicit membership roster of a private-category channel + the addable
// (not-yet-member) server members for its picker.
channelMembers: (channelId: string, relation?: "access" | "notify") =>
@@ -107,16 +96,6 @@ export const communityKeys = {
[...communityKeys.forumFeeds(channelId), tag] as const,
forumTags: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "forum-tags"] as const,
- // #3: the viewer's `communityReadState` row for a single channel, fetched
- // once per channel mount and frozen thereafter so the "New" divider stays
- // anchored while the watermark advances.
- channelReadStateSnapshot: (channelId: string) =>
- [...communityKeys.all, "channel", channelId, "read-state-snapshot"] as const,
- // DM sibling of `channelReadStateSnapshot`. Same freeze semantics — the
- // hook latches the first non-null response so the "New" divider anchor
- // stays put while the progressive watermark advances.
- dmReadStateSnapshot: (dmId: string) =>
- communityKeys.channelReadStateSnapshot(dmId),
accountReadStateSnapshot: () =>
[...communityKeys.all, "read-state-snapshot"] as const,
accountAttention: () =>
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index ce5afe1e7..736689556 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -44,15 +44,15 @@ describe("shouldPersistQueryKey", () => {
expect(shouldPersistQueryKey(communityKeys.server("srv_1"))).toBe(false)
})
- it("does NOT persist channel read-state snapshot (refetched on every mount)", () => {
+ it("does NOT persist channel entry qualification", () => {
expect(
- shouldPersistQueryKey(communityKeys.channelReadStateSnapshot("ch_1")),
+ shouldPersistQueryKey(communityKeys.conversationEntry("ch_1", { serverId: "srv_1" })),
).toBe(false)
})
- it("does NOT persist DM read-state snapshot (refetched on every mount)", () => {
+ it("does NOT persist DM entry qualification", () => {
expect(
- shouldPersistQueryKey(communityKeys.dmReadStateSnapshot("dm_1")),
+ shouldPersistQueryKey(communityKeys.conversationEntry("dm_1")),
).toBe(false)
})
@@ -659,7 +659,7 @@ describe("shouldPersistQuery", () => {
expect(shouldPersistQuery(communityKeys.servers(), { servers: [] })).toBe(false)
expect(shouldPersistQuery(communityKeys.channelMessages("ch_1"), undefined)).toBe(false)
expect(
- shouldPersistQuery(communityKeys.channelReadStateSnapshot("ch_1"), {
+ shouldPersistQuery(communityKeys.conversationEntry("ch_1", { serverId: "srv_1" }), {
lastReadMessageId: "m_1",
}),
).toBe(false)
diff --git a/src/web/src/test/community-query-owner.ts b/src/web/src/test/community-query-owner.ts
index 530ec3402..d92c2d2d6 100644
--- a/src/web/src/test/community-query-owner.ts
+++ b/src/web/src/test/community-query-owner.ts
@@ -5,6 +5,8 @@ import { createCommunityDbRegistry, getCommunityDbRegistry, type CommunityDbRegi
import { ingestMessages } from "@/lib/community-db/sync"
import type { MessagesPage } from "@/hooks/community/use-messages"
import { getCommunityRuntime } from "@/stores/community/runtime"
+import { communityKeys } from "@/lib/query-keys"
+import type { ReadStateRow } from "@/lib/community-db/schema"
import { EMPTY_STORED, messageScopeKey } from "@/stores/community/message-stream-store"
import type { MessageScope } from "@/lib/community/message-stream"
@@ -34,6 +36,14 @@ export function seedCommunityMessageWindow(client: QueryClient, key: QueryKey, w
pages: window.pages.map((page) => ({ ...page, hasMoreNewer: page.hasMoreNewer ?? false, messages: page.messages.map(({ id }) => ({ id })) })),
}, options)
}
+export function seedCommunityReadState(client: QueryClient, channelId: string, row: { lastReadMessageId?: string | null; lastReadAt?: string | null; lastReadSeq: number }) {
+ const registry = getCommunityDbRegistry(client)
+ if (!registry) throw new Error("Read-state fixture requires its original owner")
+ client.setQueryData<ReadStateRow[]>(communityKeys.communityDbCollection(registry.scopeId, "readStates"), (rows) => [
+ ...(rows ?? []).filter((current) => current.channelId !== channelId),
+ { channelId, lastReadMessageId: null, lastReadAt: null, ...row },
+ ])
+}
beforeEach(() => async () => {
const retire = async () => {
for (const registry of owners) { await registry.cleanup(); registry.queryClient.clear() }