Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): preserve confirmed read state across late attention
Gener21b5a66fcaf5
diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.tsindex c28053c2f..805e4a8af 100644--- a/src/web/src/hooks/community/account-unread-projection.ts+++ b/src/web/src/hooks/community/account-unread-projection.ts@@ -644,6 +644,10 @@ export class AccountUnreadProjection {}+ getConfirmedReadSeq(channelId: string) {+ return this.disposed ? undefined : this.readSeq.get(channelId)+ }+recordRead(channelId: string, seq: number) {return this.transition(() => {if (this.disposed || !Number.isSafeInteger(seq) || seq <= 0) returndiff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.tsindex 48c4f08ef..5ffa76097 100644--- a/src/web/src/hooks/community/read-coordinator.test.ts+++ b/src/web/src/hooks/community/read-coordinator.test.ts@@ -1,3 +1,4 @@+import { AccountAttentionSnapshotSchema } from "@alook/shared"import { QueryClient } from "@tanstack/react-query"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { ApiError } from "@/lib/errors"@@ -9,6 +10,8 @@ import {} from "@/lib/community-db/collections"import {ingestAttentionSnapshot,+ captureCommunityLiveSnapshotToken,+ publishAccountAttentionSnapshot,ingestMessages,projectCommunityWsEventToDb,} from "@/lib/community-db/sync"@@ -1174,6 +1177,51 @@ describe("read coordinator", () => {expect(apiFetch).not.toHaveBeenCalled()})+ it.each([true, false])("preserves only successful PUT confirmation after failed reconciliation and a late valid attention snapshot (committed: %s)", async (committed) => {+ const queryClient = createOwnedClient()+ const db = getCommunityDbRegistry(queryClient)!+ await db.preload()+ const at = "2026-10-08T00:00:00.000Z"+ const snapshot = (seq: number) => AccountAttentionSnapshotSchema.parse({+ scopes: [{ scopeId: "channel-1", channelId: "channel-1", serverId: "server-1", parentChannelId: "forum-1", ordinaryUnread: true, lastUnreadSeq: seq, lastAttentionSeq: seq, attentionCount: 1 }],+ items: [{ id: `reply:message-${seq}`, kind: "reply", sourceId: `message-${seq}`, scopeId: "channel-1", messageId: `message-${seq}`, actorUserId: "peer", createdAt: at }],+ limit: 100, truncated: false,+ included: {+ servers: [{ id: "server-1", name: "Server", discriminator: "0001" }],+ channels: [+ { id: "forum-1", serverId: "server-1", name: "Forum", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "peer", archived: false, lastMessageAt: at },+ { id: "channel-1", serverId: "server-1", name: "Post", type: "thread", parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: "peer", archived: false, lastMessageAt: at, openerSeq: 1, openerUnread: true },+ ],+ dms: [], profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }],+ messages: [+ { id: "opener-1", channelId: "forum-1", type: "chat", authorId: "peer", seq: 1, createdAt: at, content: "Title" },+ { id: `message-${seq}`, channelId: "channel-1", type: "chat", authorId: "peer", seq, createdAt: at, content: "Reply" },+ ],+ },+ })+ const token = captureCommunityLiveSnapshotToken(queryClient)+ const lease = timelineLease(queryClient)+ if (committed) apiFetch.mockResolvedValue({ changed: true, revision: 14, targetSeq: 4 })+ else apiFetch.mockRejectedValue(new ApiError("forbidden", 403))+ reconcileAccountReadState.mockRejectedValue(new Error("snapshot unavailable"))+ submitTimeline(lease, 4)+ await expect(flushPendingReadIntents(queryClient)).resolves.toMatchObject({ consumed: false, cutoff: 1 })+ releaseReadSurface(lease)+ await vi.advanceTimersByTimeAsync(1)+ expect(db.collections.readStates.get("channel-1")).toBeUndefined()+ expect(publishAccountAttentionSnapshot(queryClient, { snapshot: snapshot(4), proof: { token, signal: undefined } })).toBe("published")+ if (committed) {+ expect(db.collections.attentionScopes.get("channel-1")).toBeUndefined()+ expect(db.collections.attentionItems.get("reply:message-4")).toBeUndefined()+ } else {+ expect(db.collections.attentionScopes.get("channel-1")).toMatchObject({ ordinaryUnread: true, attentionCount: 1 })+ expect(db.collections.attentionItems.get("reply:message-4")).toBeDefined()+ }+ ingestAttentionSnapshot(db, snapshot(5))+ expect(db.collections.attentionScopes.get("channel-1")).toMatchObject({ ordinaryUnread: true, lastUnreadSeq: 5, attentionCount: 1 })+ expect(db.collections.attentionItems.get("reply:message-5")).toBeDefined()+ })+it("absorbs reconciliation failures after a committed read response", async () => {const queryClient = createOwnedClient()const lease = timelineLease(queryClient)diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.tsindex d812b26aa..a2311c4f3 100644--- a/src/web/src/hooks/community/read-coordinator.ts+++ b/src/web/src/hooks/community/read-coordinator.ts@@ -26,6 +26,7 @@ import {clearAttentionScopeOptimistically,commitAttentionScopeOptimisticSnapshot,hasAttentionScopeOptimisticFence,+ projectConfirmedAttention,restoreAttentionScopeOptimisticSnapshot,type AttentionScopeOptimisticSnapshot,} from "@/lib/community-db/sync"@@ -393,6 +394,10 @@ class ReadCoordinator {return { committed: false, reconciled: false }}if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }+ const unreadProjection = getAccountUnreadProjection(this.queryClient, this.ownerUserId)+ unreadProjection.recordRead(target.intent.channelId, response.targetSeq)+ const registry = getCommunityDbRegistry(this.queryClient)+ if (registry) projectConfirmedAttention(registry)await settleInboxReadReservationGeneration(this.queryClient, target.generation, true, target.intent.channelId)if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }this.update(key, (scope) => ({ ...scope, confirmedSeq: Math.max(scope.confirmedSeq, response.targetSeq), dirty: sameIntent(scope.dirty ?? target, target) ? null : scope.dirty, inFlight: scope.inFlight ? { ...scope.inFlight, phase: "reconciling" } : null }))@@ -401,7 +406,6 @@ class ReadCoordinator {const defer = active.deferInboxDms?.() === true || active.drainCutoff !== undefined && current.accepted !== null && current.accepted.generation > active.drainCutofftry {target.request.assertActive()- const registry = getCommunityDbRegistry(this.queryClient)await Promise.all([reconcileAccountReadState(this.queryClient, { surfaceMode: defer ? "non-inbox" : "all", awaitSurfaceMode: defer ? "none" : "inbox-dms", targetRevision: response.revision }),registry ? reconcileAccountAttention(registry).catch(() => undefined) : Promise.resolve(),diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.tsindex 1fddb8d23..b69dc5bb1 100644--- a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts+++ b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts@@ -495,8 +495,13 @@ describe("thread opener read handoff", () => {)await Promise.resolve()})- expect(readObserver.observed.has(messageRow)).toBe(true)+ expect(readObserver.disconnected).toBe(true)emitReadIntersection(readObserver, messageRow)+ expect(mocks.submit).not.toHaveBeenCalled()+ const revealedObserver = readObservers.findLast((record) => !record.disconnected)!+ expect(revealedObserver).not.toBe(readObserver)+ expect(revealedObserver.observed.has(messageRow)).toBe(true)+ emitReadIntersection(revealedObserver, messageRow)expect(mocks.submit).toHaveBeenCalledOnce()expect(mocks.submit).toHaveBeenCalledWith({ lease: "parent" }, {kind: "timeline",diff --git a/src/web/src/hooks/community/use-read-observer.dom.test.ts b/src/web/src/hooks/community/use-read-observer.dom.test.tsindex 4c69f94dc..90da4144f 100644--- a/src/web/src/hooks/community/use-read-observer.dom.test.ts+++ b/src/web/src/hooks/community/use-read-observer.dom.test.ts@@ -112,6 +112,7 @@ class FakeIntersectionObserver {}disconnect() {+ this.record.actions.push("disconnect")this.record.disconnected = truethis.record.observed.clear()}@@ -262,6 +263,49 @@ describe("useTimelineReadObserver", () => {vi.restoreAllMocks()})+ it.each(["reveal", "cleanup"])("does not bind added rows to a retired hidden observer before %s", (end) => {+ const { row, root } = useTestRender()+ const boundary = root.querySelector<ContentBoundary>("[data-message-list-content]")!+ const retired = observers[0]!+ boundary.setReadable(false)+ mutationCallback?.([presentationAttributeRecord(boundary, "aria-hidden")], {} as MutationObserver)+ const added = makeRow("message-5")+ boundary.append(added)+ mutationCallback?.([{+ type: "childList", target: boundary, addedNodes: [added] as unknown as NodeList,+ removedNodes: [] as unknown as NodeList,+ } as MutationRecord], {} as MutationObserver)+ expect(retired.disconnected).toBe(true)+ expect(retired.observed.size).toBe(0)+ trigger(retired, row)+ expect(coordinator.submit).not.toHaveBeenCalled()+ if (end === "reveal") {+ boundary.setReadable(true)+ mutationCallback?.([presentationAttributeRecord(boundary, "aria-hidden")], {} as MutationObserver)+ const current = observers.at(-1)!+ expect(current).not.toBe(retired)+ expect(current.observed.has(added)).toBe(true)+ trigger(current, row)+ expect(coordinator.submit).toHaveBeenCalledOnce()+ }+ takeUnmounts().forEach((unmount) => unmount())+ expect(observers.every((observer) => observer.disconnected && observer.observed.size === 0)).toBe(true)+ })++ it("accepts a current first intersection whose frame time precedes registration", () => {+ const clock = vi.spyOn(performance, "now").mockReturnValue(145)+ try {+ const { row } = useTestRender()+ act(() => observers[0]!.callback([{+ target: row, time: 144, isIntersecting: true, intersectionRatio: 1,+ } as IntersectionObserverEntry], {} as IntersectionObserver))+ expect(coordinator.submit).toHaveBeenCalledExactlyOnceWith({ lease: "timeline" }, {+ kind: "timeline", channelId: "channel-1", messageId: "message-4", seq: 4,+ })+ expect(projection.recordOptimisticRead).toHaveBeenCalledWith("channel-1", 4, 1)+ } finally { clock.mockRestore() }+ })+it.each(["channel", "dm"] as const)("keeps the %s adapter on the common observer intent and lifetime", (kind) => {const channelId = `${kind}-1`const row = makeRow("message-4")@@ -393,6 +437,8 @@ describe("useTimelineReadObserver", () => {for (const listener of visibilityListeners) listener()expect(coordinator.resume).toHaveBeenCalledWith(queryClient)trigger(observers[0]!, row)+ expect(coordinator.submit).not.toHaveBeenCalled()+ trigger(observers.at(-1)!, row)expect(coordinator.submit).toHaveBeenCalledOnce()})@@ -441,7 +487,7 @@ describe("useTimelineReadObserver", () => {expect(record.queued).toHaveLength(0)act(() => record.callback([stale], {} as IntersectionObserver))expect(coordinator.submit).not.toHaveBeenCalled()- trigger(record, row)+ trigger(observers.at(-1)!, row)expect(coordinator.submit).toHaveBeenCalledOnce()expect(projection.recordOptimisticRead).toHaveBeenCalledOnce()expect(reservation.promote).toHaveBeenCalledOnce()@@ -586,6 +632,32 @@ describe("useTimelineReadObserver", () => {)})+ it("refuses old callbacks after the same DOM node changes message identity and changes back", () => {+ const { row } = useTestRender({ messages: [{ id: "message-4", seq: 4, authorId: "other-1" }, { id: "message-5", seq: 5, authorId: "other-1" }] })+ const original = observers[0]!+ for (const id of ["message-5", "message-4"]) {+ row.dataset.msgId = id+ act(() => mutationCallback!([{ type: "attributes", target: row, attributeName: "data-msg-id", addedNodes: [] } as unknown as MutationRecord], {} as MutationObserver))+ trigger(original, row)+ expect(coordinator.submit).not.toHaveBeenCalled()+ }+ expect(observers).toHaveLength(3)+ trigger(observers.at(-1)!, row)+ expect(coordinator.submit).toHaveBeenCalledExactlyOnceWith({ lease: "timeline" }, { kind: "timeline", channelId: "channel-1", messageId: "message-4", seq: 4 })+ })++ it("retires an old intersection when a row is removed and inserted again with the same id", () => {+ const { row, root } = useTestRender()+ const original = observers[0]!+ row.remove()+ root.append(row)+ act(() => mutationCallback!([{ type: "childList", target: root, removedNodes: [row], addedNodes: [row] } as unknown as MutationRecord], {} as MutationObserver))+ trigger(original, row)+ expect(coordinator.submit).not.toHaveBeenCalled()+ trigger(observers.at(-1)!, row)+ expect(coordinator.submit).toHaveBeenCalledOnce()+ })+it("binds direct and nested message rows added after the observer mounts", () => {useTestRender()takeUnmounts()@@ -613,7 +685,7 @@ describe("useTimelineReadObserver", () => {expect(mutationObservedTarget).toBe(root)expect(mutationObserveOptions).toEqual({attributes: true,- attributeFilter: ["aria-hidden", "inert", "data-read-position-ready"],+ attributeFilter: ["aria-hidden", "inert", "data-read-position-ready", "data-msg-id"],attributeOldValue: true,childList: true,subtree: true,@@ -630,16 +702,16 @@ describe("useTimelineReadObserver", () => {} as MutationRecord], {} as MutationObserver)const drainIndex = record.actions.indexOf("takeRecords")- expect(drainIndex).toBeGreaterThan(record.actions.indexOf("unobserve:message-4"))- expect(record.actions.findIndex((action, index) => (- index > drainIndex && action === "observe:message-4"- ))).toBeGreaterThan(drainIndex)+ expect(drainIndex).toBeGreaterThan(record.actions.indexOf("disconnect"))+ expect(record.disconnected).toBe(true)+ expect(observers.at(-1)!.observed.has(row)).toBe(true)deliverQueued(record)expect(coordinator.submit).not.toHaveBeenCalled()- queueEntry(record, row)- deliverQueued(record)+ const current = observers.at(-1)!+ queueEntry(current, row)+ deliverQueued(current)expect(coordinator.submit).toHaveBeenCalledOnce()})@@ -729,7 +801,7 @@ describe("useTimelineReadObserver", () => {addedNodes: [] as unknown as NodeList,} as MutationRecord], {} as MutationObserver)- expect(record.actions).toEqual(["unobserve:message-4", "takeRecords"])+ expect(record.actions).toEqual(["disconnect", "takeRecords"])expect(record.queued).toHaveLength(0)expect(reservation.negative).toHaveBeenCalledOnce()expect(coordinator.resume).not.toHaveBeenCalled()@@ -737,11 +809,11 @@ describe("useTimelineReadObserver", () => {visibility = "visible"for (const listener of visibilityListeners) listener()expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)- expect(record.actions.at(-1)).toBe("observe:message-4")+ expect(observers.at(-1)!.observed.has(row)).toBe(true)expect(coordinator.resume).toHaveBeenCalledOnce()})- it("keeps ordinary visibility and pageshow samples independent and undrained", () => {+ it("replaces visibility and pageshow observers while refusing their retired callbacks", () => {const { row } = useTestRender()takeUnmounts()const record = observers[0]!@@ -752,7 +824,15 @@ describe("useTimelineReadObserver", () => {for (const listener of pageShowListeners) listener()expect(coordinator.resume).toHaveBeenCalledTimes(2)- expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(0)- expect(record.observed.has(row)).toBe(true)+ expect(record.actions.filter((action) => action === "takeRecords")).toHaveLength(1)+ expect(observers).toHaveLength(3)+ expect(record.disconnected).toBe(true)+ expect(observers[1]!.disconnected).toBe(true)+ expect(observers[2]!.observed.has(row)).toBe(true)+ trigger(record, row)+ trigger(observers[1]!, row)+ expect(coordinator.submit).not.toHaveBeenCalled()+ trigger(observers[2]!, row)+ expect(coordinator.submit).toHaveBeenCalledOnce()})})diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.tsindex c44abdbbb..ab39af72b 100644--- a/src/web/src/hooks/community/use-read-observer.ts+++ b/src/web/src/hooks/community/use-read-observer.ts@@ -173,60 +173,81 @@ export function useTimelineReadObserver({if (!readLease || !reservationLease) returnlet observerGeneration = 0let presentationReadable = readPresentationReadable(scrollRootEl)- const bindings = new WeakMap<Element, { id: string; generation: number; observedAt: number }>()+ let bindings = new WeakMap<Element, { id: string; generation: number }>()+ let observer: IntersectionObserver+ let observerActive = false+ const retireObserver = () => {+ if (!observerActive) return+ observerGeneration += 1+ observerActive = false+ observer.disconnect()+ observer.takeRecords()+ }const bind = (node: Element) => {+ if (!observerActive) returnconst id = (node as HTMLElement).dataset.msgIdif (!id) return- bindings.set(node, { id, generation: observerGeneration, observedAt: performance.now() })- observer.observe(node)- }- const observer = new IntersectionObserver((entries) => {- if (!readPresentationReadable(scrollRootEl)) return- if (!protocol.get().ready) return- if (document.visibilityState !== "visible") {- takeInboxReadReservationNegative(reservationLease)+ const previous = bindings.get(node)+ if (previous) {+ if (previous.id !== id) sample()return}- for (const entry of entries) {- const binding = bindings.get(entry.target)- if (!binding || binding.generation !== observerGeneration || entry.time < binding.observedAt) continue- if (!scrollRootEl.contains(entry.target)) continue- if ((entry.target as HTMLElement).dataset.msgId !== binding.id) continue- const message = protocol.get().visibleIds.has(binding.id) ? getCommunityDbRegistry(queryClient)?.collections.messages.get(binding.id) : undefined- if (!message?.seq || message.authorId === currentUser.id) continue- const activeCandidate = protocol.get().candidate- const correlated = activeCandidate?.lastMessageAt === message.createdAt- if (!entry.isIntersecting || entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) {- if (correlated) takeInboxReadReservationNegative(reservationLease)- continue- }- const generation = submitReadIntentGeneration(readLease, {- kind: "timeline",- channelId,- messageId: message.id,- seq: message.seq,- })- if (generation !== null) {- getAccountUnreadProjection(queryClient, currentUser.id)- .recordOptimisticRead(channelId, message.seq, generation)+ bindings.set(node, { id, generation: observerGeneration })+ observer.observe(node)+ }+ const createObserver = () => {+ const observerEpoch = observerGeneration+ const currentBindings = new WeakMap<Element, { id: string; generation: number }>()+ bindings = currentBindings+ observerActive = true+ return new IntersectionObserver((entries) => {+ if (observerEpoch !== observerGeneration) return+ if (!readPresentationReadable(scrollRootEl)) return+ if (!protocol.get().ready) return+ if (document.visibilityState !== "visible") {+ takeInboxReadReservationNegative(reservationLease)+ return}- if (generation !== null && correlated) {- promoteInboxReadReservation(reservationLease, generation)+ for (const entry of entries) {+ const binding = currentBindings.get(entry.target)+ if (!binding || binding.generation !== observerEpoch) continue+ if (!scrollRootEl.contains(entry.target)) continue+ if ((entry.target as HTMLElement).dataset.msgId !== binding.id) continue+ const message = protocol.get().visibleIds.has(binding.id) ? getCommunityDbRegistry(queryClient)?.collections.messages.get(binding.id) : undefined+ if (!message?.seq || message.authorId === currentUser.id) continue+ const activeCandidate = protocol.get().candidate+ const correlated = activeCandidate?.lastMessageAt === message.createdAt+ if (!entry.isIntersecting || entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) {+ if (correlated) takeInboxReadReservationNegative(reservationLease)+ continue+ }+ const generation = submitReadIntentGeneration(readLease, {+ kind: "timeline",+ channelId,+ messageId: message.id,+ seq: message.seq,+ })+ if (generation !== null) {+ getAccountUnreadProjection(queryClient, currentUser.id)+ .recordOptimisticRead(channelId, message.seq, generation)+ }+ if (generation !== null && correlated) {+ promoteInboxReadReservation(reservationLease, generation)+ }}- }- }, { root: scrollRootEl, threshold: READ_VISIBILITY_THRESHOLD })+ }, { root: scrollRootEl, threshold: READ_VISIBILITY_THRESHOLD })+ }+ observer = createObserver()const sample = () => {if (!readPresentationReadable(scrollRootEl)) return+ retireObserver()if (document.visibilityState !== "visible") {takeInboxReadReservationNegative(reservationLease)return}- observerGeneration += 1- scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach((node) => {- observer.unobserve(node)- bind(node)- })+ observer = createObserver()+ scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach(bind)resumeReadCoordinator(queryClient)}scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach(bind)@@ -240,9 +261,7 @@ export function useTimelineReadObserver({|| records.some((record) => record.type === "attributes"&& record.attributeName === "data-read-position-ready" && record.oldValue === "false")if (presentationChanged) {- observerGeneration += 1- scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach((node) => observer.unobserve(node))- observer.takeRecords()+ retireObserver()}presentationReadable = nextPresentationReadableif (presentationRevealed || (presentationChanged && nextPresentationReadable)) {@@ -250,6 +269,11 @@ export function useTimelineReadObserver({if (document.visibilityState === "visible") classifyCandidateRef.current()return}+ if (records.some((record) => record.type === "attributes" && record.attributeName === "data-msg-id"+ || [...(record.removedNodes ?? [])].some((node) => (node as Element).matches?.("[data-msg-id]") || (node as Element).querySelector?.("[data-msg-id]")))) {+ sample()+ return+ }for (const record of records) {for (const node of record.addedNodes) {if ((node as { nodeType?: number }).nodeType !== 1) continue@@ -261,7 +285,7 @@ export function useTimelineReadObserver({})mutations?.observe(scrollRootEl, {attributes: true,- attributeFilter: ["aria-hidden", "inert", "data-read-position-ready"],+ attributeFilter: ["aria-hidden", "inert", "data-read-position-ready", "data-msg-id"],attributeOldValue: true,childList: true,subtree: true,@@ -269,8 +293,7 @@ export function useTimelineReadObserver({document.addEventListener("visibilitychange", sample)window.addEventListener("pageshow", sample)return () => {- observerGeneration += 1- observer.disconnect()+ retireObserver()mutations?.disconnect()document.removeEventListener("visibilitychange", sample)window.removeEventListener("pageshow", sample)diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.tsindex b3893c5c6..7181e5de1 100644--- a/src/web/src/lib/community-db/sync.test.ts+++ b/src/web/src/lib/community-db/sync.test.ts@@ -1,7 +1,7 @@import { projectPostedMessage } from "@/lib/community/message-wire"import { QueryClient } from "@tanstack/react-query"import { afterEach, describe, expect, it, vi } from "vitest"-import type { CommunityWsEvent } from "@alook/shared"+import { AccountAttentionSnapshotSchema, type CommunityWsEvent } from "@alook/shared"import { communityKeys } from "@/lib/query-keys"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { rememberMessageAccessScope } from "./message-access-scope"@@ -52,14 +52,35 @@ import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"const registries: CommunityDbRegistry[] = []const unregisters: Array<() => void> = []-async function registry() {+async function registry(preload = true) {const result = createCommunityDbRegistry(new QueryClient(), "viewer")registries.push(result)- await result.preload()+ if (preload) await result.preload()unregisters.push(registerCommunityDbRegistry(result))return result}+function forumAttentionSnapshot(seq = 4) {+ const at = "2026-10-08T00:00:00.000Z"+ return AccountAttentionSnapshotSchema.parse({+ scopes: [{ scopeId: "post", channelId: "post", serverId: "s1", parentChannelId: "forum", ordinaryUnread: true, lastUnreadSeq: seq, lastAttentionSeq: seq, attentionCount: 1 }],+ items: [{ id: `reply:m${seq}`, kind: "reply", sourceId: `m${seq}`, scopeId: "post", messageId: `m${seq}`, actorUserId: "peer", createdAt: at }],+ limit: 100, truncated: false,+ included: {+ servers: [{ id: "s1", name: "Server", discriminator: "0001" }],+ channels: [+ { id: "forum", serverId: "s1", name: "Forum", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "peer", archived: false, lastMessageAt: at },+ { id: "post", serverId: "s1", name: "Post", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "peer", archived: false, lastMessageAt: at, openerSeq: 1, openerUnread: true },+ ],+ dms: [], profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }],+ messages: [+ { id: "opener", channelId: "forum", type: "chat", authorId: "peer", seq: 1, createdAt: at, content: "Title" },+ { id: `m${seq}`, channelId: "post", type: "chat", authorId: "peer", seq, createdAt: at, content: "Reply" },+ ],+ },+ })+}+function publishCommunityLiveSnapshot(queryClient: QueryClient,snapshot: CommunityLiveSnapshot,@@ -1197,6 +1218,106 @@ describe("community DB sync", () => {expect(db.collections.readStates.get("c1")).toBeUndefined()})+ it.each([{ label: "missing", loaded: false, cold: false }, { label: "cold", loaded: false, cold: true }, { label: "loaded", loaded: true, cold: false }])("keeps confirmed reads after a late valid attention snapshot with a $label scope", async ({ loaded, cold }) => {+ const db = await registry(!cold)+ const at = "2026-10-08T00:00:00.000Z"+ const snapshot = forumAttentionSnapshot()+ if (loaded) ingestAttentionSnapshot(db, snapshot)+ const token = captureCommunityLiveSnapshotToken(db.queryClient)+ const optimistic = clearAttentionScopeOptimistically(db, "post", 4)+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: at, lastReadSeq: 4 }] })+ await commitAttentionScopeOptimisticSnapshot(db, optimistic)+ expect(db.queryClient.getQueryData<Array<{ channelId: string; lastReadSeq: number }>>(communityKeys.communityDbCollection(db.scopeId, "readStates"))?.find((row) => row.channelId === "post")?.lastReadSeq).toBe(4)+ expect(publishAccountAttentionSnapshot(db.queryClient, { snapshot, proof: { token, signal: undefined } })).toBe("published")+ if (cold) await db.preload()+ expect(db.collections.channels.get("post")).toMatchObject({ parentChannelId: "forum", parentMessageId: "opener" })+ expect(db.collections.readStates.get("post")?.lastReadSeq).toBe(4)+ expect(db.collections.attentionScopes.get("post")).toBeUndefined()+ expect(db.collections.attentionItems.get("reply:m4")).toBeUndefined()+ })++ it.each([false, true])("projects already ingested attention when canonical read confirmation arrives without an intent (cold: %s)", async (cold) => {+ const db = await registry(!cold)+ ingestAttentionSnapshot(db, forumAttentionSnapshot())+ expect(db.queryClient.getQueryData<Array<{ scopeId: string }>>(communityKeys.communityDbCollection(db.scopeId, "attentionScopes"))?.some((scope) => scope.scopeId === "post")).toBe(true)+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: "2026-10-08T00:00:00.000Z", lastReadSeq: 4 }] })+ expect(db.queryClient.getQueryData<Array<{ scopeId: string }>>(communityKeys.communityDbCollection(db.scopeId, "attentionScopes"))?.some((scope) => scope.scopeId === "post")).toBe(false)+ if (cold) await db.preload()+ expect(db.collections.attentionItems.get("reply:m4")).toBeUndefined()+ ingestAttentionSnapshot(db, forumAttentionSnapshot(5))+ expect(db.collections.attentionScopes.get("post")).toMatchObject({ ordinaryUnread: true, lastUnreadSeq: 5, attentionCount: 1 })+ expect(db.collections.attentionItems.get("reply:m5")).toBeDefined()+ })++ it("keeps a new valid reply and ordinary unread beyond the confirmed waterline", async () => {+ const db = await registry()+ const at = "2026-10-08T00:00:00.000Z"+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: at, lastReadSeq: 4 }] })+ const newer = forumAttentionSnapshot(5)+ const older = forumAttentionSnapshot(4)+ const snapshot = AccountAttentionSnapshotSchema.parse({+ ...newer, scopes: newer.scopes.map((scope) => ({ ...scope, attentionCount: 2 })),+ items: [...older.items, ...newer.items],+ included: { ...newer.included, messages: [...newer.included.messages, ...older.included.messages.filter((message) => message.id === "m4")] },+ })+ const token = captureCommunityLiveSnapshotToken(db.queryClient)+ publishAccountAttentionSnapshot(db.queryClient, { snapshot, proof: { token, signal: undefined } })+ expect(db.collections.attentionScopes.get("post")).toMatchObject({ ordinaryUnread: true, lastUnreadSeq: 5, lastAttentionSeq: 5, attentionCount: 1 })+ expect(db.collections.attentionItems.get("reply:m4")).toBeUndefined()+ expect(db.collections.attentionItems.get("reply:m5")).toBeDefined()+ })++ it.each(["forum", "post"])("applies the %s read floor only to its exact forum or child domain", async (channelId) => {+ const db = await registry()+ const base = forumAttentionSnapshot()+ const at = base.included.messages[0]!.createdAt+ const snapshot = AccountAttentionSnapshotSchema.parse({+ ...base,+ scopes: [...base.scopes, { scopeId: "forum", channelId: "forum", serverId: "s1", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: null, attentionCount: 0 }],+ items: [...base.items, { id: "forum_post:post", kind: "forum_post", sourceId: "post", scopeId: "forum", messageId: "opener", actorUserId: null, childChannelId: "post", openerSeq: 1, readTarget: { channelId: "forum", seq: 1 }, createdAt: at }],+ })+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId, lastReadMessageId: channelId === "forum" ? "opener" : "m4", lastReadAt: at, lastReadSeq: channelId === "forum" ? 1 : 4 }] })+ const token = captureCommunityLiveSnapshotToken(db.queryClient)+ publishAccountAttentionSnapshot(db.queryClient, { snapshot, proof: { token, signal: undefined } })+ const remaining = channelId === "forum" ? "post" : "forum"+ expect(db.collections.attentionScopes.get(channelId)).toBeUndefined()+ expect(db.collections.attentionScopes.get(remaining)?.ordinaryUnread).toBe(true)+ expect(db.collections.attentionItems.get(channelId === "forum" ? "forum_post:post" : "reply:m4")).toBeUndefined()+ expect(db.collections.attentionItems.get(channelId === "forum" ? "reply:m4" : "forum_post:post")).toBeDefined()+ })++ it("retains valid friend requests when confirmed messages disappear", async () => {+ const db = await registry()+ const base = forumAttentionSnapshot()+ const at = base.included.messages[0]!.createdAt+ const snapshot = AccountAttentionSnapshotSchema.parse({+ ...base,+ items: [...base.items, { id: "friend_request:request", kind: "friend_request", sourceId: "request", actorUserId: "requester", createdAt: at }],+ included: { ...base.included, profiles: [...base.included.profiles, { userId: "requester", name: "Requester", discriminator: "0003", avatar: "R", avatarVersion: 0 }] },+ })+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: at, lastReadSeq: 4 }] })+ publishAccountAttentionSnapshot(db.queryClient, { snapshot, proof: { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined } })+ expect(db.collections.attentionScopes.get("post")).toBeUndefined()+ expect(db.collections.attentionItems.get("reply:m4")).toBeUndefined()+ expect(db.collections.attentionItems.get("friend_request:request")).toBeDefined()+ expect(db.collections.friendships.get("request")).toMatchObject({ kind: "incoming", userId: "requester" })+ })++ it("keeps an unknown-sequence cached item when another scope rebases confirmed attention", async () => {+ const db = await registry()+ const snapshot = forumAttentionSnapshot()+ ingestAttentionSnapshot(db, snapshot)+ const key = communityKeys.communityDbCollection(db.scopeId, "messages")+ db.queryClient.setQueryData(key, (rows: Array<{ id: string; seq?: number }>) => rows.map((row) => row.id === "m4" ? { ...row, seq: undefined } : row))+ db.collections.messages.utils.writeUpsert({ ...db.collections.messages.get("m4")!, seq: undefined })+ ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: snapshot.included.messages[0]!.createdAt, lastReadSeq: 4 }] })+ const optimistic = clearAttentionScopeOptimistically(db, "other", 0)+ expect(db.collections.attentionItems.get("reply:m4")).toBeDefined()+ expect(db.collections.attentionScopes.get("post")).toMatchObject({ ordinaryUnread: false, attentionCount: 1 })+ await commitAttentionScopeOptimisticSnapshot(db, optimistic)+ expect(db.collections.attentionItems.get("reply:m4")).toBeDefined()+ })+it("lets one authoritative snapshot replace the complete prior attention truth", async () => {const db = await registry()const scope = {diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex f0d22b460..458feb309 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -931,6 +931,7 @@ export function ingestReadStateSnapshot(notifyManager.batch(() => {replaceRows(registry, "readStates", readStates, () => true)replaceRows(registry, "readStateClock", [clock], () => true)+ projectConfirmedAttention(registry)})}@@ -1081,12 +1082,77 @@ function attentionIntentActive(registry: CommunityDbRegistry, intent: AttentionI&& registry.queryClient.getQueryCache().find({ queryKey: communityKeys.communityDbCollection(registry.scopeId, "attentionItems"), exact: true }) === intent.itemsQuery}+function confirmedAttentionProjection(registry: CommunityDbRegistry, scopes: AttentionScopeRow[], items: AttentionItemRow[]) {+ const readSeq = new Map(collectionRows(registry, "readStates").map((row) => [row.channelId, row.lastReadSeq]))+ const unreadProjection = getAccountUnreadProjection(registry.queryClient, registry.accountId ?? "__anonymous__")+ const floorFor = (channelId: string) => {+ const canonical = readSeq.get(channelId)+ const confirmed = unreadProjection.getConfirmedReadSeq(channelId)+ return confirmed === undefined ? canonical : Math.max(canonical ?? 0, confirmed)+ }+ const scopeById = new Map(scopes.map((scope) => [scope.scopeId, scope]))+ const messages = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))+ const removedByScope = new Map<string, number>()+ const survivingByScope = new Map<string, number>()+ const nextItems = items.filter((item) => {+ if (item.kind === "friend_request") return true+ const scope = item.scopeId ? scopeById.get(item.scopeId) : undefined+ const message = item.messageId ? messages.get(item.messageId) : undefined+ const channelId = item.readTarget?.channelId ?? scope?.channelId+ const seq = item.readTarget?.seq ?? (message?.channelId === channelId ? message?.seq : undefined)+ const floor = channelId ? floorFor(channelId) : undefined+ const removed = seq !== undefined && floor !== undefined && seq <= floor+ if (item.scopeId && (item.kind === "mention" || item.kind === "reply")) {+ const counts = removed ? removedByScope : survivingByScope+ counts.set(item.scopeId, (counts.get(item.scopeId) ?? 0) + 1)+ }+ return !removed+ })+ const nextScopes = scopes.flatMap((scope): AttentionScopeRow[] => {+ const floor = floorFor(scope.channelId)+ if (floor === undefined) return [scope]+ const ordinaryUnread = scope.ordinaryUnread && scope.lastUnreadSeq > floor+ const remaining = scope.lastAttentionSeq != null && scope.lastAttentionSeq <= floor+ ? 0+ : Math.max(0, scope.attentionCount - (removedByScope.get(scope.scopeId) ?? 0))+ const attentionCount = Math.min(scope.attentionCount, Math.max(remaining, survivingByScope.get(scope.scopeId) ?? 0))+ if (!ordinaryUnread && attentionCount === 0) return []+ return [{ ...scope, ordinaryUnread, attentionCount, lastAttentionSeq: attentionCount === 0 ? null : scope.lastAttentionSeq }]+ })+ return { scopes: nextScopes, items: nextItems }+}++function writeAttentionProjection(registry: CommunityDbRegistry, scopes: AttentionScopeRow[], items: AttentionItemRow[], projected: ReturnType<typeof confirmedAttentionProjection>) {+ const nextScopes = new Map(projected.scopes.map((scope) => [scope.scopeId, scope]))+ const previousScopes = new Map(scopes.map((scope) => [scope.scopeId, scope]))+ const nextItems = new Set(projected.items.map((item) => item.id))+ const removedScopes = new Set(scopes.filter((scope) => !nextScopes.has(scope.scopeId)).map((scope) => scope.scopeId))+ const removedItems = new Set(items.filter((item) => !nextItems.has(item.id)).map((item) => item.id))+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {+ if (removedScopes.size) deleteRows(registry, "attentionScopes", (row) => removedScopes.has(row.scopeId))+ upsertRows(registry, "attentionScopes", projected.scopes.filter((scope) => JSON.stringify(scope) !== JSON.stringify(previousScopes.get(scope.scopeId))))+ if (removedItems.size) deleteRows(registry, "attentionItems", (row) => removedItems.has(row.id))+ })+ return { nextScopes, previousScopes }+}++export function projectConfirmedAttention(registry: CommunityDbRegistry) {+ notifyManager.batch(() => {+ const scopes = collectionRows(registry, "attentionScopes")+ const items = collectionRows(registry, "attentionItems")+ writeAttentionProjection(registry, scopes, items, confirmedAttentionProjection(registry, scopes, items))+ })+}+function attentionProjection(registry: CommunityDbRegistry,scopes: AttentionScopeRow[],items: AttentionItemRow[],intents: Iterable<AttentionIntent>,) {+ const confirmed = confirmedAttentionProjection(registry, scopes, items)+ scopes = confirmed.scopes+ items = confirmed.itemsconst floors = new Map<string, { ordinary: number; mentions: number; cleared: number }>()const itemIds = new Set<string>()for (const intent of intents) {@@ -1240,16 +1306,7 @@ function publishAttentionConfirmation(registry: CommunityDbRegistry, current: Atconst scopes = collectionRows(registry, "attentionScopes")const items = collectionRows(registry, "attentionItems")const projected = attentionProjection(registry, scopes, items, [confirmed])- const nextScopes = new Map(projected.scopes.map((scope) => [scope.scopeId, scope]))- const previousScopes = new Map(scopes.map((scope) => [scope.scopeId, scope]))- const nextItems = new Set(projected.items.map((item) => item.id))- const removedScopes = new Set(scopes.filter((scope) => !nextScopes.has(scope.scopeId)).map((scope) => scope.scopeId))- const removedItems = new Set(items.filter((item) => !nextItems.has(item.id)).map((item) => item.id))- withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {- if (removedScopes.size) deleteRows(registry, "attentionScopes", (row) => removedScopes.has(row.scopeId))- upsertRows(registry, "attentionScopes", projected.scopes.filter((scope) => JSON.stringify(scope) !== JSON.stringify(previousScopes.get(scope.scopeId))))- if (removedItems.size) deleteRows(registry, "attentionItems", (row) => removedItems.has(row.id))- })+ const { nextScopes, previousScopes } = writeAttentionProjection(registry, scopes, items, projected)const store = attentionTransactionStores.get(registry)store?.setState((state) => ({ ...state, intents: new Map([...state.intents].map(([token, intent]) => {if (token === current.token) return [token, intent]@@ -1322,8 +1379,9 @@ export function ingestAttentionSnapshot(registry: CommunityDbRegistry, snapshot:const pending = collectionRows(registry, "friendships").filter((row) => row.kind === "incoming" && row.needsOwnerApproval == null)const blocked = new Set(collectionRows(registry, "friendships").filter((row) => row.kind === "blocked").map((row) => row.userId))ingestAttentionIncluded(registry, snapshot.included)- replaceRows(registry, "attentionScopes", snapshot.scopes, () => true)- replaceRows(registry, "attentionItems", snapshot.items.filter((row) => row.kind !== "friend_request" || !row.actorUserId || (!blocked.has(row.actorUserId) && !isProtectedFromQueryWrite(registry, "friendships", `user:${row.actorUserId}`))), () => true)+ const confirmed = confirmedAttentionProjection(registry, snapshot.scopes, snapshot.items)+ replaceRows(registry, "attentionScopes", confirmed.scopes, () => true)+ replaceRows(registry, "attentionItems", confirmed.items.filter((row) => row.kind !== "friend_request" || !row.actorUserId || (!blocked.has(row.actorUserId) && !isProtectedFromQueryWrite(registry, "friendships", `user:${row.actorUserId}`))), () => true)const requests = collectionRows(registry, "attentionItems").filter((row) => row.kind === "friend_request" && row.actorUserId)upsertRows(registry, "friendships", requests.filter((row) => !blocked.has(row.actorUserId!)).map((row) => ({ id: row.sourceId, userId: row.actorUserId!, kind: "incoming" as const })))if (!snapshot.truncated) retireCanonicalFriendRequests(registry, pending.filter((row) => !requests.some((item) => item.sourceId === row.id)).map((row) => row.id))