Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf: reuse community projections and publish changed rows (#1144)

Gener8f192b10d9e6
diff --git a/src/web/scripts/perf-report.test.ts b/src/web/scripts/perf-report.test.ts
index c5a828b85..6aa9a2fd1 100644
--- a/src/web/scripts/perf-report.test.ts
+++ b/src/web/scripts/perf-report.test.ts
@@ -187,3 +187,42 @@ describe("clearPerfArtifacts", () => {
rmSync(dir, { recursive: true, force: true })
})
})
+
+
+describe("analyzeSwitch target-anchor validity", () => {
+ it("rejects a resize-only record with no qualified target paint", () => {
+ const result = analyzeSwitch(baseSwitch({ paintedTs: null, contentStableTs: 1026 }))
+ expect(result.perceivedMs).toBeNull()
+ expect(result.verdict).toMatch(/incomplete capture/)
+ })
+ it.each([
+ { paintedTs: 999, contentStableTs: 1600 },
+ { paintedTs: 1500, contentStableTs: 1499 },
+ { paintedTs: Number.NaN, contentStableTs: 1600 },
+ ])("rejects invalid target anchor order %j", anchors => {
+ expect(analyzeSwitch(baseSwitch(anchors)).perceivedMs).toBeNull()
+ })
+ it("keeps raw resources while bounding network attribution at target stability", () => {
+ const resources = [
+ { name: "http://x/api/community/channels/c/messages", startTime: 1010, responseEnd: 1020 },
+ { name: "http://x/api/community/background", startTime: 1590, responseEnd: 2300 },
+ ]
+ const original = structuredClone(resources)
+ const result = analyzeSwitch(baseSwitch({ resources }))
+ expect(result.perceivedMs).toBe(600)
+ expect(result.networkMs).toBe(20)
+ expect(result.networkSpanMs).toBe(1290)
+ expect(result.verdict).toMatch(/outside measured request intervals/)
+ expect(resources).toEqual(original)
+ })
+})
+
+it("labels a server empty-channel result separately from populated message content", () => {
+ const empty = baseSwitch({ kind: "server", targetId: "server", contentChannelId: "all", contentKind: "empty" })
+ expect(analyzeSwitch(empty)).toMatchObject({ contentChannelId: "all", contentKind: "empty" })
+ const report = renderReport({ owner: { email: "[email protected]", userId: "u1" }, createdAt: "2026-11-02", switches: [empty] })
+ expect(report).toContain("empty channel (0 messages)")
+ expect(report).toContain("not a populated-message sample")
+ expect(report).toContain("`all`")
+ expect(analyzeSwitch(baseSwitch({ contentKind: "messages", contentChannelId: "chan-1" }))).toMatchObject({ contentKind: "messages", contentChannelId: "chan-1" })
+})
diff --git a/src/web/scripts/perf-report.ts b/src/web/scripts/perf-report.ts
index 54a73a630..85ba21fa7 100644
--- a/src/web/scripts/perf-report.ts
+++ b/src/web/scripts/perf-report.ts
@@ -26,6 +26,8 @@ export interface SwitchAnalysis {
kind: string
targetId: string
cacheState: string
+ contentChannelId: string | null
+ contentKind: "messages" | "empty" | null
/** click → content-stable (or painted if no resize settle). The headline. */
perceivedMs: number | null
clickToSkeletonMs: number | null
@@ -90,7 +92,9 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {
sw.skeletonTs != null && sw.paintedTs != null ? sw.paintedTs - sw.skeletonTs : null
const paintedToStableMs =
sw.paintedTs != null && sw.contentStableTs != null ? sw.contentStableTs - sw.paintedTs : null
- const stableTs = sw.contentStableTs ?? sw.paintedTs
+ const validAnchors = Number.isFinite(sw.clickTs) && sw.paintedTs != null && Number.isFinite(sw.paintedTs) && sw.paintedTs >= sw.clickTs
+ && (sw.contentStableTs == null || Number.isFinite(sw.contentStableTs) && sw.contentStableTs >= sw.paintedTs)
+ const stableTs = validAnchors ? sw.contentStableTs ?? sw.paintedTs : null
const perceivedMs = stableTs != null ? stableTs - sw.clickTs : null
const sorted = [...sw.resources].sort((a, b) => a.startTime - b.startTime)
@@ -102,12 +106,14 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {
let curStart = -1
let curEnd = -1
for (const r of sorted) {
- if (curEnd < r.startTime) {
+ const start = Math.max(sw.clickTs, r.startTime), end = Math.min(stableTs ?? Infinity, r.responseEnd)
+ if (end <= start) continue
+ if (curEnd < start) {
if (curStart >= 0) networkMs += curEnd - curStart
- curStart = r.startTime
- curEnd = r.responseEnd
+ curStart = start
+ curEnd = end
} else {
- curEnd = Math.max(curEnd, r.responseEnd)
+ curEnd = Math.max(curEnd, end)
}
}
if (curStart >= 0) networkMs += curEnd - curStart
@@ -150,14 +156,15 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {
: `network-bound (${networkMs.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms)`
} else {
const nonNetwork = perceivedMs - networkMs
- verdict = `NOT network-bound — ${nonNetwork.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms is render/remount/reflow (network only ${networkMs.toFixed(0)}ms); mounts=${mountUnique} fibers, unmounts=${sw.unmounts.length}`
+ verdict = `NOT network-bound — ${nonNetwork.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms is outside measured request intervals (network only ${networkMs.toFixed(0)}ms); mounts=${mountUnique} fibers, unmounts=${sw.unmounts.length}`
}
return {
kind: sw.kind,
targetId: sw.targetId,
cacheState: sw.cacheState,
- perceivedMs,
+ contentChannelId: sw.contentChannelId ?? null,
+ contentKind: sw.contentKind ?? null, perceivedMs,
clickToSkeletonMs,
skeletonToPaintedMs,
paintedToStableMs,
@@ -186,8 +193,8 @@ export function renderReport(file: CaptureFile): string {
lines.push(`Captured: ${file.createdAt}`)
lines.push("")
lines.push(
- "> Baseline: on local, network is ~0, so a visible loading spell is itself the anomaly. " +
- "The headline is perceived latency (click → content stable). Counts are dev-mode. " +
+ "> Local development diagnostic: compare matched runs; these are not production latency measurements. " +
+ "The headline requires a valid target-content anchor. Counts are dev-mode. " +
"Mounts are reported as `unique` (distinct fiber ids — the trustworthy number) and " +
"`raw` (react-scan re-reports every still-mounted fiber on each later commit, inflating " +
"the raw total 6-13×). Re-renders are NOT inflated (each is a genuine distinct render), " +
@@ -199,12 +206,13 @@ export function renderReport(file: CaptureFile): string {
const a = analyzeSwitch(sw)
lines.push(`## ${a.kind} switch → \`${a.targetId}\` _(cache: ${a.cacheState})_`)
lines.push("")
+ if (a.contentKind) lines.push(`- target content: **${a.contentKind === "empty" ? "empty channel (0 messages)" : "message content"}** · channel \`${a.contentChannelId ?? "unknown"}\`${a.contentKind === "empty" ? " · not a populated-message sample" : ""}`)
lines.push(`- PERCEIVED (click → content stable): **${ms(a.perceivedMs)}**`)
lines.push(` - click → skeleton: ${ms(a.clickToSkeletonMs)}`)
lines.push(` - skeleton → painted: ${ms(a.skeletonToPaintedMs)}`)
lines.push(` - painted → stable: ${ms(a.paintedToStableMs)}`)
lines.push(
- `- network: ${ms(a.networkMs)} busy / ${ms(a.networkSpanMs)} span` +
+ `- network: ${ms(a.networkMs)} busy before stability / ${ms(a.networkSpanMs)} full span` +
(a.readStateBlocksMessages == null
? ""
: a.readStateBlocksMessages
diff --git a/src/web/scripts/perf-switch.test.ts b/src/web/scripts/perf-switch.test.ts
new file mode 100644
index 000000000..f26992bae
--- /dev/null
+++ b/src/web/scripts/perf-switch.test.ts
@@ -0,0 +1,168 @@
+import { readFileSync } from "node:fs"
+import { JSDOM } from "jsdom"
+import { createSourceFile, isCallExpression, isFunctionDeclaration, isPropertyAccessExpression, isVariableStatement, ModuleKind, ScriptTarget, transpileModule } from "typescript"
+import { afterEach, expect, it } from "vitest"
+import { tid } from "../src/lib/community/testids"
+
+type Target = { serverId: string; channelId?: string; messageScrollerId: string }
+const target: Target = { serverId: "server", channelId: "target", messageScrollerId: tid.messageScroller }
+const ast = createSourceFile("switch.perf.ts", readFileSync(new URL("../src/test/e2e-ui/perf/switch.perf.ts", import.meta.url), "utf8"), ScriptTarget.ESNext, true)
+const setupSource = ast.statements.flatMap(s => isVariableStatement(s) ? [...s.declarationList.declarations] : []).find(d => d.name.getText(ast) === "INPAGE_SETUP")!.initializer!.getText(ast)
+let predicate = ast.statements.find(s => isFunctionDeclaration(s) && s.name?.text === "samplePerfTarget")?.getText(ast)
+if (!predicate) {
+ const visit = (node: import("typescript").Node) => {
+ if (isCallExpression(node) && isPropertyAccessExpression(node.expression) && node.expression.name.text === "waitForFunction" && node.arguments[0]?.getText(ast).includes("__PERF_PAINTED_TS__")) predicate = node.arguments[0].getText(ast)
+ node.forEachChild(visit)
+ }
+ ast.forEachChild(visit)
+}
+const compiled = transpileModule(`const samplePerfTarget = ${predicate}; const INPAGE_SETUP = ${setupSource}; exports.sample = samplePerfTarget; exports.setup = INPAGE_SETUP;`, { compilerOptions: { target: ScriptTarget.ESNext, module: ModuleKind.CommonJS } }).outputText
+const program = {} as { sample: (input: Target) => unknown; setup: string }
+new Function("exports", "tid", compiled)(program, tid)
+const documents: JSDOM[] = []
+afterEach(() => { documents.splice(0).forEach(dom => dom.window.close()) })
+
+function setup(path = "/c/channels/server/target") {
+ const dom = new JSDOM(`<main data-slot="community-conversation-surface" data-channel-id="target"><div data-testid="${tid.messageScroller}" aria-busy="false"><div data-message-list-content><div data-msg-id="message">Target body</div></div></div></main>`, { url: `http://localhost${path}`, runScripts: "outside-only" })
+ documents.push(dom)
+ const window = dom.window
+ let now = 100
+ Object.defineProperty(window.performance, "now", { value: () => now })
+ Object.defineProperty(window.HTMLElement.prototype, "getBoundingClientRect", { value(this: HTMLElement) { const top = Number(this.dataset.top ?? 0), height = this.hasAttribute("data-msg-id") ? 20 : 100; return { x: 0, y: top, top, bottom: top + height, left: 0, right: 100, width: 100, height } } })
+ Object.defineProperty(window.HTMLElement.prototype, "getClientRects", { value(this: HTMLElement) { return this.style.display === "none" ? [] : [this.getBoundingClientRect()] } })
+ const frames: FrameRequestCallback[] = []
+ window.requestAnimationFrame = callback => { frames.push(callback); return frames.length }
+ const resize: Array<{ disconnected: boolean; deliver: () => void }> = []
+ window.ResizeObserver = class { disconnected = false; constructor(private callback: () => void) { resize.push(this) } observe() {} disconnect() { this.disconnected = true } deliver() { if (!this.disconnected) this.callback() } } as unknown as typeof ResizeObserver
+ const observers: Array<{ disconnected: boolean }> = []
+ window.PerformanceObserver = class { disconnected = false; constructor() { observers.push(this) } observe() {} disconnect() { this.disconnected = true } } as unknown as typeof PerformanceObserver
+ const sample = window.eval(`(${program.sample.toString()})`) as (input: Target) => unknown
+ return { window, api: window as unknown as Window, sample, install: () => window.eval(program.setup), frame: () => { now += 16; frames.splice(0).forEach(callback => callback(now)) }, resize, observers, tick: (value: number) => { now = value } }
+}
+
+it("runs the serialized target predicate without a Node closure", () => {
+ const f = setup()
+ expect(f.sample(target)).toBeTruthy()
+ expect(f.api.__PERF_PAINTED_TS__).toBe(100)
+})
+it.each(["old-channel", "old-server", "inert", "hidden", "busy", "skeleton", "outside"])("rejects %s as target paint", variant => {
+ const f = setup(variant === "old-channel" ? "/c/channels/server/old" : variant === "old-server" ? "/c/channels/other/target" : undefined)
+ const surface = f.window.document.querySelector("main")!, content = surface.querySelector("[data-message-list-content]")!, row = content.querySelector<HTMLElement>("[data-msg-id]")!
+ if (variant === "inert") content.setAttribute("inert", "")
+ if (variant === "hidden") content.setAttribute("aria-hidden", "true")
+ if (variant === "busy") surface.querySelector("[aria-busy]")!.setAttribute("aria-busy", "true")
+ if (variant === "skeleton") { row.remove(); content.innerHTML = '<div data-slot="skeleton"></div>' }
+ if (variant === "outside") row.dataset.top = "200"
+ expect(f.sample(target)).toBeFalsy()
+ expect(f.api.__PERF_PAINTED_TS__ ?? null).toBeNull()
+})
+it("binds the actual channel resolved inside the requested server", () => {
+ const f = setup("/c/channels/server/resolved")
+ f.window.document.querySelector("main")!.setAttribute("data-channel-id", "resolved")
+ expect(f.sample({ ...target, channelId: undefined })).toMatchObject({ channelId: "resolved" })
+ expect(f.sample(target)).toBeFalsy()
+})
+it("settles after qualified target paint and retains the resize buffer", async () => {
+ const f = setup(); f.install()
+ expect(f.api.__PERF_ATTACH_RESIZE__!(target)).toBe(true)
+ f.resize.at(-1)!.deliver(); f.tick(150)
+ const pending = f.api.__PERF_WAIT_FOR_STABLE_RESIZE__!(target)
+ f.frame(); f.frame()
+ expect(await pending).toMatchObject({ contentChannelId: "target", contentStableTs: 182 })
+ expect(f.api.__PERF_PAINTED_TS__).toBe(100)
+ expect(f.api.__PERF_RESIZES__).toEqual([100])
+})
+it("keeps the original120-frame failure bound for a missing target", async () => {
+ const f = setup("/c/channels/server/old"); f.install()
+ const outcome = f.api.__PERF_WAIT_FOR_STABLE_RESIZE__!(target).then(() => null, error => error)
+ for (let i = 0; i < 120; i++) f.frame()
+ expect(await outcome).toBeInstanceOf(f.window.Error)
+ expect(f.api.__PERF_PAINTED_TS__ ?? null).toBeNull()
+})
+it("releases prior existing collectors without editing their saved buffer", () => {
+ const f = setup(); f.install(); f.api.__PERF_ATTACH_RESIZE__!(target)
+ const saved = f.api.__PERF_RESOURCES__!
+ saved.push({ name: "keep-original", startTime: 1, responseEnd: 2 }); f.install()
+ expect(f.observers).toHaveLength(4)
+ expect(f.observers.slice(0, 2).every(o => o.disconnected)).toBe(true)
+ expect(f.resize[0].disconnected).toBe(true)
+ expect(saved).toEqual([{ name: "keep-original", startTime: 1, responseEnd: 2 }])
+ expect(f.api.__PERF_RESOURCES__).toEqual([])
+})
+
+it("requires a current resize delivery when the qualified target root is replaced", async () => {
+ const f = setup(); f.install(); f.api.__PERF_ATTACH_RESIZE__!(target); f.resize.at(-1)!.deliver()
+ const pending = f.api.__PERF_WAIT_FOR_STABLE_RESIZE__!(target)
+ let settled = false
+ void pending.then(() => { settled = true })
+ const root = f.window.document.querySelector(`[data-testid="${tid.messageScroller}"]`)!
+ root.replaceWith(root.cloneNode(true))
+ f.frame(); f.frame(); await Promise.resolve()
+ expect(settled).toBe(false)
+ expect(f.resize[0].disconnected).toBe(true)
+ f.resize.at(-1)!.deliver(); f.frame()
+ expect(await pending).toMatchObject({ contentChannelId: "target", contentStableTs: 148 })
+})
+
+it.each([false, true])("retains the primary readiness error and never returns runner success: drainFails=%s", async drainFails => {
+ let measureSource = ""
+ const visit = (node: import("typescript").Node) => {
+ if (isFunctionDeclaration(node) && node.name?.text === "measureSwitch") measureSource = node.getText(ast)
+ node.forEachChild(visit)
+ }
+ ast.forEachChild(visit)
+ const body = transpileModule(`exports.measure = ${measureSource};`, { compilerOptions: { target: ScriptTarget.ESNext, module: ModuleKind.CommonJS } }).outputText
+ const exports = {} as { measure: (kind: string, id: string, cache: string, navigate: () => Promise<void>) => Promise<void> }
+ const failure = new Error("browser predicate failed")
+ const captured: unknown[] = []
+ let evaluations = 0
+ const page = { evaluate: async () => [undefined, undefined, 1000][evaluations++], waitForFunction: async () => { throw failure } }
+ const drained = { clickTs: 1000, skeletonTs: null, paintedTs: null, contentStableTs: null, resources: [], commits: [], unmounts: [], layoutShifts: [], degraded: false }
+ let flushes = 0
+ const drain = async () => { if (drainFails) throw new Error("capture failed after predicate"); return drained }
+ new Function("exports", "page", "captured", "targetServer", "tid", "INPAGE_SETUP", "drainSwitch", "flushCapture", "samplePerfTarget", body)(exports, page, captured, { id: "server" }, tid, program.setup, drain, () => { flushes++ }, program.sample)
+ await expect(exports.measure("channel", "target", "cold", async () => {})).rejects.toBe(failure)
+ expect(captured).toHaveLength(drainFails ? 0 : 1)
+ expect(flushes).toBe(drainFails ? 0 : 1)
+ if (!drainFails) expect(captured[0]).toMatchObject({ targetId: "target", paintedTs: null, contentStableTs: null })
+})
+
+function emptyTarget(f: ReturnType<typeof setup>) {
+ const content = f.window.document.querySelector<HTMLElement>("[data-message-list-content]")!
+ content.dataset.initialPositionPhase = "revealed"
+ content.innerHTML = '<div aria-hidden="true" data-message-empty-tail></div>'
+ return content
+}
+
+it("accepts only a revealed real empty target and records its content kind", () => {
+ const f = setup(); emptyTarget(f)
+ expect(f.sample(target)).toMatchObject({ channelId: "target", contentKind: "empty" })
+ expect(f.api.__PERF_PAINTED_TS__).toBe(100)
+})
+
+it.each(["missing-marker", "busy", "hidden", "inert", "skeleton", "positioning", "error", "old-scope", "hidden-tail", "outside-message"])("rejects empty-state lookalike %s", variant => {
+ const f = setup(variant === "old-scope" ? "/c/channels/server/old" : undefined), content = emptyTarget(f)
+ if (variant === "missing-marker") content.innerHTML = ""
+ if (variant === "busy") content.parentElement!.setAttribute("aria-busy", "true")
+ if (variant === "hidden") content.setAttribute("aria-hidden", "true")
+ if (variant === "inert") content.setAttribute("inert", "")
+ if (variant === "skeleton") content.insertAdjacentHTML("beforeend", '<div data-slot="skeleton"></div>')
+ if (variant === "positioning") content.dataset.initialPositionPhase = "positioning"
+ if (variant === "error") content.insertAdjacentHTML("beforeend", '<div role="alert">Failed</div>')
+ if (variant === "hidden-tail") content.querySelector<HTMLElement>("[data-message-empty-tail]")!.style.display = "none"
+ if (variant === "outside-message") content.insertAdjacentHTML("beforeend", '<div data-msg-id="old" data-top="200">Outside</div>')
+ expect(f.sample(target)).toBeFalsy()
+ expect(f.api.__PERF_PAINTED_TS__ ?? null).toBeNull()
+})
+
+it("settles and identifies the server's actual empty default channel", async () => {
+ const f = setup("/c/channels/server/all")
+ f.window.document.querySelector("main")!.setAttribute("data-channel-id", "all")
+ emptyTarget(f); f.install()
+ const serverTarget = { ...target, channelId: undefined }
+ expect(f.api.__PERF_ATTACH_RESIZE__!(serverTarget)).toBe(true)
+ f.resize.at(-1)!.deliver()
+ const pending = f.api.__PERF_WAIT_FOR_STABLE_RESIZE__!(serverTarget)
+ f.frame(); f.frame()
+ expect(await pending).toMatchObject({ contentChannelId: "all", contentKind: "empty", contentStableTs: 132 })
+})
diff --git a/src/web/scripts/seed-stress.test.ts b/src/web/scripts/seed-stress.test.ts
index d4bd9621e..be9ea32a2 100644
--- a/src/web/scripts/seed-stress.test.ts
+++ b/src/web/scripts/seed-stress.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import { parseSeedArgs, runSeedStress, mergeSetCookies, extractSetCookies, RatePacer } from "./seed-stress"
@@ -103,15 +104,21 @@ function installFetchMock(handlers: {
existingMessageCount?: number
/** Return 429 (with tiny Retry-After) for the first N message POSTs. */
messageFailWith429Times?: number
-}): { calls: FetchCall[] } {
+ communityResponseContract?: string | null
+}): { calls: FetchCall[]; requestHeaders: Array<{ url: string; headers: Headers }> } {
const calls: FetchCall[] = []
+ const requestHeaders: Array<{ url: string; headers: Headers }> = []
const existingServers = handlers.existingServers ?? []
const existingChannels = handlers.existingChannels ?? []
const msgCount = handlers.existingMessageCount ?? 0
let remaining429 = handlers.messageFailWith429Times ?? 0
- const jsonRes = (data: unknown): Response =>
- ({ ok: true, status: 200, headers: { get: () => null }, json: async () => data }) as unknown as Response
+ const jsonRes = (data: unknown, community = false): Response => {
+ const headers = new Headers()
+ const contract = handlers.communityResponseContract === undefined ? String(BUSINESS_SCHEMA_VERSION) : handlers.communityResponseContract
+ if (community && contract !== null) headers.set(COMMUNITY_CONTRACT_HEADER, contract)
+ return new Response(JSON.stringify(data), { status: 200, headers })
+ }
const rateLimited = (): Response =>
({
ok: false,
@@ -124,35 +131,38 @@ function installFetchMock(handlers: {
const method = init?.method ?? "GET"
const body = init?.body ? JSON.parse(init.body as string) : undefined
calls.push({ url, method, body })
+ const headers = new Headers(init?.headers)
+ requestHeaders.push({ url, headers })
+ if (new URL(url).pathname.startsWith("/api/community/") && headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) return new Response("Missing current community contract", { status: 400 })
if (url.includes("/api/auth/sign-in/email")) return jsonRes({})
if (url.endsWith("/api/ws/token")) return jsonRes({ userId: "user-seed-1" })
if (url.endsWith("/api/community/servers") && method === "GET") {
- return jsonRes({ servers: existingServers })
+ return jsonRes({ servers: existingServers }, true)
}
if (url.endsWith("/api/community/servers") && method === "POST") {
- return jsonRes({ server: { id: "new-server" } })
+ return jsonRes({ server: { id: "new-server" } }, true)
}
if (/\/api\/community\/servers\/[^/]+\/channels$/.test(url) && method === "GET") {
- return jsonRes({ channels: existingChannels })
+ return jsonRes({ channels: existingChannels }, true)
}
if (/\/channels$/.test(url) && method === "POST") {
- return jsonRes({ channel: { id: "new-channel" } })
+ return jsonRes({ channel: { id: "new-channel" } }, true)
}
if (/\/messages\?limit=100/.test(url) && method === "GET") {
- return jsonRes({ messages: new Array(msgCount).fill({}), hasMore: false })
+ return jsonRes({ messages: new Array(msgCount).fill({}), hasMore: false }, true)
}
if (/\/messages$/.test(url) && method === "POST") {
if (remaining429 > 0) {
remaining429--
return rateLimited()
}
- return jsonRes({ message: { id: "m" } })
+ return jsonRes({ message: { id: "m" } }, true)
}
throw new Error(`unhandled ${method} ${url}`)
})
vi.stubGlobal("fetch", fetchMock)
- return { calls }
+ return { calls, requestHeaders }
}
beforeEach(() => vi.unstubAllGlobals())
@@ -256,3 +266,24 @@ describe("runSeedStress — idempotency", () => {
expect(messagePosts).toHaveLength(3) // 2 rate-limited + 1 success, no abort
})
})
+
+
+describe("runSeedStress community contract", () => {
+ it("admits original community reads and writes while keeping auth and WS-token requests separate", async () => {
+ const { calls, requestHeaders } = installFetchMock({})
+ const manifest = await runSeedStress({ servers: 1, channels: 1, messages: 1, serverUrl: "http://localhost:3000", owner: "perf-seed" })
+ const community = requestHeaders.filter(({ url }) => new URL(url).pathname.startsWith("/api/community/"))
+ expect(community).toHaveLength(6)
+ expect(community.every(({ headers }) => headers.get(COMMUNITY_CONTRACT_HEADER) === String(BUSINESS_SCHEMA_VERSION))).toBe(true)
+ expect(requestHeaders.filter(({ url }) => !new URL(url).pathname.startsWith("/api/community/")).map(({ headers }) => headers.get(COMMUNITY_CONTRACT_HEADER))).toEqual([null, null])
+ expect(requestHeaders.every(({ headers }) => headers.get("Content-Type") === "application/json" && headers.get("Origin") === "http://localhost:3000")).toBe(true)
+ expect(calls.filter(({ method }) => method === "POST")).toHaveLength(4)
+ expect(manifest.servers).toEqual([{ id: "new-server", name: "Load-Test-01", channels: [{ id: "new-channel", name: "channel-01", messageCount: 1 }] }])
+ })
+
+ it.each([null, String(BUSINESS_SCHEMA_VERSION - 1)])("rejects successful community responses with contract=%s", async communityResponseContract => {
+ const { calls } = installFetchMock({ communityResponseContract })
+ await expect(runSeedStress({ servers: 1, channels: 1, messages: 1, serverUrl: "http://localhost:3000", owner: "perf-seed" })).rejects.toThrow("Fixture response did not confirm current business version")
+ expect(calls.filter(({ url, method }) => new URL(url).pathname.startsWith("/api/community/") && method === "POST")).toEqual([])
+ })
+})
diff --git a/src/web/scripts/seed-stress.ts b/src/web/scripts/seed-stress.ts
index c9bdf2a5e..fc726b306 100644
--- a/src/web/scripts/seed-stress.ts
+++ b/src/web/scripts/seed-stress.ts
@@ -35,6 +35,7 @@ import { mkdirSync, writeFileSync } from "node:fs"
import { resolve } from "node:path"
import { DEV_PASSWORD, slugify } from "@alook/shared"
import { log } from "../src/lib/logger"
+import { communityFixtureFetch } from "../src/test/e2e-ui/_fixtures/business-contract"
export interface SeedStressOptions {
servers: number
@@ -154,11 +155,12 @@ class SeedClient {
}
async post<T>(path: string, body?: unknown): Promise<T> {
+ const send = path.startsWith("/api/community/") ? communityFixtureFetch : fetch
let lastStatus = 0
// Rate-limit (429) can recur many times during a large message seed, so
// allow generous attempts and honor Retry-After rather than failing.
for (let attempt = 0; attempt < 12; attempt++) {
- const res = await fetch(`${this.baseUrl}${path}`, {
+ const res = await send(`${this.baseUrl}${path}`, {
method: "POST",
headers: this.headers(),
body: body === undefined ? undefined : JSON.stringify(body),
@@ -179,7 +181,8 @@ class SeedClient {
}
async get<T>(path: string): Promise<T> {
- const res = await fetch(`${this.baseUrl}${path}`, { headers: this.headers() })
+ const send = path.startsWith("/api/community/") ? communityFixtureFetch : fetch
+ const res = await send(`${this.baseUrl}${path}`, { headers: this.headers() })
if (!res.ok) throw new Error(`GET ${path} failed (${res.status})`)
return (await res.json()) as T
}
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 683e2b692..09b8813a8 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
@@ -151,6 +151,7 @@ vi.mock("@alook/shared", async () => {
communityFriendship: {
isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
areFriends: (...a: unknown[]) => mockAreFriends(...a),
+ hydrateApprovalsForDmMessages: vi.fn(async () => new Map()),
},
// Bot read arm (GET dual-actor): seq-window + agent-message projection.
communityAgentInbox: {
@@ -1679,6 +1680,33 @@ describe("GET explicit conversation entry", () => {
expect(mockCreateOrGetDM).not.toHaveBeenCalled()
})
+ it("reuses each full profile across the DM peer and first page", async () => {
+ mockGetChannel.mockResolvedValue({ ...channel, type: "dm", serverId: null, name: null })
+ mockGetDM.mockResolvedValue({ id: "c1", lastMessageAt: null, createdAt: channel.createdAt })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "peer" })
+ mockListMessages.mockResolvedValue([{ ...message, authorId: "peer", authorName: "Peer", authorAvatarVersion: 5 }])
+ mockGetLatestMessageSeq.mockResolvedValue(5)
+ const response = await GET(request(), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ peer: { id: "peer" }, messages: [{ authorId: "peer" }], profiles: [{ id: "peer" }] })
+ const requested = vi.mocked(queries.communityUserProfile.getResourceProfiles).mock.calls.flatMap(([, ids]) => ids)
+ expect(requested.filter(id => id === "peer")).toHaveLength(1)
+ })
+
+ it("reuses each full profile across the thread page and authorized opener", async () => {
+ const child = { ...channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }
+ mockGetChannel.mockResolvedValue(child)
+ mockGetChannelForMember.mockImplementation((_db, id) => Promise.resolve(id === "parent" ? { ...channel, id: "parent" } : child))
+ mockGetMessagesByIdsInScope.mockResolvedValue([{ ...message, id: "opener", channelId: "parent" }])
+ mockListMessages.mockResolvedValue([message])
+ mockGetLatestMessageSeq.mockResolvedValue(5)
+ const response = await GET(request(), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ opener: { id: "opener", authorId: "u1" }, messages: [{ authorId: "u1" }], profiles: [{ id: "u1" }] })
+ const requested = vi.mocked(queries.communityUserProfile.getResourceProfiles).mock.calls.flatMap(([, ids]) => ids)
+ expect(requested.filter(id => id === "u1")).toHaveLength(1)
+ })
+
it("does not read a pointer or history after the common gate denies access", async () => {
mockGetChannelForMember.mockResolvedValue(null)
const response = await GET(request(), ctx)
diff --git a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
index 43f6ab3e2..58c81decd 100644
--- a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
@@ -60,7 +60,8 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as co
expect(restoring).toBe(true)
await act(async () => { await seedConversationEntry(registry!.queryClient, fresh) })
expect(ids).toContain("m2")
- if (blocked) act(() => dispatchCommunityWsEvents([{ type: "community:friend.block", userId: "peer", ...(blockMode ? { blockedByViewer: true } : {}) }], {
+ expect(restoring).toBe(true)
+ if (blocked) await act(() => dispatchCommunityWsEvents([{ type: "community:friend.block", userId: "peer", ...(blockMode ? { blockedByViewer: true } : {}) }], {
deliveryMode: "batch", contract: BUSINESS_SCHEMA_VERSION, queryClient: registry!.queryClient, communityStore: registry!.runtime.ui, wsStore: registry!.runtime.ws,
sub: { dmConversationId: "c1" }, viewerUserIdRef: { current: "viewer" }, matchesFocus: event => event.channelId === "c1",
}))
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 7c959f5db..fe26c8471 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
@@ -126,8 +126,7 @@ describe("MessageContextSheet native query publication", () => {
it("publishes sorted complete context messages without inventing full author profiles from history hints", async () => {
const owner = await createCommunityQueryOwner("context_viewer")
- const writer = await import("@/lib/community-db/write")
- const write = vi.spyOn(writer, "writeCommunityCollectionRows")
+ const write = vi.spyOn(owner.registry.collections.profiles.utils, "writeBatch")
const signal = new AbortController().signal
mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockResolvedValueOnce(messageReadPageFixture({ messages: [
messageResourceFixture({ id: "after", channelId: "context_channel", seq: 3, content: "after", authorId: "author", authorName: "Author" }),
@@ -141,7 +140,7 @@ describe("MessageContextSheet native query publication", () => {
"/api/community/channels/context_channel/messages?anchor=anchor&limit=11",
])
expect(mocks.apiFetch.mock.calls.every(([, options]) => options.signal === signal)).toBe(true)
- expect(write.mock.calls.filter(([, collection]) => collection === "profiles")).toHaveLength(2)
+ expect(write).toHaveBeenCalledTimes(1)
expect(owner.registry.collections.messages.get("anchor")).toMatchObject({ content: "anchor", channelId: "context_channel", authorId: "author" })
expect(owner.registry.collections.profiles.get("author")).toMatchObject({ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 })
write.mockRestore()
@@ -177,7 +176,7 @@ describe("MessageContextSheet thread navigation", () => {
beforeEach(async () => {
navigationOwner = await createCommunityQueryOwner("viewer_1")
const { publishCommunityMessages, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
- publishCommunityMessages(navigationOwner.client, { channelId: "parent_1", messages: [messageResourceFixture({ id: "message_1", channelId: "parent_1", authorId: "author_1", authorName: "Author" })], profiles: [{ id: "author_1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], proof: { token: captureCommunityLiveSnapshotToken(navigationOwner.client) } })
+ await publishCommunityMessages(navigationOwner.client, { channelId: "parent_1", messages: [messageResourceFixture({ id: "message_1", channelId: "parent_1", authorId: "author_1", authorName: "Author" })], profiles: [{ id: "author_1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], proof: { token: captureCommunityLiveSnapshotToken(navigationOwner.client) } })
vi.clearAllMocks()
mocks.openThread = undefined
mocks.pin = undefined
diff --git a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
index 17af0aceb..e1b90f26a 100644
--- a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
@@ -92,7 +92,7 @@ function sheetCache(me: boolean) {
async function renderSheet(me: boolean) {
const initial = sheetCache(me)
- publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ await publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: initial.messages.map(({ id }) => ({ id })) })
const rendered = render(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, React.createElement(MessageContextSheet, {
open: true, onOpenChange: vi.fn(), channelId: "channel_1", targetSeq: 1,
@@ -129,7 +129,7 @@ describe("MessageContextSheet reaction coordinator", () => {
it("rereads fresh context IDs with a missing author before exposing row actions", async () => {
const initial = sheetCache(false)
- publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
+ await publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: [{ id: "message_1" }] })
await writeCommunityCollectionRows(owner.registry, "profiles", [], row => row.id)
let release!: (value: ReturnType<typeof messageReadPageFixture>) => void
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 e3b63eb46..f602a1920 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -125,7 +125,7 @@ export function messageContextQueryFn(
{ signal, assertActive: assert }, publicationToken,
)
const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
- publishCommunityEmbeddedMessages(queryClient, {
+ await publishCommunityEmbeddedMessages(queryClient, {
entries: messages.map((message) => ({ channelId, message })),
profiles: page.profiles,
proof: { token: publicationToken, signal },
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
index a6dd49585..de54e3384 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
@@ -75,9 +75,9 @@ function CommunityOnboardingSteps() {
services: {
assert,
request: (path, options) => origin.request(token, path, { ...options, signal: assert.signal, assertActive: assert }),
- publishBot: (bot, requested) => {
+ publishBot: async (bot, requested) => {
assert()
- writeCommunityProfilePatches([{
+ await writeCommunityProfilePatches([{
id: bot.id,
identityAbout: { name: bot.name ?? requested.name, discriminator: bot.discriminator, kind: "bot" },
avatar: { avatar: bot.image ?? requested.image, avatarVersion: bot.avatarVersion },
diff --git a/src/web/src/components/community/onboarding/initialize-community-onboarding.ts b/src/web/src/components/community/onboarding/initialize-community-onboarding.ts
index d22426670..1eb6efd4e 100644
--- a/src/web/src/components/community/onboarding/initialize-community-onboarding.ts
+++ b/src/web/src/components/community/onboarding/initialize-community-onboarding.ts
@@ -80,7 +80,7 @@ export async function initializeCommunityOnboarding({
services: {
request: <T>(path: string, options?: ApiRequestOptions) => Promise<T>
readChannels: (serverId: string) => Promise<ChannelRow[]>
- publishBot: (bot: OnboardingBotCreateResponse["bot"], requested: { name: string; image: string }) => void
+ publishBot: (bot: OnboardingBotCreateResponse["bot"], requested: { name: string; image: string }) => void | Promise<void>
resolveBot: (id: string) => { name: string; discriminator?: string } | undefined
assert: () => void
}
@@ -114,7 +114,7 @@ export async function initializeCommunityOnboarding({
})
services.assert()
if (!created.bot.id) throw new Error("Setup progress could not be restored")
- services.publishBot(created.bot, { name, image })
+ await services.publishBot(created.bot, { name, image })
const bot: OnboardingInitializedBot = {
key: template.key,
id: created.bot.id,
diff --git a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
index d647ffa34..fb7cbb9eb 100644
--- a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
@@ -36,7 +36,7 @@ async function setup(method: "push" | "pushImmediate", { cold = false, empty = f
await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
const channels = empty ? [] : [{ id: "channel", name: "Channel", active: false, unread: false, muted: false, type: "text" as const }]
if (!cold) {
- publishCommunityLiveSnapshot(client, {
+ await publishCommunityLiveSnapshot(client, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: "", private: false, channels }] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
@@ -109,8 +109,8 @@ it.each([{ empty: true }, { mobile: true }])("retains the root when the real lan
it("finishes the current root after an older server deletion retires its in-flight detail proof", async () => {
const { view, calls, release, client, registry } = await setup("push", { cold: true })
const token = createOwnerServerDeleteRouteToken(client)
- act(() => {
- publishCommunityLiveSnapshot(client, {
+ await act(async () => {
+ await publishCommunityLiveSnapshot(client, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture({ id: "deleted", name: "Deleted", discriminator: "0002", description: "", icon: null, ownerId: "viewer", categories: [{ id: "old-category", name: "", private: false, channels: [{ id: "old-channel", name: "Old", active: false, unread: false }] }] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
index f7478d045..32b33c5aa 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
@@ -35,7 +35,7 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
mocks.load.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...server, role: "owner", isOwner: true, memberId: "membership" }] }))
await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
mocks.load.mockClear()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: true, muted: false, type: "text" }] }] }) }, proof })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: true, muted: false, type: "text" }] }] }) }, proof })
client.setQueryData(communityKeys.forumSidebarThreads(server.id), { threads: [], verifiedEpoch: 0, serverNow: new Date().toISOString(), serverClockOffsetMs: 0, window: { version: BUSINESS_SCHEMA_VERSION, accountId: registry.accountId, serverId: server.id, parents: ["channel"], base: [], retained: null } })
registry.collections.channelMemberships.utils.writeUpsert({ id: "channel:viewer:access", channelId: "channel", userId: "viewer", relation: "access", source: "explicit" })
registry.runtime.ws.actions.rememberChannelAccess(server.id, "channel")
@@ -63,23 +63,23 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const row = view.getByTestId(tid.channelRow("channel"))
const indicator = () => row.querySelector('[data-slot="community-channel-unread-indicator"]')
expect(indicator()).toHaveClass("h-0")
- const attention = (seq: number) => publishAccountAttentionSnapshot(client, {
+ const attention = async (seq: number) => await publishAccountAttentionSnapshot(client, {
snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "channel", channelId: "channel", serverId: server.id, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null }], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
- await act(async () => { attention(4) })
+ await act(async () => { await attention(4) })
await waitFor(() => expect(indicator()).toHaveClass("h-2.5"))
let optimistic!: ReturnType<typeof clearAttentionScopeOptimistically>
await act(async () => { optimistic = clearAttentionScopeOptimistically(registry, "channel", 4) })
await waitFor(() => expect(indicator()).toHaveClass("h-0"))
expect(registry.collections.channels.get("channel")).not.toHaveProperty("unread")
- await act(async () => { attention(4) })
+ await act(async () => { await attention(4) })
expect(indicator()).toHaveClass("h-0")
- await act(async () => { attention(5) })
+ await act(async () => { await attention(5) })
await waitFor(() => expect(indicator()).toHaveClass("h-2.5"))
await act(async () => {
restoreAttentionScopeOptimisticSnapshot(registry, optimistic)
- publishAccountAttentionSnapshot(client, { snapshot: { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }, proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ await publishAccountAttentionSnapshot(client, { snapshot: { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }, proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
})
await waitFor(() => expect(indicator()).toHaveClass("h-0"))
const title = view.getByRole("button", { name: "Target server" })
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
index 43b88b03a..37717fe6c 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
@@ -31,8 +31,8 @@ it("uses the canonical target sidebar before commit, retaining its node while de
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0, isOwner: true, role: "owner", memberId: "membership" }] }, "viewer") }, proof })
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: "Main", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] }) }, proof })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0, isOwner: true, role: "owner", memberId: "membership" }] }, "viewer") }, proof })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: "Main", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] }) }, proof })
client.setQueryData(communityKeys.servers(), [server.id])
const sourceToken = createOwnerServerDeleteRouteToken(client)
const targetToken = createOwnerServerDeleteRouteToken(client)
@@ -67,7 +67,7 @@ it("uses the canonical target sidebar before commit, retaining its node while de
it.each(["primary", "forum"])("ends a failed cold %s read with retry", async kind => {
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
- publishCommunityLiveSnapshot(client, {
+ await publishCommunityLiveSnapshot(client, {
snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0 }] }, "viewer") },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
@@ -137,7 +137,7 @@ it.each([
await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onOpenSettings: expect.any(Function) })))
expect(view.queryByText("Server settings")).toBeNull()
}
- act(() => { publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) })
+ await act(async () => { await publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) })
view.rerender(node())
await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ serverName: "Target server", primaryReady: true })))
if (order === "detail-first") {
diff --git a/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
index aa35a0ed9..480039412 100644
--- a/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
@@ -1,3 +1,5 @@
+import { canonicalChannelRow } from "@/lib/community-db/schema"
+import { createStore } from "@tanstack/store"
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
@@ -11,6 +13,8 @@ import { setLastMeLocation } from "@/lib/community/last-me-location"
import type { CommunityDbRegistry } from "@/lib/community-db/collections"
import { useCommunityRailHrefs } from "./use-community-rail-hrefs"
+const canonicalChannelFixture = (fields: Parameters<typeof channelResourceFixture>[0]) => canonicalChannelRow(channelResourceFixture(fields))
+
const owner = vi.hoisted(() => ({ registry: null as CommunityDbRegistry | null }))
vi.mock("@/lib/community-db/projections", () => ({ useOptionalCommunityDbRegistry: () => owner.registry }))
@@ -35,10 +39,10 @@ describe("rail hrefs derived from canonical rows and existing navigation memory"
it.each(["desktop", "mobile", "unknown"] as const)("server-renders deterministic %s links without reading client memory or subscribing", (breakpoint) => {
const servers = collection([["s", serverResourceFixture({ id: "s" })], ["other", serverResourceFixture({ id: "other" })]])
const channels = collection([
- ["first", channelResourceFixture({ id: "first", serverId: "s" })],
- ["second", channelResourceFixture({ id: "second", serverId: "other" })],
+ ["first", canonicalChannelFixture({ id: "first", serverId: "s" })],
+ ["second", canonicalChannelFixture({ id: "second", serverId: "other" })],
])
- owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
+ owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", runtime: { lifecycle: createStore({ active: true, generation: 0 }) }, collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
setLastMeLocation("/c/me/machines")
setLastChannel("s", "remembered")
setLastChannel("other", "other-remembered")
@@ -84,12 +88,12 @@ describe("rail hrefs derived from canonical rows and existing navigation memory"
it("subscribes to complete canonical channels, filters placeholders/threads, and follows the latest memory", () => {
const servers = collection([["s", serverResourceFixture({ id: "s" })]])
const channels = collection<ReturnType<typeof channelResourceFixture> & { pending?: boolean }>([
- ["pending", { ...channelResourceFixture({ id: "pending", serverId: "s" }), pending: true }],
- ["thread", channelResourceFixture({ id: "thread", serverId: "s", type: "thread", parentChannelId: "first", parentMessageId: "opener" })],
- ["first", channelResourceFixture({ id: "first", serverId: "s" })],
- ["foreign", channelResourceFixture({ id: "foreign", serverId: "other" })],
+ ["pending", { ...canonicalChannelFixture({ id: "pending", serverId: "s" }), pending: true }],
+ ["thread", canonicalChannelFixture({ id: "thread", serverId: "s", type: "thread", parentChannelId: "first", parentMessageId: "opener" })],
+ ["first", canonicalChannelFixture({ id: "first", serverId: "s" })],
+ ["foreign", canonicalChannelFixture({ id: "foreign", serverId: "other" })],
])
- owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
+ owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", runtime: { lifecycle: createStore({ active: true, generation: 0 }) }, collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
const rows = [{ id: "s" }]
const view = renderHook(({ breakpoint }: { breakpoint: "desktop" | "mobile" }) =>
useCommunityRailHrefs(rows, breakpoint), { initialProps: { breakpoint: "desktop" } })
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
index 95f7210ee..701c824e3 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
@@ -384,7 +384,7 @@ describe("useShellInboxController", () => {
it("uses the complete Attention DM resource and starts the common entry at push", async () => {
const hook = await renderController()
order.length = 0
- await act(async () => { publishAccountAttentionSnapshot(hook.queryClient, {
+ await act(async () => { await publishAccountAttentionSnapshot(hook.queryClient, {
snapshot: attentionSnapshotScenarioFixture({ scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], messages: [],
dms: [{ id: "dm1", userId: "u2", name: "Peer", discriminator: "2222", avatar: "P", avatarVersion: 0, lastMessageAt: unreadDm.lastMessageAt, lastUnreadSeq: 1 }],
profiles: [{ userId: "u2", name: "Peer", discriminator: "2222", avatar: "P", avatarVersion: 0 }] } }),
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index b2e790347..2b263ab54 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
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import type { Action } from "@/lib/observability/context"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
@@ -249,7 +250,7 @@ export function useShellInboxController({
},
() => {
const summary = dmSummaryFromInbox(dm)
- publishCommunityDmSummary(queryClient, summary)
+ void Promise.resolve(completeCommunityPublication(queryClient, () => publishCommunityDmSummary(queryClient, summary))).catch(() => undefined)
},
)
}, [pushProjected, queryClient])
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
index d324bc77b..a9b2bc976 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
@@ -1,3 +1,5 @@
+import { canonicalChannelRow } from "@/lib/community-db/schema"
+import { createStore } from "@tanstack/store"
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { QueryClient } from "@tanstack/react-query"
import type { CommunityDbRegistry } from "@/lib/community-db/collections"
@@ -10,6 +12,8 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { useShellRailController } from "./use-shell-rail-controller"
+const canonicalChannelFixture = (fields: Parameters<typeof channelResourceFixture>[0]) => canonicalChannelRow(channelResourceFixture(fields))
+
const mocks = vi.hoisted(() => ({
servers: [{ id: "s1", name: "One" }, { id: "s2", name: "Two" }],
folders: [] as Array<{ id: string; name: string; position: number; servers: Array<{ id: string }> }>,
@@ -277,17 +281,17 @@ describe("useShellRailController", () => {
["s2", serverResourceFixture({ id: "s2" })],
])
const channels = new Map([
- ["pending", { ...channelResourceFixture({ id: "pending", serverId: "s1" }), pending: true }],
- ["thread", { ...channelResourceFixture({ id: "thread", serverId: "s1", type: "thread", parentChannelId: "canonical", parentMessageId: "opener" }), pending: false }],
- ["canonical", { ...channelResourceFixture({ id: "canonical", serverId: "s1" }), pending: false }],
- ["foreign", { ...channelResourceFixture({ id: "foreign", serverId: "s2" }), pending: false }],
+ ["pending", { ...canonicalChannelFixture({ id: "pending", serverId: "s1" }), pending: true }],
+ ["thread", { ...canonicalChannelFixture({ id: "thread", serverId: "s1", type: "thread", parentChannelId: "canonical", parentMessageId: "opener" }), pending: false }],
+ ["canonical", { ...canonicalChannelFixture({ id: "canonical", serverId: "s1" }), pending: false }],
+ ["foreign", { ...canonicalChannelFixture({ id: "foreign", serverId: "s2" }), pending: false }],
])
const directoryClient = new QueryClient()
directoryClient.setQueryData(communityKeys.server("s1"), { schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "s1", categoryIds: [], channelIds: ["canonical"] })
- mocks.communityDb.current = { queryClient: directoryClient, scopeId: "viewer", accountId: "viewer", collections: {
+ mocks.communityDb.current = { queryClient: directoryClient, scopeId: "viewer", accountId: "viewer", runtime: { lifecycle: createStore({ active: true, generation: 0 }) }, collections: {
categories: { values: () => [][Symbol.iterator]() },
servers: { get: (id: string) => servers.get(id), values: () => servers.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
- channels: { values: () => channels.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
+ channels: { get: (id: string) => channels.get(id), values: () => channels.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
} } as unknown as CommunityDbRegistry
const hook = await renderController()
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index b7f1e4b50..5476a4d0f 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -92,7 +92,7 @@ afterEach(() => { railStyles.remove(); api.mockReset(); vi.unstubAllGlobals() })
describe("actual native Rail controller continuation", () => {
it("current create continues icon upload and navigation through the original account", async () => {
const { resolve } = await mount()
- let result!: Promise<unknown>; act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
+ let result!: Promise<unknown>; await act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
await act(async () => { resolve({ server: { id: "created" } }); await result })
await waitFor(() => expect(api.mock.calls.some(([path]) => path === "/api/community/servers/created/icon")).toBe(true))
@@ -101,9 +101,9 @@ describe("actual native Rail controller continuation", () => {
})
it.each(["success", "failure"] as const)("old UI create %s settles only its account operation without upload, toast or navigation", async (outcome) => {
const { view, resolve, reject, original } = await mount()
- let result!: Promise<unknown>; act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
+ let result!: Promise<unknown>; await act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
- act(() => view.rerender(<Root visible={false} />))
+ await act(() => view.rerender(<Root visible={false} />))
expect(getCommunityDbRegistry(original)!.runtime.lifecycle.get().active).toBe(true)
await act(async () => { if (outcome === "success") resolve({ server: { id: "created" } }); else reject(new Error("denied")); await result })
expect(api.mock.calls.some(([path]) => path.endsWith("/icon"))).toBe(false)
@@ -112,9 +112,9 @@ describe("actual native Rail controller continuation", () => {
it.each(["new-pending", "scope-return"] as const)("retires late create UI on %s while keeping its original account operation", async (change) => {
const { view, resolve, original } = await mount()
let result!: Promise<unknown>
- act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
+ await act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
- if (change === "new-pending") act(() => navigation.push("/c/channels/s2"))
+ if (change === "new-pending") await act(() => navigation.push("/c/channels/s2"))
else {
route.pathname = "/c/me/friends"; route.revision = 1
view.rerender(<Root />)
@@ -132,7 +132,7 @@ describe("actual native Rail controller continuation", () => {
it("rechecks the original rail intent after a failure is queued for deferred display", async () => {
const { reject } = await mount()
let result!: Promise<unknown>
- act(() => { result = controller.railProps.onCreateServer("New") })
+ await act(() => { result = controller.railProps.onCreateServer("New") })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
ui.queuedError.mockImplementation(() => navigation.push("/c/channels/s2"))
await act(async () => { reject(new Error("late failure")); await result })
@@ -142,7 +142,7 @@ describe("actual native Rail controller continuation", () => {
})
it("confirmed leave still navigates the original published route after native scope eviction clears its UI pointer", async () => {
const { resolve } = await mount()
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
await act(async () => resolve(undefined))
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/me"))
@@ -150,8 +150,8 @@ describe("actual native Rail controller continuation", () => {
it("leaves into canonical folder order while server/folder refresh stays held", async () => {
const { resolve, original } = await mount(false, true)
const registry = getCommunityDbRegistry(original)!
- act(() => {
- publishCommunityLiveSnapshot(original, {
+ await act(async () => {
+ await publishCommunityLiveSnapshot(original, {
snapshot: { kind: "folders", data: {
folders: [{ id: "f", name: "Group", servers: [{ id: "s3", name: "Three", initial: "T" }, { id: "s2", name: "Two", initial: "T" }] }],
topOrder: [{ kind: "folder", id: "f" }, { kind: "server", id: "s1" }],
@@ -160,7 +160,7 @@ describe("actual native Rail controller continuation", () => {
})
})
await waitFor(() => expect(controller.railProps.servers.map((server) => server.id)).toEqual(["s3", "s2", "s1"]))
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
await act(async () => resolve(undefined))
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s3"))
@@ -169,9 +169,9 @@ describe("actual native Rail controller continuation", () => {
})
it("confirmed leave does not redirect a newer navigation intent", async () => {
const { view, resolve } = await mount()
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
- act(() => { navigation.push("/c/channels/s2"); view.rerender(<Root />) })
+ await act(() => { navigation.push("/c/channels/s2"); view.rerender(<Root />) })
await act(async () => resolve(undefined))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
expect(ui.toast).not.toHaveBeenCalled()
@@ -181,9 +181,9 @@ describe("actual native Rail controller continuation", () => {
it.each(["/c/channels/s2", "/c/me/friends"])("mounted old sidebar preserves newer %s while the real leave retires its account scope", async (target) => {
const { resolve, original } = await mount(true)
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
- act(() => navigation.push(target))
+ await act(() => navigation.push(target))
await act(async () => resolve(undefined))
const registry = getCommunityDbRegistry(original)!
await waitFor(() => expect(registry.runtime.ws.get().revokedServerIds.has("s1")).toBe(true))
@@ -215,16 +215,16 @@ describe("actual native Rail controller continuation", () => {
it("mounted old sidebar preserves an unresolved newer intent and ejects if it is canceled", async () => {
const { resolve } = await mount(true)
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
let finish!: (href: string) => void, operation!: Promise<boolean>
- act(() => { operation = navigation.resolveAndPush(() => new Promise<string>((done) => { finish = done })) })
+ await act(() => { operation = navigation.resolveAndPush(() => new Promise<string>((done) => { finish = done })) })
await act(async () => resolve(undefined))
await waitFor(() => expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s1")).toBe(true))
expect(navigation.navigationPending).toBe(true)
expect(navigation.pendingHref).toBeNull()
expect(ui.replace).not.toHaveBeenCalled()
- act(() => navigation.cancelPendingNavigation())
+ await act(() => navigation.cancelPendingNavigation())
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s2"))
await act(async () => { finish("/c/me/friends"); await operation })
expect(ui.push).not.toHaveBeenCalledWith("/c/me/friends")
@@ -232,9 +232,9 @@ describe("actual native Rail controller continuation", () => {
it.each([false, true])("mounted sidebar still ejects the revoked current scope with same-server pending=%s", async (sameServerPending) => {
const { resolve } = await mount(true)
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
- if (sameServerPending) act(() => navigation.push("/c/channels/s1/channel-2"))
+ if (sameServerPending) await act(() => navigation.push("/c/channels/s1/channel-2"))
await act(async () => resolve(undefined))
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s2"))
expect(navigation.pendingHref).not.toBe("/c/channels/s1/channel-2")
@@ -242,19 +242,19 @@ describe("actual native Rail controller continuation", () => {
it("new destination sidebar ejects when its own server access is revoked", async () => {
const { view, resolve } = await mount(true)
- act(() => controller.railProps.onLeaveServer!("s1"))
+ await act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
- act(() => navigation.push("/c/channels/s2"))
+ await act(() => navigation.push("/c/channels/s2"))
await act(async () => resolve(undefined))
await waitFor(() => expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s1")).toBe(true))
expect(ui.replace).not.toHaveBeenCalled()
- act(() => {
+ await act(() => {
route.pathname = "/c/channels/s2"; route.revision = 1
window.history.replaceState(null, "", route.pathname)
view.rerender(<Root sidebar />)
})
await waitFor(() => expect(navigation.navigationPending).toBe(false))
- act(() => { evictServerChannelScopes(client, "s2") })
+ await act(() => { evictServerChannelScopes(client, "s2") })
await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/me"))
expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s2")).toBe(true)
})
diff --git a/src/web/src/components/community/social/friends-page.dom.test.tsx b/src/web/src/components/community/social/friends-page.dom.test.tsx
index 24452c46f..117c6462a 100644
--- a/src/web/src/components/community/social/friends-page.dom.test.tsx
+++ b/src/web/src/components/community/social/friends-page.dom.test.tsx
@@ -97,7 +97,7 @@ describe("FriendsPage actionable requests", () => {
const onAccept = vi.fn((_id: string) => new Promise<void>((next) => { resolve = next }))
const onOpenProfile = vi.fn()
const { client, registry } = await createCommunityQueryOwner()
- publishCommunityFriendships(client, pending.map(({ id, userId, kind, needsOwnerApproval }) => ({ id, userId, kind, needsOwnerApproval })), { token: captureCommunityLiveSnapshotToken(client), signal: undefined })
+ await publishCommunityFriendships(client, pending.map(({ id, userId, kind, needsOwnerApproval }) => ({ id, userId, kind, needsOwnerApproval })), { token: captureCommunityLiveSnapshotToken(client), signal: undefined })
function NativeRequests() {
const rows = useFriendshipRows()
const command = useMutation({ mutationKey: ["community", "friend-request", "accept"], mutationFn: async ({ friendshipId }: { friendshipId: string }) => {
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
index 0134d58e3..f2f5a352f 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
@@ -177,7 +177,7 @@ describe("useCommunityWs — operation bundles", () => {
it("applies archive and null-tag sidebar semantics inside committed batches", async () => {
await mountHook()
const baseKey = communityKeys.forumSidebarThreads("s1")
- seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
+ await seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
await act(async () => { await capturedOnMessage!(await batchFor("forum-archive", [{
type: "community:channel.child_update",
@@ -501,7 +501,7 @@ describe("useCommunityWs — operation bundles", () => {
}],
pageParams: [null],
})
- seedCanonicalThread("s1", "forum_1", "forum", "ch-1")
+ await seedCanonicalThread("s1", "forum_1", "forum", "ch-1")
const parentScope = { kind: "channel" as const, id: "forum_1", serverId: "s1" }
seedCanonicalStream(parentScope, {
type: "wsMessage",
diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.ts
index e54d1f0c7..1edf5aa1d 100644
--- a/src/web/src/hooks/community/community-ws/cache.test.ts
+++ b/src/web/src/hooks/community/community-ws/cache.test.ts
@@ -66,7 +66,7 @@ describe("community WS canonical publication and ID windows", () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
ingestMessages(registry, "ch_1", [messageResourceFixture({ id: "m_1", channelId: "ch_1" }), messageResourceFixture({ id: "m_2", channelId: "ch_1", seq: 2, content: "target", authorId: "author", createdAt: "2026-08-15T00:00:02.000Z" })])
const messages = [...registry.collections.messages.values()].map(row => messageResourceFixture(Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("$")))))
- publishCommunityMessages(client, { channelId: "ch_1", messages, profiles: messageProfilesFixture(messages), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { channelId: "ch_1", messages, profiles: messageProfilesFixture(messages), proof: { token: captureCommunityLiveSnapshotToken(client) } })
expect(findCachedMessage(client, "m_2")).toMatchObject({ id: "m_2", content: "target" })
expect(findCachedMessage(client, "missing")).toBeUndefined()
})
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
index 9fc272260..c2130b75a 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
@@ -103,7 +103,7 @@ describe.each(["text", "forum"] as const)("%s canonical thread scope eviction",
await mountHook({ viewerUserId: "u_me" })
const parentControl = "channelId" in event
if (parentControl) {
- seedCanonicalThread("server", "parent", shape, "active_child")
+ await seedCanonicalThread("server", "parent", shape, "active_child")
}
seedThreads("server", "parent", ["active_child", "preview_child"], shape)
seedThreads("server", "other_parent", ["other_child"], shape)
diff --git a/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts b/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts
index eea91bc71..38fb8c34a 100644
--- a/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts
@@ -47,7 +47,7 @@ async function deliver(value: unknown, apply = true) {
describe("current membership producer to consumer", () => {
it("delivers committed participant notify membership through actual route, ingress and hook", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
+ await seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
const value = JSON.parse(serializeMessageDeliveryBatch(batch()))
const result = await act(() => deliver(value))
expect(result.response?.status).toBe(200)
@@ -58,7 +58,7 @@ describe("current membership producer to consumer", () => {
it("calibrates the actual singular dispatch on a normal current single relationship frame", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
+ await seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
const encoded = encodeCommunityBrowserEvent({ type: "community:channel.membership.change", serverId: "server-current", channelId: "thread-current", userId: "u_me", relation: "notify", present: true })
if (!encoded.ok) throw new Error("Current relationship fixture rejected")
const dispatch = vi.spyOn(registry, "dispatchCommunityWsEvent")
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index 2a910f512..1b3edb1cc 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -1,18 +1,24 @@
import { communityKeys } from "@/lib/query-keys"
import type { CommunityWsProjectionTransaction } from "./projection-transaction"
+import { channelRefTargetAffected, type ChannelRefTarget } from "@/lib/community/channel-ref"
+
+type ReferenceScope = { serverId?: string | null; channelId?: string }
export function invalidateChannelRefDirectory(
projection: CommunityWsProjectionTransaction,
+ scope?: ReferenceScope,
) {
projection.invalidate("channel-ref-directory", {
queryKey: communityKeys.channelRefDirectory(),
exact: true,
})
- invalidateChannelRefTargets(projection)
+ invalidateChannelRefTargets(projection, scope)
}
-export function invalidateChannelRefTargets(projection: CommunityWsProjectionTransaction) {
- projection.fence("channel-ref-targets", { queryKey: communityKeys.channelRefTargets() })
+export function invalidateChannelRefTargets(projection: CommunityWsProjectionTransaction, scope?: ReferenceScope) {
+ projection.fence(`channel-ref-targets:${scope?.channelId ?? scope?.serverId ?? "all"}`, {
+ queryKey: communityKeys.channelRefTargets(), predicate: query => channelRefTargetAffected((query.state.data as { target?: ChannelRefTarget } | undefined)?.target, scope),
+ })
}
export function invalidateServerDetail(
diff --git a/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts b/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
index 5c8baa1d8..96056afa0 100644
--- a/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
@@ -32,7 +32,7 @@ describe("live forum window participation convergence", () => {
{ signal: "batch", participates: true, retires: true },
])("confirms $signal participation through the same window resource (eligible=$participates, retired=$retires)", async ({ signal, participates, retires }) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalForumSidebar(serverId)
+ await seedCanonicalForumSidebar(serverId)
const api = getCommunityApiFetchMock()
const original = api.getMockImplementation()!
let reads = 0
@@ -47,7 +47,7 @@ describe("live forum window participation convergence", () => {
const sidebar = await mountCanonicalHook(() => useForumSidebarThreads(serverId, null))
await expect.poll(() => sidebar.result.current.error?.message ?? sidebar.result.current.sidebar.status).toBe("ready")
expect(reads).toBe(1)
- act(() => { publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({
+ await act(async () => { await publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({
id: "post_live", serverId, name: "New live post", type: "thread", parentChannelId: "forum_1", parentMessageId: "opener-post_live",
creatorId: "u_me", archived: false, lastMessageAt: new Date().toISOString(),
}), proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined } }) })
@@ -69,7 +69,7 @@ describe("live forum window participation convergence", () => {
expect(hasCanonicalChannelNotify("post_live", "u_me")).toBe(signal === "membership")
if (signal !== "membership") expect(sidebar.result.current.threads.some(row => row.id === "post_live")).toBe(false)
const previousWindow = capturedQueryClient.getQueryData(communityKeys.forumSidebarThreads(serverId))
- if (retires) act(() => { canonicalRegistry!.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 })) })
+ if (retires) await act(() => { canonicalRegistry!.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 })) })
await act(async () => { release(envelope(participates ? ["post_1", "post_live"] : ["post_1"])) })
if (retires) {
await expect.poll(() => capturedQueryClient.getQueryState(communityKeys.forumSidebarThreads(serverId))?.fetchStatus).toBe("idle")
diff --git a/src/web/src/hooks/community/community-ws/live-sidebar-race.dom.test.ts b/src/web/src/hooks/community/community-ws/live-sidebar-race.dom.test.ts
index 19d3b4177..7c5db3ec5 100644
--- a/src/web/src/hooks/community/community-ws/live-sidebar-race.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/live-sidebar-race.dom.test.ts
@@ -27,7 +27,7 @@ async function frame(events: CommunityWsEvent[], id: string) {
it.each(["forum", "text"] as const)("retains a promoted %s participant when an older bounded response settles after live activity", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
const visible = ["post_7", "post_6", "post_5", "post_4", "post_3"]
- seedCanonicalForumSidebar(serverId, [...visible, "post_old"])
+ await seedCanonicalForumSidebar(serverId, [...visible, "post_old"])
act(() => { patchCanonicalCommunityChannel(capturedQueryClient, "post_old", row => ({ ...row, lastMessageAt: new Date(Date.now() - 60_000).toISOString() })) })
const api = getCommunityApiFetchMock()
const original = api.getMockImplementation()!
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
index aaf86cf9e..5c5759567 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
@@ -55,7 +55,7 @@ describe("useCommunityWs — member events", () => {
const { useCommunityStore } = await import("@/stores/community")
getCapturedRuntime().ui.actions.setCurrentServerId("srv_1")
getCapturedRuntime().ui.actions.setCurrentChannelId("private_child")
- seedCanonicalFocusedChannel({
+ await seedCanonicalFocusedChannel({
name: "Private title",
parentChannelId: "private_parent",
})
@@ -432,7 +432,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
it("retires notification arrivals on participant removal without retiring access", async () => {
await mountHook({ viewerUserId: "u_me" })
const { useCommunityWsStore } = await import("@/stores/community/ws")
- seedCanonicalThread("srv_1", "private_parent", "forum", "private")
+ await seedCanonicalThread("srv_1", "private_parent", "forum", "private")
seedCommunityAttentionScope(capturedQueryClient, { channelId: "private", serverId: "srv_1", seq: 1 })
capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", relation: "notify", present: false, serverId: "srv_1", channelId: "private", userId: "u_me" }))
@@ -506,7 +506,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
it("removes a private channel from the viewer's server tree on access loss", async () => {
await mountHook({ viewerUserId: "u_me" })
const serverKey = communityKeys.server("srv_1")
- seedCanonicalThread("srv_1", "ch_1", "text", "private-child")
+ await seedCanonicalThread("srv_1", "ch_1", "text", "private-child")
capturedQueryClient.setQueryData(serverKey, {
id: "srv_1",
categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],
@@ -525,13 +525,13 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
await mountHook({ viewerUserId: "u_me" })
const { useCommunityStore } = await import("@/stores/community")
const key = communityKeys.forumSidebarThreads("srv_1")
- await act(async () => { seedCanonicalForumSidebar("srv_1", ["post_1", "post_2"]) })
+ await act(async () => { await seedCanonicalForumSidebar("srv_1", ["post_1", "post_2"]) })
await act(async () => {
patchCanonicalCommunityChannel(capturedQueryClient, "forum_1", row => ({ ...row, type: parentType }))
seedCommunityAttentionScope(capturedQueryClient, { channelId: "post_1", serverId: "srv_1", parentChannelId: "forum_1", seq: 1 })
})
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("post_1") })
- await act(async () => { seedCanonicalFocusedChannel({
+ await act(async () => { await seedCanonicalFocusedChannel({
name: "Private forum title",
parentChannelId: "forum_1",
parentMessageId: "opener-post_1",
@@ -560,14 +560,14 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
expect(hasCanonicalChannelNotify("post_2", "u_me")).toBe(true)
})
- it("does not touch forum resources for a known ordinary text child", async () => {
+ it("refreshes the shared text-thread sidebar without evicting other resources", async () => {
await mountHook({ viewerUserId: "u_me" })
const { useCommunityStore } = await import("@/stores/community")
const baseKey = communityKeys.forumSidebarThreads("srv_1")
const retainedKey = communityKeys.forumSidebarRetained("srv_1", "forum_post")
const metaKey = entryKey("srv_1", "text_thread")
const hintKey = communityKeys.forumOpenerHint("srv_1", "forum_opener")
- seedCanonicalThread("srv_1", "text_parent", "text", "text_thread")
+ await seedCanonicalThread("srv_1", "text_parent", "text", "text_thread")
capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
categories: [{
@@ -585,33 +585,33 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
hint: capturedQueryClient.getQueryData(hintKey),
}
- capturedOnMessage!(currentCommunityEventFixture({
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: true,
serverId: "srv_1",
channelId: "text_thread",
userId: "u_me",
- }))
+ })) })
expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
- expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
expect(capturedQueryClient.getQueryData(retainedKey)).toBe(before.retained)
expect(capturedQueryClient.getQueryData(metaKey)).toBe(before.meta)
expect(capturedQueryClient.getQueryData(hintKey)).toBe(before.hint)
getCapturedRuntime().ui.actions.setCurrentChannelId("text_thread")
- seedCanonicalFocusedChannel({
+ await seedCanonicalFocusedChannel({
name: "Private title",
parentChannelId: "text_parent",
})
- capturedOnMessage!(currentCommunityEventFixture({
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: false,
serverId: "srv_1",
channelId: "text_thread",
userId: "u_me",
- }))
+ })) })
expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
- expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
expect(capturedQueryClient.getQueryData(retainedKey)).toBe(before.retained)
expect(capturedQueryClient.getQueryData(metaKey)).toBe(before.meta)
expect(capturedQueryClient.getQueryData(hintKey)).toBe(before.hint)
@@ -624,7 +624,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
describe("membership metadata and access lifetime", () => {
it.each([false, true])("rechecks explicit access present=%s without treating it as a notify change", async present => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const key = communityKeys.channelMessages("child")
const content = { pages: [{ messages: [{ id: "private" }] }] }
capturedQueryClient.setQueryData(key, content)
@@ -662,7 +662,7 @@ describe("membership metadata and access lifetime", () => {
it.each([403, 404, 500])("lets the real metadata owner resolve access failure %s without a second retirement", async status => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const key = communityKeys.channelMessages("child")
const content = { pages: [{ messages: [{ id: "private" }] }] }
capturedQueryClient.setQueryData(key, content)
@@ -684,7 +684,7 @@ describe("membership metadata and access lifetime", () => {
it("retires a channel when its explicit access refresh confirms it is archived", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const api = getCommunityApiFetchMock()
const fallback = api.getMockImplementation()!
const archived = new ApiError("archived", 403)
@@ -703,7 +703,7 @@ describe("membership metadata and access lifetime", () => {
it("publishes the current notify roster and rejects the retired response without replacing the body", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
}, "u_me")
@@ -752,7 +752,7 @@ describe("membership metadata and access lifetime", () => {
})
it.each([true, false])("keeps the verified body and access generation for explicit notify present=%s", async (present) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z" }, "u_me")
getCommunityApiFetchMock().mockResolvedValue(payload)
@@ -772,7 +772,7 @@ describe("membership metadata and access lifetime", () => {
})
it.each(["text", "forum"] as const)("replaces an in-flight %s child metadata read when explicit access refresh changes again", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", parentType, "child")
+ await seedCanonicalThread("server", "parent", parentType, "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent",
parentMessageId: "opener", creatorId: "u_me", name: "Current child", archived: false,
@@ -842,7 +842,7 @@ describe("membership metadata and access lifetime", () => {
it("hands batched explicit access refreshes to the latest access generation", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "text", "child")
+ await seedCanonicalThread("server", "parent", "text", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
@@ -873,7 +873,7 @@ describe("membership metadata and access lifetime", () => {
it("settles a failed current-generation read without rebuilding it and recovers on explicit Retry", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
@@ -899,7 +899,7 @@ describe("membership metadata and access lifetime", () => {
it.each(["parent", "server", "account", "unmount"] as const)("does not restart participation metadata after %s retirement before handoff", async (race) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
@@ -940,7 +940,7 @@ describe("membership metadata and access lifetime", () => {
it.each(["text", "forum"] as const)("keeps %s child content after notify removal with ID-only metadata", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("server", "parent", parentType, "child")
+ await seedCanonicalThread("server", "parent", parentType, "child")
act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "child", "u_me", "notify", true) })
getCommunityApiFetchMock().mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent",
@@ -1048,7 +1048,7 @@ describe("membership metadata and access lifetime", () => {
await mountHook({ viewerUserId: "u_me" })
const { useCommunityWsStore } = await import("@/stores/community/ws")
const { useCommunityStore } = await import("@/stores/community")
- seedCanonicalThread("server", "parent", "forum", "child")
+ await seedCanonicalThread("server", "parent", "forum", "child")
getCapturedRuntime().ws.actions.rememberChannelAccess("server", "parent")
getCapturedRuntime().ws.actions.rememberChannelAccess("server", "child", "parent")
capturedQueryClient.setQueryData(communityKeys.pins("child"), { pins: [{ id: "m1" }] })
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index 05d0f2a73..7d2bc3a8a 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -29,6 +29,7 @@ import {
} from "./reaction-details-invalidation"
import {
getCanonicalCommunityChannels,
+ completeCommunityPublication,
retireCommunityChannelReading,
setCanonicalCommunityChannelMember,
} from "@/lib/community-db/sync"
@@ -50,7 +51,7 @@ function refreshChannelAccess(event: { serverId: string | null; channelId: strin
await queryClient.query({ ...options, staleTime: 0, retry: false, select: undefined })
if (!isChannelMetadataTokenCurrent(token)) return
const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)
- if (channel?.archived) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
+ if (channel?.archived) await completeCommunityPublication(queryClient, () => runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection })))
} catch {}
})()
@@ -60,7 +61,7 @@ export function handleChannelMembershipChange(event: CommunityChannelMembershipC
const { queryClient, projection, viewerUserIdRef } = context
setCanonicalCommunityChannelMember(queryClient, event.channelId, event.userId, event.relation, event.present, { event: true })
if (event.serverId) invalidateServerDetail(projection, event.serverId)
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId, channelId: event.channelId })
projection.fence("channel-roster", { queryKey: communityKeys.channelMembers(event.channelId, event.relation) })
projection.invalidate("channel-addable-members", { queryKey: communityKeys.channelAddableMembers(event.channelId) })
if (event.relation === "notify") projection.invalidate("thread-participants", { queryKey: communityKeys.threadParticipants(event.channelId) })
@@ -106,7 +107,7 @@ export function handleMemberJoin(
if (viewerId) {
getCommunityRuntime(context.queryClient).ws.actions.grantServerAccess(event.serverId)
}
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId })
invalidateServersList(projection)
invalidateServerDetail(projection, event.serverId)
}
@@ -126,7 +127,7 @@ export function handleMemberLeave(
if (event.userId === viewerUserIdRef.current) {
evictServerChannelScopes(queryClient, event.serverId)
removeServerReactionDetails(queryClient, event.serverId)
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId })
// Rail LIST only (the layout's eject effect reads it to route the
// kicked viewer away). `exact` so a kick doesn't cascade-refetch
// every server's nested detail subtree.
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 920e9ddbd..85c48c781 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -122,7 +122,7 @@ describe("useCommunityWs — message.create", () => {
it("patches a loaded forum-sidebar child activity without a refetch", async () => {
await mountHook()
- seedCanonicalForumSidebar("srv_1")
+ await seedCanonicalForumSidebar("srv_1")
const key = communityKeys.forumSidebarThreads("srv_1")
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event = {
@@ -161,7 +161,7 @@ describe("useCommunityWs — message.create", () => {
it("warms an unknown forum child owner from live message evidence", async () => {
await mountHook()
- seedCanonicalForumSidebar("srv_1")
+ await seedCanonicalForumSidebar("srv_1")
expect(hasCanonicalChannel("post_live")).toBe(false)
getCommunityApiFetchMock().mockImplementation(async (url: string) => {
if (url === "/api/community/channels/post_live/messages?entry=1") {
@@ -220,7 +220,7 @@ describe("useCommunityWs — message.create", () => {
getCapturedRuntime().ui.actions.subscribe({ channelId: "post_retained" })
}
await mountHook()
- seedCanonicalForumSidebar("srv_1", ["post_retained"])
+ await seedCanonicalForumSidebar("srv_1", ["post_retained"])
const key = communityKeys.forumSidebarThreads("srv_1")
capturedOnMessage!(currentCommunityEventFixture({
@@ -397,7 +397,7 @@ describe("useCommunityWs — message.create", () => {
const { useCommunityStore } = await import("@/stores/community")
const store = getCapturedRuntime().ui.get()
getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1")
- seedCanonicalFocusedChannel({ name: "thread", parentChannelId: "parent_1" })
+ await seedCanonicalFocusedChannel({ name: "thread", parentChannelId: "parent_1" })
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_1" })
resetHookMemoization()
await mountHook()
@@ -430,7 +430,7 @@ describe("useCommunityWs — message.create", () => {
const { useCommunityStore } = await import("@/stores/community")
const store = getCapturedRuntime().ui.get()
getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1")
- seedCanonicalFocusedChannel({ name: "thread", parentChannelId: "parent_1" })
+ await seedCanonicalFocusedChannel({ name: "thread", parentChannelId: "parent_1" })
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_1" })
resetHookMemoization()
await mountHook()
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 0255fd5b3..0c7bd9219 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
@@ -22,7 +22,7 @@ it.each(["community:read_state.advanced", "community:inbox.changed"] as const)("
{ channelId: "c1", lastReadMessageId: "m8", lastReadAt: "2026-10-27T00:00:08.000Z", lastReadSeq: 8 },
{ channelId: "c2", lastReadMessageId: "m7", lastReadAt: "2026-10-27T00:00:07.000Z", lastReadSeq: 7 },
] }
- publishCommunityConversationReadState(owner.client, snapshot.readStates[0], 8, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
+ await publishCommunityConversationReadState(owner.client, snapshot.readStates[0], 8, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
expect(owner.registry.collections.readStateClock.get("account")).toBeUndefined()
apiFetch.mockImplementation(async (path: string) => path.endsWith("/read-state") ? snapshot : emptyAttention)
const event = { type, revision: 8, inboxChanged: true, ...(type === "community:inbox.changed" ? { reason: "read_all" as const } : {}) }
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 3dc388122..15fe8300a 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
@@ -107,7 +107,7 @@ describe("native account read-state reconciliation", () => {
})
it("preserves a newer confirmed ACK floor across an older full snapshot", async () => {
- publishCommunityConversationReadState(owner.client, row(7), 7, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
+ await publishCommunityConversationReadState(owner.client, row(7), 7, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
apiFetch.mockResolvedValue(snapshot(6))
await reconcileAccountReadState(owner.client, { reconcileAttention: false })
expect(currentConversationReadState(owner.client, "c1")).toMatchObject(row(7))
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 e5b60488a..bcd262db8 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
@@ -38,7 +38,7 @@ function accountReadStateOptions(queryClient: QueryClient, requestedRevision = -
const snapshot = await apiFetch<AccountReadStateSnapshot>("/api/community/users/me/read-state", communityRequestOptions(queryClient, requestToken, signal))
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
if (!original || queryClient.getQueryCache().get(original.queryHash) !== original) throw new DOMException("Read-state query retired", "AbortError")
- const publication = publishCommunityLiveSnapshot(queryClient, {
+ const publication = await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "read-state", data: snapshot },
proof: { kind: "read-state", token: requestToken, signal, requestGeneration: 0, currentRequestGeneration: 0, targetRevision: Math.max(minimumRevision, targetRevision(queryClient)) },
})
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
index 1a125232a..da7448f70 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
@@ -38,7 +38,7 @@ async function setup(sequences = [98, 99, 100], tag: string | null = null) {
page: { ...fixture().page, latestSeq: last.seq, hasMoreOlder: true, hasMoreNewer: false },
}
const options = conversationEntryOptions(owner.client, target)
- const resource = publishConversationEntry(owner.client, target, packet, { token: captureCommunityLiveSnapshotToken(owner.client, "c1") })
+ const resource = await publishConversationEntry(owner.client, target, packet, { token: captureCommunityLiveSnapshotToken(owner.client, "c1") })
owner.client.setQueryData(options.queryKey, resource)
const key = resource.windowKey
const observer = new QueryObserver(owner.client, { queryKey: key, queryFn: vi.fn(), staleTime: Infinity })
@@ -57,7 +57,7 @@ describe("complete canonical coverage at the existing repair owner", () => {
const fresh = { ...fixture(), messages: [{ ...row(100), content: "edited" }, row(101)],
selection: { reason: "tail" as const, anchorMessageId: null }, page: { ...fixture().page, latestSeq: 101 },
}
- publishConversationEntry(h.client, h.target, fresh, { token: captureCommunityLiveSnapshotToken(h.client, "c1") })
+ await publishConversationEntry(h.client, h.target, fresh, { token: captureCommunityLiveSnapshotToken(h.client, "c1") })
load.mockResolvedValue(page([row(101)], 101))
try {
await reconcileConversationLanding(h.client, { kind: "channel", scopeId: "c1", serverId: "s1" }, h.key,
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 deaf930f2..6a7b85b5d 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,3 +1,4 @@
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { COMMUNITY_CONTRACT_HEADER, CommunityMessageResourceSchema } from "@alook/shared"
import { CancelledError, hashKey, queryOptions, type InfiniteData, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
@@ -40,8 +41,7 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
function cachedCoverage(queryClient: QueryClient, scopeId: string, cache: MessageCache, refreshed: MessagesPage, target: number, tag: string | null) {
if (tag !== null || !Number.isSafeInteger(target)) return
- const byId = new Map<string, MessageInput>(getCanonicalCommunityMessages(queryClient)
- .filter(row => row.channelId === scopeId).map(row => [row.id, row]))
+ const byId = new Map<string, MessageInput>(getCanonicalCommunityMessages(queryClient, scopeId).map(row => [row.id, row]))
for (const message of refreshed.messages) {
const parsed = CommunityMessageResourceSchema.strip().safeParse(message)
if (parsed.success && parsed.data.channelId === scopeId) byId.set(message.id, parsed.data)
@@ -194,7 +194,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
cached = coverage?.page
cachedCovered = coverage?.covered ?? 0
if (coverage ? coverage.covered >= required : required <= latest(current, false)) return
- if (cached?.messages.length) publish(refreshed)
+ if (cached?.messages.length) await publish(refreshed)
const nextCursor = coverage?.cursor ?? cursor(current)
if (!nextCursor && (refreshed.latestSeq ?? 0) >= target()) return
const param: MessagesPageParam = nextCursor ? { mode: "since", since: nextCursor } : current.pageParams[0]
@@ -207,14 +207,14 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
if (remaining) { cached = remaining.page; cachedCovered = remaining.covered }
}
}
- const publish = (refreshed: MessagesReadPage) => {
+ const publish = async (refreshed: MessagesReadPage) => {
assert()
const fetchedEnd = Math.max(0, ...(prefetched?.page.messages.map(message => message.seq ?? 0) ?? []))
const catchUp = cached && prefetched && cachedCovered >= fetchedEnd
? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]
const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))
if (pending.length) {
- publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), profiles: [...new Map(pending.flatMap(page => page.profiles).map(profile => [profile.id, profile])).values()], proof: { token, signal } })
+ await publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), profiles: [...new Map(pending.flatMap(page => page.profiles).map(profile => [profile.id, profile])).values()], proof: { token, signal } })
for (const page of pending) published.add(page)
}
queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
@@ -227,7 +227,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const refreshed = landingPage.page
if (!isMessageCache(originalQuery?.state.data)) { record("retired"); return { latestSeq: 0 } }
await prefetch(current, refreshed)
- publish(refreshed)
+ await publish(refreshed)
if (pendingDirection && !paginationReplayed) {
paginationReplayed = true
await originalQuery?.fetch(undefined, { meta: { fetchMore: { direction: pendingDirection } } })
@@ -236,7 +236,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const afterPagination = originalQuery?.state.data
if (!prefetched && isMessageCache(afterPagination) && target() > latest(afterPagination, false)) {
await prefetch(afterPagination, refreshed)
- publish(refreshed)
+ await publish(refreshed)
}
assert()
const latestSeq = Math.max(refreshed.latestSeq ?? 0, prefetched?.page.latestSeq ?? 0, cachedCovered)
@@ -249,10 +249,10 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
record(signal.aborted ? "cancelled" : isAbortError(error) ? "retired" : "error")
assert()
if (!(error instanceof ApiError) || (error.status !== 403 && error.status !== 404) || isConversationAnchorMissingError(error)) throw error
- if (registry) retireCommunityChannelReading(registry, scopeId, {
+ if (registry) await completeCommunityPublication(registry, () => retireCommunityChannelReading(registry, scopeId, {
reason: "read-denied", serverId,
preserveQuery: queryClient.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true }),
- })
+ }))
return { latestSeq: 0 }
}
},
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 1fd89201f..b611269ac 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
@@ -316,7 +316,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
it("invalidates the focused thread opener's single-message query on reconnect", async () => {
const { useCommunityStore } = await import("@/stores/community")
getCapturedRuntime().ui.actions.setCurrentChannelId("thread_focus")
- seedCanonicalFocusedChannel({
+ await seedCanonicalFocusedChannel({
name: "thread",
parentChannelId: "ch_parent",
parentMessageId: "m_opener",
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 7b912b162..17369facb 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -56,6 +56,8 @@ import {
handleProfileUpdate,
} from "@/hooks/community/community-ws/identity-events"
import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { withCommunityCollectionWrites } from "@/lib/community-db/write"
import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"
type CommunityEventType = CommunityWsEvent["type"]
@@ -169,7 +171,9 @@ export function dispatchCommunityWsEvents(
}
const receipts: Array<{ id: string; start: number; type: CommunityEventType; operation?: PageOperation }> = []
const publications: Promise<void>[] = []
- try { runCommunityWsProjectionTransaction(context.queryClient, (projection) => {
+ try {
+ const registry = getCommunityDbRegistry(context.queryClient)
+ const publish = () => runCommunityWsProjectionTransaction(context.queryClient, (projection) => {
const handlerContext: CommunityWsHandlerContext = {
...context,
projection,
@@ -201,7 +205,10 @@ export function dispatchCommunityWsEvents(
scheduleAccountAttentionReconcile(context.queryClient)
}
}
- }) } catch (error) {
+ })
+ const publication = registry ? withCommunityCollectionWrites(registry, publish) : publish()
+ if (publication instanceof Promise) publications.push(publication.then(() => undefined))
+ } catch (error) {
void Promise.allSettled(publications)
for (const receipt of receipts) {
finishPageOperation(receipt.operation, "partial")
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
index f6da2654e..bd92e772e 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
@@ -98,9 +98,9 @@ function forumFeedFixture(rows: Parameters<typeof forumFeedTransportFixture>[0])
return { ...transport, pages: transport.pages.map(page => forumFeedWindow(normalizeThreadResources("forum_1", page))) }
}
-function seedKnownThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string, openerId: string) {
+async function seedKnownThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string, openerId: string) {
seedCanonicalServer({ id: serverId, channels: [{ id: parentId, type: parentType, name: "Parent" }] })
- publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({ id: childId, serverId, type: "thread", parentChannelId: parentId, parentMessageId: openerId }),
+ await publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({ id: childId, serverId, type: "thread", parentChannelId: parentId, parentMessageId: openerId }),
proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient, childId) } })
}
@@ -113,10 +113,10 @@ function forumFeedIds(filter: string | null) {
return mapForumFeedPages(pages, messages, channels, new Map(), filter).map((thread) => thread.id)
}
-function seedForumFeed(rows: Parameters<typeof forumFeedFixture>[0]) {
+async function seedForumFeed(rows: Parameters<typeof forumFeedFixture>[0]) {
seedCanonicalServer({ id: "s1", categories: [{ id: "cat1", name: "Forum", channels: [{ id: "forum_1", name: "Forum", type: "forum", active: false, unread: false }] }] })
const page = forumFeedTransportFixture(rows).pages[0]!
- act(() => { publishCommunityForumFeed(capturedQueryClient, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined }) })
+ await act(async () => { await publishCommunityForumFeed(capturedQueryClient, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined }) })
}
beforeEach(resetCommunityWsHarness)
@@ -217,8 +217,8 @@ describe("useCommunityWs — invite.create", () => {
await mountHook()
const matchingKey = communityKeys.invites("srv_1")
const otherKey = communityKeys.invites("srv_2")
- act(() => { capturedQueryClient.setQueryData(matchingKey, { invites: [] }) })
- act(() => { capturedQueryClient.setQueryData(otherKey, { invites: [] }) })
+ await act(() => { capturedQueryClient.setQueryData(matchingKey, { invites: [] }) })
+ await act(() => { capturedQueryClient.setQueryData(otherKey, { invites: [] }) })
capturedOnMessage!(currentCommunityEventFixture({
type: "community:invite.create",
@@ -239,7 +239,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
it("clears ephemeral channel state after scope eviction", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.setState((state) => ({ ...state, ...{
+ await act(() => { getCapturedRuntime().ui.setState((state) => ({ ...state, ...{
typingByScope: new Map([["ch:ch_old", new Map([["u_typing", "Typer"]])]]),
} })) })
capturedOnMessage!(currentCommunityEventFixture({
@@ -275,7 +275,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
await act(async () => { capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] }) })
await act(async () => { capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] }) })
const sidebarKey = communityKeys.forumSidebarThreads("srv_1")
- await act(async () => { seedCanonicalForumSidebar("srv_1", ["ch_dead"]) })
+ await act(async () => { await seedCanonicalForumSidebar("srv_1", ["ch_dead"]) })
const event: CommunityChannelDelete = {
type: "community:channel.delete",
@@ -310,7 +310,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
categories: [{ id: "cat_1", name: "Category", private: false, channels: [] }],
}
seedCanonicalServer({ ...freshServer, categories: [{ ...freshServer.categories[0], channels: [{ ...deletedChannel, active: false, unread: false }] }] })
- act(() => { capturedQueryClient.setQueryData(serverKey, {
+ await act(() => { capturedQueryClient.setQueryData(serverKey, {
...freshServer,
categories: [{
...freshServer.categories[0],
@@ -351,7 +351,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
await act(async () => { getCapturedRuntime().ui.actions.registerUiHandlers({ replacePath }) })
await act(async () => { getCapturedRuntime().ui.actions.setCurrentServerId("srv_1") })
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("post_1") })
- await act(async () => { seedCanonicalFocusedChannel({
+ await act(async () => { await seedCanonicalFocusedChannel({
name: "Post",
parentChannelId: "forum_1",
parentMessageId: "opener-post_1",
@@ -374,7 +374,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
}
await act(async () => { capturedQueryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), forumFeed) })
await act(async () => { capturedQueryClient.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] }) })
- await act(async () => { seedCanonicalForumSidebar("srv_1", ["post_1", "post_keep"]) })
+ await act(async () => { await seedCanonicalForumSidebar("srv_1", ["post_1", "post_keep"]) })
await act(async () => { capturedQueryClient.setQueryData(
communityKeys.forumOpenerHint("srv_1", "opener-post_1"),
{ id: "opener-post_1", content: "Post" },
@@ -424,10 +424,10 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
seedCanonicalServer({ id: "s1", categories: [{ id: "cat1", name: "General", channels: [{ id: "ch_parent", name: "Parent", type: "text", active: false, unread: false }] }] })
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_parent" }) })
+ await act(() => { getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_parent" }) })
resetHookMemoization()
await mountHook()
- act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
pages: [{ messages: [], hasMore: false }],
pageParams: [null],
}) })
@@ -462,11 +462,11 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_create then message.create invalidates and preserves the enriched forum card", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_parent" }) })
+ await act(() => { getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_parent" }) })
resetHookMemoization()
await mountHook()
const parentMessagesKey = communityKeys.channelMessages("ch_parent")
- act(() => { capturedQueryClient.setQueryData(parentMessagesKey, {
+ await act(() => { capturedQueryClient.setQueryData(parentMessagesKey, {
pages: [{ messages: [], hasMore: false }],
pageParams: [null],
}) })
@@ -486,7 +486,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
capturedOnMessage!(currentCommunityEventFixture(event))
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: parentMessagesKey })
- act(() => { capturedQueryClient.setQueryData(parentMessagesKey, {
+ await act(() => { capturedQueryClient.setQueryData(parentMessagesKey, {
pages: [{
messages: [{
id: "m_parent",
@@ -508,9 +508,9 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update still applies the reported messageCount unchanged", async () => {
await mountHook()
- seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
+ await seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
seedCanonicalMessages("ch_parent", [{ id: "m_parent", content: "hello", thread: { id: "ch_thread", name: "old", messageCount: 0 } }])
- act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
pages: [
{
messages: [
@@ -548,7 +548,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
const tags = communityKeys.forumTags("forum_1")
const messages = communityKeys.channelMessages("forum_1")
for (const key of [allFeed, archivedFeed, tags, messages]) {
- act(() => { capturedQueryClient.setQueryData(key, { value: "stale" }) })
+ await act(() => { capturedQueryClient.setQueryData(key, { value: "stale" }) })
}
capturedOnMessage!(currentCommunityEventFixture({
@@ -592,16 +592,16 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("projects remote Archive out of warm All and ordinary feeds synchronously", async () => {
await mountHook()
- seedForumFeed([{ id: "post_1", opener: "opener_1", tags: ["bug"] }])
- act(() => { capturedQueryClient.setQueryData(
+ await seedForumFeed([{ id: "post_1", opener: "opener_1", tags: ["bug"] }])
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", null),
forumFeedFixture([{ id: "post_1", opener: "opener_1", tags: ["bug"] }]),
) })
- act(() => { capturedQueryClient.setQueryData(
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", "bug"),
forumFeedFixture([{ id: "post_1", opener: "opener_1", tags: ["bug"] }]),
) })
- act(() => { capturedQueryClient.setQueryData(
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", "archived"),
forumFeedFixture([]),
) })
@@ -620,8 +620,8 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("projects remote Unarchive out of Archived without inventing an All rank", async () => {
await mountHook()
- seedForumFeed([{ id: "post_1", opener: "opener_1", tags: ["bug", "archived"] }])
- act(() => { capturedQueryClient.setQueryData(
+ await seedForumFeed([{ id: "post_1", opener: "opener_1", tags: ["bug", "archived"] }])
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", "archived"),
forumFeedFixture([{
id: "post_1",
@@ -629,7 +629,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
tags: ["bug", "archived"],
}]),
) })
- act(() => { capturedQueryClient.setQueryData(
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", null),
forumFeedFixture([]),
) })
@@ -647,12 +647,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("leaves warm feeds untouched when parent and child resolve conflicting openers", async () => {
await mountHook()
- seedForumFeed([{ id: "post_1", opener: "opener_one", tags: ["bug"] }])
- act(() => { capturedQueryClient.setQueryData(
+ await seedForumFeed([{ id: "post_1", opener: "opener_one", tags: ["bug"] }])
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", null),
forumFeedFixture([{ id: "post_1", opener: "opener_one", tags: ["bug"] }]),
) })
- act(() => { capturedQueryClient.setQueryData(
+ await act(() => { capturedQueryClient.setQueryData(
communityKeys.forumFeed("forum_1", "bug"),
forumFeedFixture([{ id: "post_1", opener: "opener_two", tags: ["bug"] }]),
) })
@@ -675,9 +675,9 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const baseKey = communityKeys.forumSidebarThreads("s1")
- await act(async () => { seedCanonicalForumSidebar("s1", ["post_1", "post_2"]) })
+ await act(async () => { await seedCanonicalForumSidebar("s1", ["post_1", "post_2"]) })
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("post_1") })
- await act(async () => { seedCanonicalFocusedChannel({
+ await act(async () => { await seedCanonicalFocusedChannel({
name: "Post one",
parentChannelId: "forum_1",
parentMessageId: "opener-post_1",
@@ -708,10 +708,10 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const baseKey = communityKeys.forumSidebarThreads("s1")
- await act(async () => { seedCanonicalForumSidebar("s1", ["post_1", "post_2"]) })
+ await act(async () => { await seedCanonicalForumSidebar("s1", ["post_1", "post_2"]) })
const before = canonicalForumSidebar("s1").threads
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("post_1") })
- await act(async () => { seedCanonicalFocusedChannel({
+ await act(async () => { await seedCanonicalFocusedChannel({
name: "Post one",
parentChannelId: "forum_1",
parentMessageId: "opener-post_1",
@@ -733,14 +733,14 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update rename patches focused child metadata and its cached channel meta", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("s1") })
- act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_thread") })
- seedCanonicalFocusedChannel({
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("s1") })
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_thread") })
+ await seedCanonicalFocusedChannel({
name: "old",
parentChannelId: "ch_parent",
parentMessageId: "m_parent",
})
- act(() => { capturedQueryClient.setQueryData(communityKeys.channelMeta("s1", "ch_thread"), {
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.channelMeta("s1", "ch_thread"), {
id: "ch_thread",
name: "old",
parentChannelId: "ch_parent",
@@ -763,9 +763,9 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const key = communityKeys.forumSidebarThreads("s1")
- await act(async () => { seedCanonicalForumSidebar("s1", ["ch_thread"]) })
+ await act(async () => { await seedCanonicalForumSidebar("s1", ["ch_thread"]) })
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_thread") })
- await act(async () => { seedCanonicalFocusedChannel({
+ await act(async () => { await seedCanonicalFocusedChannel({
name: "Private title",
parentChannelId: "forum_1",
parentMessageId: "opener-ch_thread",
@@ -791,7 +791,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("absorbs a failed unarchive ownership probe", async () => {
await mountHook()
- seedCanonicalForumSidebar("s1", [])
+ await seedCanonicalForumSidebar("s1", [])
getCommunityApiFetchMock().mockRejectedValueOnce(new Error("offline"))
capturedOnMessage!(currentCommunityEventFixture({
@@ -811,8 +811,8 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("clears active child metadata synchronously on channel.delete", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_dead") })
- seedCanonicalFocusedChannel({
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_dead") })
+ await seedCanonicalFocusedChannel({
name: "Private title",
parentChannelId: "forum_1",
})
@@ -833,14 +833,14 @@ describe("useCommunityWs — child_create patches parent thread badge with count
const retainedKey = communityKeys.forumSidebarRetained("s1", "forum_post")
const metaKey = communityKeys.channelMeta("s1", "text_thread")
const hintKey = communityKeys.forumOpenerHint("s1", "forum_opener")
- act(() => { capturedQueryClient.setQueryData(communityKeys.server("s1"), {
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.server("s1"), {
id: "s1",
categories: [{ id: "cat_1", channels: [{ id: "text_parent", type: "text" }] }],
}) })
- act(() => { capturedQueryClient.setQueryData(baseKey, forumSidebarFixture()) })
- act(() => { capturedQueryClient.setQueryData(retainedKey, { id: "forum_post" }) })
- act(() => { capturedQueryClient.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" }) })
- act(() => { capturedQueryClient.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" }) })
+ await act(() => { capturedQueryClient.setQueryData(baseKey, forumSidebarFixture()) })
+ await act(() => { capturedQueryClient.setQueryData(retainedKey, { id: "forum_post" }) })
+ await act(() => { capturedQueryClient.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" }) })
+ await act(() => { capturedQueryClient.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" }) })
const before = [
capturedQueryClient.getQueryData(baseKey),
capturedQueryClient.getQueryData(retainedKey),
@@ -872,7 +872,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
await mountHook()
- seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
+ await seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
const { useCommunityStore } = await import("@/stores/community")
await act(async () => { getCapturedRuntime().ui.actions.setCurrentServerId("s1") })
const scope = { kind: "channel" as const, id: "ch_parent", serverId: "s1" }
@@ -937,7 +937,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {
it.each(["forum", "text"] as const)("invalidates the %s parent feed while preserving ordinary thread openers", async parentType => {
await mountHook()
- seedKnownThread("srv_1", "forum_1", parentType, "post_1", "opener_1")
+ await seedKnownThread("srv_1", "forum_1", parentType, "post_1", "opener_1")
seedCanonicalServer({ id: "srv_1", categories: [{ id: "cat1", name: "Forum", channels: [{ id: "forum_1", name: "Forum", type: parentType, active: false, unread: false }] }] })
seedCanonicalMessages("forum_1", [{ id: "opener_1", content: "Post", thread: { id: "post_1", name: "Post", messageCount: 0 } }])
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
@@ -947,8 +947,8 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()
pages: [{ messages: [{ id: "opener_1", thread: { id: "post_1" } }], hasMore: false }],
pageParams: [null],
}
- act(() => { capturedQueryClient.setQueryData(allKey, page) })
- act(() => { capturedQueryClient.setQueryData(bugKey, page) })
+ await act(() => { capturedQueryClient.setQueryData(allKey, page) })
+ await act(() => { capturedQueryClient.setQueryData(bugKey, page) })
const event: CommunityChannelDelete = {
type: "community:channel.delete",
@@ -968,7 +968,7 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()
it("does not throw and still evicts own caches when the optional parentChannelId is absent", async () => {
await mountHook()
// Seed the deleted channel's own message cache so we can assert eviction.
- act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] }) })
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] }) })
const query = capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("post_1"), exact: true })!
const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")
@@ -988,7 +988,7 @@ describe("useCommunityWs — server.update icon removal", () => {
it("clears icon when changes.icon is null (does not fall back to the prior icon)", async () => {
await mountHook()
seedCanonicalServer({ id: "srv_1", name: "n", description: "d", icon: "https://cdn/x.png", ownerId: "u_1" })
- act(() => { capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
+ await act(() => { capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
name: "n",
description: "d",
@@ -1024,9 +1024,9 @@ describe("useCommunityWs — server.delete resets store when focused server dies
it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("srv_doomed") })
- act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1") })
- seedCanonicalFocusedChannel({
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("srv_doomed") })
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1") })
+ await seedCanonicalFocusedChannel({
name: "Private title",
parentChannelId: "private_parent",
})
@@ -1045,8 +1045,8 @@ describe("useCommunityWs — server.delete resets store when focused server dies
it("does NOT touch the store when a different server is deleted", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
- act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("srv_active") })
- act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1") })
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentServerId("srv_active") })
+ await act(() => { getCapturedRuntime().ui.actions.setCurrentChannelId("ch_1") })
const event: CommunityServerDelete = {
type: "community:server.delete",
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index 7e579b8db..abc3fa225 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -44,7 +44,7 @@ import {
} from "./invalidation-projections"
export function handleChildChannelCreate(event: CommunityChildChannelCreate, { queryClient, projection }: StructureTreeEventContext) {
- invalidateChannelRefTargets(projection)
+ invalidateChannelRefTargets(projection, { channelId: event.channel.id })
const parent = getCanonicalCommunityChannels(queryClient).find(row => row.id === event.parentChannelId && supportsSidebarThreads(row.type))
if (parent?.serverId) invalidateForumSidebar(projection, parent.serverId)
projection.fence("threads", { queryKey: communityKeys.threads(event.parentChannelId) })
@@ -57,7 +57,7 @@ export function handleChildChannelUpdate(
) {
invalidateThreads(projection, event.parentChannelId)
const changes = event.changes
- if (changes.name !== undefined || changes.archived !== undefined || changes.tags !== undefined) invalidateChannelRefTargets(projection)
+ if (changes.name !== undefined || changes.archived !== undefined || changes.tags !== undefined) invalidateChannelRefTargets(projection, { channelId: event.channelId })
if (changes.tags !== undefined) {
projection.fence("threads", {
queryKey: communityKeys.threads(event.parentChannelId),
@@ -122,7 +122,7 @@ export function handleServerUpdate(
event: CommunityServerUpdate,
{ projection }: StructureTreeEventContext,
) {
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId })
}
@@ -131,7 +131,7 @@ export function handleServerDelete(
{ queryClient, projection }: StructureTreeEventContext,
) {
evictServerChannelScopes(queryClient, event.serverId)
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId })
// Refresh the rail LIST only (drop the deleted server). `exact`
// so this doesn't cascade-refetch every other server's nested
// detail subtree.
@@ -148,7 +148,7 @@ export function handleChannelEvent(
event: ChannelEvent,
{ queryClient, projection }: StructureTreeEventContext,
) {
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId, channelId: event.type === "community:channel.create" ? event.channel.id : "channelId" in event ? event.channelId : undefined })
// #3: on channel.delete, evict every channel-scoped cache before
// invalidating the server. Without this the messages/pins/threads/
// child-thread caches for the dead channel linger forever — a
@@ -197,7 +197,7 @@ export function handleCategoryEvent(
event: CategoryEvent,
{ projection }: StructureTreeEventContext,
) {
- invalidateChannelRefDirectory(projection)
+ invalidateChannelRefDirectory(projection, { serverId: event.serverId })
invalidateServerDetail(projection, event.serverId)
}
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index f125e796d..2f76c1566 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -293,11 +293,11 @@ export function forumSidebarFixture(ids = ["post_1"]) {
}
}
-export function seedCanonicalForumSidebar(serverId: string, ids = ["post_1"]) {
+export async function seedCanonicalForumSidebar(serverId: string, ids = ["post_1"]) {
if (!canonicalRegistry) throw new Error("Community test owner missing")
const envelope = forumSidebarEnvelopeFixture(serverId, ids, canonicalRegistry.accountId!)
seedCanonicalServer({ ...envelope.resources.servers[0], channels: [envelope.resources.channels[0]] })
- act(() => publishCommunityForumSidebar(capturedQueryClient, {
+ await act(async () => await publishCommunityForumSidebar(capturedQueryClient, {
serverId, resources: envelope.resources,
channels: envelope.resources.channels.filter(channel => channel.type === "thread").map(channel => ({ ...channel, activityAt: envelope.serverNow, unread: false, participating: true })),
openers: envelope.resources.messages,
@@ -309,10 +309,10 @@ export function canonicalForumSidebar(serverId: string) {
return getForumSidebarBase(capturedQueryClient, serverId)
}
-export function seedCanonicalThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string) {
+export async function seedCanonicalThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string) {
if (!canonicalRegistry) throw new Error("Community test owner missing")
seedCanonicalServer({ id: serverId, ownerId: "u_me", categories: [{ id: `${serverId}-category`, name: "Category", channels: [{ id: parentId, name: "Parent", type: parentType }] }] })
- act(() => publishCommunityChannelMetadata(capturedQueryClient, {
+ await act(async () => await publishCommunityChannelMetadata(capturedQueryClient, {
metadata: channelResourceFixture({ id: childId, serverId, name: "Child", type: "thread", parentChannelId: parentId,
parentMessageId: `${childId}-opener`, creatorId: "u_me", lastMessageAt: "2026-08-01T00:00:00.000Z" }),
proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined },
@@ -333,13 +333,13 @@ export function hasCanonicalChannelNotify(channelId: string, userId: string) {
?? false
}
-export function seedCanonicalFocusedChannel(metadata: { name: string; parentChannelId?: string | null; parentMessageId?: string | null }) {
- act(() => {
+export async function seedCanonicalFocusedChannel(metadata: { name: string; parentChannelId?: string | null; parentMessageId?: string | null }) {
+ await act(async () => {
if (!canonicalRegistry) throw new Error("Community test owner missing")
const state = canonicalRegistry.runtime.ui.get()
const channelId = state.currentChannelId ?? state.subscription.channelId
if (!channelId) throw new Error("Focused test channel missing")
- publishCommunityChannelMetadata(capturedQueryClient, {
+ await publishCommunityChannelMetadata(capturedQueryClient, {
metadata: channelResourceFixture({ ...Object.fromEntries(Object.entries(canonicalRegistry.collections.channels.get(channelId) ?? {}).filter(([key]) => key in CommunityChannelResourceSchema.shape)), id: channelId, serverId: canonicalRegistry.collections.channels.get(channelId)?.serverId ?? state.currentServerId ?? "s1", type: metadata.parentChannelId ? "thread" : "text", ...metadata }),
proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined },
})
diff --git a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts b/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
index 9189c6dfa..e247ff24d 100644
--- a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
@@ -27,7 +27,7 @@ afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — typing follows membership", () => {
it.each(["text", "forum"] as const)("clears a departed %s child participant and timer, denies a repeated start, and permits rejoin", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("s1", "parent", parentType, "child")
+ await seedCanonicalThread("s1", "parent", parentType, "child")
act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "parent", "u_me", "access", true) })
getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })
await mountHook({ viewerUserId: "u_me" })
@@ -65,7 +65,7 @@ describe("useCommunityWs — typing follows membership", () => {
it.each(["text", "forum"] as const)("removes access to a %s parent from the typer and its known child without changing another scope", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
- seedCanonicalThread("s1", "parent", parentType, "child")
+ await seedCanonicalThread("s1", "parent", parentType, "child")
act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "parent", "u_me", "access", true) })
getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })
await mountHook({ viewerUserId: "u_me" })
diff --git a/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
index dff56b6da..d8b31b8c4 100644
--- a/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
@@ -85,7 +85,7 @@ it("rejects a pre-confirmation attention count and retries with the same origina
await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "u_me"))) })
expect(requests).toBe(1)
await act(async () => {
- publishCommunityConversationReadState(capturedQueryClient, { channelId: "c1", lastReadMessageId: "m2", lastReadAt: at, lastReadSeq: 2 }, 2, { token: captureCommunityLiveSnapshotToken(capturedQueryClient) }, "advance")
+ await publishCommunityConversationReadState(capturedQueryClient, { channelId: "c1", lastReadMessageId: "m2", lastReadAt: at, lastReadSeq: 2 }, 2, { token: captureCommunityLiveSnapshotToken(capturedQueryClient) }, "advance")
old.resolve(attention(4, "dm"))
await vi.advanceTimersByTimeAsync(0)
})
diff --git a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
index 0e8bf2392..d1aa105ce 100644
--- a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
+++ b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
@@ -82,9 +82,9 @@ function attentionData(ids: readonly string[]) {
included: { servers: [], channels: [], dms: [], messages: [], profiles: inboxRows.filter((row) => ids.includes(row.id)).map((row) => ({ userId: row.userId, name: row.name, discriminator: "0001", avatar: row.avatar, avatarVersion: row.avatarVersion ?? 0 })) },
}
}
-function publishRows(client: QueryClient, ids: readonly string[], token = captureCommunityLiveSnapshotToken(client)) {
- publishCommunityFriendships(client, pendingRows.filter((row) => ids.includes(row.id)).map((row) => ({ id: row.id, userId: row.userId, kind: row.kind })), { token })
- publishAccountAttentionSnapshot(client, { snapshot: attentionData(ids), proof: { token } })
+async function publishRows(client: QueryClient, ids: readonly string[], token = captureCommunityLiveSnapshotToken(client)) {
+ await publishCommunityFriendships(client, pendingRows.filter((row) => ids.includes(row.id)).map((row) => ({ id: row.id, userId: row.userId, kind: row.kind })), { token })
+ await publishAccountAttentionSnapshot(client, { snapshot: attentionData(ids), proof: { token } })
}
function handleFriendEvent(event: Parameters<typeof handleFriendEventLeaf>[0], context: SocialEventContext) {
projectCommunityWsEventToDb(context.queryClient, event)
@@ -237,7 +237,7 @@ async function createClient(ids: readonly string[] = ["a", "b"]) {
const registry = createCommunityDbRegistry(client, "viewer")
registerCommunityDbRegistry(registry)
await registry.preload()
- publishRows(client, ids)
+ await publishRows(client, ids)
client.setQueryData(communityKeys.friends(), { ids })
client.setQueryData(communityKeys.accountAttention(), { loaded: true })
return client
@@ -288,7 +288,7 @@ describe("friend-request action authority RED", () => {
const client = await createClient(["a"])
const { controls, rendered } = mount(client)
let request!: Promise<void>
- act(() => { request = controls.current!.act("inbox", "a") })
+ await act(() => { request = controls.current!.act("inbox", "a") })
await act(async () => { await Promise.all([fetchFriends(client), fetchAttention(client)]) })
await act(async () => {
gate.reject(new Error("ambiguous failure"))
@@ -389,7 +389,7 @@ describe("friend-request action authority RED", () => {
await act(async () => { await controls.current!.act("inbox", "a") })
paints.length = 0
- act(() => {
+ await act(() => {
runCommunityWsProjectionTransaction(client, (projection) => {
handleFriendEvent(
{ type: "community:friend.remove", friendshipId: "a" },
@@ -444,7 +444,7 @@ describe("friend-request action authority RED", () => {
invalidate: vi.fn(),
fence: vi.fn(),
} satisfies CommunityWsProjectionTransaction
- act(() => {
+ await act(async () => {
handleFriendEvent(
{ type: "community:friend.block", userId: "ua" },
{
@@ -456,7 +456,7 @@ describe("friend-request action authority RED", () => {
} satisfies SocialEventContext,
)
- publishRows(client, ["a"], beforeBlock)
+ await publishRows(client, ["a"], beforeBlock)
})
await act(async () => {
@@ -491,7 +491,7 @@ describe("friend-request action authority RED", () => {
expect(rendered.queryByTestId("friends-row-a")).toBeNull()
await act(async () => {
- publishRows(client, ["a"])
+ await publishRows(client, ["a"])
})
await waitFor(() => {
expect(rendered.getByTestId("inbox-row-a")).toBeInTheDocument()
@@ -543,7 +543,7 @@ describe("friend-request shared owner RED", () => {
const client = await createClient()
const { controls, rendered } = mount(client)
let request!: Promise<void>
- act(() => { request = controls.current!.act(origin, "a") })
+ await act(() => { request = controls.current!.act(origin, "a") })
try {
await waitFor(() => {
expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "pending")
@@ -574,13 +574,13 @@ describe("friend-request shared owner RED", () => {
const { controls, rendered } = mount(client)
await act(async () => { await controls.current!.act("inbox", "a") })
await waitFor(() => expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error"))
- act(() => {
+ await act(() => {
client.removeQueries({ queryKey: communityKeys.friends(), exact: true })
client.removeQueries({ queryKey: communityKeys.accountAttention(), exact: true })
})
let retry!: Promise<void>
- act(() => { retry = controls.current!.retry("inbox", "a") })
+ await act(() => { retry = controls.current!.retry("inbox", "a") })
try {
await waitFor(() => {
expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "pending")
@@ -609,7 +609,7 @@ describe("friend-request shared owner RED", () => {
const { controls } = mount(client)
let inboxRequest!: Promise<void>
let friendsRequest!: Promise<void>
- act(() => {
+ await act(() => {
inboxRequest = controls.current!.act("inbox", "a")
friendsRequest = controls.current!.act("friends", "a")
})
@@ -640,7 +640,7 @@ describe("friend-request shared owner RED", () => {
await waitFor(() => expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error"))
let first!: Promise<void>
let second!: Promise<void>
- act(() => {
+ await act(() => {
first = controls.current!.retry("inbox", "a")
second = controls.current!.retry("inbox", "a")
})
@@ -674,7 +674,7 @@ describe("friend-request shared owner RED", () => {
const { controls, rendered } = mount(client)
let actionA!: Promise<void>
let actionB!: Promise<void>
- act(() => {
+ await act(() => {
actionA = controls.current!.act("inbox", "a")
actionB = controls.current!.act("inbox", "b")
})
diff --git a/src/web/src/hooks/community/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.ts
index 329822e61..fd76d8576 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.test.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts
@@ -66,7 +66,7 @@ async function seedProjection(queryClient: QueryClient, data: {
return [{ id: parent.channelId, name: parent.channelId, type: parent.children?.length ? "forum" as const : "text" as const, active: false, unread: true, lastMessageAt: parent.lastMessageAt }, ...(parent.children ?? []).map((child) => ({ id: child.channelId, name: child.channelId, type: "thread" as const, active: false, unread: true, lastMessageAt: child.lastMessageAt, parentChannelId: parent.channelId, parentMessageId: child.openerMessageId }))]
})
ingestServerDetail(registry, serverDirectoryFixture({ id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "user-1", categories: [{ id: "category:" + serverId, name: "Category", channels: channels.filter(channel => !channel.parentChannelId) }] }))
- for (const channel of channels.filter(channel => channel.parentChannelId)) publishCommunityChannelMetadata(queryClient, { metadata: channelResourceFixture({ id: channel.id, serverId, name: channel.name, type: "thread", parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId, lastMessageAt: channel.lastMessageAt }), proof: { token: captureCommunityLiveSnapshotToken(queryClient) } })
+ for (const channel of channels.filter(channel => channel.parentChannelId)) await publishCommunityChannelMetadata(queryClient, { metadata: channelResourceFixture({ id: channel.id, serverId, name: channel.name, type: "thread", parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId, lastMessageAt: channel.lastMessageAt }), proof: { token: captureCommunityLiveSnapshotToken(queryClient) } })
for (const channel of channels) publishCommunityChannelFields(queryClient, channel.id, { lastMessageAt: channel.lastMessageAt }, { token: captureCommunityLiveSnapshotToken(queryClient) })
}
ingestAttentionSnapshot(registry, { resources: resourceBundleFixture({ viewerId: "user-1" }), scopes, items, limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } })
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 c8c790624..70d92915d 100644
--- a/src/web/src/hooks/community/message-surface-ownership.test.ts
+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts
@@ -121,11 +121,11 @@ describe("embedded message surface ownership", () => {
})
expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
- publishCommunityCreatedChannel(queryClient, channelResourceFixture({
+ await publishCommunityCreatedChannel(queryClient, channelResourceFixture({
id: "post-1", serverId: "s1", parentChannelId: "c1", parentMessageId: "m1", name: "transport", type: "thread", position: 0,
archived: false, creatorId: "author", messageCount: 1, createdAt: transport.createdAt,
}), { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
- publishCommunityEmbeddedMessages(queryClient, {
+ await publishCommunityEmbeddedMessages(queryClient, {
entries: [{ channelId: "c1", message: transport }],
profiles: messageProfilesFixture([transport]),
proof: {
diff --git a/src/web/src/hooks/community/mutations/bot-creation.ts b/src/web/src/hooks/community/mutations/bot-creation.ts
index 310b20c0a..e56634a2d 100644
--- a/src/web/src/hooks/community/mutations/bot-creation.ts
+++ b/src/web/src/hooks/community/mutations/bot-creation.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useQueryClient } from "@tanstack/react-query"
import { BotCreationPayloadSchema, type BotCreationPayload } from "@alook/shared"
@@ -28,7 +29,7 @@ export function useBotCreationDecision() {
const botCreation = BotCreationPayloadSchema.parse(data.botCreation)
if (botCreation.requestId !== requestId) throw new Error("The request changed. Reload this conversation before trying again.")
origin.assert(original)
- publishCommunityMessageFields(client, messageId, { botCreation }, { token: original })
+ await completeCommunityPublication(client, () => publishCommunityMessageFields(client, messageId, { botCreation }, { token: original }))
return { botCreation }
},
onSuccess: ({ botCreation }, { resources }) => {
diff --git a/src/web/src/hooks/community/mutations/channels.dom.test.ts b/src/web/src/hooks/community/mutations/channels.dom.test.ts
index 8fcbda79f..8e5d659e6 100644
--- a/src/web/src/hooks/community/mutations/channels.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.dom.test.ts
@@ -30,11 +30,11 @@ afterEach(async () => {
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
const server = { id: "s1", name: "Studio", discriminator: "0042", description: "", icon: null, ownerId: "viewer" }
const categories: ServerDetail["categories"] = [{ id: "cat_1", name: "General", private: false, channels: [{ id: "c1", name: "general", active: false, unread: false }, { id: "c2", name: "random", active: false, unread: true }] }, { id: "cat_2", name: "Ideas", private: false, channels: [] }]
-function publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) { publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) }
-function seed(cats = categories) {
- publish({ kind: "servers", data: serverRailResponseFixture({ servers: [server, { ...server, id: "s2", name: "Elsewhere" }] }, "viewer") })
- publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: cats.filter(category => category.id !== UNCATEGORIZED_CATEGORY_ID), channels: cats.filter(category => category.id === UNCATEGORIZED_CATEGORY_ID).flatMap(category => category.channels) }) })
- publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, id: "s2", categories: [{ id: "other-cat", name: "Other", channels: [{ id: "c3", name: "other", active: false, unread: false }] }] }) })
+async function publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) { await publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) }
+async function seed(cats = categories) {
+ await publish({ kind: "servers", data: serverRailResponseFixture({ servers: [server, { ...server, id: "s2", name: "Elsewhere" }] }, "viewer") })
+ await publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: cats.filter(category => category.id !== UNCATEGORIZED_CATEGORY_ID), channels: cats.filter(category => category.id === UNCATEGORIZED_CATEGORY_ID).flatMap(category => category.channels) }) })
+ await publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, id: "s2", categories: [{ id: "other-cat", name: "Other", channels: [{ id: "c3", name: "other", active: false, unread: false }] }] }) })
client.setQueryData(communityKeys.channelRefDirectory(), { serverIds: ["s1", "s2"] })
}
function mount<T>(hook: () => T) { return renderHook(() => { const command = hook(), tree = useServerTreeProjection("s1"), directory = useChannelRefDirectoryProjection(), sidebar = useChannelTree(tree?.categories ?? []); return { command, tree, directory, sidebar } }, { wrapper: Owner }) }
@@ -51,7 +51,7 @@ const treeChannels = (tree: ServerDetail | null | undefined) => tree?.categories
describe("canonical channel rename", () => {
it("cancels both exact queries before optimistically updating tree and directory consumers", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useRenameChannel)
+ await seed(); const held = deferred(), rendered = mount(commands.useRenameChannel)
const cancel = vi.spyOn(client, "cancelQueries"), pending = start(rendered.result.current.command, rename)
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.id === "c1")?.name).toBe("General Chat"))
expect(rendered.result.current.directory?.[0]?.channels.find((row) => row.id === "c1")?.name).toBe("General Chat")
@@ -60,7 +60,7 @@ describe("canonical channel rename", () => {
await act(async () => { held.resolve({ id: "c1", name: "General-Chat" }); await pending })
})
it("reconciles both consumers to the PATCH response normalized name", async () => {
- seed(); api.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })
+ await seed(); api.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })
const rendered = mount(commands.useRenameChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(rename) })
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.id === "c1")?.name).toBe("General-Chat"))
@@ -69,14 +69,14 @@ describe("canonical channel rename", () => {
expect(registry.collections.channels.get("c3")?.name).toBe("other")
})
it("restores both consumers on failure without optimistic residue", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useRenameChannel), pending = start(rendered.result.current.command, rename)
+ await seed(); const held = deferred(), rendered = mount(commands.useRenameChannel), pending = start(rendered.result.current.command, rename)
await waitFor(() => expect(registry.collections.channels.get("c1")?.name).toBe("General Chat"))
await act(async () => { held.reject(new Error("duplicate")); expect(await pending).toMatchObject({ message: "duplicate" }) })
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.id === "c1")?.name).toBe("general"))
expect(rendered.result.current.directory?.[0]?.channels.find((row) => row.id === "c1")?.name).toBe("general")
})
it.each(["success", "error"] as const)("invalidates only original exact tree and directory after %s", async (outcome) => {
- seed(); if (outcome === "success") api.mockResolvedValueOnce({ id: "c1", name: "renamed" }); else api.mockRejectedValueOnce(new Error("boom"))
+ await seed(); if (outcome === "success") api.mockResolvedValueOnce({ id: "c1", name: "renamed" }); else api.mockRejectedValueOnce(new Error("boom"))
client.setQueryData(communityKeys.server("s2"), "s2")
const rendered = mount(commands.useRenameChannel), invalidate = vi.spyOn(client, "invalidateQueries")
await act(async () => { await rendered.result.current.command.mutateAsync(rename).catch(() => {}) })
@@ -84,7 +84,7 @@ describe("canonical channel rename", () => {
expect(client.getQueryState(communityKeys.server("s2"))?.isInvalidated).toBe(false)
})
it("leaves present canonical facts and transports unchanged when the channel is missing", async () => {
- seed(); api.mockResolvedValueOnce({ id: "missing", name: "renamed" })
+ await seed(); api.mockResolvedValueOnce({ id: "missing", name: "renamed" })
const before = registry.collections.channels.get("c1"), directory = client.getQueryData(communityKeys.channelRefDirectory()), rendered = mount(commands.useRenameChannel)
await act(async () => { await rendered.result.current.command.mutateAsync({ ...rename, channelId: "missing" }) })
expect(registry.collections.channels.get("c1")).toBe(before)
@@ -95,7 +95,7 @@ describe("canonical channel rename", () => {
describe("canonical channel move and create", () => {
it.each(["cat_2", null])("saves categoryId %s and final positions in one request", async (categoryId) => {
- seed(); api.mockResolvedValueOnce(undefined)
+ await seed(); api.mockResolvedValueOnce(undefined)
const rendered = mount(commands.useReorderChannels)
const args = { serverId: "s1", channelIds: ["c2", "c1"], move: { channelId: "c1", categoryId } }
await act(async () => { await rendered.result.current.command.mutateAsync(args) })
@@ -106,7 +106,7 @@ describe("canonical channel move and create", () => {
for (const key of [communityKeys.server("s1"), communityKeys.channelRefDirectory()]) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
})
it("rolls back category and ordering in the actual sidebar projection on one failed save", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useReorderChannels)
+ await seed(); const held = deferred(), rendered = mount(commands.useReorderChannels)
const args = { serverId: "s1", channelIds: ["c2", "c1"], move: { channelId: "c1", categoryId: "cat_2" } }
const pending = start(rendered.result.current.command, args)
await waitFor(() => expect(rendered.result.current.sidebar.order.cat_2.map((row) => row.id)).toEqual(["c1"]))
@@ -119,14 +119,14 @@ describe("canonical channel move and create", () => {
expect(api).toHaveBeenCalledTimes(1)
})
it("inserts a pending channel into the matching category", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
+ await seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.pending)).toMatchObject({ name: "hi", type: "text" }))
const row = treeChannels(rendered.result.current.tree).find((row) => row.pending)!
expect(row.id).toMatch(/^tmp_ch_/)
await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); await pending })
})
it("physically cancels an in-flight server refetch before the optimistic write", async () => {
- seed()
+ await seed()
let signal!: AbortSignal
const read = client.query({ queryKey: communityKeys.server("s1"), staleTime: 0, queryFn: (context) => { signal = context.signal; return new Promise<string>(() => {}) } }).catch((error) => error)
const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
@@ -135,7 +135,7 @@ describe("canonical channel move and create", () => {
await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); await pending; await read })
})
it("leaves existing categories unchanged when the target category is absent", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId: "missing" })
+ await seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId: "missing" })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
expect(treeChannels(rendered.result.current.tree).map((row) => row.id)).toEqual(["c1", "c2"])
expect(registry.collections.categories.has("missing")).toBe(false)
@@ -143,14 +143,14 @@ describe("canonical channel move and create", () => {
expect(registry.collections.channels.size).toBe(3)
})
it("rolls back a pending channel on failure", async () => {
- seed(); api.mockRejectedValueOnce(new Error("boom"))
+ await seed(); api.mockRejectedValueOnce(new Error("boom"))
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(create).catch(() => {}) })
await waitFor(() => expect(treeChannels(rendered.result.current.tree).map((row) => row.id)).toEqual(["c1", "c2"]))
expect(Array.from(registry.collections.channels.values()).some((row) => row.pending)).toBe(false)
})
it("swaps the temp id to the real id and clears pending on success", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
+ await seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
await waitFor(() => expect(Array.from(registry.collections.channels.values()).some((row) => row.pending)).toBe(true))
const temp = Array.from(registry.collections.channels.values()).find((row) => row.pending)!.id
await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "normalized", position: 8 }) }); await pending })
@@ -158,27 +158,27 @@ describe("canonical channel move and create", () => {
expect(registry.collections.channels.get("ch_real")).toMatchObject({ name: "normalized", pending: false, position: 8 })
})
it.each(["success", "failure"] as const)("invalidates the original server tree on create %s", async (outcome) => {
- seed(); if (outcome === "success") api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); else api.mockRejectedValueOnce(new Error("boom"))
+ await seed(); if (outcome === "success") api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); else api.mockRejectedValueOnce(new Error("boom"))
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(create).catch(() => {}) })
expect(client.getQueryState(communityKeys.server("s1"))?.isInvalidated).toBe(true)
})
it("POSTs type, serverId, categoryId and original name to the unified create door", async () => {
- seed(); api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) })
+ await seed(); api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) })
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(create) })
expect(api).toHaveBeenCalledWith("/api/community/channels", expect.objectContaining({ method: "POST" }))
expect(JSON.parse(api.mock.calls[0][1].body)).toEqual(create)
})
it.each(["", UNCATEGORIZED_CATEGORY_ID, null])("creates one derived uncategorized bucket and sends null for categoryId %s", async (categoryId) => {
- seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId })
+ await seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId })
await waitFor(() => expect(rendered.result.current.tree?.categories.find((row) => row.id === UNCATEGORIZED_CATEGORY_ID)?.channels[0]).toMatchObject({ pending: true, name: "hi" }))
expect(JSON.parse(api.mock.calls[0][1].body)).toEqual({ ...create, categoryId: null })
await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: null, name: "hi" }) }); await pending })
expect(rendered.result.current.tree?.categories.filter((row) => row.id === UNCATEGORIZED_CATEGORY_ID)).toHaveLength(1)
})
it("reuses the canonical uncategorized projection without a duplicate category", async () => {
- seed([...categories, { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [{ id: "top", name: "Top", active: false, unread: false }] }])
+ await seed([...categories, { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [{ id: "top", name: "Top", active: false, unread: false }] }])
api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: null, name: "hi", position: 1 }) })
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync({ ...create, categoryId: "" }) })
@@ -190,7 +190,7 @@ describe("canonical channel move and create", () => {
describe("current create resource admission", () => {
it.each(["channel", "category"] as const)("rejects incomplete successful %s confirmation without publishing a confirmed row", async kind => {
- seed()
+ await seed()
api.mockResolvedValueOnce({ [kind]: { id: "partial-real" } })
const rendered = mount(kind === "channel" ? commands.useCreateChannel : commands.useCreateCategory)
let error: unknown
@@ -206,26 +206,26 @@ describe("current create resource admission", () => {
describe("canonical category commands and channel deletion", () => {
it("appends a pending category with a tmp_cat_ id", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useCreateCategory), pending = start(rendered.result.current.command, { serverId: "s1", name: " New Ideas " })
+ await seed(); const held = deferred(), rendered = mount(commands.useCreateCategory), pending = start(rendered.result.current.command, { serverId: "s1", name: " New Ideas " })
await waitFor(() => expect(rendered.result.current.tree?.categories.find((row) => row.pending)).toMatchObject({ name: "New Ideas" }))
expect(rendered.result.current.tree?.categories.find((row) => row.pending)?.id).toMatch(/^tmp_cat_/)
await act(async () => { held.resolve({ category: categoryResourceFixture({ id: "cat_real", serverId: "s1", name: "New Ideas" }) }); await pending })
})
it("swaps the temp category id to the real id and clears pending", async () => {
- seed(); api.mockResolvedValueOnce({ category: categoryResourceFixture({ id: "cat_real", serverId: "s1", name: "New Ideas" }) })
+ await seed(); api.mockResolvedValueOnce({ category: categoryResourceFixture({ id: "cat_real", serverId: "s1", name: "New Ideas" }) })
const rendered = mount(commands.useCreateCategory)
await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", name: "New Ideas" }) })
expect(registry.collections.categories.get("cat_real")).toMatchObject({ name: "New Ideas", pending: false })
expect(Array.from(registry.collections.categories.values()).some((row) => row.id.startsWith("tmp_cat_"))).toBe(false)
})
it("rolls back category creation on failure", async () => {
- seed(); api.mockRejectedValueOnce(new Error("boom"))
+ await seed(); api.mockRejectedValueOnce(new Error("boom"))
const rendered = mount(commands.useCreateCategory)
await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", name: "New Ideas" }).catch(() => {}) })
await waitFor(() => expect(rendered.result.current.tree?.categories.map((row) => row.id)).toEqual(["cat_1", "cat_2"]))
})
it("retires projected unread after a successful DELETE without waiting for self WS", async () => {
- seed()
+ await seed()
seedCommunityAttentionScope(client, { channelId: "c1", serverId: "s1", seq: 1 })
api.mockResolvedValueOnce(undefined)
const rendered = mount(commands.useDeleteChannel)
@@ -235,7 +235,7 @@ describe("canonical category commands and channel deletion", () => {
expect(registry.collections.channels.has("c1")).toBe(false)
})
it("keeps projected unread when DELETE fails", async () => {
- seed()
+ await seed()
seedCommunityAttentionScope(client, { channelId: "c1", serverId: "s1", seq: 1 })
api.mockRejectedValueOnce(new Error("500"))
const rendered = mount(commands.useDeleteChannel)
@@ -245,18 +245,18 @@ describe("canonical category commands and channel deletion", () => {
expect(registry.collections.channels.has("c1")).toBe(true)
})
it("removes a category optimistically", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useDeleteCategory), pending = start(rendered.result.current.command, { serverId: "s1", categoryId: "cat_2" })
+ await seed(); const held = deferred(), rendered = mount(commands.useDeleteCategory), pending = start(rendered.result.current.command, { serverId: "s1", categoryId: "cat_2" })
await waitFor(() => expect(rendered.result.current.tree?.categories.map((row) => row.id)).toEqual(["cat_1"]))
await act(async () => { held.resolve(undefined); await pending })
})
it("restores the category on a rejected non-empty delete", async () => {
- seed(); const held = deferred(), rendered = mount(commands.useDeleteCategory), pending = start(rendered.result.current.command, { serverId: "s1", categoryId: "cat_2" })
+ await seed(); const held = deferred(), rendered = mount(commands.useDeleteCategory), pending = start(rendered.result.current.command, { serverId: "s1", categoryId: "cat_2" })
await waitFor(() => expect(registry.collections.categories.has("cat_2")).toBe(false))
await act(async () => { held.reject(new Error("Move or delete its channels first")); await pending })
await waitFor(() => expect(rendered.result.current.tree?.categories.map((row) => row.id)).toEqual(["cat_1", "cat_2"]))
})
it("sends the category name update and publishes it without self WS", async () => {
- seed(); api.mockResolvedValueOnce(undefined)
+ await seed(); api.mockResolvedValueOnce(undefined)
const rendered = mount(commands.useUpdateCategory)
await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", categoryId: "cat_1", name: "Renamed" }) })
expect(api).toHaveBeenCalledWith("/api/community/servers/s1/categories/cat_1", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ name: "Renamed" }) }))
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index 3c95099e1..316a9cfe1 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useCommunityCommandMutation, type CommunityCommandArgs } from "../use-community-command-mutation"
import { beginCommunityCommandRevision } from "@/lib/community-db/sync"
@@ -109,7 +110,7 @@ export function useCreateChannel() {
origin.assert(proof.token)
const channel = CommunityChannelResourceSchema.parse(result.channel)
if (channel.serverId !== args.serverId || channel.type !== args.type || channel.categoryId !== categoryId) throw new Error("Created channel scope mismatch")
- publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, proof)
+ await completeCommunityPublication(queryClient, () => publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, proof))
return result
})
},
@@ -149,7 +150,7 @@ export function useRenameChannel() {
...communityRequestOptions(queryClient, token, undefined, () => origin.assert(original)),
})
origin.assert(original)
- publishCommunityChannelPatch(queryClient, args.channelId, (row) => ({ ...row, name: result.name }), { token, signal: undefined })
+ await completeCommunityPublication(queryClient, () => publishCommunityChannelPatch(queryClient, args.channelId, (row) => ({ ...row, name: result.name }), { token, signal: undefined }))
return result
} catch (error) {
origin.assert(original)
@@ -184,7 +185,7 @@ export function useDeleteChannel() {
}, async (proof, options) => {
await apiFetch(`/api/community/channels/${args.channelId}`, { method: "DELETE", ...options })
origin.assert(proof.token)
- retireCommunityChannelReading(origin.registry!, args.channelId, { reason: "resource-deleted", serverId: args.serverId })
+ await completeCommunityPublication(origin.registry!, () => retireCommunityChannelReading(origin.registry!, args.channelId, { reason: "resource-deleted", serverId: args.serverId }))
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
@@ -218,7 +219,7 @@ export function useCreateCategory() {
origin.assert(proof.token)
const category = CommunityCategoryResourceSchema.parse(result.category)
if (category.serverId !== args.serverId) throw new Error("Created category scope mismatch")
- publishCommunityCreatedCategory(queryClient, { ...category, pending: false }, proof)
+ await completeCommunityPublication(queryClient, () => publishCommunityCreatedCategory(queryClient, { ...category, pending: false }, proof))
return result
})
},
@@ -242,7 +243,7 @@ export function useUpdateCategory() {
}, async (proof, options) => {
const result = await apiFetch<{ name?: string }>(`/api/community/servers/${args.serverId}/categories/${args.categoryId}`, { method: "PATCH", body: JSON.stringify({ name: args.name }), ...options })
origin.assert(proof.token)
- if (args.name !== undefined) publishCommunityCategoryFields(queryClient, args.categoryId, { name: result?.name ?? args.name.trim() }, proof)
+ if (args.name !== undefined) await completeCommunityPublication(queryClient, () => publishCommunityCategoryFields(queryClient, args.categoryId, { name: result?.name ?? args.name!.trim() }, proof))
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
@@ -259,7 +260,7 @@ export function useDeleteCategory() {
}, async (proof, options) => {
await apiFetch(`/api/community/servers/${args.serverId}/categories/${args.categoryId}`, { method: "DELETE", ...options })
origin.assert(proof.token)
- publishCommunityDeletedCategory(queryClient, args.categoryId, proof)
+ await completeCommunityPublication(queryClient, () => publishCommunityDeletedCategory(queryClient, args.categoryId, proof))
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
@@ -276,7 +277,9 @@ export function useReorderCategories() {
}, async (proof, options) => {
await apiFetch(`/api/community/servers/${args.serverId}/categories/reorder`, { method: "PATCH", body: JSON.stringify({ categoryIds: args.categoryIds }), ...options })
origin.assert(proof.token)
- args.categoryIds.forEach((id, position) => publishCommunityCategoryFields(queryClient, id, { position }, proof))
+ await completeCommunityPublication(queryClient, () => {
+ args.categoryIds.forEach((id, position) => publishCommunityCategoryFields(queryClient, id, { position }, proof))
+ })
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
@@ -293,7 +296,9 @@ export function useReorderChannels() {
}, async (proof, options) => {
await apiFetch(`/api/community/servers/${args.serverId}/channels/reorder`, { method: "PATCH", body: JSON.stringify({ channelIds: args.channelIds, ...(args.move ? { move: args.move } : {}) }), ...options })
origin.assert(proof.token)
- args.channelIds.forEach((id, position) => publishCommunityChannelFields(queryClient, id, { position, ...(args.move?.channelId === id ? { categoryId: args.move.categoryId } : {}) }, proof))
+ await completeCommunityPublication(queryClient, () => {
+ args.channelIds.forEach((id, position) => publishCommunityChannelFields(queryClient, id, { position, ...(args.move?.channelId === id ? { categoryId: args.move.categoryId } : {}) }, proof))
+ })
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
})
diff --git a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
index 792d25080..703d3ac9e 100644
--- a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
@@ -65,15 +65,15 @@ async function setup(ids = ["before", "p2", "after"], observeCatalog = false) {
useLayoutEffect(() => { frames.push({ pending: tags.isPending, all: result.all.map(({ id }) => id), archived: result.archived.map(({ id }) => id) }) })
return result
}, { wrapper })
- function seed(rows: string[], append = false) {
+ async function seed(rows: string[], append = false) {
const page = wire(rows), token = captureCommunityLiveSnapshotToken(owner.client)
- publishCommunityForumSidebar(owner.client, { serverId: "server_1", resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server_1" })], [page.channel, ...page.threads], page.included.messages, page.included.profiles), channels: page.threads.map((row) => ({ ...row, name: row.name!, unread: false, parentChannelId: "forum_1", type: "thread", archived: false })), openers: page.included.messages.filter(message => message.channelId === "forum_1"), proof: { token, signal: undefined } })
- publishCommunityForumFeed(owner.client, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
+ await publishCommunityForumSidebar(owner.client, { serverId: "server_1", resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server_1" })], [page.channel, ...page.threads], page.included.messages, page.included.profiles), channels: page.threads.map((row) => ({ ...row, name: row.name!, unread: false, parentChannelId: "forum_1", type: "thread", archived: false })), openers: page.included.messages.filter(message => message.channelId === "forum_1"), proof: { token, signal: undefined } })
+ await publishCommunityForumFeed(owner.client, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
for (const filter of [null, "bug", "archived"]) owner.client.setQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", filter), (current) => ({ pages: append && current ? [{ ...current.pages[0], threads: [...current.pages[0].threads, ...forumFeedWindow(normalizeThreadResources("forum_1", page)).threads] }] : [forumFeedWindow(normalizeThreadResources("forum_1", page))], pageParams: [null] }))
}
- act(() => {
+ await act(async () => {
projectCommunityWsEventToDb(owner.client, { type: "community:channel.create", serverId: "server_1", channel: channelResourceFixture({ id: "forum_1", serverId: "server_1", name: "Forum", type: "forum", createdAt: new Date().toISOString() }) })
- seed(ids)
+ await seed(ids)
owner.client.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [{ messages: ids.map((id) => ({ id: `opener_${id}` })) }], pageParams: [null] })
owner.client.setQueryData([...communityKeys.channelMessages("forum_1"), "tag", "bug"], { pages: [], pageParams: [null] })
if (!observeCatalog) owner.client.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] })
@@ -87,7 +87,7 @@ type View = Awaited<ReturnType<typeof setup>>
async function begin(view: View, command: "tags" | "remove", input = command === "tags" ? tagInput : deleteInput) {
const held = deferred(); mocks.api.mockReturnValueOnce(held.promise)
let request!: Promise<unknown>
- act(() => { request = command === "tags" ? view.view.result.current.tags.mutateAsync(input as typeof tagInput).catch((error) => error) : view.view.result.current.remove.mutateAsync(input).catch((error) => error) })
+ await act(() => { request = command === "tags" ? view.view.result.current.tags.mutateAsync(input as typeof tagInput).catch((error) => error) : view.view.result.current.remove.mutateAsync(input).catch((error) => error) })
await waitFor(() => expect(mocks.api.mock.calls.some(([, options]) => options?.method === (command === "tags" ? "PUT" : "DELETE"))).toBe(true))
return { held, request }
}
@@ -120,7 +120,7 @@ describe("Native forum creation", () => {
const view = await setup(), held = deferred()
const { opener, replied } = mockForumCreation("create_1", "New post", "Body", held)
let request!: Promise<unknown>
- act(() => { request = view.view.result.current.create.mutateAsync({ nonce: "create_1", channelId: "forum_1", name: "New post", content: "Body" }) })
+ await act(() => { request = view.view.result.current.create.mutateAsync({ nonce: "create_1", channelId: "forum_1", name: "New post", content: "Body" }) })
await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(3))
expect(view.registry.collections.messages.get(opener.id)).toMatchObject({ channelId: "forum_1", content: "New post", clientNonce: "create_1:opener", seq: 40 })
expect(view.registry.collections.channels.get("p_new")).toMatchObject({ serverId: "server_1", parentChannelId: "forum_1", parentMessageId: opener.id, name: "New post", type: "thread" })
@@ -163,7 +163,7 @@ describe("Native forum tag transactions", () => {
let oldRead: Promise<void> | undefined
if (kind === "refetch") {
await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
- act(() => { oldRead = view.client.refetchQueries({ queryKey: communityKeys.forumTags("forum_1"), exact: true }) })
+ await act(() => { oldRead = view.client.refetchQueries({ queryKey: communityKeys.forumTags("forum_1"), exact: true }) })
await waitFor(() => expect(reads).toBe(2))
} else {
await waitFor(() => expect(reads).toBe(1))
@@ -182,7 +182,7 @@ describe("Native forum tag transactions", () => {
await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
const pending = await begin(view, "tags"), key = communityKeys.forumTags("forum_1"), held = deferred()
let replacementSignal: AbortSignal | undefined, replacementRead!: Promise<{ tags: string[] }>
- act(() => {
+ await act(() => {
view.client.removeQueries({ queryKey: key, exact: true })
replacementRead = view.client.query({ queryKey: key, queryFn: ({ signal }) => {
replacementSignal = signal
@@ -203,7 +203,7 @@ describe("Native forum tag transactions", () => {
const view = await setup(undefined, true)
await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
const pending = await begin(view, "tags")
- act(() => view.view.unmount())
+ await act(() => view.view.unmount())
await act(async () => { pending.held.resolve({ tags: ["bug", "archived"] }); await pending.request })
expect(mocks.api.mock.calls.filter(([path]) => path.endsWith("/messages/tags"))).toHaveLength(1)
expect(view.client.getQueryData(communityKeys.forumTags("forum_1"))).toEqual({ tags: ["bug"] })
@@ -231,7 +231,7 @@ describe("Native forum tag transactions", () => {
})
it("restores only the failed canonical slice while preserving updated and inserted siblings", async () => {
const view = await setup(), { held, request } = await begin(view, "tags")
- act(() => {
+ await act(() => {
publishCommunityForumTags(view.client, "before", ["updated"], { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined })
view.seed(["concurrent"], true)
})
@@ -242,10 +242,10 @@ describe("Native forum tag transactions", () => {
})
it("keeps a newer confirmed archive through older failure and a concurrent unarchive rollback", async () => {
const view = await setup(["p2"]), { held, request } = await begin(view, "tags"), newer = deferred()
- act(() => publishCommunityForumTags(view.client, "p2", ["bug", "archived"], { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined }))
+ await act(() => publishCommunityForumTags(view.client, "p2", ["bug", "archived"], { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined }))
mocks.api.mockReturnValueOnce(newer.promise)
let newerRequest!: Promise<unknown>
- act(() => { newerRequest = view.view.result.current.tags.mutateAsync({ ...tagInput, previousTags: ["bug", "archived"], tags: ["bug"] }).catch((error) => error) })
+ await act(() => { newerRequest = view.view.result.current.tags.mutateAsync({ ...tagInput, previousTags: ["bug", "archived"], tags: ["bug"] }).catch((error) => error) })
await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(2))
await act(async () => { held.reject(new Error("older failed")); await request })
await waitFor(() => { expect(mocks.api).toHaveBeenCalledTimes(2); expect(view.view.result.current.archived).toEqual([]); expect(view.view.result.current.all.map(({ id }) => id)).toEqual(["p2"]) })
@@ -261,7 +261,7 @@ describe("Native forum tag transactions", () => {
})
it("restores notify on unarchive and derives ranking from current canonical activity", async () => {
const view = await setup()
- act(() => { publishCommunityForumTags(view.client, "p2", ["bug", "archived"], { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined }); removeCanonicalCommunityChannelMembership(view.client, "p2", "notify") })
+ await act(() => { publishCommunityForumTags(view.client, "p2", ["bug", "archived"], { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined }); removeCanonicalCommunityChannelMembership(view.client, "p2", "notify") })
mocks.api.mockResolvedValueOnce({ tags: ["bug"] })
await act(async () => { await view.view.result.current.tags.mutateAsync({ ...tagInput, previousTags: ["bug", "archived"], tags: ["bug"] }) })
expect(getForumSidebarBase(view.client, "server_1").threads.map(({ id }) => id).sort()).toEqual(["after", "before", "p2"])
@@ -291,7 +291,7 @@ describe("Native forum post deletion", () => {
it("clears local stream, unread and active route once without requiring a self WS frame", async () => {
const view = await setup()
const disk = vi.spyOn(view.registry, "retireReadingDisk").mockResolvedValue(undefined)
- act(() => {
+ await act(() => {
seedCommunityAttentionScope(view.client, { channelId: "p2", serverId: "server_1", seq: 1 })
view.runtime.ui.actions.setCurrentServerId("server_1"); view.runtime.ui.actions.setCurrentChannelId("p2")
view.runtime.ui.actions.registerUiHandlers({ replacePath: view.navigate })
@@ -310,7 +310,7 @@ describe("Native forum post deletion", () => {
expect(view.navigate).toHaveBeenCalledWith("/c/channels/server_1/forum_1")
expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(false)
expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(false)
- act(() => applyForumPostUnitClientEffects(view.client, { serverId: "server_1", forumChannelId: "forum_1", childChannelId: "p2", openerMessageId: "opener_p2" }))
+ await act(() => applyForumPostUnitClientEffects(view.client, { serverId: "server_1", forumChannelId: "forum_1", childChannelId: "p2", openerMessageId: "opener_p2" }))
expect(mocks.clearLastChannel).toHaveBeenCalledOnce(); expect(view.navigate).toHaveBeenCalledOnce()
expect(disk).toHaveBeenCalledOnce()
expect(disk).toHaveBeenCalledWith(new Set(["p2"]), true)
@@ -343,17 +343,17 @@ describe("Native forum post deletion", () => {
describe("Native forum partition and transaction controls", () => {
const ids = (view: View, filter: "all" | "bug" | "archived" = "all") => view.view.result.current[filter].map(({ id }) => id)
- function window(view: View, filter: string | null, pages: string[][], pageParams: (string | null)[] = pages.map((_, index) => index ? `cursor_${index}` : null)) {
- act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", filter), { pages: pages.map((rows) => forumFeedWindow(normalizeThreadResources("forum_1", wire(rows)))), pageParams }))
+ async function window(view: View, filter: string | null, pages: string[][], pageParams: (string | null)[] = pages.map((_, index) => index ? `cursor_${index}` : null)) {
+ await act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", filter), { pages: pages.map((rows) => forumFeedWindow(normalizeThreadResources("forum_1", wire(rows)))), pageParams }))
}
- function wsTags(view: View, tags: string[], id = "p2") {
- act(() => projectCommunityWsEventToDb(view.client, { type: "community:channel.update", serverId: "server_1", channelId: id, changes: { tags } }))
+ async function wsTags(view: View, tags: string[], id = "p2") {
+ await act(() => projectCommunityWsEventToDb(view.client, { type: "community:channel.update", serverId: "server_1", channelId: id, changes: { tags } }))
}
async function second(view: View, input = { ...tagInput, tags: ["help"] }) {
const held = deferred(), count = mocks.api.mock.calls.length
mocks.api.mockReturnValueOnce(held.promise)
let request!: Promise<unknown>
- act(() => { request = view.view.result.current.tags.mutateAsync(input).catch((error) => error) })
+ await act(() => { request = view.view.result.current.tags.mutateAsync(input).catch((error) => error) })
await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(count + 1))
return { held, request }
}
@@ -364,12 +364,12 @@ describe("Native forum partition and transaction controls", () => {
})
it("removes Archive and Unarchive source rows without inserting a destination rank", async () => {
const view = await setup(["p2"])
- window(view, "archived", [[]])
+ await window(view, "archived", [[]])
const first = await begin(view, "tags")
await waitFor(() => expect(ids(view)).toEqual([]))
expect(ids(view, "archived")).toEqual([])
await act(async () => { first.held.resolve({ tags: ["bug", "archived"] }); await first.request })
- window(view, null, [[]]); window(view, "archived", [["p2"]])
+ await window(view, null, [[]]); await window(view, "archived", [["p2"]])
await waitFor(() => expect(ids(view, "archived")).toEqual(["p2"]))
const next = await second(view, { ...tagInput, previousTags: ["bug", "archived"], tags: ["bug"] })
await waitFor(() => expect(ids(view, "archived")).toEqual([]))
@@ -385,8 +385,8 @@ describe("Native forum partition and transaction controls", () => {
})
it("merges only the rolled-back canonical slice and preserves concurrent siblings", async () => {
const view = await setup(), pending = await begin(view, "tags")
- act(() => view.seed(["concurrent"], true))
- wsTags(view, ["help"], "before")
+ await act(() => view.seed(["concurrent"], true))
+ await wsTags(view, ["help"], "before")
await act(async () => { pending.held.reject(new Error("denied")); await pending.request })
await waitFor(() => expect(ids(view)).toEqual(["concurrent", "before", "p2", "after"]))
expect(view.registry.collections.channels.get("before")?.tags).toEqual(["help"])
@@ -408,7 +408,7 @@ describe("Native forum partition and transaction controls", () => {
})
it("retains an authoritative non-archive response in its moved cursor page", async () => {
const view = await setup(), pending = await begin(view, "tags")
- window(view, null, [["before"], ["p2", "after"]], [null, "moved_cursor"])
+ await window(view, null, [["before"], ["p2", "after"]], [null, "moved_cursor"])
await act(async () => { pending.held.resolve({ tags: ["bug"] }); await pending.request })
await waitFor(() => expect(ids(view)).toEqual(["before", "p2", "after"]))
expect(view.client.getQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", null))?.pageParams).toEqual([null, "moved_cursor"])
@@ -417,7 +417,7 @@ describe("Native forum partition and transaction controls", () => {
const view = await setup(["p2"]), other = { value: "outside partition" }
view.client.setQueryData(communityKeys.forumFeeds("forum_1"), other)
const pending = await begin(view, "tags")
- window(view, null, [[]], ["replacement_cursor"])
+ await window(view, null, [[]], ["replacement_cursor"])
await act(async () => { pending.held.reject(new Error("denied")); await pending.request })
await waitFor(() => expect(ids(view)).toEqual([]))
expect(view.client.getQueryData(communityKeys.forumFeeds("forum_1"))).toBe(other)
@@ -451,23 +451,23 @@ describe("Native forum partition and transaction controls", () => {
const view = await setup(["p2"])
const invalid = forumFeedWindow(normalizeThreadResources("forum_1", wire(["p2"])))
invalid.threads[0].openerMessageId = "retired_opener"
- act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", "bug"), { pages: [invalid], pageParams: [null] }))
+ await act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", "bug"), { pages: [invalid], pageParams: [null] }))
await waitFor(() => expect(ids(view, "bug")).toEqual([]))
- wsTags(view, ["archived"])
+ await wsTags(view, ["archived"])
await waitFor(() => expect(ids(view)).toEqual([]))
expect(ids(view, "archived")).toEqual(["p2"])
})
it("does not manufacture opener evidence for a malformed transport window", async () => {
const view = await setup(["p2"]), invalid = forumFeedWindow(normalizeThreadResources("forum_1", wire(["p2"])))
invalid.threads[0].openerMessageId = null
- act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [invalid], pageParams: ["invalid_cursor"] }))
+ await act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [invalid], pageParams: ["invalid_cursor"] }))
await waitFor(() => expect(ids(view)).toEqual([]))
- wsTags(view, ["archived"])
+ await wsTags(view, ["archived"])
expect(view.client.getQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", null))?.pages[0].threads[0].openerMessageId).toBeNull()
})
it("keeps a local optimistic intent dominant over an intervening WS frame", async () => {
const view = await setup(["p2"]), pending = await begin(view, "tags")
- wsTags(view, ["help"])
+ await wsTags(view, ["help"])
expect(ids(view)).toEqual([])
await act(async () => { pending.held.reject(new Error("denied")); await pending.request })
await waitFor(() => expect(view.registry.collections.channels.get("p2")?.tags).toEqual(["help"]))
@@ -475,9 +475,9 @@ describe("Native forum partition and transaction controls", () => {
})
it("removes a WS Unarchive from Archived without inventing an All rank", async () => {
const view = await setup(["p2"])
- wsTags(view, ["bug", "archived"]); window(view, null, [[]])
+ await wsTags(view, ["bug", "archived"]); await window(view, null, [[]])
await waitFor(() => expect(ids(view, "archived")).toEqual(["p2"]))
- wsTags(view, ["bug"])
+ await wsTags(view, ["bug"])
await waitFor(() => expect(ids(view, "archived")).toEqual([]))
expect(ids(view)).toEqual([])
})
diff --git a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
index b501acdf8..ab730efcb 100644
--- a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
@@ -26,12 +26,12 @@ function Root({ id = sdk.id, show = true }: { id?: string; show?: boolean }) { r
async function seed(qc: QueryClient) {
const registry = getCommunityDbRegistry(qc)!
await act(async () => { await registry.ready; await registry.preload() })
- act(() => {
+ await act(async () => {
projectCommunityWsEventToDb(qc, { type: "community:channel.create", serverId: "server", channel: { ...channelResourceFixture({ id: "forum", name: "Forum", type: "forum", serverId: "server" }), type: "forum" } })
const parent = channelResourceFixture({ id: "forum", type: "forum", serverId: "server" })
const child = channelResourceFixture({ id: "child", type: "thread", name: "Original", serverId: "server", parentChannelId: "forum", parentMessageId: "opener" })
const opener = messageResourceFixture({ id: "opener", channelId: "forum", content: "Original opener" })
- publishCommunityForumSidebar(qc, { serverId: "server", resources: fullResourceBundleFixture(registry.accountId!, [serverResourceFixture({ id: "server" })], [parent, child], [opener]),
+ await publishCommunityForumSidebar(qc, { serverId: "server", resources: fullResourceBundleFixture(registry.accountId!, [serverResourceFixture({ id: "server" })], [parent, child], [opener]),
channels: [{ ...child, activityAt: new Date().toISOString(), unread: false, participating: true }], openers: [opener], proof: { token: captureCommunityLiveSnapshotToken(qc), signal: undefined } })
const runtime = getCommunityRuntime(qc); runtime.ui.actions.setCurrentServerId("server"); runtime.ui.actions.setCurrentChannelId("child"); runtime.ui.actions.registerUiHandlers({ replacePath: navigate })
})
@@ -65,19 +65,19 @@ function wsDelete(qc: QueryClient) { const runtime = getCommunityRuntime(qc); di
beforeEach(async () => { await clearAllPersistedCaches(); api.mockReset(); sdk.id = "A"; navigate.mockClear(); client = undefined as unknown as QueryClient })
describe("actual native forum post-unit deletion", () => {
it("hides both canonical identities optimistically and restores them on ordinary failure", async () => {
- const { reject } = await mount(); let result!: Promise<unknown>; act(() => { result = command() }); await pending()
+ const { reject } = await mount(); let result!: Promise<unknown>; await act(() => { result = command() }); await pending()
expect(screen.getByTestId("child").textContent).toBe("missing"); expect(screen.getByTestId("opener").textContent).toBe("missing")
await act(async () => { reject(new Error("denied")); await result })
expect(screen.getByTestId("child").textContent).toBe("Original"); expect(screen.getByTestId("opener").textContent).toBe("Original opener"); expect(navigate).not.toHaveBeenCalled()
})
it("reveals newer committed child WS fields on failed deletion", async () => {
- const { reject, original } = await mount(); let result!: Promise<unknown>; act(() => { result = command() }); await pending()
- act(() => projectCommunityWsEventToDb(original, { type: "community:channel.child_update", parentChannelId: "forum", channelId: "child", changes: { name: "newer-ws" } }))
+ const { reject, original } = await mount(); let result!: Promise<unknown>; await act(() => { result = command() }); await pending()
+ await act(() => projectCommunityWsEventToDb(original, { type: "community:channel.child_update", parentChannelId: "forum", channelId: "child", changes: { name: "newer-ws" } }))
await act(async () => { reject(new Error("denied")); await result })
expect(screen.getByTestId("child").textContent).toBe("newer-ws"); expect(screen.getByTestId("opener").textContent).toBe("Original opener")
})
it("keeps newer authoritative WS post deletion absent when HTTP fails", async () => {
- const { reject, original } = await mount(); let result!: Promise<unknown>; act(() => { result = command() }); await pending(); act(() => wsDelete(original))
+ const { reject, original } = await mount(); let result!: Promise<unknown>; await act(() => { result = command() }); await pending(); await act(() => wsDelete(original))
await act(async () => { reject(new Error("denied")); await result })
expect(screen.getByTestId("child").textContent).toBe("missing"); expect(screen.getByTestId("opener").textContent).toBe("missing")
expect(navigate).toHaveBeenCalledTimes(1)
@@ -85,17 +85,17 @@ describe("actual native forum post-unit deletion", () => {
it("finishes an issued DELETE after self WS and view retirement without repeating navigation", async () => {
const { view, resolve, original } = await mount()
let result!: Promise<unknown>
- act(() => { result = command() })
+ await act(() => { result = command() })
await pending()
const mutation = original.getMutationCache().find({ mutationKey: ["community", "forum-post-delete"], exact: true })!
const options = api.mock.calls.find(([, value]) => value.method === "DELETE")![1] as { signal: AbortSignal; assertActive: () => void }
- act(() => wsDelete(original))
- act(() => view.rerender(<Root show={false} />))
+ await act(() => wsDelete(original))
+ await act(() => view.rerender(<Root show={false} />))
expect(options.signal.aborted).toBe(false)
expect(() => options.assertActive()).not.toThrow()
await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })
expect(mutation.state.status).toBe("success")
- act(() => view.rerender(<Root />))
+ await act(() => view.rerender(<Root />))
expect(screen.getByTestId("child").textContent).toBe("missing")
expect(screen.getByTestId("opener").textContent).toBe("missing")
expect(navigate).toHaveBeenCalledTimes(1)
@@ -104,13 +104,13 @@ describe("actual native forum post-unit deletion", () => {
it("physically cancels the original DELETE through A to B to A without deleting the new A's facts", async () => {
const { view, resolve, original } = await mount()
let result!: Promise<unknown>
- act(() => { result = command() })
+ await act(() => { result = command() })
await pending()
const signal = api.mock.calls.find(([, value]) => value.method === "DELETE")![1].signal as AbortSignal
- act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) })
+ await act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) })
await waitFor(() => expect(client).not.toBe(original))
const accountB = client
- act(() => { sdk.id = "A"; view.rerender(<Root id="A" />) })
+ await act(() => { sdk.id = "A"; view.rerender(<Root id="A" />) })
await waitFor(() => { expect(client).not.toBe(original); expect(client).not.toBe(accountB) })
await seed(client)
navigate.mockClear()
@@ -122,15 +122,15 @@ describe("actual native forum post-unit deletion", () => {
expect(navigate).not.toHaveBeenCalled()
})
it("commits both identities and ejects the active child once without self WS", async () => {
- const { resolve, original } = await mount(); let result!: Promise<unknown>; act(() => { result = command() }); await pending()
+ const { resolve, original } = await mount(); let result!: Promise<unknown>; await act(() => { result = command() }); await pending()
await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })
expect(screen.getByTestId("child").textContent).toBe("missing"); expect(screen.getByTestId("opener").textContent).toBe("missing")
expect(navigate).toHaveBeenCalledTimes(1); expect(getCommunityRuntime(original).ui.get().currentChannelId).toBe("forum")
- act(() => wsDelete(original)); expect(navigate).toHaveBeenCalledTimes(1)
+ await act(() => wsDelete(original)); expect(navigate).toHaveBeenCalledTimes(1)
})
it.each(["success", "failure"] as const)("rejects old account %s without restoring old caches or navigating B", async (outcome) => {
- const { view, resolve, reject, original } = await mount(); let result!: Promise<unknown>; act(() => { result = command() }); await pending()
- act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) }); await waitFor(() => expect(client).not.toBe(original)); await seed(client); navigate.mockClear()
+ const { view, resolve, reject, original } = await mount(); let result!: Promise<unknown>; await act(() => { result = command() }); await pending()
+ await act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) }); await waitFor(() => expect(client).not.toBe(original)); await seed(client); navigate.mockClear()
await act(async () => { if (outcome === "success") resolve(undefined); else reject(new Error("old error")); expect(await result).toMatchObject({ name: "AbortError" }) })
expect(original.getQueryCache().getAll()).toHaveLength(0); expect(screen.getByTestId("child").textContent).toBe("Original"); expect(screen.getByTestId("opener").textContent).toBe("Original opener"); expect(navigate).not.toHaveBeenCalled()
})
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 5d5ea097d..cb3dd1c92 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import type { CommunityMessagePosted } from "@alook/shared"
import type { CommunityChannelResource } from "@alook/shared"
@@ -70,11 +71,11 @@ export function useCreateForumThread() {
assert()
const parent = origin.registry!.collections.channels.get(channelId)
if (parent && structure.message) {
- publishCommunityMessages(queryClient, { channelId, profiles: structure.profiles, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
+ await publishCommunityMessages(queryClient, { channelId, profiles: structure.profiles, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
const child = await origin.request<CommunityChannelResource>(token, `/api/community/channels/${structure.threadId}`, { method: "GET", signal: assertActive?.signal, assertActive })
assert()
if (child.parentChannelId !== channelId || child.parentMessageId !== structure.message.id || child.serverId !== parent.serverId) throw new Error("Created forum child scope mismatch")
- publishCommunityCreatedChannel(queryClient, child, { token, signal: assertActive?.signal })
+ await completeCommunityPublication(queryClient, () => publishCommunityCreatedChannel(queryClient, child, { token, signal: assertActive?.signal }))
}
assert()
const reply = await origin.request<Pick<CommunityMessagePosted, "message" | "profiles">>(token, `/api/community/channels/${structure.threadId}/messages`, {
@@ -82,7 +83,7 @@ export function useCreateForumThread() {
body: JSON.stringify({ content, attachments: attachmentIds, nonce: `${nonce}:reply` }),
})
assert()
- if (reply.message) publishCommunityMessages(queryClient, { channelId: structure.threadId, profiles: reply.profiles, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
+ if (reply.message) await publishCommunityMessages(queryClient, { channelId: structure.threadId, profiles: reply.profiles, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
for (const query of resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)
return structure
},
@@ -141,7 +142,7 @@ export function useUpdatePostTags() {
result = { tags: [...new Set(result.tags.map((tag) => tag.trim().toLowerCase()).filter(Boolean))] }
const child = registry.collections.channels.get(args.threadId)
if (currentCommand(args) && child?.serverId === args.serverId && child.parentChannelId === args.forumChannelId && child.parentMessageId === args.openerMessageId
- && publishCommunityForumTags(queryClient, args.threadId, result.tags, { token, signal }) && previousArchived !== result.tags.includes(FORUM_ARCHIVE_TAG)) {
+ && await completeCommunityPublication(queryClient, () => publishCommunityForumTags(queryClient, args.threadId, result.tags, { token, signal })) && previousArchived !== result.tags.includes(FORUM_ARCHIVE_TAG)) {
await reconcileForumSidebarArchiveTag(queryClient, args.serverId, args.threadId, result.tags.includes(FORUM_ARCHIVE_TAG))
assert()
}
@@ -238,10 +239,10 @@ export function useDeleteForumThread() {
try { origin.assert(token) } catch { return }
let navigationAllowed = true
try { assert() } catch { navigationAllowed = false }
- applyForumPostUnitClientEffects(queryClient, unit, { proof: { token, signal: controller.signal }, queries: new Set(args.resources), assertView: () => {
+ await completeCommunityPublication(queryClient, () => applyForumPostUnitClientEffects(queryClient, unit, { proof: { token, signal: controller.signal }, queries: new Set(args.resources), assertView: () => {
if (!navigationAllowed) throw new DOMException("Retired post navigation", "AbortError")
args.view.assertOwner()
- } })
+ } }))
for (const query of args.resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query && [communityKeys.channelMessages(args.forumChannelId), communityKeys.threads(args.forumChannelId), communityKeys.forumTags(args.forumChannelId), communityKeys.server(args.serverId)].some((key) => startsWithQueryKey(query.queryKey, key))) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)
} catch (error) { assertOwner(); throw error }
finally { subscription.unsubscribe() }
diff --git a/src/web/src/hooks/community/mutations/friends.dom.test.ts b/src/web/src/hooks/community/mutations/friends.dom.test.ts
index 3f99771b4..6d7447196 100644
--- a/src/web/src/hooks/community/mutations/friends.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/friends.dom.test.ts
@@ -31,9 +31,9 @@ afterEach(async () => {
})
})
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
-function seed(rows: Row[] = [incoming("a"), incoming("b")], transport = true) {
- publishCommunityFriendships(client, rows, { token: captureCommunityLiveSnapshotToken(client) })
- publishAccountAttentionSnapshot(client, { snapshot: attention(), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+async function seed(rows: Row[] = [incoming("a"), incoming("b")], transport = true) {
+ await publishCommunityFriendships(client, rows, { token: captureCommunityLiveSnapshotToken(client) })
+ await publishAccountAttentionSnapshot(client, { snapshot: attention(), proof: { token: captureCommunityLiveSnapshotToken(client) } })
if (transport) client.setQueryData(communityKeys.friends(), { ids: rows.map((row) => row.id) })
}
function mount<T>(hook: () => T) { return renderHook(() => ({ command: hook(), rows: useFriendshipRows(), items: useAttentionItems() }), { wrapper: Owner }) }
@@ -49,7 +49,7 @@ function exactFriends(spy: ReturnType<typeof vi.spyOn>) { expect(spy).toHaveBeen
describe("native friendship commands", () => {
it("invalidates the original Friends resource after sending", async () => {
- seed(); const rendered = mount(commands.useSendFriendRequest), invalidate = vi.spyOn(client, "invalidateQueries")
+ await seed(); const rendered = mount(commands.useSendFriendRequest), invalidate = vi.spyOn(client, "invalidateQueries")
await act(async () => { await rendered.result.current.command.mutateAsync({ username: "alice" }) })
exactFriends(invalidate)
})
@@ -60,14 +60,14 @@ describe("native friendship commands", () => {
expect(JSON.parse(api.mock.calls[0]![1].body)).toEqual({ userId: "u_1", username: "alice#0042" })
})
it("commits attention removal and starts qualified reconciliation after ACK", async () => {
- seed(); const rendered = mount(commands.useAcceptFriendRequest)
+ await seed(); const rendered = mount(commands.useAcceptFriendRequest)
await act(async () => { await rendered.result.current.command.mutateAsync({ friendshipId: "a" }) })
await waitFor(() => expect(rendered.result.current.items.map((row) => row.sourceId)).toEqual(["b"]))
expect(registry.collections.friendships.get("a")?.kind).toBe("accepted")
expect(api).toHaveBeenCalledWith("/api/community/users/me/attention", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
})
it("does not compensate a late rejection after its actual native action is terminal", async () => {
- seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), success = vi.fn(), error = vi.fn()
+ await seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), success = vi.fn(), error = vi.fn()
let pending!: Promise<unknown>
act(() => { pending = rendered.result.current.command.mutateAsync({ friendshipId: "a" }, { onSuccess: success, onError: error }) })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
@@ -77,7 +77,7 @@ describe("native friendship commands", () => {
expect(registry.collections.attentionItems.has("friend_request:a")).toBe(false)
})
it("keeps an intervening canonical terminal event after an action fails", async () => {
- seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), pending = start(rendered.result.current.command, { friendshipId: "a" })
+ await seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), pending = start(rendered.result.current.command, { friendshipId: "a" })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
act(() => projectCommunityWsEventToDb(client, { type: "community:friend.reject", friendshipId: "a" }))
await act(async () => { held.reject(new Error("failed")); await pending })
@@ -86,7 +86,7 @@ describe("native friendship commands", () => {
expect(api.mock.calls.some(([path]) => path === "/api/community/users/me/attention")).toBe(true)
})
it.each(["accept", "reject"] as const)("preserves the pending canonical relationship and sibling through failed %s", async (action) => {
- seed(); const before = registry.collections.friendships.get("a"), held = hold(), rendered = mount(action === "accept" ? commands.useAcceptFriendRequest : commands.useRejectFriendRequest)
+ await seed(); const before = registry.collections.friendships.get("a"), held = hold(), rendered = mount(action === "accept" ? commands.useAcceptFriendRequest : commands.useRejectFriendRequest)
const cancel = vi.spyOn(client, "cancelQueries"), pending = start(rendered.result.current.command, { friendshipId: "a" })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
expect(ids("incoming")).toEqual(["a", "b"])
@@ -102,7 +102,7 @@ describe("native friendship commands", () => {
{ successfulId: "b", failedId: "a", order: "failed-first" },
{ successfulId: "b", failedId: "a", order: "success-first" },
])("never resurrects $successfulId when $failedId fails $order", async ({ successfulId, failedId, order }) => {
- seed(); const a = deferred(), b = deferred(), gates = { a, b }, rendered = mount(commands.useRejectFriendRequest)
+ await seed(); const a = deferred(), b = deferred(), gates = { a, b }, rendered = mount(commands.useRejectFriendRequest)
api.mockImplementation(async (path: string) => path === "/api/community/users/me/attention" ? attention() : gates[path.includes("/a/") ? "a" : "b"].promise)
const first = start(rendered.result.current.command, { friendshipId: "a" }), second = start(rendered.result.current.command, { friendshipId: "b" })
await waitFor(() => expect(api).toHaveBeenCalledTimes(2))
@@ -113,7 +113,7 @@ describe("native friendship commands", () => {
expect(registry.collections.attentionItems.has(`friend_request:${successfulId}`)).toBe(false)
})
it("preserves an unrelated canonical arrival when an optimistic removal rolls back", async () => {
- seed([{ ...incoming("a"), kind: "accepted" }]); const held = hold(), rendered = mount(commands.useRemoveFriend), pending = start(rendered.result.current.command, { friendshipId: "a" })
+ await seed([{ ...incoming("a"), kind: "accepted" }]); const held = hold(), rendered = mount(commands.useRemoveFriend), pending = start(rendered.result.current.command, { friendshipId: "a" })
await waitFor(() => expect(ids()).toEqual([]))
act(() => projectCommunityWsEventToDb(client, { type: "community:friend.request", friendship: { id: "c", requesterId: "u_c", addresseeId: "viewer", status: "pending", createdAt: "2026-09-27T00:00:00.000Z" } }))
await act(async () => { held.reject(new Error("failed")); await pending })
@@ -121,13 +121,13 @@ describe("native friendship commands", () => {
expect(client.getQueryData(communityKeys.inboxUnreads())).toBeUndefined()
})
it("never reconstructs an absent Friends transport after failure", async () => {
- seed([incoming("a")], false); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), pending = start(rendered.result.current.command, { friendshipId: "a" })
+ await seed([incoming("a")], false); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), pending = start(rendered.result.current.command, { friendshipId: "a" })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
await act(async () => { held.reject(new Error("failed")); await pending })
expect(client.getQueryData(communityKeys.friends())).toBeUndefined()
})
it("awaits settled invalidation of the active original Friends resource", async () => {
- seed(); const refresh = deferred(), observer = new QueryObserver(client, { queryKey: communityKeys.friends(), queryFn: () => refresh.promise, staleTime: Infinity })
+ await seed(); const refresh = deferred(), observer = new QueryObserver(client, { queryKey: communityKeys.friends(), queryFn: () => refresh.promise, staleTime: Infinity })
const unsubscribe = observer.subscribe(() => undefined), rendered = mount(commands.useAcceptFriendRequest)
let settled = false
const pending = start(rendered.result.current.command, { friendshipId: "a" }).then(() => { settled = true })
@@ -137,14 +137,14 @@ describe("native friendship commands", () => {
expect(settled).toBe(true); unsubscribe()
})
it.each(["success", "failure"] as const)("optimistically removes an outgoing request and settles %s", async (outcome) => {
- seed([{ ...incoming("a"), kind: "outgoing" }]); const held = hold(), rendered = mount(commands.useCancelBotFriendRequest), pending = start(rendered.result.current.command, { requestId: "a" })
+ await seed([{ ...incoming("a"), kind: "outgoing" }]); const held = hold(), rendered = mount(commands.useCancelBotFriendRequest), pending = start(rendered.result.current.command, { requestId: "a" })
await waitFor(() => expect(ids()).toEqual([]))
expect(api).toHaveBeenCalledWith("/api/community/friends/a", expect.objectContaining({ method: "DELETE", assertActive: expect.any(Function) }))
await act(async () => { if (outcome === "success") held.resolve(); else held.reject(new Error("failed")); await pending })
expect(ids()).toEqual(outcome === "success" ? [] : ["a"])
})
it("optimistically removes an accepted friend and restores only its own failure", async () => {
- seed([{ ...incoming("a"), kind: "accepted" }, { ...incoming("b"), kind: "accepted" }]); const held = hold(), rendered = mount(commands.useRemoveFriend), pending = start(rendered.result.current.command, { friendshipId: "a" })
+ await seed([{ ...incoming("a"), kind: "accepted" }, { ...incoming("b"), kind: "accepted" }]); const held = hold(), rendered = mount(commands.useRemoveFriend), pending = start(rendered.result.current.command, { friendshipId: "a" })
await waitFor(() => expect(ids()).toEqual(["b"]))
await act(async () => { held.reject(new Error("failed")); await pending })
expect(ids()).toEqual(["a", "b"])
@@ -155,7 +155,7 @@ describe("native friendship commands", () => {
expect(client.getQueryData(communityKeys.friends())).toBeUndefined(); exactFriends(invalidate)
})
it("publishes a canonical block and invalidates Friends", async () => {
- seed()
+ await seed()
ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" })] })
ingestMessages(registry, "dm_a", [messageResourceFixture({ id: "private", channelId: "dm_a", content: "private body" })])
const rendered = mount(commands.useBlockUser), invalidate = vi.spyOn(client, "invalidateQueries"), success = vi.fn()
@@ -168,7 +168,7 @@ describe("native friendship commands", () => {
expect(registry.collections.attentionItems.has("friend_request:a")).toBe(false); exactFriends(invalidate)
})
it("keeps visible DM reading intact when the normal block command fails", async () => {
- seed()
+ await seed()
ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" })] })
ingestMessages(registry, "dm_a", [messageResourceFixture({ id: "private", channelId: "dm_a", content: "private body" })])
const held = hold(), rendered = mount(commands.useBlockUser), pending = start(rendered.result.current.command, { userId: "u_a" })
@@ -179,7 +179,7 @@ describe("native friendship commands", () => {
expect(registry.collections.friendships.has("blocked:u_a")).toBe(false)
})
it("starts a new permission generation after a confirmed own unblock", async () => {
- seed([{ id: "blocked:u_a", userId: "u_a", kind: "blocked" }])
+ await seed([{ id: "blocked:u_a", userId: "u_a", kind: "blocked" }])
ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "" })] })
registry.runtime.ws.actions.revokeChannelAccess(null, "dm_a")
const generation = registry.runtime.ws.get().channelAccessScopes.get("dm_a")!.generation
@@ -191,13 +191,13 @@ describe("native friendship commands", () => {
expect(registry.collections.messages.size).toBe(0)
})
it("restores a blocked row when unblock fails", async () => {
- seed([{ ...incoming("a"), kind: "blocked" }]); const held = hold(), rendered = mount(commands.useUnblockUser), pending = start(rendered.result.current.command, { userId: "u_a" })
+ await seed([{ ...incoming("a"), kind: "blocked" }]); const held = hold(), rendered = mount(commands.useUnblockUser), pending = start(rendered.result.current.command, { userId: "u_a" })
await waitFor(() => expect(ids()).toEqual([]))
await act(async () => { held.reject(new Error("failed")); await pending })
expect(ids("blocked")).toEqual(["a"])
})
it.each(["success", "failure"] as const)("withholds old-owner %s and external callbacks after account retirement", async (outcome) => {
- seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), success = vi.fn(), error = vi.fn()
+ await seed(); const held = hold(), rendered = mount(commands.useAcceptFriendRequest), success = vi.fn(), error = vi.fn()
let pending!: Promise<unknown>
act(() => { pending = rendered.result.current.command.mutateAsync({ friendshipId: "a" }, { onSuccess: success, onError: error }).catch((cause: unknown) => cause) })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.ts
index 3ae997d16..72429a538 100644
--- a/src/web/src/hooks/community/mutations/friends.ts
+++ b/src/web/src/hooks/community/mutations/friends.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { resolveActionName } from "@/lib/observability/actions"
import { useQueryClient } from "@tanstack/react-query"
@@ -38,8 +39,8 @@ function useFriendCommand<Args extends object>(action: string, build: (args: Arg
const token = beginCommunityCommandRevision(queryClient, original)
const persist = async () => {
await origin.request(token, command.path, { method: command.method, ...(command.body ? { body: command.body } : {}) })
- if (command.friendshipId && command.decision) publishCommunityFriendDecision(queryClient, command.friendshipId, command.decision, { token })
- if (command.userId && command.blocked !== undefined) publishCommunityFriendBlock(queryClient, command.userId, command.blocked, { token })
+ if (command.friendshipId && command.decision) await completeCommunityPublication(queryClient, () => publishCommunityFriendDecision(queryClient, command.friendshipId!, command.decision!, { token }))
+ if (command.userId && command.blocked !== undefined) await completeCommunityPublication(queryClient, () => publishCommunityFriendBlock(queryClient, command.userId!, command.blocked!, { token }))
}
const transaction = registry!.dbClient.createTransaction({ autoCommit: false, mutationFn: persist })
transaction.mutate(() => {
@@ -67,7 +68,7 @@ function useFriendCommand<Args extends object>(action: string, build: (args: Arg
for (const mutation of queryClient.getMutationCache().findAll({ mutationKey: ["community", "friend-request"], predicate: (entry) => entry.state.variables === args })) queryClient.getMutationCache().remove(mutation)
}
const command = build(args)
- if (!error && command.userId && command.blocked !== undefined) applyCommunityDmBlockAccess(origin.registry!, command.userId, command.blocked)
+ if (!error && command.userId && command.blocked !== undefined) await completeCommunityPublication(origin.registry!, () => applyCommunityDmBlockAccess(origin.registry!, command.userId!, command.blocked!))
},
}, action === "block" ? (args) => origin.assertOwner(args.original) : undefined)
}
diff --git a/src/web/src/hooks/community/mutations/members.ts b/src/web/src/hooks/community/mutations/members.ts
index 29fe012a2..be7f74ba0 100644
--- a/src/web/src/hooks/community/mutations/members.ts
+++ b/src/web/src/hooks/community/mutations/members.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useMutation, useQueryClient, type Query, type MutateOptions } from "@tanstack/react-query"
import { useCallback } from "react"
@@ -38,11 +39,11 @@ function useMemberCommand<TInput extends KickMemberArgs>(kind: "role" | "kick")
await origin.request(original, "/api/community/servers/" + input.serverId + "/members/" + input.memberId, { method: kind === "role" ? "PATCH" : "DELETE", signal: input.assertActive?.signal, assertActive: input.assertActive, ...(kind === "role" ? { body: JSON.stringify({ role: (input as SetMemberRoleArgs).role }) } : {}) })
origin.assert(original)
if (kind === "role") {
- if (memberKey) publishCommunityMemberRole(queryClient, memberKey, input.memberId, (input as SetMemberRoleArgs).role, { token: proof, signal: input.assertActive?.signal })
+ if (memberKey) await completeCommunityPublication(queryClient, () => publishCommunityMemberRole(queryClient, memberKey, input.memberId, (input as SetMemberRoleArgs).role, { token: proof, signal: input.assertActive?.signal }))
} else {
const current = memberKey ? committed().find((row) => row.id === memberKey) : undefined
if (!memberKey || current?.memberId === input.memberId) {
- if (memberKey) publishCommunityMemberRemoval(queryClient, memberKey, input.memberId, { token: proof, signal: input.assertActive?.signal })
+ if (memberKey) await completeCommunityPublication(queryClient, () => publishCommunityMemberRemoval(queryClient, memberKey, input.memberId, { token: proof, signal: input.assertActive?.signal }))
patchMemberKickWindows(queryClient, resources, input.memberId)
}
}
diff --git a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
index 571a173bd..b3eb284f2 100644
--- a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
@@ -57,7 +57,7 @@ describe("canonical message identity and reaction publication", () => {
})
it("WS reactions update canonical facts without overwriting the exact-message ID transport", async () => {
const { original } = await mount(), runtime = getCommunityRuntime(original)
- act(() => dispatchCommunityWsEvent({ type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" },
+ await act(() => dispatchCommunityWsEvent({ type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" },
{ deliveryMode: "single", queryClient: original, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
expect(original.getQueryData(communityKeys.message("m1"))).toBe("m1")
expect(getCommunityDbRegistry(original)!.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
diff --git a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts b/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
index 3b71c6660..5286e230a 100644
--- a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
@@ -32,8 +32,8 @@ afterEach(async () => {
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
const args = { serverId: "s1", channelId: "ch_1", messageId: "m_1", emoji: "👍", userId: "u_me" }
const mine = [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }]
-function seed(reactions: Msg["reactions"] = [], channelId = "ch_1", id = "m_1") {
- publishCommunityMessages(client, { profiles: messageProfilesFixture([messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })]), channelId, messages: [messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+async function seed(reactions: Msg["reactions"] = [], channelId = "ch_1", id = "m_1") {
+ await publishCommunityMessages(client, { profiles: messageProfilesFixture([messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })]), channelId, messages: [messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
}
function rows(id = "m_1") { return registry.collections.messages.get(id)?.reactions }
function mounted() { return renderHook(() => ({ add: useAddReactionApi(), toggle: useToggleReactionApi(), messages: useCanonicalMessagesById() }), { wrapper: Owner }) }
@@ -46,7 +46,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(rendered.result.current.add).toBe(first)
})
it("treats add on me=true as a strict fact, mutation, and network no-op", async () => {
- seed(mine)
+ await seed(mine)
const rendered = mounted(), before = registry.collections.messages.get("m_1")
vi.useFakeTimers()
act(() => rendered.result.current.add(args))
@@ -56,7 +56,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(api).not.toHaveBeenCalled()
})
it("does not rewrite facts or postpone the first PUT when add is repeated", async () => {
- seed(); api.mockResolvedValue(undefined)
+ await seed(); api.mockResolvedValue(undefined)
const rendered = mounted()
vi.useFakeTimers()
act(() => rendered.result.current.add(args))
@@ -72,7 +72,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(api).toHaveBeenCalledWith(expect.stringContaining("/api/community/messages/m_1/reactions/"), expect.objectContaining({ method: "PUT", signal: expect.anything(), assertActive: expect.any(Function) }))
})
it("coalesces chip remove followed by picker add to the original state and zero requests", async () => {
- seed(mine)
+ await seed(mine)
const rendered = mounted()
vi.useFakeTimers()
act(() => { rendered.result.current.toggle(args); rendered.result.current.add(args) })
@@ -82,7 +82,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(client.getMutationCache().findAll({ status: "pending" })).toHaveLength(0)
})
it("drives additional consumers through canonical optimistic add and rollback", async () => {
- seed()
+ await seed()
const first = mounted(), second = mounted(), onError = vi.fn()
api.mockRejectedValueOnce(new Error("boom")); vi.useFakeTimers()
act(() => first.result.current.add({ ...args, onError }))
@@ -95,7 +95,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "boom" }))
})
it("optimistically patches and rolls back a thread opener shared by the single-message consumer", async () => {
- seed([{ emoji: "👍", count: 1, me: false, userIds: ["other"] }])
+ await seed([{ emoji: "👍", count: 1, me: false, userIds: ["other"] }])
client.setQueryData(communityKeys.message("m_1"), "m_1")
const rendered = mounted()
api.mockRejectedValueOnce(new Error("boom")); vi.useFakeTimers()
@@ -108,7 +108,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
})
it.each(["channel", "dm"] as const)("updates and rolls back a fallback-only %s row without creating a second row", async (kind) => {
const id = kind === "dm" ? "dm_1" : "ch_1"
- seed(mine, id)
+ await seed(mine, id)
const scope = kind === "dm" ? { kind, id } : { kind, id, serverId: "s1" }
registry.runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: { id: "m_1", seq: 1, type: "chat", content: "hello", reactions: mine } })
const key = kind === "dm" ? communityKeys.dmMessages(id) : communityKeys.channelMessages(id)
@@ -151,7 +151,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(client.getMutationCache().findAll({ status: "pending" })).toHaveLength(0)
})
it.each([3, 5])("%s rapid alternating clicks settle to exactly one API call at the end of the window", async (clicks) => {
- seed(); api.mockResolvedValue(undefined)
+ await seed(); api.mockResolvedValue(undefined)
const rendered = mounted()
vi.useFakeTimers()
act(() => { for (let index = 0; index < clicks; index++) rendered.result.current.toggle(args) })
@@ -163,7 +163,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(rows()).toEqual(mine)
})
it("flip-back (net-zero) cancels the intent — zero API calls fire", async () => {
- seed(); api.mockResolvedValue(undefined)
+ await seed(); api.mockResolvedValue(undefined)
const rendered = mounted()
vi.useFakeTimers()
act(() => { rendered.result.current.toggle(args); rendered.result.current.toggle(args) })
@@ -172,7 +172,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(rows()).toEqual([])
})
it("retiring the original account before the delay ends cancels the pending API call", async () => {
- seed(); api.mockResolvedValue(undefined)
+ await seed(); api.mockResolvedValue(undefined)
const rendered = mounted()
vi.useFakeTimers()
act(() => rendered.result.current.toggle(args))
@@ -184,7 +184,7 @@ describe("native reaction intents — original debounce and rollback guarantees"
expect(client.getMutationCache().findAll({ status: "pending" })).toHaveLength(0)
})
it.each(["success", "failure"] as const)("preserves a newer WS reaction on original command %s", async (outcome) => {
- seed()
+ await seed()
let resolve!: () => void, reject!: (error: Error) => void
api.mockReturnValueOnce(new Promise<void>((done, fail) => { resolve = done; reject = fail }))
const rendered = mounted()
diff --git a/src/web/src/hooks/community/mutations/message-reactions.ts b/src/web/src/hooks/community/mutations/message-reactions.ts
index 8df682118..26a5e0af1 100644
--- a/src/web/src/hooks/community/mutations/message-reactions.ts
+++ b/src/web/src/hooks/community/mutations/message-reactions.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import type { Transaction } from "@tanstack/react-db"
import { createStore } from "@tanstack/store"
@@ -36,7 +37,7 @@ function useReactionIntent(intent: "toggle" | "add") {
const proof = beginCommunityCommandRevision(queryClient, args.token)
await origin.request(args.token, `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`, { method: args.nextMe ? "PUT" : "DELETE", signal: args.assertActive?.signal, assertActive: args.assertActive })
assert(args)
- publishCommunityMessageReaction(queryClient, args.messageId, args.emoji, args.userId, args.nextMe, { token: proof, signal: args.assertActive?.signal })
+ await completeCommunityPublication(queryClient, () => publishCommunityMessageReaction(queryClient, args.messageId, args.emoji, args.userId, args.nextMe, { token: proof, signal: args.assertActive?.signal }))
}
const mutation = useMutation<void, Error, Intent>({ meta: { observabilityAction: intent === "add" ? "message.reaction.add" : "message.reaction.toggle" },
mutationKey: key, scope: { id: "community-reaction-commands" }, gcTime: 0,
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index fe146283f..9bbe4e927 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { CommunityChannelResourceSchema, type CommunityChannelResource, type CommunityMessagePosted } from "@alook/shared"
@@ -185,7 +186,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
await origin.registry!.collections.messages.preload()
origin.assert(token); (assertCommand ?? assertActive)?.()
const message = postedMessageForIntent(result.message, nonce ?? "", scope.id)
- publishCommunityMessages(queryClient, { channelId: scope.id, profiles: result.profiles,
+ await publishCommunityMessages(queryClient, { channelId: scope.id, profiles: result.profiles,
messages: [{ ...message, ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],
proof: { token, ...(scope.kind === "channel" && !assertCommand ? { signal: assertActive?.signal } : {}) } })
return result
@@ -212,7 +213,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
if (error instanceof ApiError && error.status === 429) toast.error("Rate limited — please wait a moment before trying again")
else toastApiError(error, "Failed to send message", () => { origin.assert(args.original); args.assertActive?.() })
},
- onSuccess: (data, args) => {
+ onSuccess: async (data, args) => {
try { origin.assert(args.original); args.assertCommand?.() } catch { return }
if ("serverId" in args) captureOnboardingFirstMessage(args.author.id, args.serverId)
if (
@@ -223,13 +224,13 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
getForumSidebarBase(queryClient, args.serverId),
args.channelId,
)
- patchForumSidebarActivityExact(
+ await completeCommunityPublication(queryClient, () => patchForumSidebarActivityExact(
queryClient,
args.serverId,
args.channelId,
- args.forumParentChannelId,
+ args.forumParentChannelId!,
data.message.createdAt,
- )
+ ))
if (!canonical) {
void invalidateForumSidebarBaseExact(queryClient, args.serverId)
}
@@ -291,7 +292,7 @@ export function useCreateThread() {
origin.assert(token); args.assertActive?.()
const channel = CommunityChannelResourceSchema.parse(data)
if (channel.type !== "thread" || channel.serverId !== args.serverId || channel.parentChannelId !== args.channelId || channel.parentMessageId !== args.messageId) throw new Error("Created thread scope mismatch")
- publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, { token, signal: args.assertActive?.signal })
+ await completeCommunityPublication(queryClient, () => publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, { token, signal: args.assertActive?.signal }))
if (args.resource && queryClient.getQueryCache().find({ queryKey: communityKeys.threads(args.channelId), exact: true }) === args.resource) void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.channelId), exact: true }, { cancelRefetch: false }).catch(() => undefined)
return data
},
diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.ts
index 05af143e3..75f5bab39 100644
--- a/src/web/src/hooks/community/mutations/notifications.ts
+++ b/src/web/src/hooks/community/mutations/notifications.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
@@ -44,7 +45,7 @@ function useNotificationCommand(kind: "server" | "channel") {
...(level === null ? {} : { body: JSON.stringify({ level }) }),
})
assert()
- publishCommunityNotificationSetting(client, target, level, { token, signal })
+ await completeCommunityPublication(client, () => publishCommunityNotificationSetting(client, target, level, { token, signal }))
}
const transaction = registry.dbClient.createTransaction({ autoCommit: false, mutationFn: persist })
transaction.mutate(() => {
diff --git a/src/web/src/hooks/community/mutations/profile.dom.test.ts b/src/web/src/hooks/community/mutations/profile.dom.test.ts
index b7f6d46a4..1a1201cea 100644
--- a/src/web/src/hooks/community/mutations/profile.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/profile.dom.test.ts
@@ -126,7 +126,7 @@ it("publishes only the confirmed command fields and keeps newer unrelated profil
let operation!: Promise<unknown>
act(() => { operation = hook.result.current.mutateAsync({ name: "Confirmed" }) })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => writeCommunityProfilePatches([{ id: "viewer", avatar: { avatar: "newer-avatar", avatarVersion: 6 }, status: { statusEmoji: "🌿", statusText: "Newer status" } }], owner.registry, { event: true }))
+ await act(() => writeCommunityProfilePatches([{ id: "viewer", avatar: { avatar: "newer-avatar", avatarVersion: 6 }, status: { statusEmoji: "🌿", statusText: "Newer status" } }], owner.registry, { event: true }))
await act(async () => { release({ ...initial, name: "Confirmed", aboutMe: "Unrequested response about", bannerColor: "#abcdef" }); await operation })
expect(owner.registry.collections.profiles.get("viewer")).toMatchObject({ ...initial, name: "Confirmed", avatar: "newer-avatar", avatarVersion: 6, statusEmoji: "🌿", statusText: "Newer status" })
expect(apiFetchMock).toHaveBeenCalledOnce()
diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.ts
index a68e9c127..8c4443869 100644
--- a/src/web/src/hooks/community/mutations/profile.ts
+++ b/src/web/src/hooks/community/mutations/profile.ts
@@ -36,7 +36,7 @@ export function useUpdateProfile() {
const snapshot = beginCommunityProfileSeed(origin.registry)
const profile = parseCommunitySelfProfileRead(await origin.request<unknown>(original, "/api/community/users/me/profile", { method: "PATCH", body: JSON.stringify(patch), signal: assertActive?.signal, assertActive }), original.viewerId!)
origin.assert(original); assertActive?.()
- writeCommunityProfilePatches([{
+ await writeCommunityProfilePatches([{
id: profile.id,
...(patch.name !== undefined || patch.aboutMe !== undefined ? { identityAbout: { ...(patch.name === undefined ? {} : { name: profile.name }), ...(patch.aboutMe === undefined ? {} : { aboutMe: profile.aboutMe }) } } : {}),
...(patch.statusEmoji !== undefined || patch.statusText !== undefined ? { status: { ...(patch.statusEmoji === undefined ? {} : { statusEmoji: profile.statusEmoji }), ...(patch.statusText === undefined ? {} : { statusText: profile.statusText }) } } : {}),
@@ -69,7 +69,7 @@ export function useUploadUserAvatar() {
formData.append("file", file)
const data = await origin.request<UploadUserAvatarResult>(original, "/api/community/users/me/avatar", { method: "POST", body: formData, signal: assertActive?.signal, assertActive })
origin.assert(original); assertActive?.()
- if (original.viewerId) writeCommunityProfilePatches([{ id: original.viewerId, avatar: { avatar: data.url, avatarVersion: data.avatarVersion } }], snapshot.registry, { snapshot, command: true })
+ if (original.viewerId) await writeCommunityProfilePatches([{ id: original.viewerId, avatar: { avatar: data.url, avatarVersion: data.avatarVersion } }], snapshot.registry, { snapshot, command: true })
return data
},
})
diff --git a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
index cc925ae15..c5ad216e7 100644
--- a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
@@ -53,12 +53,12 @@ async function setup() {
type View = Awaited<ReturnType<typeof setup>>
async function begin(view: View, operation: "leave" | "remove") {
let request!: Promise<unknown>
- act(() => { request = view.view.result.current[operation].mutateAsync({ serverId: "srv_1" }).catch((error) => error) })
+ await act(() => { request = view.view.result.current[operation].mutateAsync({ serverId: "srv_1" }).catch((error) => error) })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options?.method)).toBe(true))
return { request }
}
-function seedPrivateScope(view: View) {
- for (const channel of [{ id: "private_parent", name: "Private parent", type: "text" as const, parentChannelId: null, parentMessageId: null }, { id: "private_child", name: "Private title", type: "thread" as const, parentChannelId: "private_parent", parentMessageId: "private_opener" }]) publishCommunityCreatedChannel(view.client, channelResourceFixture({ ...channel, serverId: "srv_1" }), { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined })
+async function seedPrivateScope(view: View) {
+ for (const channel of [{ id: "private_parent", name: "Private parent", type: "text" as const, parentChannelId: null, parentMessageId: null }, { id: "private_child", name: "Private title", type: "thread" as const, parentChannelId: "private_parent", parentMessageId: "private_opener" }]) await publishCommunityCreatedChannel(view.client, channelResourceFixture({ ...channel, serverId: "srv_1" }), { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined })
view.runtime.ui.actions.setCurrentServerId("srv_1")
view.runtime.ui.actions.setCurrentChannelId("private_child")
view.runtime.messageStream.actions.dispatch({ kind: "channel", id: "private_child", serverId: "srv_1" }, { type: "wsMessage", message: messageResourceFixture({ id: "message_1", channelId: "private_child", authorId: "user_1", authorName: "User", content: "Private content" }) })
@@ -82,7 +82,7 @@ describe("Native server membership commands", () => {
await waitFor(() => expect(view.view.result.current.rail.servers.map(({ id }) => id)).toEqual(["srv_1", "srv_2"]))
})
it.each(["leave", "remove"] as const)("%s success clears the server subtree, stream and private route", async (operation) => {
- const view = await setup(); act(() => seedPrivateScope(view))
+ const view = await setup(); await act(async () => await seedPrivateScope(view))
expect(view.registry.collections.channels.get("private_child")?.name).toBe("Private title")
const { request } = await begin(view, operation)
view.view.rerender({ detailActive: false })
@@ -90,7 +90,7 @@ describe("Native server membership commands", () => {
if (operation === "remove") {
expect(view.runtime.ui.get().currentServerId).toBe("srv_1")
expect(observeOwnerServerDeleteRouteCommit(view.client, "/c/me")).toEqual(["srv_1"])
- act(() => expect(flushOwnerServerDeleteRouteCommit(view.client)).toEqual(["srv_1"]))
+ await act(() => expect(flushOwnerServerDeleteRouteCommit(view.client)).toEqual(["srv_1"]))
}
expect(view.runtime.ui.get()).toMatchObject({ currentServerId: null, currentChannelId: null })
expect(view.registry.collections.channels.has("private_child")).toBe(false)
@@ -127,7 +127,7 @@ describe("Native owner-delete navigation lifecycle", () => {
expect(claimOwnerServerDeleteNavigation(view.client, "srv_1", view.routeToken, "/c/me")).toBe(false)
view.view.rerender({ detailActive: false })
expect(observeOwnerServerDeleteRouteCommit(view.client, "/c/me")).toEqual(["srv_1"])
- act(() => expect(flushOwnerServerDeleteRouteCommit(view.client)).toEqual(["srv_1"]))
+ await act(() => expect(flushOwnerServerDeleteRouteCommit(view.client)).toEqual(["srv_1"]))
expect(isOwnerServerDeleteRouteProtected(view.client, "srv_1")).toBe(false)
expect(isOwnerServerDeleteRouteProtected(view.client, "srv_1", view.routeToken)).toBe(true)
})
@@ -147,14 +147,14 @@ describe("Native owner-delete navigation lifecycle", () => {
describe("Native server field commands", () => {
it("restores the canonical detail and rail on PATCH failure", async () => {
const view = await setup(); let request!: Promise<unknown>
- act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "d2" }).catch((error) => error) })
+ await act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "d2" }).catch((error) => error) })
await waitFor(() => { expect(view.view.result.current.detail.server?.name).toBe("new"); expect(view.view.result.current.rail.servers[0]?.name).toBe("new") })
await act(async () => { view.held.reject(new Error("boom")); await request })
await waitFor(() => { expect(view.view.result.current.detail.server?.name).toBe("old"); expect(view.view.result.current.rail.servers[0]).toMatchObject({ name: "old", description: "d" }) })
})
it("aligns optimistic detail and rail while preserving the unrelated server", async () => {
const view = await setup(), untouched = view.registry.collections.servers.get("srv_2"); let request!: Promise<unknown>
- act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "new description" }) })
+ await act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "new description" }) })
await waitFor(() => { expect(view.view.result.current.detail.server?.name).toBe("new"); expect(view.view.result.current.rail.servers[0]).toMatchObject({ name: "new", description: "new description", initial: "N" }) })
expect(view.registry.collections.servers.get("srv_2")).toBe(untouched)
await act(async () => { view.held.resolve(); await request })
@@ -163,21 +163,21 @@ describe("Native server field commands", () => {
})
it("invalidates the original channel-ref directory after settling", async () => {
const view = await setup(); let request!: Promise<unknown>
- act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "updated" }) })
+ await act(() => { request = view.view.result.current.update.mutateAsync({ serverId: "srv_1", name: "new", description: "updated" }) })
await waitFor(() => expect(api.mock.calls.some(([, options]) => options?.method === "PATCH")).toBe(true))
await act(async () => { view.held.resolve(); await request })
expect(view.client.getQueryState(communityKeys.channelRefDirectory())?.isInvalidated).toBe(true)
})
it("invalidates the actual server rail after create success", async () => {
const view = await setup(); let request!: Promise<unknown>
- act(() => { request = view.view.result.current.create.mutateAsync({ name: "n" }) })
+ await act(() => { request = view.view.result.current.create.mutateAsync({ name: "n" }) })
await waitFor(() => expect(api.mock.calls.some(([path, options]) => path === "/api/community/servers" && options?.method === "POST")).toBe(true))
await act(async () => { view.held.resolve({ server: { id: "srv_new" } }); await request })
await waitFor(() => expect(api.mock.calls.some(([path, options]) => path === "/api/community/servers" && !options?.method)).toBe(true))
})
it("publishes the same canonical versioned icon to detail and rail", async () => {
const view = await setup(), file = new File(["icon"], "icon.png", { type: "image/png" }); let request!: Promise<unknown>
- act(() => { request = view.view.result.current.icon.mutateAsync({ serverId: "srv_1", file }) })
+ await act(() => { request = view.view.result.current.icon.mutateAsync({ serverId: "srv_1", file }) })
await waitFor(() => expect(api.mock.calls.some(([path]) => path === "/api/community/servers/srv_1/icon")).toBe(true))
const url = "/api/community/servers/srv_1/icon?v=server-icon%2Fsrv_1%2Fobject-one"
await act(async () => { view.held.resolve({ url }); await request })
diff --git a/src/web/src/hooks/community/mutations/server-rail.ts b/src/web/src/hooks/community/mutations/server-rail.ts
index df02a2748..47270ce54 100644
--- a/src/web/src/hooks/community/mutations/server-rail.ts
+++ b/src/web/src/hooks/community/mutations/server-rail.ts
@@ -54,7 +54,7 @@ export function useServerRailCommit() {
for (const command of commands) if (command.kind === "create-folder" && !response.createdFolderIds[command.clientId]) throw new Error("Missing confirmed folder identity")
const confirmed = projectServerRailCommit(snapshot, { commands }, (id) => response!.createdFolderIds[id]!)
if (!confirmed.ok) throw new Error(confirmed.error)
- publishCommunityServerRailCommit(queryClient, confirmed.value, { token, signal: undefined })
+ await publishCommunityServerRailCommit(queryClient, confirmed.value, { token, signal: undefined })
} catch (error) { origin.assert(original); throw error }
} })
transaction.mutate(() => mutateCommunityServerRail(registry!, optimistic.value))
diff --git a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
index 16b74fe36..7706836b7 100644
--- a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
@@ -283,7 +283,7 @@ describe("actual canonical server and tree command owner", () => {
let result!: Promise<unknown>; act(() => { result = remove.mutateAsync({ serverId: "s1" }).catch((error) => error) })
await waitFor(() => expect(api.mock.calls.some(([, o]) => o.method === "DELETE")).toBe(true))
const runtime = getCommunityRuntime(original)
- act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: original, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
+ await act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: original, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
expect(getCommunityDbRegistry(original)!.collections.channels.has("c1")).toBe(true)
expect(screen.getByTestId("server-detail").textContent).toBe("original|before")
await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })
@@ -388,7 +388,7 @@ describe("actual canonical server and tree command owner", () => {
await waitFor(() => expect(screen.getByTestId("server-detail").textContent).toBe("original|before"))
const current = client, runtime = getCommunityRuntime(current)
if (delivery === "ws") {
- act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: current, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "B" }, matchesFocus: () => false }))
+ await act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: current, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "B" }, matchesFocus: () => false }))
} else {
const previous = api.getMockImplementation()!
api.mockImplementation((path: string, options: unknown) => path === "/api/community/servers" ? Promise.resolve({ servers: [] }) : previous(path, options))
diff --git a/src/web/src/hooks/community/mutations/servers.dom.test.tsx b/src/web/src/hooks/community/mutations/servers.dom.test.tsx
index 7349e3b44..35680d872 100644
--- a/src/web/src/hooks/community/mutations/servers.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/servers.dom.test.tsx
@@ -32,7 +32,7 @@ async function setup(serverId: string, callbacks: Omit<Callbacks, "routeToken">)
await act(async () => {
const registry = getCommunityDbRegistry(client)!
await registry.ready; await registry.preload()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ id: serverId, name: "Server", isOwner: true, ownerId: "viewer", role: "owner", memberId: `member-${serverId}` }] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ id: serverId, name: "Server", isOwner: true, ownerId: "viewer", role: "owner", memberId: `member-${serverId}` }] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
client.setQueryData(communityKeys.servers(), [serverId])
})
return { client, routeToken: originalToken, result: { get current() { return current } }, unmount: () => mounted.rerender(<Root visible={false} />), rerender: ({ activeCallbacks }: { activeCallbacks: Callbacks }) => mounted.rerender(<Root activeCallbacks={activeCallbacks} />) }
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index fcbbad47c..d2d490154 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { communityCommandInput, useCommunityCommandMutation, type CommunityCommandArgs } from "../use-community-command-mutation"
import { useCallback } from "react"
@@ -116,7 +117,7 @@ export function useLeaveServer() {
try {
await apiFetch(`/api/community/servers/${args.serverId}/leave`, { method: "POST", ...communityRequestOptions(queryClient, token, undefined, () => origin.assert(token)) })
origin.assert(token)
- publishCommunityServerMembershipRemoval(queryClient, args.serverId, { token, signal: undefined })
+ await completeCommunityPublication(queryClient, () => publishCommunityServerMembershipRemoval(queryClient, args.serverId, { token, signal: undefined }))
} catch (error) { origin.assert(token); throw error }
} })
transaction.mutate(() => mutateViewerMembership(registry, args.serverId))
@@ -154,7 +155,7 @@ export function useDeleteServer(callbacks: DeleteServerCallbacks) {
try {
await apiFetch(`/api/community/servers/${args.serverId}`, { method: "DELETE", ...communityRequestOptions(queryClient, token, undefined, () => origin.assert(token)) })
origin.assert(token)
- publishCommunityServerMembershipRemoval(queryClient, args.serverId, { token, signal: undefined })
+ await completeCommunityPublication(queryClient, () => publishCommunityServerMembershipRemoval(queryClient, args.serverId, { token, signal: undefined }))
} catch (error) { origin.assert(token); throw error }
} })
transaction.mutate(() => mutateViewerMembership(registry, args.serverId))
@@ -206,7 +207,7 @@ export function useUpdateServer() {
...communityRequestOptions(queryClient, token, undefined, () => origin.assert(original)),
})
origin.assert(original)
- publishCommunityServerFields(queryClient, args.serverId, { name: result.name, description: result.description }, { token, signal: undefined })
+ await completeCommunityPublication(queryClient, () => publishCommunityServerFields(queryClient, args.serverId, { name: result.name, description: result.description }, { token, signal: undefined }))
} catch (error) { origin.assert(original); throw error }
}
if (!registry!.collections.servers.has(args.serverId)) return persist()
@@ -246,7 +247,7 @@ export function useUploadServerIcon() {
...communityRequestOptions(queryClient, token, undefined, () => origin.assert(token)),
})
origin.assert(token)
- publishCommunityServerFields(queryClient, serverId, { icon: result.url }, { token, signal: undefined })
+ await completeCommunityPublication(queryClient, () => publishCommunityServerFields(queryClient, serverId, { icon: result.url }, { token, signal: undefined }))
return result
} catch (error) { origin.assert(token); throw error }
},
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 2ae92f95c..ff43e9109 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -1200,7 +1200,7 @@ describe("read coordinator", () => {
releaseReadSurface(lease)
await vi.advanceTimersByTimeAsync(1)
expect(db.collections.readStates.get("channel-1")?.lastReadSeq).toBe(committed ? 4 : undefined)
- expect(publishAccountAttentionSnapshot(queryClient, { snapshot: snapshot(4), proof: { token, signal: undefined } })).toBe("published")
+ expect(await 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()
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
index 2b176b621..dff47b749 100644
--- a/src/web/src/hooks/community/read-coordinator.ts
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -418,10 +418,10 @@ class ReadCoordinator {
return { committed: false, reconciled: false }
}
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }
- if (target.intent.seq === response.targetSeq && target.messageCreatedAt) publishCommunityConversationReadState(this.queryClient, {
+ if (target.intent.seq === response.targetSeq && target.messageCreatedAt) await publishCommunityConversationReadState(this.queryClient, {
channelId: target.intent.channelId,
lastReadMessageId: target.intent.messageId,
- lastReadAt: target.messageCreatedAt,
+ lastReadAt: target.messageCreatedAt!,
lastReadSeq: response.targetSeq,
}, response.revision, { token: target.proof, signal: target.request.signal ?? undefined }, "advance")
await settleInboxReadReservationGeneration(this.queryClient, target.generation, true, target.intent.channelId)
diff --git a/src/web/src/hooks/community/use-account-attention.ts b/src/web/src/hooks/community/use-account-attention.ts
index 84645cc9f..9ae154e04 100644
--- a/src/web/src/hooks/community/use-account-attention.ts
+++ b/src/web/src/hooks/community/use-account-attention.ts
@@ -71,7 +71,7 @@ const accountAttentionQueryFn = (queryClient: QueryClient) => {
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
if (!query || queryClient.getQueryCache().get(query.queryHash) !== query) throw new DOMException("Attention query retired", "AbortError")
if (currentReadRevision(token.registry) !== readRevision) throw new StaleAttentionReadError()
- publishAccountAttentionSnapshot(queryClient, { snapshot, proof: { token: requestToken, signal } })
+ await publishAccountAttentionSnapshot(queryClient, { snapshot, proof: { token: requestToken, signal } })
return { loaded: true, readRevision }
}
}
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 54245bfe0..290d46ddc 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -40,8 +40,8 @@ type BotCommandContext = {
resources: Query[]
assert: () => void
request: <T>(path: string, options?: ApiRequestOptions) => Promise<T>
- publishProfile: (patch: CommunityProfilePatch) => void
- removeProfile: (id: string) => void
+ publishProfile: (patch: CommunityProfilePatch) => Promise<void>
+ removeProfile: (id: string) => Promise<void>
}
const botSurfaceKeys = (id?: string) => [communityKeys.bots(), communityKeys.friends(), communityKeys.dms(), ...(id ? [communityKeys.profile(id)] : [])]
@@ -65,8 +65,8 @@ function useBotCommand<TInput extends BotViewInput, TResult>(kind: string, execu
const context: BotCommandContext = {
client, resources, assert,
request: (path, options) => origin.request(original, path, { ...options, signal: input.assertActive?.signal, assertActive: assert }),
- publishProfile: (patch) => { assert(); writeCommunityProfilePatches([patch], origin.registry, { snapshot, command: true }) },
- removeProfile: (id) => { assert(); if (origin.registry) retireCommunityProfile(id, origin.registry) },
+ publishProfile: async (patch) => { assert(); await writeCommunityProfilePatches([patch], origin.registry, { snapshot, command: true }) },
+ removeProfile: async (id) => { assert(); if (origin.registry) await retireCommunityProfile(id, origin.registry) },
}
try {
for (const resource of resources) if (client.getQueryCache().find({ queryKey: resource.queryKey, exact: true }) === resource) await client.cancelQueries({ queryKey: resource.queryKey, exact: true })
@@ -110,7 +110,7 @@ export function invalidateBotSurfaces(client: ReturnType<typeof useQueryClient>,
export function useCreateBot() {
return useBotCommand<CreateBotInput, { bot: BotSummary }>("create-command", async ({ assertActive: _assertActive, ...input }, context) => {
const data = await context.request<{ bot: BotSummary }>("/api/community/bots", { method: "POST", body: JSON.stringify(input) })
- context.publishProfile(botProfilePatch(data.bot))
+ await context.publishProfile(botProfilePatch(data.bot))
return data
}, allBotSurfaceKeys)
}
@@ -166,7 +166,7 @@ export type UpdateBotResponse = {
export function useUpdateBot() {
return useBotCommand<UpdateBotInput, UpdateBotResponse>("update-command", async ({ id, assertActive: _assertActive, ...input }, context) => {
const data = await context.request<UpdateBotResponse>("/api/community/bots/" + id, { method: "PATCH", body: JSON.stringify(input) })
- context.publishProfile(botProfilePatch(data.bot))
+ await context.publishProfile(botProfilePatch(data.bot))
const key = communityKeys.bots(), resource = context.resources.find((resource) => context.client.getQueryCache().find({ queryKey: key, exact: true }) === resource)
if (resource) context.client.setQueryData<BotsResourceResponse>(key, (current) => current ? { ...current, bots: current.bots.map((bot) => bot.id === id && bot.runtimeConfigRevision <= data.bot.runtimeConfigRevision ? { ...bot, runtime: data.bot.runtime, modelName: data.bot.modelName, reasoningEffort: data.bot.reasoningEffort, runtimeConfigRevision: data.bot.runtimeConfigRevision } : bot) } : current)
return data
@@ -188,7 +188,7 @@ function useBotIdFacade<TResult>(native: ReturnType<typeof useBotCommand<BotIdIn
return { ...native, mutate, mutateAsync }
}
export function useDeleteBot() {
- const native = useBotCommand<BotIdInput, void>("delete-command", async ({ id }, context) => { await context.request<void>("/api/community/bots/" + id, { method: "DELETE" }); context.removeProfile(id) }, botIdSurfaceKeys)
+ const native = useBotCommand<BotIdInput, void>("delete-command", async ({ id }, context) => { await context.request<void>("/api/community/bots/" + id, { method: "DELETE" }); await context.removeProfile(id) }, botIdSurfaceKeys)
return useBotIdFacade<void>(native)
}
@@ -211,7 +211,7 @@ export function useUploadBotAvatar() {
const body = new FormData()
body.append("file", file)
const data = await context.request<UploadBotAvatarResult>("/api/community/bots/" + botId + "/avatar", { method: "POST", body })
- context.publishProfile({ id: botId, avatar: { avatar: data.url, avatarVersion: data.avatarVersion } })
+ await context.publishProfile({ id: botId, avatar: { avatar: data.url, avatarVersion: data.avatarVersion } })
return data
}, botAvatarSurfaceKeys)
}
diff --git a/src/web/src/hooks/community/use-channel-members.dom.test.ts b/src/web/src/hooks/community/use-channel-members.dom.test.ts
index eb64a8bc4..6479039ed 100644
--- a/src/web/src/hooks/community/use-channel-members.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-members.dom.test.ts
@@ -27,7 +27,7 @@ describe("useChannelMembers", () => {
const { publishCommunityChannelMembersSnapshot, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
const owner = await createCommunityQueryOwner()
const peer = relationRow("private", "peer", "access", "explicit", "member", "m-peer")
- publishCommunityChannelMembersSnapshot(owner.client, "server", "private", "access", [peer], { token: captureCommunityLiveSnapshotToken(owner.client) }, [profile("peer", "Peer")])
+ await publishCommunityChannelMembersSnapshot(owner.client, "server", "private", "access", [peer], { token: captureCommunityLiveSnapshotToken(owner.client) }, [profile("peer", "Peer")])
apiFetchMock.mockRejectedValue(new Error("controlled first read failure"))
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(() => useChannelMembers("private", true, "server", "access"), { wrapper })
@@ -79,7 +79,7 @@ describe("useChannelMembers", () => {
const { useChannelMembers } = await import("./use-channel-members")
const { publishCommunityChannelMetadata, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
const owner = await createCommunityQueryOwner()
- publishCommunityChannelMetadata(owner.client, { metadata: { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z", id: "dm", serverId: null, name: null, type: "dm", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null }, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
+ await publishCommunityChannelMetadata(owner.client, { metadata: { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z", id: "dm", serverId: null, name: null, type: "dm", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null }, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
apiFetchMock.mockResolvedValue(roster("dm", "access", ["viewer", "peer"].map(userId => relationRow("dm", userId, "access", "explicit", null, null)), [profile("viewer", "viewer", "0001"), profile("peer", "peer", "0001")]))
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(() => useChannelMembers("dm", true, undefined, "access"), { wrapper })
diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.ts
index 6576d791a..8e8286ef0 100644
--- a/src/web/src/hooks/community/use-channel-members.ts
+++ b/src/web/src/hooks/community/use-channel-members.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
@@ -56,7 +57,7 @@ function channelMembersOptions(client: QueryClient, channelId: string, serverId?
const response = await apiFetch<CommunityMembersRead>("/api/community/channels/" + encodeURIComponent(channelId) + "/members?relation=" + dimension, communityRequestOptions(client, token, signal, assert))
assert()
const resources = response
- publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles)
+ await publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles)
assert()
return { serverId: scopeId, relation: dimension, creatorIds: resources.members.filter(member => member.isCreator).map(member => member.userId), members: resources.members.map(({ memberId, userId }) => ({ id: memberId ?? userId, userId })) }
},
@@ -156,7 +157,7 @@ export function useChannelMemberCommand(channelId: string, kind: "add" | "remove
const endpoint = options?.endpoint ?? "members"
await origin.request(original, "/api/community/channels/" + encodeURIComponent(channelId) + "/" + endpoint + (kind === "remove" ? "/" + encodeURIComponent(userId) : ""), { method: kind === "remove" ? "DELETE" : "POST", signal: assert.signal, assertActive: assert, ...(kind === "add" ? { body: JSON.stringify({ userId }) } : {}) })
assert()
- const confirmed = setCanonicalCommunityChannelMember(client, channelId, userId, relation, kind === "add", { proof: { token: proof } })
+ const confirmed = await completeCommunityPublication(client, () => setCanonicalCommunityChannelMember(client, channelId, userId, relation, kind === "add", { proof: { token: proof } }))
if (confirmed) { assert(); await options?.onConfirmed?.(userId, assert); assert() }
}
try {
diff --git a/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx b/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
index 438abb4b9..1b0aca5c5 100644
--- a/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
+++ b/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
@@ -32,7 +32,7 @@ describe("empty thread full identity across current child-create ordering", () =
entry.parent = parent.channel
entry.opener = parent.messages[0]
entry.profiles = parent.profiles
- if (timing !== "pending-absent") publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "viewer", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
+ if (timing !== "pending-absent") await publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "viewer", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
const event = () => projectCommunityWsEventToDb(owner.client, { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1", channel: timing === "full-pending" ? { ...entry.channel, name: "Event thread", topic: "Event topic", messageCount: 7 } : { ...entry.channel, name: "Event thread", creatorId: "viewer" } } as CommunityWsEvent, BUSINESS_SCHEMA_VERSION)
if (timing === "before") event()
const pending = deferred<typeof entry>()
@@ -79,7 +79,7 @@ describe("empty thread full identity across current child-create ordering", () =
entry.parent = parent.channel
entry.opener = parent.messages[0]
entry.profiles = parent.profiles
- if (known) publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "existing-creator", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
+ if (known) await publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "existing-creator", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
const wrapper = ({ children }: React.PropsWithChildren) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index 000ecb8a0..b08dcef79 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -56,7 +56,7 @@ export const threadsQueryFn = (channelId: string, queryClient: QueryClient) => a
await Promise.all([registry!.collections.channels.preload(), registry!.collections.messages.preload(), registry!.collections.channelMemberships.preload()])
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
const data = await loadThreadResources(queryClient, channelId, { token, signal })
- publishCommunityForumFeed(queryClient, channelId, data, { token, signal })
+ await publishCommunityForumFeed(queryClient, channelId, data, { token, signal })
return { threads: data.threads.map((thread) => ({ id: thread.id, ...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}) })), parentType: data.channel.type, serverId: data.channel.serverId ?? "", parentChannelId: channelId }
}
@@ -116,7 +116,7 @@ export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>
`/api/community/channels/${channelId}/pins`,
signal ? { signal } : undefined, publicationToken,
)
- publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.pins.map(row => ({ id: row.id, channelId })))
+ await publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.pins.map(row => ({ id: row.id, channelId })))
return { pins: data.pins.map((message) => ({ id: message.id })) }
}
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.ts
index d078d6243..e216b99bd 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts
@@ -48,7 +48,7 @@ export function useChannelRefDirectory(enabled = true): {
signal.addEventListener("abort", release, { once: true })
const token = captureCommunityLiveSnapshotToken(queryClient)
const { directory, resources } = await channelRefDirectoryQueryFn(communityRequestOptions(queryClient, token, signal))
- publishCommunityChannelDirectory(queryClient, {
+ await publishCommunityChannelDirectory(queryClient, {
directory, resources,
proof: { token, signal },
})
diff --git a/src/web/src/hooks/community/use-channel-ref-target.dom.test.tsx b/src/web/src/hooks/community/use-channel-ref-target.dom.test.tsx
new file mode 100644
index 000000000..c4ea78d90
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-ref-target.dom.test.tsx
@@ -0,0 +1,105 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { useChannelRefTarget } from "./use-channel-ref-target"
+import { runCommunityWsProjectionTransaction } from "./community-ws/projection-transaction"
+import { invalidateChannelRefTargets } from "./community-ws/invalidation-projections"
+
+const load = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))
+afterEach(() => load.mockReset())
+const target = { server: { id: "server", name: "Studio" }, channel: { id: "child", name: "Thread", parentChannelId: "parent" } }
+async function setup() {
+ const owner = await createCommunityQueryOwner()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ return { ...owner, wrapper }
+}
+
+it("shares a canonical target across message seqs without another request when it becomes known", async () => {
+ const owner = await setup()
+ load.mockResolvedValue({ target })
+ const view = renderHook(() => [useChannelRefTarget("/studio#0042/general#1"), useChannelRefTarget("/studio#0042/general#2")], { wrapper: owner.wrapper })
+ await waitFor(() => expect(view.result.current.map(row => row.state)).toEqual(["ready", "ready"]))
+ expect(view.result.current.map(row => row.messageSeq)).toEqual([1, 2])
+ expect(load).toHaveBeenCalledTimes(1)
+})
+
+it("keeps known targets qualified through unrelated channel and server changes", async () => {
+ const owner = await setup()
+ load.mockResolvedValue({ target })
+ const view = renderHook(() => useChannelRefTarget("/studio#0042/general#1"), { wrapper: owner.wrapper })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ await act(async () => {
+ for (let i = 0; i < 200; i++) owner.runtime.ws.actions.beginChannelMembershipChange("other", `unrelated-${i}`)
+ owner.runtime.ws.actions.revokeServerAccess("other")
+ runCommunityWsProjectionTransaction(owner.client, projection => invalidateChannelRefTargets(projection, { serverId: "other", channelId: "unrelated-0" }))
+ })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ expect(view.result.current.currentTarget()).toEqual(target)
+ expect(load).toHaveBeenCalledTimes(1)
+})
+
+it("blocks parent revocation immediately and requalifies after the existing owner restores access", async () => {
+ const owner = await setup()
+ load.mockResolvedValue({ target })
+ const view = renderHook(() => useChannelRefTarget("/studio#0042/general#1"), { wrapper: owner.wrapper })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ const previousClick = view.result.current.currentTarget
+ await act(async () => {
+ owner.runtime.ws.actions.revokeChannelAccess("server", "parent")
+ expect(previousClick()).toBeNull()
+ })
+ await waitFor(() => expect(view.result.current.state).toBe("forbidden"))
+ await act(async () => { owner.runtime.ws.actions.rememberChannelAccess("server", "child", "parent") })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ expect(load.mock.calls.length).toBeGreaterThan(1)
+})
+
+it("restarts an unknown target conservatively and rejects the older response", async () => {
+ const owner = await setup()
+ let release!: (data: { target: typeof target }) => void
+ const held = new Promise<{ target: typeof target }>(resolve => { release = resolve })
+ load.mockReturnValueOnce(held).mockResolvedValue({ target })
+ const view = renderHook(() => useChannelRefTarget("/studio#0042/general#1"), { wrapper: owner.wrapper })
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(1))
+ await act(async () => { owner.runtime.ws.actions.beginChannelMembershipChange("other", "unknown-dependency") })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ expect(load).toHaveBeenCalledTimes(2)
+ await act(async () => { release({ target: { ...target, channel: { ...target.channel, id: "late" } } }); await Promise.resolve() })
+ expect(view.result.current.target).toEqual(target)
+ expect(view.result.current.currentTarget()).toEqual(target)
+})
+
+
+it("contains cancellation failure, rejects the old target click and recovers through the original Query retry", async () => {
+ const owner = await setup()
+ load.mockResolvedValue({ target })
+ const view = renderHook(() => useChannelRefTarget("/studio#0042/general#1"), { wrapper: owner.wrapper })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ const previousClick = view.result.current.currentTarget
+ const failure = new Error("native reference cancellation failed")
+ const cancel = vi.spyOn(owner.client, "cancelQueries").mockRejectedValueOnce(failure)
+ const invalidate = vi.spyOn(owner.client, "invalidateQueries")
+ try {
+ await act(async () => { owner.runtime.ws.actions.beginChannelMembershipChange("server", "child") })
+ await waitFor(() => expect(cancel).toHaveBeenCalledOnce())
+ await expect(cancel.mock.results[0]!.value).rejects.toBe(failure)
+ expect(invalidate).not.toHaveBeenCalled()
+ expect(previousClick()).toBeNull()
+ expect(view.result.current.target).toBeNull()
+ expect(view.result.current.state).toBe("loading")
+ expect(load).toHaveBeenCalledOnce()
+ const queryKey = cancel.mock.calls[0]![0]!.queryKey!
+ expect(queryKey).toBeDefined()
+ const original = owner.client.getQueryCache().find({ queryKey, exact: true })
+ expect(original).toBeDefined()
+ await act(async () => { await view.result.current.retry() })
+ await waitFor(() => expect(view.result.current.state).toBe("ready"))
+ expect(view.result.current.currentTarget()).toEqual(target)
+ expect(owner.client.getQueryCache().find({ queryKey, exact: true })).toBe(original)
+ expect(load).toHaveBeenCalledTimes(2)
+ } finally { cancel.mockRestore(); invalidate.mockRestore() }
+})
diff --git a/src/web/src/hooks/community/use-channel-ref-target.ts b/src/web/src/hooks/community/use-channel-ref-target.ts
index 08dc45217..312f48543 100644
--- a/src/web/src/hooks/community/use-channel-ref-target.ts
+++ b/src/web/src/hooks/community/use-channel-ref-target.ts
@@ -1,48 +1,79 @@
"use client"
-import { useMemo } from "react"
+import { useEffect, useMemo, useRef } from "react"
import { useSelector } from "@tanstack/react-store"
-import { useQuery, useQueryClient } from "@tanstack/react-query"
+import { hashKey, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
-import { parseChannelRefDestination, type ChannelRefTarget } from "@/lib/community/channel-ref"
-import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
+import { channelRefAccessQualification, parseChannelRefDestination, type ChannelRefTarget, type ChannelRefAccessState } from "@/lib/community/channel-ref"
+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotOwnerCurrent } from "@/lib/community-db/sync"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityRuntime } from "@/stores/community/runtime"
export type ChannelRefTargetState = "loading" | "ready" | "missing" | "forbidden" | "error"
+type RefResource = { target: ChannelRefTarget; token: ReturnType<typeof captureCommunityLiveSnapshotToken>; access: string }
+
+function assertReferenceResource(client: QueryClient, state: ChannelRefAccessState, resource: RefResource) {
+ assertCommunityLiveSnapshotOwnerCurrent(client, resource.token, undefined)
+ if (resource.access !== channelRefAccessQualification(state, resource.target)) throw new DOMException("Stale reference access", "AbortError")
+}
export function useChannelRefTarget(ref: string) {
const client = useQueryClient()
const runtime = useCommunityRuntime()
const destination = useMemo(() => parseChannelRefDestination(ref), [ref])
const lifetime = useSelector(runtime.lifecycle, state => state.active ? state.generation : -1)
- const [accountEpoch, accessEpoch, scopes] = useSelector(runtime.ws, state => [state.profileAccountEpoch, state.accessEpoch, state.channelAccessScopes] as const,
- { compare: (left, right) => left.every((value, index) => value === right[index]) })
- const qualification = useMemo(() => ({ accountEpoch, accessEpoch, lifetime,
- scopes: [...scopes].filter(([, scope]) => scope.generation > 0 || scope.revoked)
- .sort(([left], [right]) => left.localeCompare(right)).map(([id, scope]) => [id, scope.generation, scope.revoked] as const),
- }), [accountEpoch, accessEpoch, lifetime, scopes])
- const queryKey = communityKeys.channelRefTarget(destination?.ref ?? "", qualification)
+ const accountEpoch = useSelector(runtime.ws, state => state.profileAccountEpoch)
+ const qualification = useMemo(() => ({ accountEpoch, accessEpoch: 0, lifetime, scopes: [] }), [accountEpoch, lifetime])
+ const queryKey = useMemo(() => communityKeys.channelRefTarget(destination?.ref ?? "", qualification), [destination?.ref, qualification])
const query = useQuery({
queryKey,
queryFn: async ({ signal }) => {
- const token = captureCommunityLiveSnapshotToken(client)
+ const token = captureCommunityLiveSnapshotToken(client), snapshot = runtime.ws.get()
+ const known = client.getQueryData<RefResource>(queryKey)?.target
+ const access = channelRefAccessQualification(snapshot, known)
+ const assert = () => {
+ assertCommunityLiveSnapshotOwnerCurrent(client, token, signal)
+ if (access !== channelRefAccessQualification(runtime.ws.get(), known)) throw new DOMException("Stale reference request", "AbortError")
+ }
const data = await apiFetchCommunity<{ target: ChannelRefTarget }>(
- `/api/community/channel-ref?${new URLSearchParams({ ref: destination!.ref })}`, { signal }, token,
+ `/api/community/channel-ref?${new URLSearchParams({ ref: destination!.ref })}`, { signal }, token, assert,
)
- return { target: data.target, token }
+ const resource = { target: data.target, token, access: channelRefAccessQualification(snapshot, data.target) }
+ assertReferenceResource(client, runtime.ws.get(), resource)
+ return resource
},
enabled: !!destination && lifetime >= 0,
staleTime: Infinity,
retry: false,
refetchOnWindowFocus: false,
})
+ const access = useSelector(runtime.ws, state => channelRefAccessQualification(state, query.data?.target))
+ const key = hashKey(queryKey)
+ const observed = useRef<{ key: string; access: string } | undefined>(undefined)
+ const enabled = !!destination && lifetime >= 0
+ useEffect(() => {
+ const previous = observed.current
+ observed.current = { key, access }
+ if (!previous || previous.key !== key || previous.access === access || !enabled) return
+ const current = client.getQueryCache().find({ queryKey, exact: true })
+ if (!current) return
+ const resource = current.state.data as RefResource | undefined
+ if (resource) {
+ try { assertReferenceResource(client, runtime.ws.get(), resource); return } catch {}
+ }
+ let active = true
+ const filters = { queryKey, exact: true, predicate: (candidate: typeof current) => candidate === current }
+ void client.cancelQueries(filters).then(() => {
+ if (active && runtime.lifecycle.get().active && client.getQueryCache().get(current.queryHash) === current) return client.invalidateQueries(filters)
+ }).catch(() => undefined)
+ return () => { active = false }
+ }, [key, access, enabled, client, queryKey, runtime.ws, runtime.lifecycle])
const currentTarget = () => {
const current = client.getQueryState(queryKey)
if (!query.data || query.isFetching || lifetime < 0 || current?.status !== "success" || current.fetchStatus !== "idle" || current.data !== query.data) return null
try {
- assertCommunityLiveSnapshotTokenCurrent(client, query.data.token, undefined)
+ assertReferenceResource(client, runtime.ws.get(), query.data)
const { target } = query.data
if (runtime.ws.actions.isChannelAccessRevoked(target.channel.id, target.server.id, target.channel.parentChannelId ?? undefined)) return null
return target
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
index b4526cd32..30b9e1bcd 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
@@ -548,7 +548,7 @@ it("mounts the qualified native child surface while its entry window is held and
value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = child.id
value.surfaceReceipt.surfaceKind = "thread"
value.parent = parent
- publishCommunityResourceBundle(queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server-1", ownerId: "viewer" })], [parent, child]), { token: captureCommunityLiveSnapshotToken(queryClient) })
+ await publishCommunityResourceBundle(queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server-1", ownerId: "viewer" })], [parent, child]), { token: captureCommunityLiveSnapshotToken(queryClient) })
mocks.dbParent = parent
mocks.useRealMetadata = true
let release!: (entry: typeof value) => void
@@ -626,7 +626,7 @@ it.each(["older", "newer", "jump"] as const)("rejects %s admission from a retain
expect(mocks.load).not.toHaveBeenCalled()
expect(feed.readSnapshot).toEqual(snapshot)
const { publishCommunityMessages, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
- await act(async () => { publishCommunityMessages(queryClient, { channelId: "post-1", messages: value.messages, profiles: value.profiles, proof: { token: captureCommunityLiveSnapshotToken(queryClient, "post-1") } }) })
+ await act(async () => { await publishCommunityMessages(queryClient, { channelId: "post-1", messages: value.messages, profiles: value.profiles, proof: { token: captureCommunityLiveSnapshotToken(queryClient, "post-1") } }) })
await waitFor(() => expect(feed.navigationBlocked).toBe(false))
act(() => { admitted = earlier() })
expect(admitted.accepted).toBe(true)
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
index 2f4ea42fb..3fbfaa45b 100644
--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
@@ -73,12 +73,12 @@ describe("community read-state lifecycle reconciliation", () => {
let outcome!: Promise<unknown>
act(() => { outcome = Promise.resolve(capturedUseUserWsOptions!.onAuthenticated!()).then(() => null, error => error) })
try {
- expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
+ await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1))
expect(getCapturedRuntime().ws.get().presenceByUserId.get("u_me")).toBe("online")
await vi.waitFor(() => expect(attentionCalls()).toHaveLength(1))
expect(capturedQueryClient.getQueryState(communityKeys.accountReadStateSnapshot())?.fetchStatus).toBe("fetching")
} finally {
- releaseSnapshot({ revision: 0, readStates: [] })
+ releaseSnapshot?.({ revision: 0, readStates: [] })
await act(async () => { await vi.advanceTimersByTimeAsync(0) })
expect(await outcome).toBeNull()
}
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 8b6fb2267..fc32a3d31 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -1,6 +1,8 @@
"use client"
import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { withCommunityCollectionWrites } from "@/lib/community-db/write"
import { bindCommunityTransport, useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime"
@@ -333,8 +335,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
void drainInvitedHumanJoined(runtime.lifecycle)
runtime.ws.actions.markAccessConnected()
const viewerId = viewerUserIdRef.current
- if (viewerId) {
- runtime.ws.actions.setPresence(viewerId, "online")
+ const registry = getCommunityDbRegistry(queryClient)
+ if (viewerId && registry) {
+ await withCommunityCollectionWrites(registry, () => runtime.ws.actions.setPresence(viewerId, "online"))
}
await reconcileAccountReadState(queryClient)
}, [queryClient, runtime.ws.actions, runtime.lifecycle, viewToken])
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index a3956a94e..241215a71 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -41,9 +41,9 @@ function deferred<T>() {
async function setup() {
const owner = await createCommunityQueryOwner()
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
- const publish = (value = fixture()) => {
+ const publish = async (value = fixture()) => {
const options = conversationEntryOptions(owner.client, target)
- const resource = publishConversationEntry(owner.client, target, value, { token: captureCommunityLiveSnapshotToken(owner.client, target.channelId) })
+ const resource = await publishConversationEntry(owner.client, target, value, { token: captureCommunityLiveSnapshotToken(owner.client, target.channelId) })
owner.client.setQueryData(options.queryKey, resource)
return resource
}
@@ -54,7 +54,7 @@ describe("conversation entry selection", () => {
it("keeps takeover on its original entry and retires that selection on a fresh navigation", async () => {
const { client, wrapper: Owner, publish, registry } = await setup()
const old = fixture()
- const original = publish(old)
+ const original = await publish(old)
const fresh = fixture()
fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" }]
fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: fresh.messages[0].createdAt }
@@ -92,7 +92,7 @@ describe("conversation entry selection", () => {
it("ignores actual reconnect helper cache keys when the original entry hook consumes a complete warm window", async () => {
const { client, wrapper, publish } = await setup()
const value = fixture()
- const resource = publish(value)
+ const resource = await publish(value)
const observer = new QueryObserver(client, { queryKey: resource.windowKey, queryFn: async () => client.getQueryData(resource.windowKey), staleTime: Infinity })
const stop = observer.subscribe(() => undefined)
const repairPage = { profiles: value.profiles, messages: value.messages, ...value.page }
@@ -119,9 +119,9 @@ describe("conversation entry selection", () => {
const { client, wrapper, registry, publish } = await setup()
const value = fixture()
value.selection = { reason: "tail", anchorMessageId: null }
- const current = publish(value)
+ const current = await publish(value)
const old = { ...value.messages[0], id: "old-message", authorId: "old-author", seq: 0 }
- publishCommunityMessages(client, { channelId: "c1", messages: [old], profiles: [profileResourceFixture({ id: "old-author", name: "Old Author" })], proof: { token: captureCommunityLiveSnapshotToken(client, "c1") } })
+ await publishCommunityMessages(client, { channelId: "c1", messages: [old], profiles: [profileResourceFixture({ id: "old-author", name: "Old Author" })], proof: { token: captureCommunityLiveSnapshotToken(client, "c1") } })
const oldKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: old.id })
const oldWindow = { pages: [{ ...value.page, messages: [{ id: old.id, seq: old.seq }] }], pageParams: [{ mode: "anchor", anchor: old.id }] }
client.setQueryData(oldKey, oldWindow)
@@ -143,7 +143,7 @@ describe("conversation entry selection", () => {
const { client, wrapper, registry, publish } = await setup()
const value = fixture()
value.selection = { reason: "tail", anchorMessageId: null }
- publish(value)
+ await publish(value)
const oldKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "missing-old-body" })
const oldWindow = { pages: [{ ...value.page, messages: [{ id: "missing-old-body", seq: 0 }] }], pageParams: [{ mode: "anchor", anchor: "missing-old-body" }] }
client.setQueryData(oldKey, oldWindow)
@@ -168,7 +168,7 @@ describe("conversation entry selection", () => {
const { client, wrapper, registry, publish } = await setup()
const value = defect === "forum-shape" ? forumConversationEntryFixture() : fixture()
const destination = { channelId: "c1", serverId: value.channel.serverId }
- const resource = defect === "forum-shape" ? publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") }) : publish(value)
+ const resource = defect === "forum-shape" ? await publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") }) : await publish(value)
client.setQueryData(conversationEntryOptions(client, destination).queryKey, resource)
if (defect === "messages-shape") client.setQueryData(resource.windowKey, { pages: [{ messages: 42 }], pageParams: [{ mode: "newest" }] })
if (defect === "forum-shape") client.setQueryData(communityKeys.forumFeed("c1", null), { pages: [{ threads: 42 }], pageParams: [null] })
@@ -191,7 +191,7 @@ describe("conversation entry selection", () => {
])("keeps current $kind permission separate from a missing owned entry window", async ({ kind, useSurface }) => {
const { client, wrapper } = await setup()
const value = kind === "dm" ? dmConversationEntryFixture() : fixture()
- publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId,
+ await publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId,
value.channel.serverId ? [serverResourceFixture({ id: value.channel.serverId, ownerId: value.viewerId })] : [],
[value.channel], [], value.peer ? [value.peer] : []), { token: captureCommunityLiveSnapshotToken(client) })
const held = deferred<typeof value>()
@@ -215,7 +215,7 @@ describe("conversation entry selection", () => {
it("offers the existing retry after a scope-only entry window fails, while retaining identity", async () => {
const { client, wrapper } = await setup()
const value = dmConversationEntryFixture()
- publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId, [], [value.channel], [], [value.peer!]),
+ await publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId, [], [value.channel], [], [value.peer!]),
{ token: captureCommunityLiveSnapshotToken(client) })
load.mockRejectedValue(new ConversationReadTimeoutError())
const hook = renderHook(() => ({ metadata: useChannelMetadata(null, "c1"), messages: useDmMessages("c1") }), { wrapper })
@@ -246,7 +246,7 @@ describe("conversation entry selection", () => {
value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }
}
const destination = { channelId: "c1", serverId: value.channel.serverId }
- const resource = publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
client.setQueryData(conversationEntryOptions(client, destination).queryKey, resource)
client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
const held = deferred<typeof value>()
@@ -277,7 +277,7 @@ describe("conversation entry selection", () => {
value.readState = { ...value.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
value.selection = { reason: "tail", anchorMessageId: null }
value.page = { ...value.page, olderCursor: null, hasMoreOlder: false, latestSeq: 0 }
- publish(value)
+ await publish(value)
client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
load.mockReturnValue(new Promise(() => {}))
const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
@@ -292,7 +292,7 @@ describe("conversation entry selection", () => {
it("keeps the current qualified cache while another server retires old entry proofs", async () => {
const { wrapper, publish, registry } = await setup()
- publish()
+ await publish()
const held = deferred<ReturnType<typeof fixture>>()
load.mockReturnValue(held.promise)
const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
@@ -312,7 +312,7 @@ describe("conversation entry selection", () => {
const value = fixture()
value.messages.push({ ...value.messages[0], id: "m2", seq: 2, content: "Second" })
value.page.latestSeq = 2
- publish(value)
+ await publish(value)
let active = true
const navigation = { entryIntent: { href: "/c/channels/s1/c1" } as { href: string; resume?: boolean } }
function Wrapper({ children }: PropsWithChildren) {
@@ -345,7 +345,7 @@ describe("conversation entry selection", () => {
const { wrapper: Owner, registry, client } = await setup()
const dmTarget = { channelId: "c1", serverId: null }
const old = dmConversationEntryFixture()
- const oldResource = publishConversationEntry(client, dmTarget, old, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const oldResource = await publishConversationEntry(client, dmTarget, old, { token: captureCommunityLiveSnapshotToken(client, "c1") })
client.setQueryData(conversationEntryOptions(client, dmTarget).queryKey, oldResource)
ingestReadStateSnapshot(registry, { revision: 6, readStates: [{ channelId: "c1", lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: "later" }] })
const next = dmConversationEntryFixture()
@@ -388,7 +388,7 @@ describe("conversation entry selection", () => {
const value = fixture()
value.messages.push({ ...value.messages[0], id: "m2", seq: 2, content: "Second" })
value.page.latestSeq = 2
- publish(value)
+ await publish(value)
ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ channelId: "c1", lastReadMessageId: "m2", lastReadAt: "at", lastReadSeq: 2 }] })
const hook = renderHook(() => useConversationEntry(target), { wrapper })
expect(hook.result.current.window).not.toBeNull()
@@ -403,7 +403,7 @@ describe("conversation entry selection", () => {
it("keeps its selected window and NEW during a background timeout", async () => {
const { wrapper, publish } = await setup()
- publish()
+ await publish()
const hook = renderHook(() => useConversationEntry(target), { wrapper })
const window = hook.result.current.window
const transport = deferred<ReturnType<typeof fixture>>()
@@ -434,7 +434,7 @@ describe("conversation entry selection", () => {
it("loads one new entry when a newer current pointer is outside all cached windows", async () => {
const { wrapper, publish, registry } = await setup()
- publish()
+ await publish()
ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ channelId: "c1", lastReadMessageId: "m2", lastReadAt: "second", lastReadSeq: 2 }] })
const transport = deferred<ReturnType<typeof fixture>>()
load.mockReturnValue(transport.promise)
@@ -459,7 +459,7 @@ describe("conversation entry selection", () => {
const packet = fixture()
packet.messages.push({ ...packet.messages[0], id: "m2", seq: 2 })
packet.page.latestSeq = 2
- publish(packet)
+ await publish(packet)
const navigation: { entryIntent: { href: string } | null } = { entryIntent: null }
const wrapper = ({ children }: PropsWithChildren) => createElement(Owner, null, createElement(CommunityRouteContext, { value: { navigation } as never }, children))
const hook = renderHook(() => useConversationEntry(target), { wrapper })
@@ -475,7 +475,7 @@ describe("conversation entry selection", () => {
it("withdraws a selected window immediately on target revocation", async () => {
const { wrapper, publish, registry } = await setup()
- publish()
+ await publish()
const hook = renderHook(() => useConversationEntry(target), { wrapper })
expect(hook.result.current.canRead).toBe(true)
await act(async () => { registry.runtime.ws.actions.revokeChannelAccess("s1", "c1") })
@@ -507,7 +507,7 @@ describe("conversation entry selection", () => {
it("retires the old entry proof and refetches while qualifying the current canonical scope after registry registration changes", async () => {
const { wrapper, publish, registry, client } = await setup()
- const original = publish()
+ const original = await publish()
const hook = renderHook(() => useConversationEntry({ ...target }), { wrapper })
expect(hook.result.current.canRead).toBe(true)
const invalidate = vi.spyOn(client, "invalidateQueries")
@@ -552,7 +552,7 @@ describe("conversation entry return during accepted reading", () => {
value.readState = { channelId: "c1", lastReadMessageId: "m30", lastReadSeq: 30, lastReadAt: value.messages[29].createdAt }
value.selection = { reason: "read_pointer", anchorMessageId: "m30" }
value.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }
- owner.publish(value)
+ await owner.publish(value)
const put = deferred<{ changed: boolean; revision: number; targetSeq: number }>()
const canonical = deferred<{ revision: number; readStates: typeof value.readState[] }>()
load.mockImplementation((url: string) => {
@@ -645,7 +645,7 @@ describe("conversation entry return during accepted reading", () => {
fresh.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 45 }
await act(async () => {
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [readState] })
- publishAccountAttentionSnapshot(owner.client, {
+ await publishAccountAttentionSnapshot(owner.client, {
snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1",
ordinaryUnread: true, lastUnreadSeq: 45, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
@@ -786,7 +786,7 @@ describe("conversation entry return during accepted reading", () => {
} finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }
})
- function evictOrdinaryEntryWithAlternateCoverage(owner: Awaited<ReturnType<typeof readingOwner>>) {
+ async function evictOrdinaryEntryWithAlternateCoverage(owner: Awaited<ReturnType<typeof readingOwner>>) {
const alternateTarget = { ...target, anchorMessageId: "m42" }
const alternate = fixture()
alternate.messages = [{ ...alternate.messages[0], id: "m42", seq: 42, createdAt: owner.read42.lastReadAt! }]
@@ -794,7 +794,7 @@ describe("conversation entry return during accepted reading", () => {
alternate.readState = { channelId: "c1", lastReadMessageId: "m30", lastReadSeq: 30, lastReadAt: "2026-10-01T00:00:30.000Z" }
alternate.selection = { reason: "explicit_anchor", anchorMessageId: "m42" }
alternate.page = { ...alternate.page, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 42 }
- const alternateResource = publishConversationEntry(owner.client, alternateTarget, alternate,
+ const alternateResource = await publishConversationEntry(owner.client, alternateTarget, alternate,
{ token: captureCommunityLiveSnapshotToken(owner.client, "c1") })
const alternateKey = conversationEntryOptions(owner.client, alternateTarget).queryKey
owner.client.setQueryData(alternateKey, alternateResource)
@@ -808,7 +808,7 @@ describe("conversation entry return during accepted reading", () => {
it.each([true, false])("uses qualified canonical coverage after ordinary entry eviction with alternate entry retained=%s", async qualified => {
const owner = await readingOwner()
- const { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey } = evictOrdinaryEntryWithAlternateCoverage(owner)
+ const { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey } = await evictOrdinaryEntryWithAlternateCoverage(owner)
if (!qualified) owner.client.removeQueries({ queryKey: alternateKey, exact: true })
expect(owner.client.getQueryData(ordinaryKey)).toBeUndefined()
expect(owner.client.getQueryData(alternateKey)).toBe(qualified ? alternateResource : undefined)
@@ -874,7 +874,7 @@ describe("conversation entry return during accepted reading", () => {
it.each([42, 100])("uses the higher canonical target %i with qualified cached coverage or its actual read", async seq => {
const owner = await readingOwner()
- const { alternate, alternateResource, retainedWindow } = evictOrdinaryEntryWithAlternateCoverage(owner)
+ const { alternate, alternateResource, retainedWindow } = await evictOrdinaryEntryWithAlternateCoverage(owner)
const read = { channelId: "c1", lastReadMessageId: `m${seq}`, lastReadSeq: seq,
lastReadAt: seq === 42 ? owner.read42.lastReadAt : "2026-10-01T00:01:40.000Z" }
const response = { ...alternate, readState: read, readStateRevision: 5,
@@ -1122,7 +1122,7 @@ describe("native entry freshness with authoritative newer attention", () => {
const original = await client.query(conversationEntryOptions(client, selectedTarget))
expect(client.getQueryCache().find({ queryKey: original.windowKey, exact: true })?.isActive()).toBe(false)
load.mockClear()
- publishAccountAttentionSnapshot(client, {
+ await publishAccountAttentionSnapshot(client, {
snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: packet.channelId, channelId: packet.channelId, serverId: packet.channel.serverId,
ordinaryUnread: newer, lastUnreadSeq: newer ? 2 : 1, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
index a164ee13c..f56db6e84 100644
--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
@@ -112,7 +112,7 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {
await seedConversationEntry(owner.client, options.cached ?? entry(kind, "c1", ownTail))
await seedConversationEntry(owner.client, entry("channel", "c2"))
if (options.readPointer) ingestReadStateSnapshot(owner.registry, { revision: 2, readStates: [options.readPointer] })
- if (options.latestAttentionSeq) publishAccountAttentionSnapshot(owner.client, {
+ if (options.latestAttentionSeq) await publishAccountAttentionSnapshot(owner.client, {
snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1", ordinaryUnread: true,
lastUnreadSeq: options.latestAttentionSeq, lastAttentionSeq: null, attentionCount: 0 }],
items: [], limit: 100, truncated: false,
@@ -315,7 +315,7 @@ describe("conversation entry positioning through real reading owners", () => {
expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),
fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,
readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),
- }).toEqual({ latestSeq: 13, messages: ["m1"], fetching: false, readSnapshotFetching: true, readReady: "false" })
+ }).toEqual({ latestSeq: previousTail ? 13 : 1, messages: ["m1"], fetching: !previousTail, readSnapshotFetching: true, readReady: "false" })
await act(async () => { await publish(); await vi.advanceTimersByTimeAsync(0) })
resize()
}
diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.ts
index 57fbf10d4..6b9496990 100644
--- a/src/web/src/hooks/community/use-conversation-entry.ts
+++ b/src/web/src/hooks/community/use-conversation-entry.ts
@@ -1,14 +1,14 @@
"use client"
-import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState } from "react"
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState, useSyncExternalStore } from "react"
import { createStore, useSelector } from "@tanstack/react-store"
-import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query"
+import { hashKey, useIsRestoring, useQuery, useQueryClient } from "@tanstack/react-query"
import { useConversationActivity, useConversationPresentation } from "@/contexts/community/conversation-activity"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"
-import { communityMessageProfileIds, CommunityMessageResourceSchema, CommunityResourceProfileSchema, type CommunityReadStateResource } from "@alook/shared"
+import { communityMessageProfileIds, type CommunityReadStateResource } from "@alook/shared"
import { useCanonicalMessagesById, useCanonicalProfilesProjection, useChannelReadStateProjection, useChannelRosterRows, useRouteChannelProjection } from "@/lib/community-db/projections"
-import { getCanonicalCommunityMessageResources } from "@/lib/community-db/sync"
+import { canonicalMessageResource } from "@/lib/community-db/resources"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"
@@ -28,6 +28,7 @@ type EntryWindow = NonNullable<ReturnType<typeof findConversationEntryWindow>>
export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, useLocalPosition = false, consumer: "metadata" | "messages" | "forum" = "metadata", networkEnabled = true) {
const client = useQueryClient()
+ const restoring = useIsRestoring()
const active = useConversationActivity()
const presented = useConversationPresentation()
const runtime = useCommunityRuntime()
@@ -75,6 +76,14 @@ export function useConversationResource(target: ConversationEntryTarget | null,
}, [client, baseInput, cachedSelection, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])
const input = landing.input
const options = useMemo(() => conversationEntryOptions(client, landing.requestInput), [client, landing])
+ const entryHash = hashKey(options.queryKey)
+ const restoreSubscriptionEnabled = restoring && target !== null
+ const subscribeRestoredEntry = useCallback((notify: () => void) => restoreSubscriptionEnabled
+ ? client.getQueryCache().subscribe(event => { if (event.query.queryHash === entryHash) notify() }) : () => undefined,
+ [client, entryHash, restoreSubscriptionEnabled])
+ const readRestoredEntry = useCallback(() => restoreSubscriptionEnabled ? client.getQueryData<ConversationEntryResource>(options.queryKey) : undefined,
+ [client, options.queryKey, restoreSubscriptionEnabled])
+ const restoredEntry = useSyncExternalStore(subscribeRestoredEntry, readRestoredEntry, readRestoredEntry)
const parentId = canonical?.parentChannelId ?? undefined
const [verification, setVerification] = useState(() => ({ runtime, channelId, serverId,
needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation }))
@@ -90,6 +99,7 @@ export function useConversationResource(target: ConversationEntryTarget | null,
const fallback = useQuery({ ...fallbackOptions, enabled: presented && enabled && anchorMissing && !revoked, subscribed: !!target && anchorMissing,
refetchOnReconnect: false, refetchOnWindowFocus: false })
const resource = query.data && isChannelMetadataTokenCurrent(query.data.proof) ? query.data
+ : restoredEntry && isChannelMetadataTokenCurrent(restoredEntry.proof) ? restoredEntry
: fallback.data && isChannelMetadataTokenCurrent(fallback.data.proof) ? fallback.data
: cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? cachedResource : undefined
const readableScope = useMemo(() => scope ?? resource, [scope, resource])
@@ -122,9 +132,11 @@ export function useConversationResource(target: ConversationEntryTarget | null,
return value.pages.flatMap(page => page.messages.map(message => message.id))
})
const forumMessageIds: string[] = []
+ const forumProfileIds: string[] = []
const forum = client.getQueryData<{ pages: import("./forum-feed-window").ForumFeedPage[] }>(communityKeys.forumFeed(channelId, tag))
if (Array.isArray(forum?.pages)) for (const page of forum.pages) if (Array.isArray(page?.threads)) for (const thread of page.threads) {
if (!thread || typeof thread.id !== "string") continue
+ if (Array.isArray(thread.participantIds)) forumProfileIds.push(...thread.participantIds.filter(id => typeof id === "string"))
if (typeof thread.openerMessageId === "string") forumMessageIds.push(thread.openerMessageId)
const child = getCommunityDbRegistry(client)?.collections.channels.get(thread.id)
if (child?.firstMessageId) forumMessageIds.push(child.firstMessageId)
@@ -132,20 +144,17 @@ export function useConversationResource(target: ConversationEntryTarget | null,
retainedIds.push(...forumMessageIds)
const retainedMessages = useCanonicalMessagesById([...new Set(retainedIds)])
const retainedResources = [...(retainedMessages?.keys() ?? [])].flatMap(id => {
- const parsed = CommunityMessageResourceSchema.strip().safeParse(getCommunityDbRegistry(client)?.collections.messages.get(id))
- return parsed.success ? [parsed.data] : []
+ const registry = getCommunityDbRegistry(client)
+ const parsed = registry && canonicalMessageResource(registry, registry.collections.messages.get(id))
+ return parsed ? [parsed] : []
})
- const retainedProfileIds = communityMessageProfileIds(retainedResources)
+ const retainedProfileIds = [...new Set([...communityMessageProfileIds(retainedResources), ...forumProfileIds])]
const retainedProfiles = useCanonicalProfilesProjection(retainedProfileIds)
const availableWindow = readableScope ? findConversationDisplayWindow(client, baseInput, readableScope) : undefined
- const availableMessageIds = availableWindow && messageWindowIdentity(availableWindow.key)
- ? client.getQueryData<MessageWindowData>(availableWindow.key)!.pages.flatMap(page => page.messages.map(message => message.id))
- : forumMessageIds
- const availableGraph = availableWindow ? getCanonicalCommunityMessageResources(client,
- availableMessageIds.map(id => getCommunityDbRegistry(client)?.collections.messages.get(id))) : undefined
+ const availableGraph = availableWindow?.resources
const requiredProfileIds = availableGraph?.profiles.map(profile => profile.id) ?? retainedProfileIds
const profilesReady = requiredProfileIds.length === 0 || retainedProfiles.isReady && !retainedProfiles.isError
- && requiredProfileIds.every(id => CommunityResourceProfileSchema.strip().safeParse(retainedProfiles.resourceProfiles.get(id)).success)
+ && requiredProfileIds.every(id => retainedProfiles.resourceProfiles.has(id))
const cachedWindow = profilesReady ? availableWindow : undefined
const dependencyWindowKey = availableWindow?.key ?? resource?.windowKey
const dependencyWindow = dependencyWindowKey && messageWindowIdentity(dependencyWindowKey)
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index c1410cd6e..825361c13 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -65,7 +65,7 @@ export const dmsProjectedQueryFn = (
try {
const data = await loadDms(context, publicationToken)
assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, context.signal)
- publishCommunityLiveSnapshot(queryClient, {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "dms", data },
proof: { kind: "structural", token: publicationToken, signal: context.signal },
})
diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.ts
index 307ca2e61..80bdbd5ea 100644
--- a/src/web/src/hooks/community/use-folders.ts
+++ b/src/web/src/hooks/community/use-folders.ts
@@ -62,7 +62,7 @@ export const foldersProjectedQueryFn = (
) => async (context: QueryFunctionContext = {} as QueryFunctionContext) => {
const token = captureCommunityLiveSnapshotToken(queryClient)
const data = await foldersQueryFn(context)
- publishCommunityLiveSnapshot(queryClient, {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "folders", data },
proof: { kind: "structural", token, signal: context.signal },
})
diff --git a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
index d168f16e1..9c3a902a5 100644
--- a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
@@ -47,7 +47,7 @@ describe("useForumFeed", () => {
it.each([null, "bug"])("refreshes a pending first list after child_create for tag %s", async (tag) => {
client.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } })
const target = { channelId: "forum_one", serverId: "server_one", tag }
- client.setQueryData(conversationEntryOptions(client, target).queryKey, publishConversationEntry(client, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(client, "forum_one") }))
+ client.setQueryData(conversationEntryOptions(client, target).queryKey, await publishConversationEntry(client, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(client, "forum_one") }))
const page = (ids: string[]): ForumFeedTransportPage => (forumFeedScenarioFixture("forum_one", {
serverId: "server_one", parentType: "forum", hasMore: false,
threads: ids.map((id) => ({ id, name: id, creatorId: "author", messageCount: 1, parentMessageId: `opener_${id}`, createdAt: "2026-10-26T00:00:00Z", activityAt: "2026-10-26T00:00:00Z", lastMessageAt: null })),
@@ -63,8 +63,8 @@ describe("useForumFeed", () => {
wrapper: ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client }, children),
})
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
- act(() => {
- publishCommunityForumFeed(client, "forum_one", normalizeThreadResources("forum_one", page(["new"])), { token: captureCommunityLiveSnapshotToken(client, "forum_one") })
+ await act(async () => {
+ await publishCommunityForumFeed(client, "forum_one", normalizeThreadResources("forum_one", page(["new"])), { token: captureCommunityLiveSnapshotToken(client, "forum_one") })
runCommunityWsProjectionTransaction(client, (projection) => handleChildChannelCreate({ type: "community:channel.child_create", parentChannelId: "forum_one", channel: { id: "new", name: "new", type: "thread", createdAt: "2026-10-26T00:00:00Z" }, parentMessageId: "opener_new" }, { queryClient: client, projection }))
release(page(["old"]))
})
@@ -77,7 +77,7 @@ describe("useForumFeed", () => {
it("does not restart a pending forum list removed during child_create", async () => {
client.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } })
const target = { channelId: "forum_one", serverId: "server_one" }
- client.setQueryData(conversationEntryOptions(client, target).queryKey, publishConversationEntry(client, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(client, "forum_one") }))
+ client.setQueryData(conversationEntryOptions(client, target).queryKey, await publishConversationEntry(client, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(client, "forum_one") }))
client.removeQueries({ queryKey: communityKeys.threads("forum_one") })
let release!: (value: ForumFeedTransportPage) => void
apiFetchMock.mockImplementation(() => new Promise((resolve) => { release = resolve }))
diff --git a/src/web/src/hooks/community/use-forum-feed.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
index 5eb899ce2..8dd1473bb 100644
--- a/src/web/src/hooks/community/use-forum-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
@@ -465,7 +465,7 @@ describe("useForumFeed", () => {
pageParams: [null],
})
const target = { channelId: "forum_one", serverId: "server_one" }
- queryClient.setQueryData(conversationEntryOptions(queryClient, target).queryKey, publishConversationEntry(queryClient, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(queryClient, "forum_one") }))
+ queryClient.setQueryData(conversationEntryOptions(queryClient, target).queryKey, await publishConversationEntry(queryClient, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(queryClient, "forum_one") }))
function QueryWrapper({ children }: PropsWithChildren) {
return createElement(QueryClientProvider, { client: queryClient }, children)
}
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index c2d86656c..d2b797a2e 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -74,7 +74,7 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, quer
const ids = new Set(freshThreads.map((thread) => thread.id)), openerIds = new Set(freshThreads.map((thread) => thread.parentMessageId))
const messages = page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId))
const users = new Set([...page.included.members.filter((member) => ids.has(member.channelId)).map((member) => member.userId), ...messages.flatMap(messageProfileIds)])
- publishCommunityForumFeed(queryClient, channelId, { ...page, threads: freshThreads, included: {
+ await publishCommunityForumFeed(queryClient, channelId, { ...page, threads: freshThreads, included: {
messages,
previews: page.included.previews.filter((message) => ids.has(message.channelId)),
tags: page.included.tags.filter((row) => openerIds.has(row.messageId)),
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts b/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
index 4e863b3a0..477c11b39 100644
--- a/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
@@ -78,7 +78,7 @@ describe("useForumOpenerHint", () => {
it("keeps a readable canonical opener after a transient background failure", async () => {
const { queryClient, wrapper } = await canonicalSetup()
- publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })]), channelId: "forum-1", messages: [messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })], proof: { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined } })
+ await publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })]), channelId: "forum-1", messages: [messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })], proof: { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined } })
apiFetchMock.mockRejectedValue(new Error("offline"))
const rendered = renderHook(() => useForumOpenerHint("server-1", "opener-1", true), { wrapper })
await waitFor(() => expect(rendered.result.current.isError).toBe(true))
@@ -126,7 +126,7 @@ describe("useForumOpenerHint", () => {
it("exposes a warm canonical opener without waiting for its background transport", async () => {
const { queryClient, wrapper } = await canonicalSetup()
- publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({
+ await publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({
id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7,
})]),
channelId: "forum-1",
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
index b43d0838f..6509ef13e 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
@@ -192,9 +192,9 @@ async function setup() {
return { queryClient, registry, wrapper }
}
-function publish(queryClient: QueryClient, data = envelope(), completeWindow = false, serverId = "server-1") {
+async function publish(queryClient: QueryClient, data = envelope(), completeWindow = false, serverId = "server-1") {
const normalized = normalizeForumSidebarEnvelope(data, null)
- publishCommunityForumSidebar(queryClient, {
+ await publishCommunityForumSidebar(queryClient, {
serverId,
resources: data.resources,
channels: data.resources.channels.filter(row => row.type === "thread").map(row => ({ ...row, activityAt: data.channels.find(summary => summary.id === row.id)?.activityAt ?? data.serverNow, unread: data.channels.find(summary => summary.id === row.id)?.unread ?? false, participating: true })),
@@ -214,8 +214,8 @@ function publish(queryClient: QueryClient, data = envelope(), completeWindow = f
return normalized
}
-function publishResourceSet(queryClient: QueryClient, resources: SidebarThreadEnvelope["resources"]) {
- publishCommunityForumSidebar(queryClient, { serverId: resources.servers[0]!.id, resources,
+async function publishResourceSet(queryClient: QueryClient, resources: SidebarThreadEnvelope["resources"]) {
+ await publishCommunityForumSidebar(queryClient, { serverId: resources.servers[0]!.id, resources,
channels: [], openers: resources.messages, proof: { token: captureCommunityLiveSnapshotToken(queryClient) } })
}
@@ -265,7 +265,7 @@ describe("forum sidebar canonical projection", () => {
const { queryClient, registry, wrapper } = await setup()
const previous = envelopeFor(["older-1", "older-2", "older-3", "older-4", "older-5"])
previous.channels.forEach((_, index) => setActivity(previous, index, new Date(Date.now() - (index + 2) * 60_000).toISOString()))
- publishResourceSet(queryClient, previous.resources)
+ await publishResourceSet(queryClient, previous.resources)
const response = envelopeFor(["new", "older-1", "older-2", "older-3", "older-4"])
response.channels.forEach((_, index) => setActivity(response, index, new Date(Date.now() - (index + 1) * 60_000).toISOString()))
const zeroReply = response.resources.channels.find(row => row.id === "new")!
@@ -303,7 +303,7 @@ describe("forum sidebar canonical projection", () => {
row.createdAt = stale.channels[index]!.activityAt
row.lastMessageAt = null
}
- publishResourceSet(queryClient, stale.resources)
+ await publishResourceSet(queryClient, stale.resources)
const fresh = envelopeFor(["a", "b", "c", "d", "e"])
fresh.channels.forEach((_, index) => setActivity(fresh, index, new Date(Date.now() - 120_000).toISOString()))
apiFetchMock.mockResolvedValue(fresh)
@@ -317,14 +317,14 @@ describe("forum sidebar canonical projection", () => {
it("admits repeated full current Sidebar resource bundles from live collection rows", async () => {
const { queryClient, registry } = await setup()
- publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
- publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
+ await publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
+ await publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
expect(registry.collections.channels.get("post-1")?.type).toBe("thread")
expect(registry.collections.serverMemberships.get("server-1:viewer")?.memberId).toBe("member-server-1")
})
it("keeps visible posts through unrelated metadata admission and a same-window post switch", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
+ await publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
apiFetchMock.mockReturnValue(new Promise(() => {}))
const frames: string[][] = []
const view = renderHook(({ retainId }: { retainId: string }) => {
@@ -335,7 +335,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(view.result.current.threads).toHaveLength(2))
frames.length = 0
await act(async () => {
- publishCommunityChannelMetadata(queryClient, {
+ await publishCommunityChannelMetadata(queryClient, {
metadata: {
...envelopeFor(["unlisted"]).resources.channels.find(row => row.id === "unlisted")!,
parentChannelId: "forum-1",
@@ -387,8 +387,8 @@ describe("forum sidebar canonical projection", () => {
}
await waitFor(() => expect(rendered.result.current.metadata.isVerified).toBe(true))
await waitFor(() => expect(rendered.result.current.sidebar.isSuccess).toBe(true))
- act(() => {
- publishCommunityLiveSnapshot(queryClient, {
+ await act(async () => {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture({
id: "server-1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer", categories: [{
@@ -417,8 +417,8 @@ describe("forum sidebar canonical projection", () => {
it("clears only the reserved opener archive tag on a current eligible response", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
- act(() => {
+ await publish(queryClient)
+ await act(() => {
projectCommunityWsEventToDb(queryClient, {
type: "community:channel.child_update", channelId: "post-1", parentChannelId: "forum-1",
changes: { tags: ["bug", "archived"] },
@@ -438,7 +438,7 @@ describe("forum sidebar canonical projection", () => {
it.each(["pending", "failed"].flatMap(refresh => [false, true].map(existing => [refresh, existing] as const)))("keeps late metadata unarchived after WS unarchive with %s Sidebar refresh and existing=%s", async (refresh, existing) => {
const { queryClient, registry, wrapper } = await setup()
- if (existing) publish(queryClient)
+ if (existing) await publish(queryClient)
const negative = { ...envelopeFor([]), retainedChannel: null, retainedDisposition: "opener-archived" as const }
apiFetchMock.mockResolvedValueOnce(negative)
const sidebar = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
@@ -472,7 +472,7 @@ describe("forum sidebar canonical projection", () => {
it("preserves a newer WS opener archive against an older positive response and permits current unarchive", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
let resolveStale!: (value: SidebarThreadEnvelope) => void
const eligible = envelope()
eligible.retainedChannel = eligible.channels[0]
@@ -481,7 +481,7 @@ describe("forum sidebar canonical projection", () => {
.mockResolvedValue(eligible)
const rendered = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => {
+ await act(() => {
projectCommunityWsEventToDb(queryClient, {
type: "community:channel.child_update", channelId: "post-1", parentChannelId: "forum-1",
changes: { tags: ["bug", "archived"] },
@@ -507,8 +507,8 @@ describe("forum sidebar canonical projection", () => {
it("publishes archive qualification without overwriting newer unrelated metadata", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
- act(() => {
+ await publish(queryClient)
+ await act(() => {
projectCommunityWsEventToDb(queryClient, {
type: "community:channel.child_update", channelId: "post-1", parentChannelId: "forum-1",
changes: { tags: ["bug"] },
@@ -518,7 +518,7 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>((resolve) => { resolveNegative = resolve }))
const rendered = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => {
+ await act(() => {
projectCommunityWsEventToDb(queryClient, {
type: "community:channel.child_update", channelId: "post-1", parentChannelId: "forum-1",
changes: { name: "Newer title" },
@@ -528,7 +528,7 @@ describe("forum sidebar canonical projection", () => {
resolveNegative({ ...envelopeFor([]), retainedChannel: null, retainedDisposition: "opener-archived" })
})
await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
- act(() => { setCanonicalCommunityChannelMembership(queryClient, "post-1", "notify", true) })
+ await act(() => { setCanonicalCommunityChannelMembership(queryClient, "post-1", "notify", true) })
await waitFor(() => expect(rendered.result.current.threads).toEqual([]))
expect(registry.collections.channels.get("post-1")).toMatchObject({
name: "Newer title", tags: ["bug", "archived"], archived: false,
@@ -539,7 +539,7 @@ describe("forum sidebar canonical projection", () => {
it("includes a notified text reply in the shared sidebar after its message read", async () => {
const { queryClient, registry, wrapper } = await setup()
- act(() => ingestServerDetail(registry, serverDirectoryFixture({
+ await act(() => ingestServerDetail(registry, serverDirectoryFixture({
id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "cat-1", name: "Channels", channels: [
{ id: "forum-1", name: "forum", active: false, unread: false, type: "forum" },
@@ -549,8 +549,8 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockResolvedValue(envelope())
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
await waitFor(() => expect(rendered.result.current.threads.map((row) => row.id)).toEqual(["post-1"]))
- act(() => {
- publishCommunityCreatedChannel(queryClient, channelResourceFixture({ id: "text-child", serverId: "server-1", type: "thread", parentChannelId: "text-1", parentMessageId: "text-opener", name: "Text reply" }), { token: captureCommunityLiveSnapshotToken(queryClient) })
+ await act(async () => {
+ await publishCommunityCreatedChannel(queryClient, channelResourceFixture({ id: "text-child", serverId: "server-1", type: "thread", parentChannelId: "text-1", parentMessageId: "text-opener", name: "Text reply" }), { token: captureCommunityLiveSnapshotToken(queryClient) })
ingestMessages(registry, "text-1", messageSeedFixture("text-1", [{ id: "text-opener", type: "chat", content: "Text reply opener", seq: 1,
thread: { id: "text-child", name: "Text reply", messageCount: 1, lastReplyAt: new Date().toISOString() } }]))
setCanonicalCommunityChannelMembership(queryClient, "text-child", "notify", true)
@@ -612,7 +612,7 @@ describe("forum sidebar canonical projection", () => {
const { queryClient, registry } = await setup()
const response = envelope()
response.resources.channels.find(row => row.id === "post-1")!.archived = true
- publish(queryClient, response)
+ await publish(queryClient, response)
expect(registry.collections.channels.get("post-1")?.archived).toBe(true)
expect(queryClient.getQueryData(communityKeys.channelMeta("server-1", "post-1"))).toBeUndefined()
})
@@ -625,7 +625,7 @@ describe("forum sidebar canonical projection", () => {
const response = envelopeFor(["post-1", "post-2", "post-3", "post-4", "post-5", "post-6"])
const expired = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()
setActivity(response, 5, expired)
- publishResourceSet(queryClient, response.resources)
+ await publishResourceSet(queryClient, response.resources)
seedCommunityAttentionScope(queryClient, { channelId: "post-6", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(() => useForumSidebarProjection("server-1", "post-6", Date.now()), { wrapper })
await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(5))
@@ -645,7 +645,7 @@ describe("forum sidebar canonical projection", () => {
it("ignores another user's notify row in both Sidebar views and bounded negative reconciliation", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
removeCanonicalCommunityChannelMembership(queryClient, "post-1", "notify")
registry.collections.channelMemberships.utils.writeUpsert({ id: "post-1:other:notify",
channelId: "post-1", userId: "other", relation: "notify", source: "explicit" })
@@ -665,7 +665,7 @@ describe("forum sidebar canonical projection", () => {
patchCanonicalCommunityChannel(queryClient, "forum-1", row => ({ ...row, type: parentType }))
const data = envelopeFor(["0", "9", "A", "Z", "a", "z", "expired"])
setActivity(data, 6, new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString())
- publishResourceSet(queryClient, data.resources)
+ await publishResourceSet(queryClient, data.resources)
const rendered = renderHook(() => useForumSidebarProjection("server-1", retainId, Date.now()), { wrapper })
const expected = retainId === null ? ["z", "a", "Z", "A", "9"] : ["z", "a", "Z", "A", retainId]
await waitFor(() => expect(rendered.result.current?.threads.map((row) => row.id)).toEqual(expected))
@@ -693,7 +693,7 @@ describe("forum sidebar canonical projection", () => {
setActivity(stale, 3, new Date(now - 120_000).toISOString())
setActivity(stale, 4, new Date(now - (73 * 60 * 60 * 1000)).toISOString())
setActivity(stale, 5, "invalid")
- publishResourceSet(queryClient, stale.resources)
+ await publishResourceSet(queryClient, stale.resources)
const fresh = envelopeFor(["z-fresh", "y-fresh", "x-fresh", "w-fresh", "a-cutoff"])
fresh.channels.forEach((_, index) => setActivity(fresh, index, new Date(now - 120_000).toISOString()))
apiFetchMock.mockResolvedValue({ ...fresh, canonicalChannels: fresh.channels })
@@ -739,8 +739,8 @@ describe("forum sidebar canonical projection", () => {
it("does not let an older reconnect response delete a newer WS notify membership", async () => {
const { queryClient, registry } = await setup()
- publish(queryClient, envelopeFor(["post-ws"]))
- act(() => { removeCanonicalCommunityChannelMembership(queryClient, "post-ws", "notify") });
+ await publish(queryClient, envelopeFor(["post-ws"]))
+ await act(() => { removeCanonicalCommunityChannelMembership(queryClient, "post-ws", "notify") });
let settle!: (value: SidebarThreadEnvelope) => void
apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>((resolve) => {
settle = resolve
@@ -764,7 +764,7 @@ describe("forum sidebar canonical projection", () => {
it("keeps warm DB rows visible while the HTTP transport is stalled", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelope(), true)
+ await publish(queryClient, envelope(), true)
apiFetchMock.mockReturnValue(new Promise(() => {}))
const frames: string[][] = []
@@ -789,7 +789,7 @@ describe("forum sidebar canonical projection", () => {
it("projects complete first frames for remounted A to B to A cached servers", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient, envelope(), true)
+ await publish(queryClient, envelope(), true)
ingestServerDetail(registry, serverDirectoryFixture({
id: "server-2", name: "Second", discriminator: "0002", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "cat-2", name: "Second forums", channels: [{ id: "forum-2", name: "Second forum", type: "forum", active: false, unread: false }] }],
@@ -801,7 +801,7 @@ describe("forum sidebar canonical projection", () => {
second.resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server-2" })],
second.resources.channels.map(row => ({ ...row, id: row.type === "forum" ? "forum-2" : row.id, serverId: "server-2", parentChannelId: row.type === "thread" ? "forum-2" : null })),
second.resources.messages.map(row => ({ ...row, channelId: "forum-2" })))
- publish(queryClient, second, true, "server-2")
+ await publish(queryClient, second, true, "server-2")
apiFetchMock.mockReturnValue(new Promise(() => {}))
const frames: Array<{ serverId: string; ids: string[]; ready: boolean }> = []
function Probe({ serverId }: { serverId: string }) {
@@ -867,7 +867,7 @@ describe("forum sidebar canonical projection", () => {
it("keeps SSR and hydration consistent before projecting the mounted client clock", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelope(), true)
+ await publish(queryClient, envelope(), true)
apiFetchMock.mockReturnValue(new Promise(() => {}))
function Probe() {
const sidebar = useForumSidebarThreads("server-1", null)
@@ -902,7 +902,7 @@ describe("forum sidebar canonical projection", () => {
"post-3",
"post-2",
])
- publish(queryClient, restored)
+ await publish(queryClient, restored)
const fresh = envelopeFor([
"post-5",
"post-4",
@@ -979,7 +979,7 @@ describe("forum sidebar canonical projection", () => {
it("stores opener-archive exclusion without archiving the child route", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
const rendered = renderHook(
() => useForumSidebarProjection("server-1", null, Date.now()),
{ wrapper },
@@ -1019,7 +1019,7 @@ describe("forum sidebar canonical projection", () => {
it("keeps normalized child unread and parent ownership in the canonical view", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelope())
+ await publish(queryClient, envelope())
seedCommunityAttentionScope(queryClient, { channelId: "post-1", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(() => useForumSidebarProjection("server-1", null, Date.now()), { wrapper })
await waitFor(() => expect(rendered.result.current).toEqual({
@@ -1041,7 +1041,7 @@ describe("forum sidebar canonical projection", () => {
vi.useFakeTimers()
vi.setSystemTime(new Date("2026-09-26T00:00:00.000Z"))
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelopeFor(["post-1"]))
+ await publish(queryClient, envelopeFor(["post-1"]))
apiFetchMock.mockReturnValue(new Promise(() => {}))
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
@@ -1063,11 +1063,11 @@ describe("forum sidebar canonical projection", () => {
const serverNow = Date.now() + 60 * 60 * 1000
response.serverNow = new Date(serverNow).toISOString()
setActivity(response, 0, new Date(serverNow - 72 * 60 * 60 * 1000 + 60_000).toISOString())
- publish(queryClient, response, true)
+ await publish(queryClient, response, true)
apiFetchMock.mockReturnValue(new Promise(() => {}))
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
await act(async () => { await vi.advanceTimersByTimeAsync(30_000) })
- act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "Changed") })
+ await act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "Changed") })
expect(rendered.result.current.threads[0]?.title).toBe("Changed")
await act(async () => { await vi.advanceTimersByTimeAsync(30_024) })
expect(rendered.result.current.threads).toHaveLength(1)
@@ -1129,7 +1129,7 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => {
+ await act(() => {
getCommunityDbRegistry(queryClient)!.runtime.ws.actions.markAccessDisconnected()
getCommunityDbRegistry(queryClient)!.runtime.ws.actions.markAccessConnected()
})
@@ -1140,20 +1140,20 @@ describe("forum sidebar canonical projection", () => {
it("folds in-flight title, activity, and removal deltas into one canonical publish", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelopeFor(["post-1", "post-2"]))
+ await publish(queryClient, envelopeFor(["post-1", "post-2"]))
const activityAt = new Date(Date.now() - 60_000).toISOString()
let resolveRequest!: (value: SidebarThreadEnvelope) => void
apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "live title") });
- act(() => { patchForumSidebarActivityExact(
+ await act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "live title") });
+ await act(() => { patchForumSidebarActivityExact(
queryClient, "server-1", "post-1", "forum-1", activityAt,
) });
- act(() => { patchForumSidebarActivityExact(
+ await act(() => { patchForumSidebarActivityExact(
queryClient, "server-1", "missing", "forum-1", activityAt,
) });
- act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-2") });
+ await act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-2") });
await act(async () => resolveRequest(envelopeFor(["post-1", "post-2"])))
await waitFor(() => expect(rendered.result.current.threads).toEqual([
expect.objectContaining({
@@ -1169,7 +1169,7 @@ describe("forum sidebar canonical projection", () => {
it("folds an in-flight activity delta into an eligible retained row", async () => {
const { queryClient, wrapper } = await setup()
- publish(queryClient, envelopeFor(["post-1"]))
+ await publish(queryClient, envelopeFor(["post-1"]))
const activityAt = new Date(Date.now() - 60_000).toISOString()
let resolveRequest!: (value: SidebarThreadEnvelope) => void
apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
@@ -1178,7 +1178,7 @@ describe("forum sidebar canonical projection", () => {
{ wrapper },
)
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => { patchForumSidebarActivityExact(
+ await act(() => { patchForumSidebarActivityExact(
queryClient, "server-1", "post-1", "forum-1", activityAt,
) });
const retained = envelopeFor(["post-1"])
@@ -1234,14 +1234,14 @@ describe("forum sidebar canonical projection", () => {
it("keeps invalid canonical activity literal and removes children by parent", async () => {
const { queryClient } = await setup()
- publish(queryClient)
- act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "updated title") });
+ await publish(queryClient)
+ await act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "updated title") });
expect(getCanonicalCommunityMessages(queryClient).find(({ id }) => id === "opener-1")?.content)
.toBe("updated title")
- act(() => { patchForumSidebarActivityExact(queryClient, "server-1", "post-1", "forum-1", "invalid") });
+ await act(() => { patchForumSidebarActivityExact(queryClient, "server-1", "post-1", "forum-1", "invalid") });
expect(getForumSidebarBase(queryClient, "server-1").threads[0]?.expiresAt).toBe("invalid")
- act(() => { removeForumSidebarProjectionExact(queryClient, "server-1", "post-1") });
- act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "forum-1") });
+ await act(() => { removeForumSidebarProjectionExact(queryClient, "server-1", "post-1") });
+ await act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "forum-1") });
expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1"))
.toBe(false)
})
@@ -1304,7 +1304,7 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveGrant = resolve }))
const grant = grantForumSidebarChild(queryClient, "server-1", "post-1").catch((error) => error)
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-1") });
+ await act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-1") });
await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)
const retained = envelopeFor(["post-1"])
resolveGrant({
@@ -1338,8 +1338,8 @@ describe("forum sidebar canonical projection", () => {
it("treats a negative retained result as notify evidence, not access revocation", async () => {
const { queryClient, registry } = await setup()
- publish(queryClient)
- publishCommunityForumSidebar(queryClient, {
+ await publish(queryClient)
+ await publishCommunityForumSidebar(queryClient, {
serverId: "server-1",
resources: envelopeFor([]).resources,
channels: [],
@@ -1360,7 +1360,7 @@ describe("forum sidebar canonical projection", () => {
it("clears hidden unread ownership when a canonical refetch removes participation", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
apiFetchMock.mockResolvedValue({
...envelopeFor([]),
canonicalChannels: [],
@@ -1412,7 +1412,7 @@ describe("forum sidebar canonical projection", () => {
it("aggregates persisted unread child ownership even without notify membership", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
registry.collections.channelMemberships.utils.writeDelete("post-1:viewer:notify")
seedCommunityAttentionScope(queryClient, { channelId: "post-1", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(
@@ -1428,7 +1428,7 @@ describe("forum sidebar canonical projection", () => {
it("uses exact scope attention beyond the bounded item window for thread dots", async () => {
const { queryClient, registry, wrapper } = await setup()
- publish(queryClient)
+ await publish(queryClient)
ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] },
resources: envelope().resources,
scopes: [{
@@ -1461,7 +1461,7 @@ describe("forum sidebar canonical projection", () => {
it("restores a warm persisted sidebar while HTTP is stalled", async () => {
const { queryClient } = await setup()
- publish(queryClient, envelope(), true)
+ await publish(queryClient, envelope(), true)
const { queryClient: restoredClient, wrapper } = await restorePersistedSidebar(queryClient)
apiFetchMock.mockReturnValue(new Promise(() => {}))
const frames: string[][] = []
@@ -1550,13 +1550,13 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
const publishPrimary = () => ingestServerDetail(registry, serverDirectoryFixture({ id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "cat-1", name: "Forum", channels: [{ id: "forum-1", name: "Forum", type: "forum", active: false, unread: false }] }] }))
- if (order === "primary-first") act(publishPrimary)
+ if (order === "primary-first") await act(publishPrimary)
else await act(async () => { release(envelope()) })
expect(view.getByTestId(tid.channelSidebarPending("server-1"))).toBeVisible()
expect(view.queryByTestId(tid.channelRow("forum-1"))).toBeNull()
expect(view.queryByTestId(tid.forumSidebarThread("post-1"))).toBeNull()
if (order === "primary-first") await act(async () => { release(envelope()) })
- else act(publishPrimary)
+ else await act(publishPrimary)
await waitFor(() => expect(view.queryByTestId(tid.channelSidebarPending("server-1"))).toBeNull())
expect(view.getByTestId(tid.channelRow("forum-1"))).toBeVisible()
expect(view.getByTestId(tid.forumSidebarThread("post-1"))).toBeVisible()
@@ -1579,7 +1579,7 @@ describe("forum sidebar canonical projection", () => {
it.each(["memory", "restored"])("does not treat a single cached post as a complete %s window", async (kind) => {
const owner = await setup()
- publish(owner.queryClient)
+ await publish(owner.queryClient)
const target = kind === "restored" ? await restorePersistedSidebar(owner.queryClient) : owner
let release!: (value: SidebarThreadEnvelope) => void
apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>(resolve => { release = resolve }))
@@ -1638,7 +1638,7 @@ describe("forum sidebar canonical projection", () => {
it("rejects the window after the real message budget prunes its opener and starts a fresh read", async () => {
const owner = await setup()
- publish(owner.queryClient, envelope(), true)
+ await publish(owner.queryClient, envelope(), true)
ingestMessages(owner.registry, "forum-1", messageSeedFixture("forum-1", Array.from({ length: MAX_PERSISTED_MESSAGES_PER_SCOPE }, (_, index) => ({
id: `newer-${index}`, type: "chat" as const, content: "Newer", seq: index + 2, createdAt: new Date().toISOString(),
}))))
@@ -1657,7 +1657,7 @@ describe("forum sidebar canonical projection", () => {
it.each(["opener", "legacy-result"])("actively repairs a warm window after local %s loss without a retirement invalidation", async missing => {
const owner = await setup()
- publish(owner.queryClient, envelope(), true)
+ await publish(owner.queryClient, envelope(), true)
if (missing === "legacy-result") owner.queryClient.setQueryData(communityKeys.forumSidebarThreads("server-1"), {
threads: [], serverNow: new Date().toISOString(), serverClockOffsetMs: 0, verifiedEpoch: -1,
})
@@ -1680,13 +1680,13 @@ describe("forum sidebar canonical projection", () => {
it("actively rereads an Infinity window when a referenced canonical post retires", async () => {
const owner = await setup()
- publish(owner.queryClient, envelope(), true)
+ await publish(owner.queryClient, envelope(), true)
let release!: (value: SidebarThreadEnvelope) => void
apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>(resolve => { release = resolve }))
const view = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper: owner.wrapper })
expect(view.result.current.sidebar.status).toBe("ready")
expect(apiFetchMock).not.toHaveBeenCalled()
- act(() => { purgeCommunityChannel(owner.registry, "post-1") })
+ await act(() => { purgeCommunityChannel(owner.registry, "post-1") })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
await act(async () => { release(envelopeFor([])) })
await waitFor(() => expect(view.result.current.sidebar.status).toBe("ready"))
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index da5d3de94..200971c15 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -1,4 +1,5 @@
"use client"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { getServerDirectoryWindow } from "@/lib/community/server-directory-window"
import { useHydratedClient } from "@/hooks/use-hydrated-client"
@@ -157,7 +158,7 @@ async function fetchForumSidebar(
return normalizeForumSidebarEnvelope(envelope, retainId)
}
-function publishNormalizedForumSidebar(
+async function publishNormalizedForumSidebar(
queryClient: QueryClient,
serverId: string,
normalized: NormalizedForumSidebarEnvelope,
@@ -166,7 +167,7 @@ function publishNormalizedForumSidebar(
token: ReturnType<typeof captureCommunityLiveSnapshotToken>,
) {
if (normalized.serverId !== serverId) throw new Error("Forum sidebar server mismatch")
- publishCommunityForumSidebar(queryClient, {
+ await publishCommunityForumSidebar(queryClient, {
serverId, resources: normalized.resources, channels: normalized.channels, openers: normalized.openers,
negativeRetain: retainId && normalized.retainedDisposition !== "eligible"
? {
@@ -176,8 +177,8 @@ function publishNormalizedForumSidebar(
: null,
proof: { token, signal },
})
- const reconciliation = reconcileForumSidebarNotifyMembershipsFromBase(queryClient, serverId, normalized.base, { token, signal },
- normalized.retainedDisposition === "eligible" ? normalized.retained?.id ?? null : null)
+ const reconciliation = await completeCommunityPublication(queryClient, () => reconcileForumSidebarNotifyMembershipsFromBase(queryClient, serverId, normalized.base, { token, signal },
+ normalized.retainedDisposition === "eligible" ? normalized.retained?.id ?? null : null))
const reference = ({ id, parentChannelId, parentMessageId }: ForumSidebarThread) => ({ id, parentChannelId, parentMessageId })
const result = {
...normalized.base, threads: [], verifiedEpoch: token.accessEpoch,
@@ -314,7 +315,7 @@ async function fetchForumSidebarBaseExact(
normalized = await fetchForumSidebar(queryClient, serverId, null, signal, token)
if (signal.aborted) throw new DOMException("Aborted", "AbortError")
proof = { token, signal }
- const result = publishNormalizedForumSidebar(
+ const result = await publishNormalizedForumSidebar(
queryClient,
serverId,
normalized,
@@ -425,7 +426,7 @@ export async function grantForumSidebarChild(queryClient: QueryClient, serverId:
queryFn: async ({ signal }: { signal: AbortSignal }) => {
const token = captureCommunityLiveSnapshotToken(queryClient)
const normalized = await fetchForumSidebar(queryClient, serverId, childId, signal, token)
- const result = publishNormalizedForumSidebar(queryClient, serverId, normalized, childId, signal, token)
+ const result = await publishNormalizedForumSidebar(queryClient, serverId, normalized, childId, signal, token)
queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId), result.data)
return { id: childId, disposition: normalized.retainedDisposition, verifiedEpoch: token.accessEpoch }
},
@@ -445,9 +446,9 @@ export async function reconcileForumSidebarArchiveTag(
void queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads(serverId), exact: true, refetchType: "none" })
const cancellation = queryClient.cancelQueries({ queryKey: communityKeys.forumSidebarRetained(serverId, childId), exact: true })
if (archived) {
- removeCanonicalCommunityChannelMembership(queryClient, childId, "notify")
+ await completeCommunityPublication(queryClient, () => removeCanonicalCommunityChannelMembership(queryClient, childId, "notify"))
} else {
- setCanonicalCommunityChannelMembership(queryClient, childId, "notify", true)
+ await completeCommunityPublication(queryClient, () => setCanonicalCommunityChannelMembership(queryClient, childId, "notify", true))
}
await cancellation
return invalidateForumSidebarBaseExact(queryClient, serverId)
@@ -468,7 +469,7 @@ export function useForumSidebarThreads(
const token = captureCommunityLiveSnapshotToken(queryClient)
const normalized = await fetchForumSidebar(queryClient, serverId, retainId, signal, token)
if (signal.aborted) throw new DOMException("Aborted", "AbortError")
- const result = publishNormalizedForumSidebar(queryClient, serverId, normalized, retainId, signal, token)
+ const result = await publishNormalizedForumSidebar(queryClient, serverId, normalized, retainId, signal, token)
return result.data
},
diff --git a/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts b/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts
index 394c4d303..2e72b0462 100644
--- a/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts
+++ b/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts
@@ -14,8 +14,8 @@ beforeEach(() => { api.mockReset(); api.mockResolvedValue(undefined) })
afterEach(() => vi.useRealTimers())
async function fixture() {
const { client, registry } = await createCommunityQueryOwner()
- const seed = (ids: string[]) => publishCommunityFriendships(client, ids.map((id) => ({ id, userId: `user-${id}`, kind: "incoming" })), { token: captureCommunityLiveSnapshotToken(client) })
- seed(["a", "b"])
+ const seed = async (ids: string[]) => await publishCommunityFriendships(client, ids.map((id) => ({ id, userId: `user-${id}`, kind: "incoming" })), { token: captureCommunityLiveSnapshotToken(client) })
+ await seed(["a", "b"])
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children))
const commands = renderHook(() => ({ accept: useAcceptFriendRequest(), reject: useRejectFriendRequest() }), { wrapper })
const onAccept = (id: string) => commands.result.current.accept.mutateAsync({ friendshipId: id })
@@ -34,7 +34,7 @@ function deferred() {
describe("Native friend-request action projection", () => {
it("does not create rows from unrelated mutation variables or an absent canonical request", async () => {
const { surfaces, seed } = await fixture()
- act(() => seed([]))
+ await act(async () => await seed([]))
await waitFor(() => expect(surfaces.result.current.inbox.items).toEqual([]))
expect(surfaces.result.current.friends.items).toEqual([])
})
@@ -42,14 +42,14 @@ describe("Native friend-request action projection", () => {
const { wrapper, commands } = await fixture(); const gate = deferred(); api.mockReturnValue(gate.promise)
const surface = renderHook(() => useFriendRequestActionState({ rows: [{ id: "a" }], onAccept: (id) => commands.result.current.accept.mutateAsync({ friendshipId: id }), surface: "inbox" }), { wrapper })
let request!: Promise<void>
- act(() => { request = surface.result.current.act(surface.result.current.items[0]!, "accept") })
+ await act(() => { request = surface.result.current.act(surface.result.current.items[0]!, "accept") })
await waitFor(() => expect(surface.result.current.items[0]).toMatchObject({ row: { id: "a" }, action: "accept", status: "pending" }))
await act(async () => { gate.resolve(); await request })
})
it("keeps the canonical request through ACK and locks only its id on both surfaces", async () => {
const { registry, surfaces } = await fixture(); const gate = deferred(); api.mockReturnValue(gate.promise)
let request!: Promise<void>
- act(() => { request = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept") })
+ await act(() => { request = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept") })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
expect(registry.collections.friendships.get("a")?.kind).toBe("incoming")
for (const surface of Object.values(surfaces.result.current)) expect(surface.items.map((item) => item.status)).toEqual(["pending", undefined])
@@ -71,7 +71,7 @@ describe("Native friend-request action projection", () => {
const { surfaces } = await fixture(); const a = deferred(), b = deferred()
api.mockImplementation((path: string) => path.endsWith("/a/accept") ? a.promise : path.endsWith("/b/accept") ? b.promise : Promise.resolve(undefined))
let first!: Promise<void>, second!: Promise<void>
- act(() => { first = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept"); second = surfaces.result.current.inbox.act(surfaces.result.current.inbox.items[1]!, "accept") })
+ await act(() => { first = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept"); second = surfaces.result.current.inbox.act(surfaces.result.current.inbox.items[1]!, "accept") })
await waitFor(() => expect(surfaces.result.current.inbox.items.map((item) => item.status)).toEqual(["pending", "pending"]))
await act(async () => { b.resolve(); await second })
expect(surfaces.result.current.friends.items[0]?.status).toBe("pending")
@@ -92,16 +92,16 @@ describe("Native friend-request action projection", () => {
const { client, surfaces, seed } = await fixture(); api.mockRejectedValueOnce(new Error("offline"))
await act(async () => { await surfaces.result.current.inbox.act(surfaces.result.current.inbox.items[0]!, "accept") })
await waitFor(() => expect(surfaces.result.current.friends.items[0]?.status).toBe("error"))
- act(() => seed(["b"]))
+ await act(async () => await seed(["b"]))
expect(client.getMutationCache().findAll({ mutationKey: ["community", "friend-request"] })).toHaveLength(0)
await waitFor(() => expect(surfaces.result.current.inbox.items.map((item) => item.row.id)).toEqual(["b"]))
})
it("never rebuilds a blocked user from failure and clears native errors on account retirement", async () => {
const { client, registry, surfaces } = await fixture(); const gate = deferred(); api.mockReturnValue(gate.promise)
let request!: Promise<void>
- act(() => { request = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept") })
+ await act(() => { request = surfaces.result.current.friends.act(surfaces.result.current.friends.items[0]!, "accept") })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
- act(() => projectCommunityWsEventToDb(client, { type: "community:friend.block", userId: "user-a" }))
+ await act(() => projectCommunityWsEventToDb(client, { type: "community:friend.block", userId: "user-a" }))
api.mockResolvedValue(undefined)
await act(async () => { gate.reject(new Error("late")); await request })
expect(surfaces.result.current.friends.items.map((item) => item.row.id)).toEqual(["b"])
diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.ts
index 0c2cb0557..cdf3e50f7 100644
--- a/src/web/src/hooks/community/use-friends.ts
+++ b/src/web/src/hooks/community/use-friends.ts
@@ -77,7 +77,7 @@ export const friendsQueryFn = async (context: QueryFunctionContext) => {
...pendingData.pending,
...blockedData.blocked.map(row => ({ ...row, id: `blocked:${row.userId}`, kind: "blocked" as const })),
]
- publishCommunityFriendships(context.client, rows, { token, signal: context.signal })
+ await publishCommunityFriendships(context.client, rows, { token, signal: context.signal })
return { ids: rows.map(row => row.id) }
}
diff --git a/src/web/src/hooks/community/use-inbox.dom.test.ts b/src/web/src/hooks/community/use-inbox.dom.test.ts
index 56b8b5c39..94a939910 100644
--- a/src/web/src/hooks/community/use-inbox.dom.test.ts
+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts
@@ -437,7 +437,7 @@ describe("useInboxAttention", () => {
const child = harness.registry.collections.channels.get("child")!
await writeCommunityCollectionRows(harness.registry, "channels", [{ ...child, openerSeq: 9, openerUnread: true }], row => row.id)
projectCommunityWsEventToDb(harness.queryClient, { type: "community:channel.update", channelId: "child", serverId: "server", changes: { name: "Newer child" } })
- publishAccountAttentionSnapshot(harness.queryClient, { snapshot, proof: { token, signal: undefined } })
+ await publishAccountAttentionSnapshot(harness.queryClient, { snapshot, proof: { token, signal: undefined } })
expect(harness.registry.collections.channels.get("child")).toMatchObject({ name: "Newer child", openerSeq: 9, openerUnread: true })
} finally { harness.dispose() }
})
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index f82ea4cdd..b3c26d083 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -290,7 +290,7 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>
"/api/community/users/me/marks",
signal ? { signal } : undefined, publicationToken,
))
- publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.marked.map(row => ({ id: row.m.id, channelId: row.channelId })))
+ await publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.marked.map(row => ({ id: row.m.id, channelId: row.channelId })))
return { marked: data.marked.map((row) => ({ ...row, m: { id: row.m.id } })) }
}
diff --git a/src/web/src/hooks/community/use-message-unread-count.dom.test.ts b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
index 1deee1e20..a5e0dd876 100644
--- a/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
+++ b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
@@ -21,7 +21,7 @@ it("projects admitted local progress without changing the frozen entry boundary
await waitFor(() => expect(rendered.result.current).toBe(1))
expect(owner.registry.collections.readStates.get("c1")).toBeUndefined()
expect(entry.lastReadSeq).toBe(2)
- await act(async () => { publishCommunityConversationReadState(owner.client, { channelId: "c1", lastReadMessageId: "m9", lastReadAt: messages[2]!.createdAt, lastReadSeq: 9 }, 1, { token: captureCommunityLiveSnapshotToken(owner.client) }) })
+ await act(async () => { await publishCommunityConversationReadState(owner.client, { channelId: "c1", lastReadMessageId: "m9", lastReadAt: messages[2]!.createdAt, lastReadSeq: 9 }, 1, { token: captureCommunityLiveSnapshotToken(owner.client) }) })
await waitFor(() => expect(rendered.result.current).toBe(0))
confirmReadSurface(lease, 9)
releaseReadSurface(lease)
diff --git a/src/web/src/hooks/community/use-message.dom.test.ts b/src/web/src/hooks/community/use-message.dom.test.ts
index 6afb823dc..80329298c 100644
--- a/src/web/src/hooks/community/use-message.dom.test.ts
+++ b/src/web/src/hooks/community/use-message.dom.test.ts
@@ -35,7 +35,7 @@ const message = messageResourceFixture({ id: "m_1", channelId: scope.channelId,
describe("useMessage cache-first placeholder", () => {
it("returns a cached canonical list message while the exact query is pending", async () => {
- publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
client.setQueryData(communityKeys.channelMessages(scope.channelId), { pages: [{ ids: [message.id], hasMore: false }], pageParams: [{ mode: "newest" }] })
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.message).toMatchObject({ id: message.id, type: message.type, seq: message.seq, authorId: message.authorId, authorName: message.authorName, content: message.content, createdAt: message.createdAt }))
@@ -44,7 +44,7 @@ describe("useMessage cache-first placeholder", () => {
})
it.each(["body", "profile"] as const)("repairs a fresh cached ID with its native %s missing through the same query", async missing => {
- publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
client.setQueryData(communityKeys.message(message.id), message.id)
if (missing === "body") await writeCommunityCollectionRows(registry, "messages", [], row => row.id)
else await writeCommunityCollectionRows(registry, "profiles", [], row => row.id)
@@ -72,7 +72,7 @@ describe("useMessage cache-first placeholder", () => {
it("uses canonical identity exclusively when the DB provider is active", async () => {
client.setQueryData(communityKeys.message(message.id), { ...message, authorId: "raw", content: "raw query" })
- publishCommunityMessages(client, { channelId: scope.channelId, messages: [{ ...message, authorId: "canonical", authorName: "Canonical", content: "canonical row" }], profiles: messageProfilesFixture([{ ...message, authorId: "canonical", authorName: "Canonical" }]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { channelId: scope.channelId, messages: [{ ...message, authorId: "canonical", authorName: "Canonical", content: "canonical row" }], profiles: messageProfilesFixture([{ ...message, authorId: "canonical", authorName: "Canonical" }]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.message).toMatchObject({ authorId: "canonical", content: "canonical row" }))
})
@@ -86,7 +86,7 @@ describe("useMessage cache-first placeholder", () => {
})
it.each(["current", "retired"] as const)("observes a %s native server retirement without copying access state", async lifetime => {
- publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
client.setQueryData(communityKeys.message(message.id), message.id)
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.message?.id).toBe(message.id))
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 51317cb86..62f3ad1ce 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -69,7 +69,7 @@ export const messageQueryFn = (
const message = read.message
const publishChannelId = message.channelId ?? channelId
if (publishChannelId) {
- publishCommunityMessages(queryClient, {
+ await publishCommunityMessages(queryClient, {
channelId: publishChannelId,
messages: [message],
profiles: read.profiles,
@@ -119,7 +119,7 @@ export async function prefetchCommunityLatestMessage(queryClient: QueryClient, c
`/api/community/channels/${channelId}/messages?limit=1`,
{ signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
)
- publishCommunityMessages(queryClient, { channelId, messages: page.messages, profiles: page.profiles, proof: { token, signal: readSignal } })
+ await publishCommunityMessages(queryClient, { channelId, messages: page.messages, profiles: page.profiles, proof: { token, signal: readSignal } })
return page.messages[0]?.id ?? null
}),
select: undefined,
diff --git a/src/web/src/hooks/community/use-notification-settings.dom.test.ts b/src/web/src/hooks/community/use-notification-settings.dom.test.ts
index 243db6986..2c42f3795 100644
--- a/src/web/src/hooks/community/use-notification-settings.dom.test.ts
+++ b/src/web/src/hooks/community/use-notification-settings.dom.test.ts
@@ -93,7 +93,7 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
const disposeRegistry = registry.cleanup.bind(registry)
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- publishCommunityLiveSnapshot(queryClient, {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: {
kind: "notification-settings",
data: {
diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.ts
index 44e05fadf..49a480a4d 100644
--- a/src/web/src/hooks/community/use-notification-settings.ts
+++ b/src/web/src/hooks/community/use-notification-settings.ts
@@ -88,7 +88,7 @@ export const notificationSettingsQueryFn = async (
}
const data = { raw: rows, server, channel }
if (context.client && publicationToken) {
- publishCommunityLiveSnapshot(context.client, {
+ await publishCommunityLiveSnapshot(context.client, {
snapshot: { kind: "notification-settings", data },
proof: { kind: "structural", token: publicationToken, signal: context.signal },
})
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index a7dd5d84f..def05e955 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -265,8 +265,8 @@ export const membersPageQueryFn = (serverId: string, search = "", limit?: number
const data = parseCommunityServerMembersRead(await apiFetch<unknown>(path, communityRequestOptions(client, token, signal, assert)), serverId, registry.accountId!, !!search)
assert()
if (data.hasMore && !data.cursor) throw new Error("members page missing cursor")
- writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member)), registry, { snapshot: profileSnapshot })
- publishCommunityMembersSnapshot(client, serverId, data.members, { token, signal })
+ await writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member)), registry, { snapshot: profileSnapshot })
+ await publishCommunityMembersSnapshot(client, serverId, data.members, { token, signal })
assert()
return { members: data.members.map(({ id, userId }) => ({ id, userId })), hasMore: data.hasMore, cursor: data.cursor, limit: data.limit, ...("total" in data ? { total: data.total } : {}), liveRevision: protocol.liveRevision }
}
diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.ts
index 5419789e2..b6620186f 100644
--- a/src/web/src/hooks/community/use-servers.dom.test.ts
+++ b/src/web/src/hooks/community/use-servers.dom.test.ts
@@ -33,16 +33,16 @@ const canonical = (id = "srv_1") => serverRailResponseFixture({ servers: [{ ...i
function publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) {
return publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
}
-function seedList(servers: ServersResponse["servers"] = [canonical()]) {
- publish({ kind: "servers", data: serverRailResponseFixture({ servers }, "viewer") })
+async function seedList(servers: ServersResponse["servers"] = [canonical()]) {
+ await publish({ kind: "servers", data: serverRailResponseFixture({ servers }, "viewer") })
client.setQueryData(communityKeys.servers(), servers.map((server) => server.id))
}
-function seedDetail(channels: ServerDetail["categories"][number]["channels"] = []) {
- seedList()
- publish({ kind: "server-detail", data: serverDirectoryFixture({ ...identity, categories: [{ id: "cat_1", name: "Main", private: false, channels }] }) })
+async function seedDetail(channels: ServerDetail["categories"][number]["channels"] = []) {
+ await seedList()
+ await publish({ kind: "server-detail", data: serverDirectoryFixture({ ...identity, categories: [{ id: "cat_1", name: "Main", private: false, channels }] }) })
}
-function attention(channelId: string, count = 1, parentChannelId: string | null = null) {
- publishAccountAttentionSnapshot(client, {
+async function attention(channelId: string, count = 1, parentChannelId: string | null = null) {
+ await publishAccountAttentionSnapshot(client, {
snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], parentChannelId
? [channelResourceFixture({ id: parentChannelId, serverId: identity.id, type: "forum" }), channelResourceFixture({ id: channelId, serverId: identity.id, type: "thread", parentChannelId, parentMessageId: `opener-${channelId}` })]
: [(registry.collections.channels.get(channelId) ? CommunityChannelResourceSchema.strip().parse(registry.collections.channels.get(channelId)) : channelResourceFixture({ id: channelId, serverId: identity.id }))]), scopes: [{ scopeId: channelId, channelId, serverId: identity.id, parentChannelId, ordinaryUnread: true, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: count }], items: [], limit: 100, truncated: false },
@@ -116,7 +116,7 @@ describe("useServers / serversQueryFn", () => {
const rendered = renderHook(() => useServers(), { wrapper: Owner })
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
- act(() => registry.runtime.ws.actions.activateProfileAccount("replacement"))
+ await act(() => registry.runtime.ws.actions.activateProfileAccount("replacement"))
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(false))
rendered.unmount()
const other = new QueryClient({ defaultOptions: { queries: { retry: false } } })
@@ -133,7 +133,7 @@ describe("useServers / serversQueryFn", () => {
apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [] }, "viewer"))
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
- act(() => registry.runtime.ws.actions.revokeServerAccess("s1"))
+ await act(() => registry.runtime.ws.actions.revokeServerAccess("s1"))
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(false))
})
@@ -143,15 +143,15 @@ describe("useServers / serversQueryFn", () => {
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
expect(rendered.result.current.servers.map((server) => server.id)).toEqual(servers.map((server) => server.id))
- act(() => client.setQueryData(communityKeys.servers(), [...servers.map((server) => server.id)].reverse()))
+ await act(() => client.setQueryData(communityKeys.servers(), [...servers.map((server) => server.id)].reverse()))
expect(rendered.result.current.isLiveAuthoritative).toBe(true)
- act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: servers.slice(0, 6) }, "viewer") }))
+ await act(async () => await publish({ kind: "servers", data: serverRailResponseFixture({ servers: servers.slice(0, 6) }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(6))
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers }, "viewer"))
await act(async () => { await rendered.result.current.refetch() })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
- act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: [...servers, canonical("s8")] }, "viewer") }))
+ await act(async () => await publish({ kind: "servers", data: serverRailResponseFixture({ servers: [...servers, canonical("s8")] }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(8))
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
})
@@ -164,14 +164,14 @@ describe("useServers / serversQueryFn", () => {
})
it("does not let the legacy unread ledger override canonical attention", async () => {
- seedList([canonical(), { ...canonical("s2"), unread: true, mentions: 2 }, { ...canonical("s3"), unread: true }])
+ await seedList([canonical(), { ...canonical("s2"), unread: true, mentions: 2 }, { ...canonical("s3"), unread: true }])
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(3))
expect(rendered.result.current.servers.map(({ unread, mentions }) => ({ unread, mentions }))).toEqual(Array.from({ length: 3 }, () => ({ unread: false, mentions: 0 })))
})
it("projects live mention-source evidence onto canonical rail rows", async () => {
- seedList(); attention("c1")
+ await seedList(); await attention("c1")
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers[0]).toMatchObject({ id: identity.id, unread: true, mentions: 1 }))
})
@@ -186,27 +186,27 @@ describe("useServers / serversQueryFn", () => {
})
it("does not retain a legacy rail unread without canonical attention", async () => {
- seedList([{ ...canonical(), unread: true }])
+ await seedList([{ ...canonical(), unread: true }])
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
- act(() => seedList())
+ await act(async () => await seedList())
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
})
it("keeps legacy rail source transitions subordinate to canonical attention", async () => {
- seedList([{ ...canonical(), unread: true }])
+ await seedList([{ ...canonical(), unread: true }])
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
- act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: [{ ...canonical(), unread: true, unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }] }] }, "viewer") }))
+ await act(async () => await publish({ kind: "servers", data: serverRailResponseFixture({ servers: [{ ...canonical(), unread: true, unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }] }] }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
- act(() => publish({ kind: "read-state", data: { revision: 1, readStates: [{ channelId: "c1", lastReadMessageId: "m4", lastReadAt: null, lastReadSeq: 4 }] } }))
+ await act(async () => await publish({ kind: "read-state", data: { revision: 1, readStates: [{ channelId: "c1", lastReadMessageId: "m4", lastReadAt: null, lastReadSeq: 4 }] } }))
expect(rendered.result.current.servers[0]?.unread).toBe(false)
})
})
describe("useServer / projected canonical detail", () => {
it.each(["denial", "membership"] as const)("restarts a directory read superseded by channel %s without losing the server", async change => {
- seedList()
+ await seedList()
let release!: () => void
const response = new Promise<void>(resolve => { release = resolve })
let initial = true
@@ -234,7 +234,7 @@ describe("useServer / projected canonical detail", () => {
})
it.each(["account", "owner"])("rechecks %s ownership after structural retirement rejects and before the hook restarts", async retirement => {
- seedList()
+ await seedList()
let release!: () => void
const response = new Promise<void>(resolve => { release = resolve })
apiFetchMock.mockImplementation(async (url: string) => { await response; return detailApi(url) })
@@ -259,7 +259,7 @@ describe("useServer / projected canonical detail", () => {
})
it.each(["target", "account", "signal", "generic-abort"])("does not restart a current detail read after %s retirement", async retirement => {
- seedList()
+ await seedList()
let release!: () => void
const response = new Promise<void>(resolve => { release = resolve })
apiFetchMock.mockImplementation(async (url: string) => {
@@ -282,7 +282,7 @@ describe("useServer / projected canonical detail", () => {
})
it("retains a current server deadline failure across another native consumer and recovers on explicit retry", async () => {
- seedList()
+ await seedList()
const key = communityKeys.server(identity.id)
client.setQueryDefaults(key, { retry: 1, retryDelay: 0 })
let categorySignal!: AbortSignal
@@ -321,7 +321,7 @@ describe("useServer / projected canonical detail", () => {
})
it.each([403, 404])("hides retained server detail after a definitive %s", async (status) => {
- seedDetail()
+ await seedDetail()
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server?.id).toBe(identity.id))
apiFetchMock.mockRejectedValue(new ApiError("denied", status))
@@ -338,14 +338,14 @@ describe("useServer / projected canonical detail", () => {
})
it("executes the enabled hook query through the projected detail adapter", async () => {
- seedList(); apiFetchMock.mockImplementation(detailApi)
+ await seedList(); apiFetchMock.mockImplementation(detailApi)
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server).toMatchObject({ ...identity, categories: [{ id: "cat_1", channels: [] }] }))
expect(client.getQueryData(communityKeys.server(identity.id))).toMatchObject({ serverId: identity.id })
})
it.each([["offline", new Error("offline")], ["5xx", new ApiError("unavailable", 503)]])("keeps the cached server list on a transient %s failure", async (_label, error) => {
- seedDetail(); apiFetchMock.mockRejectedValue(error)
+ await seedDetail(); apiFetchMock.mockRejectedValue(error)
await expect(fetchDetail()).rejects.toBe(error)
expect(client.getQueryData(communityKeys.servers())).toEqual([identity.id])
expect(registry.collections.servers.get(identity.id)).toMatchObject(identity)
@@ -353,7 +353,7 @@ describe("useServer / projected canonical detail", () => {
})
it.each([403, 404])("evicts live and persisted server state on definitive %s", async (status) => {
- seedDetail([{ id: "c1", name: "General", active: false, unread: false }])
+ await seedDetail([{ id: "c1", name: "General", active: false, unread: false }])
apiFetchMock.mockRejectedValue(new ApiError("denied", status))
await expect(fetchDetail()).rejects.toBeInstanceOf(CancelledError)
expect(client.getQueryState(communityKeys.server(identity.id))).toBeUndefined()
@@ -364,36 +364,36 @@ describe("useServer / projected canonical detail", () => {
})
it("does not merge stale positives from the retired server unread endpoint", async () => {
- seedList(); apiFetchMock.mockImplementation((url: string) => url.endsWith("/unreads") ? { channelIds: ["c1"], sources: [{ channelId: "c1", lastUnreadSeq: 3 }], stale: true } : detailApi(url))
+ await seedList(); apiFetchMock.mockImplementation((url: string) => url.endsWith("/unreads") ? { channelIds: ["c1"], sources: [{ channelId: "c1", lastUnreadSeq: 3 }], stale: true } : detailApi(url))
await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
it("projects child scope metadata and confirms every loaded channel", async () => {
- seedList()
+ await seedList()
apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1" }].map(row => channelResourceFixture({ ...row, serverId: identity.id })) } : detailApi(url))
await fetchDetail()
expect(registry.collections.channels.get("forum_1")).toMatchObject({ serverId: identity.id, type: "forum" })
})
it("projects server-detail channels from canonical sources only", async () => {
- seedDetail([{ id: "c1", name: "One", active: false, unread: false }, { id: "c2", name: "Two", active: false, unread: true }]); attention("c1")
+ await seedDetail([{ id: "c1", name: "One", active: false, unread: false }, { id: "c2", name: "Two", active: false, unread: true }]); await attention("c1")
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map((channel) => channel.unread)).toEqual([true, false]))
const currentWindow = client.getQueryData(communityKeys.server(identity.id))
- act(() => client.setQueryData(communityKeys.server(identity.id), { id: identity.id, categories: [{ channels: [{ id: "raw", unread: true }] }] }))
+ await act(() => client.setQueryData(communityKeys.server(identity.id), { id: identity.id, categories: [{ channels: [{ id: "raw", unread: true }] }] }))
expect(registry.collections.channels.has("raw")).toBe(false)
expect(registry.collections.channels.has("c1")).toBe(true)
expect(registry.collections.channels.has("c2")).toBe(true)
- act(() => client.setQueryData(communityKeys.server(identity.id), currentWindow))
+ await act(() => client.setQueryData(communityKeys.server(identity.id), currentWindow))
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map(channel => channel.id)).toEqual(["c1", "c2"]))
})
it("does not retain rolling-deploy server-detail unread without canonical attention", async () => {
- seedDetail([{ id: "c1", name: "One", active: false, unread: true }, { id: "forum-base", name: "Base", type: "forum", active: false, unread: true }, { id: "forum-child", name: "Child", type: "forum", active: false, unread: true }])
+ await seedDetail([{ id: "c1", name: "One", active: false, unread: true }, { id: "forum-base", name: "Base", type: "forum", active: false, unread: true }, { id: "forum-child", name: "Child", type: "forum", active: false, unread: true }])
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map((channel) => channel.unread)).toEqual([false, false, false]))
- act(() => seedDetail([{ id: "c1", name: "One", active: false, unread: false }]))
+ await act(async () => await seedDetail([{ id: "c1", name: "One", active: false, unread: false }]))
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map((channel) => channel.unread)).toEqual([false]))
})
@@ -411,7 +411,7 @@ describe("useServer / projected canonical detail", () => {
})
it("passes the navigation AbortSignal to every server-detail resource", async () => {
- seedList()
+ await seedList()
apiFetchMock.mockImplementation(() => new Promise(() => {}))
const controller = new AbortController()
const result = serverProjectedQueryFn(client, identity.id, controller.signal)()
@@ -427,7 +427,7 @@ describe("useServer / projected canonical detail", () => {
})
it("resolves warm canonical detail without joining an in-flight rail replacement", async () => {
- seedList()
+ await seedList()
let release!: (value: { servers: typeof identity[] }) => void
apiFetchMock.mockImplementation((url: string) => url === "/api/community/servers" ? new Promise((resolve) => { release = resolve }) : Promise.resolve(detailApi(url)))
const rail = fetchList()
@@ -453,7 +453,7 @@ describe("useServer / projected canonical detail", () => {
})
it("reads warm server identity without issuing another list request", async () => {
- seedList(); apiFetchMock.mockImplementation(detailApi)
+ await seedList(); apiFetchMock.mockImplementation(detailApi)
await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(0)
expect(apiFetchMock).toHaveBeenCalledTimes(2)
@@ -495,7 +495,7 @@ function deferred<T>() {
describe("qualified viewer server role", () => {
it.each([false, true])("admits an authoritative owner role with newer forum-presence confirmation=%s", async confirmed => {
const entry = forumConversationEntryFixture("forum", identity.id)
- publishAccountAttentionSnapshot(client, {
+ await publishAccountAttentionSnapshot(client, {
snapshot: { resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], [entry.channel]), scopes: [], items: [], limit: 100, truncated: false, included: {
servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],
channels: [AttentionIncludedChannelSchema.strip().parse(entry.channel)], dms: [], profiles: [], messages: [],
@@ -514,13 +514,13 @@ describe("qualified viewer server role", () => {
})
it("keeps a newer role demotion while admitting an older owner response", async () => {
- seedList([{ ...canonical(), isOwner: true, role: "owner", memberId: "own-member" }])
+ await seedList([{ ...canonical(), isOwner: true, role: "owner", memberId: "own-member" }])
const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()
apiFetchMock.mockReturnValue(held.promise)
let request!: ReturnType<typeof fetchList>
await act(async () => { request = fetchList() })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))
- act(() => projectCommunityWsEventToDb(client, {
+ await act(() => projectCommunityWsEventToDb(client, {
type: "community:member.update", serverId: identity.id, memberId: "own-member", userId: "viewer", changes: { role: "member" },
}))
await act(async () => {
@@ -534,7 +534,7 @@ describe("qualified viewer server role", () => {
it("keeps confirmed membership when an older server list omits it", async () => {
const entry = forumConversationEntryFixture("forum", identity.id)
- publishAccountAttentionSnapshot(client, {
+ await publishAccountAttentionSnapshot(client, {
snapshot: { resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], [entry.channel]), scopes: [], items: [], limit: 100, truncated: false, included: {
servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],
channels: [AttentionIncludedChannelSchema.strip().parse(entry.channel)], dms: [], profiles: [], messages: [],
@@ -557,9 +557,9 @@ describe("qualified viewer server role", () => {
const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
await waitFor(() => expect(view.result.current).toBe("admin"))
expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/community/servers"])
- act(() => publishCommunityChannelDirectory(client, { resources: resourceBundleFixture({ viewerId: "viewer", servers: [serverResourceFixture(identity)], serverMemberships: [{ serverId: identity.id, userId: "viewer", memberId: "own-member", role: "admin" }] }), directory: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator, channels: [] }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } }))
+ await act(async () => await publishCommunityChannelDirectory(client, { resources: resourceBundleFixture({ viewerId: "viewer", servers: [serverResourceFixture(identity)], serverMemberships: [{ serverId: identity.id, userId: "viewer", memberId: "own-member", role: "admin" }] }), directory: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator, channels: [] }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } }))
expect(registry.collections.serverMemberships.get("srv_1:viewer")).toMatchObject({ role: "admin", memberId: "own-member" })
- act(() => projectCommunityWsEventToDb(client, { type: "community:member.update", serverId: identity.id, memberId: "own-member", changes: { role: "member" } }))
+ await act(() => projectCommunityWsEventToDb(client, { type: "community:member.update", serverId: identity.id, memberId: "own-member", changes: { role: "member" } }))
await waitFor(() => expect(view.result.current).toBe("member"))
view.unmount()
})
@@ -569,13 +569,13 @@ describe("qualified viewer server role", () => {
await fetchList()
const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
await waitFor(() => expect(view.result.current).toBe("admin"))
- act(() => registry.runtime.ws.actions.revokeChannelAccess("other-server", "other-channel"))
+ await act(() => registry.runtime.ws.actions.revokeChannelAccess("other-server", "other-channel"))
expect(view.result.current).toBe("admin")
view.unmount()
})
it("does not authorize a restored role, a revoked server or another viewer", async () => {
- seedList()
+ await seedList()
const restoredMembership = registry.collections.serverMemberships.get("srv_1:viewer")!
await registry.collections.serverMemberships.utils.writeUpsert([{ id: restoredMembership.id, serverId: restoredMembership.serverId,
userId: restoredMembership.userId, memberId: restoredMembership.memberId, role: "admin", viewer: true }])
@@ -588,7 +588,7 @@ describe("qualified viewer server role", () => {
view.rerender({ viewerId: "other-account" })
expect(view.result.current).toBeUndefined()
view.rerender({ viewerId: "viewer" })
- act(() => registry.runtime.ws.actions.revokeServerAccess(identity.id))
+ await act(() => registry.runtime.ws.actions.revokeServerAccess(identity.id))
expect(view.result.current).toBeUndefined()
view.unmount()
})
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index c21e1f427..bbaf57386 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -109,7 +109,7 @@ export const serversProjectedQueryFn = (
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, context?.signal)
const data = await serversQueryFn(context)
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, context?.signal)
- publishCommunityLiveSnapshot(queryClient, {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "servers", data },
proof: { kind: "structural", token: structuralToken, signal: context?.signal },
})
@@ -287,7 +287,7 @@ export const serverProjectedQueryFn = (
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, readSignal)
const data = await serverQueryFn(queryClient, serverId, readSignal)()
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, readSignal)
- publishCommunityLiveSnapshot(queryClient, {
+ await publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "server-detail", data },
proof: { kind: "structural", token: structuralToken, signal: readSignal },
})
diff --git a/src/web/src/hooks/community/use-thread-participants.dom.test.ts b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
index 16ed9a5a5..21fd606aa 100644
--- a/src/web/src/hooks/community/use-thread-participants.dom.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
@@ -30,14 +30,14 @@ afterEach(async () => {
function Owner({ children }: PropsWithChildren) {
return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children))
}
-function seedSidebar(parentType: "forum" | "text" = "forum") {
+async function seedSidebar(parentType: "forum" | "text" = "forum") {
ingestServerDetail(registry, serverDirectoryFixture({ id: "server_1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer_1", categories: [{ id: "category", name: "Channels", channels: [{ id: "forum_1", name: "Forum", type: parentType, active: false, unread: false }] }] }))
const key = communityKeys.forumSidebarThreads("server_1")
const now = new Date().toISOString()
const parent = channelResourceFixture({ id: "forum_1", serverId: "server_1", type: parentType })
const child = channelResourceFixture({ id: "post_1", serverId: "server_1", type: "thread", name: "Post", parentChannelId: parent.id, parentMessageId: "opener_1", lastMessageAt: now })
const opener = messageResourceFixture({ id: "opener_1", channelId: parent.id, authorId: "viewer_1", content: "Post" })
- publishCommunityForumSidebar(client, {
+ await publishCommunityForumSidebar(client, {
serverId: "server_1", resources: fullResourceBundleFixture("viewer_1", [serverResourceFixture({ id: "server_1", ownerId: "viewer_1" })], [parent, child], [opener]),
channels: [{ ...child, activityAt: now, unread: false, participating: true }], openers: [opener],
proof: { token: captureCommunityLiveSnapshotToken(client) },
@@ -56,7 +56,7 @@ async function command<T>(run: () => Promise<T>) {
}
describe("useRemoveThreadParticipant", () => {
it.each(["forum", "text"] as const)("removes the %s child from every sidebar view when the viewer leaves", async (parentType) => {
- seedSidebar(parentType)
+ await seedSidebar(parentType)
const metaKey = communityKeys.channelMeta("server_1", "post_1")
client.setQueryData(metaKey, { id: "post_1", parentChannelId: "forum_1" })
@@ -72,7 +72,7 @@ describe("useRemoveThreadParticipant", () => {
})
it("does not retire viewer unread scope when participant removal fails", async () => {
- seedSidebar()
+ await seedSidebar()
seedCommunityAttentionScope(client, { channelId: "post_1", serverId: "server_1", seq: 7 })
apiFetchMock.mockRejectedValueOnce(new Error("failed"))
@@ -84,7 +84,7 @@ describe("useRemoveThreadParticipant", () => {
})
it("keeps the viewer's sidebar row when the creator removes someone else", async () => {
- seedSidebar()
+ await seedSidebar()
seedCommunityAttentionScope(client, { channelId: "post_1", serverId: "server_1", seq: 7 })
const rendered = renderHook(() => useRemoveThreadParticipant("post_1", "server_1", "viewer_1"), { wrapper: Owner })
@@ -94,7 +94,7 @@ describe("useRemoveThreadParticipant", () => {
})
it("does not revalidate the viewer's forum access when adding someone else", async () => {
- const key = seedSidebar()
+ const key = await seedSidebar()
const rendered = renderHook(() => useAddThreadParticipant("post_1", "server_1", "viewer_1"), { wrapper: Owner })
await command(() => rendered.result.current.mutateAsync("other_1"))
expect(client.getQueryState(key)?.isInvalidated).toBe(false)
@@ -113,7 +113,7 @@ describe("useRemoveThreadParticipant", () => {
})
it("does not touch forum sidebar resources for an ordinary text thread", async () => {
- const baseKey = seedSidebar(), retainedKey = communityKeys.forumSidebarRetained("server_1", "forum_post")
+ const baseKey = await seedSidebar(), retainedKey = communityKeys.forumSidebarRetained("server_1", "forum_post")
const metaKey = communityKeys.channelMeta("server_1", "text_thread"), hintKey = communityKeys.forumOpenerHint("server_1", "opener_1")
client.setQueryData(retainedKey, { id: "forum_post" })
client.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" })
diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.ts
index 40f14006f..96c6a6a02 100644
--- a/src/web/src/hooks/community/use-thread-participants.ts
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -1,6 +1,7 @@
"use client"
import { useQueryClient } from "@tanstack/react-query"
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { useChannelMemberCommand } from "./use-channel-members"
import { grantForumSidebarChild, removeForumSidebarProjectionExact } from "./use-forum-sidebar-threads"
@@ -13,8 +14,8 @@ export function useAddThreadParticipant(channelId: string, serverId?: string, vi
export function useRemoveThreadParticipant(channelId: string, serverId?: string, viewerUserId?: string, forumSidebar = !!serverId) {
const client = useQueryClient()
- return useChannelMemberCommand(channelId, "remove", { endpoint: "participants", relation: "notify", onConfirmed: (userId) => {
+ return useChannelMemberCommand(channelId, "remove", { endpoint: "participants", relation: "notify", onConfirmed: async (userId) => {
if (userId !== viewerUserId) return
- if (serverId && forumSidebar) { removeForumSidebarProjectionExact(client, serverId, channelId) }
+ if (serverId && forumSidebar) await completeCommunityPublication(client, () => removeForumSidebarProjectionExact(client, serverId, channelId))
} })
}
diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.ts
index b7f2fa0ec..d3ecd3953 100644
--- a/src/web/src/hooks/community/use-user-profile.ts
+++ b/src/web/src/hooks/community/use-user-profile.ts
@@ -55,7 +55,7 @@ export const userProfileQueryFn = (userId: string) => async (context: QueryFunct
} catch (error) {
if (error instanceof ApiError && error.status === 404 && registry && presence) {
assertCommunityLiveSnapshotTokenCurrent(context.client, token, context.signal)
- if ((registry.runtime.ws.get().presenceRevisionsByUserId.get(userId) ?? 0) <= presence.revision) retireCommunityProfile(userId, registry, token.profileSnapshot)
+ if ((registry.runtime.ws.get().presenceRevisionsByUserId.get(userId) ?? 0) <= presence.revision) await retireCommunityProfile(userId, registry, token.profileSnapshot)
}
throw error
}
diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.ts
index e30fca79b..00ecce6e6 100644
--- a/src/web/src/lib/community-db/collections.ts
+++ b/src/web/src/lib/community-db/collections.ts
@@ -9,7 +9,7 @@ import {
type InferSchemaOutput,
} from "@tanstack/react-db"
import { queryCollectionOptions } from "@tanstack/query-db-collection"
-import { writeCommunityCollectionRows } from "./write"
+import { readCommunityCollectionRow, writeCommunityCollectionChanges } from "./write"
import type { QueryClient, QueryFunctionContext } from "@tanstack/react-query"
import { createStore } from "@tanstack/store"
import { createCommunityStore } from "@/stores/community/ui-store"
@@ -118,12 +118,11 @@ function buildCommunityDbRegistry(
const runtime = {
ui: createCommunityStore(), ws: createCommunityWsStore(accountId, (patches) => {
if (!runtime.lifecycle.get().active || runtime.ws.get().profileViewerId !== accountId) return
- const rows = queryClient.getQueryData<InferSchemaOutput<typeof profileSchema>[]>(collectionQueryKey(scopeId, "profiles")) ?? [...profiles.values()]
- const next = rows.map(row => {
- const presence = patches.get(row.id)
- return presence === undefined || presence === row.presence ? row : { ...row, presence }
+ const next = [...patches].flatMap(([id, presence]) => {
+ const row = readCommunityCollectionRow(registry, "profiles", id)
+ return !row || presence === row.presence ? [] : [{ ...row, presence }]
})
- if (next.some((row, index) => row !== rows[index])) writeCommunityCollectionRows(registry, "profiles", next, row => row.id)
+ return writeCommunityCollectionChanges(registry, "profiles", next)
}), messageStream: createMessageStreamStore(() => ({ get: (id) => { const message = messages.get(id); return typeof message?.seq === "number" ? message as CanonicalMessage : undefined } }), queryClient),
serverEject: createOwnerServerDeleteStore(),
lifecycle: createStore({ active: true, generation: 0 }), transport: { send: null as ((message: object) => void) | null },
diff --git a/src/web/src/lib/community-db/directory-publication.test.ts b/src/web/src/lib/community-db/directory-publication.test.ts
new file mode 100644
index 000000000..83d1d9410
--- /dev/null
+++ b/src/web/src/lib/community-db/directory-publication.test.ts
@@ -0,0 +1,107 @@
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, expect, it, vi } from "vitest"
+import { createCommunityDbRegistry, registerCommunityDbRegistry, type CommunityDbRegistry } from "./collections"
+import { ingestMessages, ingestServerDetail, projectCommunityWsEventToDb, completeCommunityPublication } from "./sync"
+import { readCommunityCollectionRow, writeCommunityCollectionChanges } from "./write"
+import { recordServerDirectoryWindow, reconcileExistingServerDirectoryWindows } from "@/lib/community/server-directory-window"
+import { communityKeys } from "@/lib/query-keys"
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
+
+const owners: CommunityDbRegistry[] = []
+const releases: Array<() => void> = []
+afterEach(async () => {
+ releases.splice(0).forEach(release => release())
+ await Promise.all(owners.splice(0).map(owner => owner.cleanup()))
+ vi.restoreAllMocks()
+})
+async function setup() {
+ const db = createCommunityDbRegistry(new QueryClient(), "viewer")
+ owners.push(db)
+ await db.preload()
+ releases.push(registerCommunityDbRegistry(db))
+ for (const id of ["s1", "s2"]) ingestServerDetail(db, {
+ server: serverResourceFixture({ id }), categories: [],
+ channels: [channelResourceFixture({ id: `${id}-parent`, serverId: id })],
+ })
+ return db
+}
+function directoryWrites(spy: ReturnType<typeof vi.spyOn>) {
+ return spy.mock.calls.filter(([key]) => Array.isArray(key) && key.length === 3 && key[0] === "community" && key[1] === "servers").map(([key]) => (key as unknown[])[2])
+}
+
+it("batches repeated thread facts once and retains sequential optional fields without touching directories", async () => {
+ const db = await setup()
+ for (const id of ["a", "b"]) projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.create", serverId: "s1", channel: channelResourceFixture({ id, serverId: "s1", type: "thread", parentChannelId: "s1-parent", parentMessageId: `opener-${id}` }) })
+ const writes = vi.spyOn(db.collections.channels.utils, "writeBatch")
+ const cache = vi.spyOn(db.queryClient, "setQueryData")
+ const rows = [
+ messageResourceFixture({ id: "m1", channelId: "s1-parent", thread: { id: "a", name: "first", messageCount: 1, tags: ["kept"], lastReplyAt: "2026-11-01T00:00:00Z" } }),
+ messageResourceFixture({ id: "m2", channelId: "s1-parent", thread: { id: "b", name: "second", messageCount: 2 } }),
+ messageResourceFixture({ id: "m3", channelId: "s1-parent", thread: { id: "a", name: "final", messageCount: 3 } }),
+ ]
+ ingestMessages(db, "s1-parent", rows)
+ expect(db.collections.channels.get("a")).toMatchObject({ name: "final", messageCount: 3, tags: ["kept"], lastMessageAt: "2026-11-01T00:00:00Z" })
+ expect(db.collections.channels.get("b")).toMatchObject({ name: "second", messageCount: 2 })
+ expect(writes).toHaveBeenCalledTimes(1)
+ expect(directoryWrites(cache)).toEqual([])
+ writes.mockClear()
+ ingestMessages(db, "s1-parent", rows)
+ expect(writes).not.toHaveBeenCalled()
+})
+
+it("retains accepted thread fields through an unrelated optimistic overlay", async () => {
+ const db = await setup()
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.create", serverId: "s1", channel: channelResourceFixture({ id: "thread", serverId: "s1", type: "thread", parentChannelId: "s1-parent", parentMessageId: "opener" }) })
+ await writeCommunityCollectionChanges(db, "channels", [{ ...readCommunityCollectionRow(db, "channels", "thread"), tags: ["accepted"] }])
+ let release!: () => void
+ const held = new Promise<void>(resolve => { release = resolve })
+ const transaction = db.dbClient.createTransaction({ mutationFn: () => held })
+ transaction.mutate(() => db.collections.channels.update("thread", row => { row.tags = ["optimistic"] }))
+ try {
+ await completeCommunityPublication(db, () => ingestMessages(db, "s1-parent", [messageResourceFixture({ id: "message", channelId: "s1-parent", thread: { id: "thread", name: "Confirmed", messageCount: 3 } })]))
+ expect(readCommunityCollectionRow(db, "channels", "thread")).toMatchObject({ name: "Confirmed", tags: ["accepted"] })
+ } finally { release(); await transaction.when("settled") }
+ expect(db.collections.channels.get("thread")).toMatchObject({ name: "Confirmed", tags: ["accepted"] })
+})
+
+it("does not republish an unchanged ID window and preserves the existing window object", async () => {
+ const db = await setup()
+ const before = db.queryClient.getQueryData(communityKeys.server("s1"))
+ const cache = vi.spyOn(db.queryClient, "setQueryData")
+ expect(recordServerDirectoryWindow(db, "s1")).toBe(before)
+ expect(directoryWrites(cache)).toEqual([])
+})
+
+it("only publishes the directory whose top-level membership changes", async () => {
+ const db = await setup()
+ const cache = vi.spyOn(db.queryClient, "setQueryData")
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.create", serverId: "s1", channel: channelResourceFixture({ id: "new", serverId: "s1" }) })
+ expect(directoryWrites(cache)).toEqual(["s1"])
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ channelIds: ["s1-parent", "new"] })
+ cache.mockClear()
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.update", serverId: "s1", channelId: "new", changes: { name: "renamed" } })
+ expect(directoryWrites(cache)).toEqual([])
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.delete", serverId: "s1", channelId: "new" })
+ expect(directoryWrites(cache)).toEqual(["s1"])
+})
+
+it("reconciles both existing scopes when a confirmed directory row moves servers", async () => {
+ const db = await setup()
+ const cache = vi.spyOn(db.queryClient, "setQueryData")
+ ingestServerDetail(db, { server: serverResourceFixture({ id: "s2" }), categories: [], channels: [channelResourceFixture({ id: "s1-parent", serverId: "s2" })] })
+ expect(new Set(directoryWrites(cache))).toEqual(new Set(["s1", "s2"]))
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ channelIds: [] })
+ expect(db.queryClient.getQueryData(communityKeys.server("s2"))).toMatchObject({ channelIds: ["s1-parent"] })
+})
+
+it("keeps authoritative empty snapshots and does not create uncached directories during reconciliation", async () => {
+ const db = await setup()
+ const cache = vi.spyOn(db.queryClient, "setQueryData")
+ ingestServerDetail(db, { server: serverResourceFixture({ id: "s1" }), categories: [], channels: [] })
+ expect(directoryWrites(cache)).toEqual(["s1"])
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ categoryIds: [], channelIds: [] })
+ cache.mockClear()
+ reconcileExistingServerDirectoryWindows(db, new Set(["unknown"]))
+ expect(directoryWrites(cache)).toEqual([])
+ expect(db.queryClient.getQueryData(communityKeys.server("unknown"))).toBeUndefined()
+})
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 86677e9f2..d655eff11 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -30,8 +30,32 @@ import {
import { ingestMessages, ingestServerDetail, ingestServers, restoreCommunityCollections } from "./sync"
import { PERSIST_BUSTER, readCommunityRestoredCollections } from "@/lib/query-persister"
import { profileSchema } from "./schema"
+import { writeCommunityCollectionRows } from "./write"
describe("community DB projections", () => {
+ it("updates attention without rebuilding rail order or unrelated tree categories", async () => {
+ const client = new QueryClient(), registry = createCommunityDbRegistry(client, "viewer")
+ await registry.preload()
+ ingestServers(registry, serverRailResponseFixture({ servers: [{ id: "s1", name: "Server", initial: "S", active: false, unread: false, mentions: 0, ownerId: "viewer" }] }, "viewer"))
+ ingestServerDetail(registry, serverDirectoryFixture({ id: "s1", name: "Server", categories: [
+ { id: "a", name: "A", channels: [{ id: "c1", name: "One", active: false, unread: false }] },
+ { id: "b", name: "B", channels: [{ id: "c2", name: "Two", active: false, unread: false }] },
+ ] }))
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children))
+ const view = renderHook(() => ({ rail: useServerRailProjection(), tree: useServerTreeProjection("s1") }), { wrapper })
+ try {
+ await waitFor(() => expect(view.result.current.tree?.categories).toHaveLength(2))
+ const order = view.result.current.rail!.topOrder, folders = view.result.current.rail!.folders
+ const unrelated = view.result.current.tree!.categories.find(row => row.id === "b")
+ await act(async () => { await writeCommunityCollectionRows(registry, "attentionScopes", [{ scopeId: "c1", channelId: "c1", serverId: "s1", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: 1, attentionCount: 2 }], row => row.scopeId) })
+ await waitFor(() => expect(view.result.current.rail?.servers[0]).toMatchObject({ unread: true, mentions: 2 }))
+ expect(view.result.current.tree?.categories[0].channels[0].unread).toBe(true)
+ expect(view.result.current.rail!.topOrder).toBe(order)
+ expect(view.result.current.rail!.folders).toBe(folders)
+ expect(view.result.current.tree!.categories.find(row => row.id === "b")).toBe(unrelated)
+ } finally { view.unmount(); await registry.cleanup() }
+ })
+
it("preserves the real fetcher when a passive tree mounts after a read and the key is invalidated", async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const key = communityKeys.server("srv")
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index f9766b9ef..772be4164 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -13,7 +13,7 @@ import { DbProvider, and, eq, inArray, useLiveQuery as useNativeLiveQuery, type
import { createStore, useSelector } from "@tanstack/react-store"
import { CommunityRuntimeProvider } from "@/stores/community/runtime"
import { serverRailTopOrder, sortServerRailRows, notifLevelDisplay } from "@alook/shared"
-import { projectForumSidebar, supportsSidebarThreads } from "@/lib/community/forum-sidebar"
+import { projectForumSidebarStructure, applyForumSidebarAttention, projectCommunityAttention, supportsSidebarThreads } from "@/lib/community/forum-sidebar"
import { avatarInitial } from "@/lib/community/avatar"
import { readCommunityProfile } from "@/lib/community/profile-read"
import type { DM } from "@/lib/community/models/people"
@@ -135,7 +135,7 @@ export function useServerRailProjection() {
folders: useFolderRows(),
folderItems: useFolderItemRows(),
}
- return useMemo(() => {
+ const structure = useMemo(() => {
if (!rows.registry || !rows.servers || !rows.serverMemberships) return undefined
const viewerId = rows.registry.accountId
const allowed = new Set(
@@ -158,8 +158,8 @@ export function useServerRailProjection() {
ownerId: server.ownerId,
initial: avatarInitial(server.name),
active: false,
- unread: rows.attention.some(scope => scope.serverId === server.id && scope.ordinaryUnread),
- mentions: rows.attention.reduce((sum, scope) => sum + (scope.serverId === server.id ? scope.attentionCount : 0), 0),
+ unread: false,
+ mentions: 0,
official: server.official,
isOwner: server.isOwner,
icon: server.icon,
@@ -197,7 +197,17 @@ export function useServerRailProjection() {
const topOrder = serverRailTopOrder(state)
const byFolder = new Map(folders.map((folder) => [folder.id, folder]))
return { servers: sortServerRailRows(state, servers), folders: topOrder.flatMap((entry) => entry.kind === "folder" ? [byFolder.get(entry.id)!] : []), topOrder }
- }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems, rows.serverRail, rows.attention])
+ }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems, rows.serverRail])
+ return useMemo(() => {
+ if (!structure) return undefined
+ const attention = projectCommunityAttention(rows.attention)
+ const servers = structure.servers.map(server => {
+ const summary = attention.servers.get(server.id)
+ const unread = summary?.unread ?? false, mentions = summary?.mentions ?? 0
+ return unread === server.unread && mentions === server.mentions ? server : { ...server, unread, mentions }
+ })
+ return servers.every((server, index) => server === structure.servers[index]) ? structure : { ...structure, servers }
+ }, [structure, rows.attention])
}
export function useServerTreeProjection(serverId: string | null) {
@@ -216,26 +226,33 @@ export function useServerTreeProjection(serverId: string | null) {
const attention = useAttentionScopes()
const ready = servers.isReady && categories.isReady && channels.isReady
const rows = { servers: servers.data, categories: categories.data, channels: channels.data }
- return useMemo(() => {
+ const structure = useMemo(() => {
if (!ready || !serverId || !rows.servers || !rows.categories || !rows.channels) return undefined
const server = rows.servers.find((candidate) => candidate.id === serverId)
- if (!server || !registry || !directory || !serverDirectoryWindowComplete(directory, { servers: [...registry.collections.servers.base.values()], categories: [...registry.collections.categories.base.values()], channels: [...registry.collections.channels.base.values()] }, registry.accountId, serverId)) return undefined
+ if (!server || !registry || !directory || !serverDirectoryWindowComplete(directory, { servers: [registry.collections.servers.base.get(serverId)].filter(row => row !== undefined), categories: directory.categoryIds.flatMap(id => { const row = registry.collections.categories.base.get(id); return row ? [row] : [] }), channels: directory.channelIds.flatMap(id => { const row = registry.collections.channels.base.get(id); return row ? [row] : [] }) }, registry.accountId, serverId)) return undefined
+ const channelIds = new Set(directory.channelIds), categoryIds = new Set(directory.categoryIds)
const channels = rows.channels.filter((channel) => (
- channel.serverId === serverId && channel.type !== "thread" && (directory.channelIds.includes(channel.id) || channel.pending)
+ channel.serverId === serverId && channel.type !== "thread" && (channelIds.has(channel.id) || channel.pending)
))
const channelView = (channel: ChannelRow): Category["channels"][number] => ({
id: channel.id,
name: channel.name ?? "",
active: false,
- unread: attention.some((scope) => scope.serverId === serverId && (scope.channelId === channel.id || scope.parentChannelId === channel.id) && (scope.ordinaryUnread || scope.attentionCount > 0)),
+ unread: false,
muted: channel.muted,
type: channel.type === "forum" ? "forum" : "text",
tags: channel.tags,
creatorId: channel.creatorId,
pending: channel.pending,
})
+ const byCategory = new Map<string | null, ChannelRow[]>()
+ for (const channel of channels) {
+ const bucket = byCategory.get(channel.categoryId) ?? []
+ bucket.push(channel)
+ byCategory.set(channel.categoryId, bucket)
+ }
const categories: Category[] = rows.categories
- .filter((category) => category.serverId === serverId && (directory.categoryIds.includes(category.id) || category.pending))
+ .filter((category) => category.serverId === serverId && (categoryIds.has(category.id) || category.pending))
.sort((a, b) => a.position - b.position)
.map((category) => ({
id: category.id,
@@ -243,13 +260,11 @@ export function useServerTreeProjection(serverId: string | null) {
private: category.private,
creatorId: category.creatorId,
pending: category.pending,
- channels: channels
- .filter((channel) => channel.categoryId === category.id)
+ channels: (byCategory.get(category.id) ?? [])
.sort((a, b) => a.position - b.position)
.map(channelView),
}))
- const uncategorized = channels
- .filter((channel) => !channel.categoryId)
+ const uncategorized = (byCategory.get(null) ?? [])
.sort((a, b) => a.position - b.position)
.map(channelView)
if (uncategorized.length > 0) {
@@ -261,7 +276,19 @@ export function useServerTreeProjection(serverId: string | null) {
ownerId: server.ownerId, categories,
}
return view
- }, [attention, ready, rows.servers, rows.categories, rows.channels, serverId, directory, registry])
+ }, [ready, rows.servers, rows.categories, rows.channels, serverId, directory, registry])
+ return useMemo(() => {
+ if (!structure || !serverId) return undefined
+ const unread = projectCommunityAttention(attention).channels.get(serverId)
+ const categories = structure.categories.map(category => {
+ const channels = category.channels.map(channel => {
+ const value = unread?.has(channel.id) ?? false
+ return channel.unread === value ? channel : { ...channel, unread: value }
+ })
+ return channels.every((channel, index) => channel === category.channels[index]) ? category : { ...category, channels }
+ })
+ return categories.every((category, index) => category === structure.categories[index]) ? structure : { ...structure, categories }
+ }, [structure, attention, serverId])
}
export function useDmProjection() {
@@ -513,10 +540,11 @@ function useForumSidebarRows(serverId: string) {
export function useForumSidebarProjection(serverId: string, retainId: string | null, serverNowMs: number | null) {
const rows = useForumSidebarRows(serverId)
- return useMemo(() => {
+ const structure = useMemo(() => {
if (serverNowMs === null || !rows.ready || !rows.registry || !rows.channels || !rows.channelMemberships || !rows.messages) return undefined
- return projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, rows.registry.accountId, serverId, retainId, serverNowMs, rows.attention)
- }, [rows.attention, serverNowMs, rows.ready, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])
+ return projectForumSidebarStructure(rows.channels, rows.channelMemberships, rows.messages, rows.registry.accountId, serverId, retainId, serverNowMs)
+ }, [serverNowMs, rows.ready, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])
+ return useMemo(() => structure && applyForumSidebarAttention(structure, serverId, rows.attention), [structure, serverId, rows.attention])
}
export function useServerSidebarProjection(
@@ -524,16 +552,18 @@ export function useServerSidebarProjection(
) {
const server = useServerTreeProjection(serverId)
const { ready, registry, servers, channels, channelMemberships, messages, attention } = useForumSidebarRows(serverId)
- return useMemo(() => {
- if (serverNowMs === null || !ready || !registry || !servers || !channels || !channelMemberships || !messages) {
- return { server, projection: undefined, status: failed ? "error" as const : "pending" as const, needsRead: false }
- }
- const complete = !!server && (!channels.some(row => supportsSidebarThreads(row.type))
- || !!window && forumSidebarWindowComplete(window, { directory: getServerDirectoryWindow(registry, serverId), servers, channels, channelMemberships, messages }, registry.accountId, serverId, retainId, serverNowMs))
- const projection = projectForumSidebar(channels, channelMemberships, messages, registry.accountId, serverId, retainId, serverNowMs, attention)
- return { server, projection, status: complete ? "ready" as const : failed ? "error" as const : "pending" as const,
- needsRead: !!server && !!window && !complete }
- }, [attention, server, serverNowMs, ready, registry, servers, channels, channelMemberships, messages, window, serverId, retainId, failed])
+ const structure = useMemo(() => {
+ if (serverNowMs === null || !ready || !registry || !servers || !channels || !channelMemberships || !messages) return undefined
+ return projectForumSidebarStructure(channels, channelMemberships, messages, registry.accountId, serverId, retainId, serverNowMs)
+ }, [serverNowMs, ready, registry, servers, channels, channelMemberships, messages, serverId, retainId])
+ const hasServer = !!server
+ const complete = useMemo(() => !!structure && hasServer && !!registry && !!channels && !!servers && !!channelMemberships && !!messages && serverNowMs !== null
+ && (!channels.some(row => supportsSidebarThreads(row.type)) || !!window && forumSidebarWindowComplete(window,
+ { directory: getServerDirectoryWindow(registry, serverId), servers, channels, channelMemberships, messages }, registry.accountId, serverId, retainId, serverNowMs, structure.threads)),
+ [structure, hasServer, registry, channels, servers, channelMemberships, messages, window, serverId, retainId, serverNowMs])
+ const projection = useMemo(() => structure && applyForumSidebarAttention(structure, serverId, attention), [structure, serverId, attention])
+ return { server, projection, status: complete ? "ready" as const : failed ? "error" as const : "pending" as const,
+ needsRead: !!structure && hasServer && !!window && !complete }
}
export function useChannelReadStateProjection(channelId: string | null) {
diff --git a/src/web/src/lib/community-db/publication-completion.test.ts b/src/web/src/lib/community-db/publication-completion.test.ts
new file mode 100644
index 000000000..26dbd4e02
--- /dev/null
+++ b/src/web/src/lib/community-db/publication-completion.test.ts
@@ -0,0 +1,192 @@
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, expect, it, vi } from "vitest"
+import { createCommunityDbRegistry, registerCommunityDbRegistry, type CommunityDbRegistry } from "./collections"
+import { captureCommunityLiveSnapshotToken, completeCommunityPublication, patchCanonicalCommunityMessage, publishCommunityCreatedChannel, publishCommunityConversationReadState, publishCommunityChannelMembersSnapshot, ingestServerDetail } from "./sync"
+import { withCommunityCollectionWrites, writeCommunityCollectionRows, writeCommunityCollectionChanges, parseCommunityCollectionRows } from "./write"
+import { profileSchema, messageSchema, canonicalChannelRow } from "./schema"
+import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { publishConversationEntry, conversationEntryOptions } from "@/lib/community/conversation-entry"
+import { dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"
+import { profileResourceFixture, messageResourceFixture, channelResourceFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
+import { communityKeys } from "@/lib/query-keys"
+import { BusinessSchemaMismatch } from "@/lib/business-schema-lifecycle"
+
+const owners: CommunityDbRegistry[] = []
+const releases: Array<() => void> = []
+afterEach(async () => {
+ releases.splice(0).forEach(release => release())
+ await Promise.all(owners.splice(0).map(owner => owner.cleanup()))
+ vi.restoreAllMocks()
+})
+async function setup() {
+ const db = createCommunityDbRegistry(new QueryClient(), "viewer")
+ owners.push(db)
+ await db.preload()
+ releases.push(registerCommunityDbRegistry(db))
+ return db
+}
+function heldCompletion(db: CommunityDbRegistry) {
+ let resolve!: () => void, reject!: (error: Error) => void
+ const held = new Promise<void>((yes, no) => { resolve = yes; reject = no })
+ const utils = db.collections.profiles.utils
+ const write = utils.writeBatch.bind(utils)
+ vi.spyOn(utils, "writeBatch").mockImplementation(callback => write(callback).then(() => held))
+ return { resolve, reject }
+}
+
+it.each(["complete", "reject", "retire"] as const)("keeps the entry window unpublished until native completion: %s", async outcome => {
+ const db = await setup(), held = heldCompletion(db)
+ const target = { channelId: "c1", serverId: null }
+ const initial = dmConversationEntryFixture()
+ const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
+ const operation = Promise.resolve(publishConversationEntry(db.queryClient, target, initial, { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }))
+ let settled = false
+ void operation.then(() => { settled = true }, () => { settled = true })
+ await Promise.resolve()
+ expect(settled).toBe(false)
+ expect(db.queryClient.getQueryData(key)).toBeUndefined()
+ expect(db.queryClient.getQueryData(conversationEntryOptions(db.queryClient, target).queryKey)).toBeUndefined()
+ if (outcome === "reject") {
+ const error = new Error("native completion rejected")
+ held.reject(error)
+ await expect(operation).rejects.toBe(error)
+ expect(db.collections.messages.get("m1")?.content).toBe("Body")
+ expect(db.queryClient.getQueryData(key)).toBeUndefined()
+ } else if (outcome === "retire") {
+ retireCommunityAccount(db)
+ held.resolve()
+ await expect(operation).rejects.toMatchObject({ name: "AbortError" })
+ expect(db.queryClient.getQueryData(key)).toBeUndefined()
+ } else {
+ held.resolve()
+ const resource = await operation
+ expect(db.queryClient.getQueryData(resource.windowKey)).toMatchObject({ pages: [{ messages: [{ id: "m1" }] }] })
+ }
+})
+
+it("handles already-started completion rejection when synchronous publication fails", async () => {
+ const db = await setup(), held = heldCompletion(db)
+ const error = new Error("synchronous publication failed")
+ expect(() => withCommunityCollectionWrites(db, () => {
+ writeCommunityProfilePatches([{ id: "peer", identityAbout: { name: "Peer", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], db)
+ throw error
+ })).toThrow(error)
+ held.reject(new Error("native rejected after body failure"))
+ await Promise.resolve()
+ await Promise.resolve()
+})
+
+it.each([0, 1000])("validates only changed profile keys with %s unrelated profiles", async count => {
+ const db = await setup()
+ await writeCommunityCollectionRows(db, "profiles", [profileResourceFixture({ id: "peer" }), ...Array.from({ length: count }, (_, i) => profileResourceFixture({ id: `unrelated-${i}` }))], row => row.id)
+ const untouched = db.collections.profiles.get("unrelated-0")
+ const parse = vi.spyOn(profileSchema, "parse"), safeParse = vi.spyOn(profileSchema, "safeParse")
+ await writeCommunityProfilePatches([{ id: "peer", identityAbout: { name: "changed" } }], db)
+ expect(parse).toHaveBeenCalledTimes(1)
+ expect(safeParse.mock.calls.length).toBeLessThanOrEqual(2)
+ expect([...parse.mock.calls, ...safeParse.mock.calls].every(([row]) => (row as { id: string }).id === "peer")).toBe(true)
+ expect(db.collections.profiles.get("unrelated-0")).toBe(untouched)
+ expect(db.collections.profiles.get("peer")?.name).toBe("changed")
+})
+
+it.each([0, 1000])("validates a keyed message patch independently of %s unrelated messages", async count => {
+ const db = await setup()
+ await writeCommunityCollectionRows(db, "messages", [messageResourceFixture({ id: "target" }), ...Array.from({ length: count }, (_, i) => messageResourceFixture({ id: `unrelated-${i}`, channelId: "other" }))], row => row.id)
+ const parse = vi.spyOn(messageSchema, "parse"), safeParse = vi.spyOn(messageSchema, "safeParse")
+ await completeCommunityPublication(db, () => patchCanonicalCommunityMessage(db.queryClient, "target", row => ({ ...row, content: "changed" })))
+ expect(parse).toHaveBeenCalledTimes(1)
+ expect(safeParse).toHaveBeenCalledTimes(1)
+ expect([...parse.mock.calls, ...safeParse.mock.calls].every(([row]) => (row as { id: string }).id === "target")).toBe(true)
+ expect(db.collections.messages.get("target")?.content).toBe("changed")
+})
+
+it.each([false, true])("still rejects mutated parsed inputs at native or pre-ready admission: ready=%s", async ready => {
+ const db = createCommunityDbRegistry(new QueryClient(), "viewer")
+ owners.push(db)
+ if (ready) await db.preload()
+ const key = communityKeys.communityDbCollection(db.scopeId, "profiles")
+ const before = db.queryClient.getQueryData(key)
+ await expect(async () => withCommunityCollectionWrites(db, () => {
+ const [row] = parseCommunityCollectionRows(db, "profiles", [profileResourceFixture({ id: "peer" })])
+ row!.avatar = undefined as never
+ return writeCommunityCollectionChanges(db, "profiles", [row])
+ })).rejects.toThrow()
+ expect(db.queryClient.getQueryData(key)).toBe(before)
+})
+
+function heldAcceptance(db: CommunityDbRegistry, name: "profiles" | "channels" | "readStates") {
+ const utils = db.collections[name].utils
+ const write = utils.writeBatch.bind(utils)
+ const pending: Array<() => Promise<void>> = []
+ const spy = vi.spyOn(utils, "writeBatch").mockImplementation(callback => new Promise<void>((resolve, reject) => {
+ pending.push(() => write(callback).then(resolve, reject))
+ }))
+ return async () => { spy.mockRestore(); await Promise.all(pending.splice(0).map(publish => publish())) }
+}
+
+it("keeps newer message avatar hints after a profile acceptance wait", async () => {
+ const db = await setup(), release = heldAcceptance(db, "profiles")
+ const entry = dmConversationEntryFixture()
+ entry.messages = entry.messages.map(message => ({ ...message, authorAvatar: "new-avatar", authorAvatarVersion: 7 }))
+ const operation = Promise.resolve(publishConversationEntry(db.queryClient, { channelId: "c1", serverId: null }, entry, { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }))
+ try {
+ expect(db.collections.profiles.get("peer")).toBeUndefined()
+ } finally { await release() }
+ await operation
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "new-avatar", avatarVersion: 7 })
+})
+
+it("records creator membership only after the new channel is accepted", async () => {
+ const db = await setup()
+ ingestServerDetail(db, { server: serverResourceFixture({ id: "server" }), categories: [], channels: [] })
+ const release = heldAcceptance(db, "channels")
+ let settle!: () => void
+ const held = new Promise<void>(resolve => { settle = resolve })
+ const transaction = db.dbClient.createTransaction({ mutationFn: () => held })
+ transaction.mutate(() => db.collections.channels.insert(canonicalChannelRow({ ...channelResourceFixture({ id: "new", serverId: "server" }), pending: true })))
+ const operation = Promise.resolve(completeCommunityPublication(db, () => publishCommunityCreatedChannel(db.queryClient, { ...channelResourceFixture({ id: "new", serverId: "server" }), pending: false }, { token: captureCommunityLiveSnapshotToken(db.queryClient) })))
+ try {
+ expect(db.collections.channels.get("new")?.pending).toBe(true)
+ expect(db.queryClient.getQueryData(communityKeys.server("server"))).toMatchObject({ channelIds: [] })
+ await release()
+ await operation
+ expect(db.queryClient.getQueryData(communityKeys.server("server"))).toMatchObject({ channelIds: ["new"] })
+ } finally { await release(); settle(); await transaction.when("settled") }
+ expect(db.collections.channels.get("new")?.pending).toBe(false)
+ expect(db.collections.channelMemberships.get("new:viewer:access")).toMatchObject({ channelId: "new", userId: "viewer", relation: "access" })
+})
+
+it("projects confirmed attention after the read-state row is accepted", async () => {
+ const db = await setup()
+ await writeCommunityCollectionRows(db, "attentionScopes", [{ scopeId: "c1", channelId: "c1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 3, lastAttentionSeq: null, attentionCount: 0 }], row => row.scopeId)
+ const release = heldAcceptance(db, "readStates")
+ const operation = Promise.resolve(publishCommunityConversationReadState(db.queryClient, { channelId: "c1", lastReadMessageId: "m3", lastReadAt: "2026-11-01T00:00:00Z", lastReadSeq: 3 }, 1, { token: captureCommunityLiveSnapshotToken(db.queryClient) }))
+ try { expect(db.collections.attentionScopes.get("c1")?.ordinaryUnread).toBe(true) }
+ finally { await release() }
+ await operation
+ expect(db.collections.attentionScopes.has("c1")).toBe(false)
+})
+
+
+it.each(["schema", "write"] as const)("preserves the public query publication failure contract after native completion: %s", async kind => {
+ const db = await setup(), held = heldCompletion(db)
+ const invalid = profileSchema.safeParse({ id: "peer" })
+ if (invalid.success) throw new Error("Invalid canonical profile fixture was accepted")
+ const error = kind === "schema" ? invalid.error : new Error("native member profile write failed")
+ const operation = Promise.resolve(publishCommunityChannelMembersSnapshot(db.queryClient, null, "c1", "access", [
+ { channelId: "c1", userId: "peer", relation: "access", source: "added", isCreator: false, role: null, memberId: null },
+ ], { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }, [profileResourceFixture({ id: "peer", name: "Peer" })]))
+ let settled = false
+ void operation.then(() => { settled = true }, () => { settled = true })
+ await Promise.resolve()
+ expect(settled).toBe(false)
+ held.reject(error)
+ const failure = await operation.then(() => null, cause => cause)
+ if (kind === "schema") {
+ expect(failure).toBeInstanceOf(BusinessSchemaMismatch)
+ expect(failure).not.toBe(error)
+ } else expect(failure).toBe(error)
+ expect(db.collections.profiles.get("peer")?.name).toBe("Peer")
+ expect(db.runtime.lifecycle.get().active).toBe(true)
+})
diff --git a/src/web/src/lib/community-db/resources.test.ts b/src/web/src/lib/community-db/resources.test.ts
new file mode 100644
index 000000000..cadecbb16
--- /dev/null
+++ b/src/web/src/lib/community-db/resources.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { createCommunityDbRegistry } from "./collections"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { messageResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
+import { getCanonicalCommunityMessageResources, getCanonicalCommunityMessages } from "./sync"
+import { messageSchema, profileSchema } from "./schema"
+import { writeCommunityCollectionRows } from "./write"
+
+describe("canonical message resource reads", () => {
+ it("validates the canonical schema before admitting profiles from a pre-ready snapshot", async () => {
+ const client = new QueryClient()
+ const registry = createCommunityDbRegistry(client, "viewer")
+ try {
+ const key = communityKeys.communityDbCollection("viewer", "profiles")
+ const profile = profileResourceFixture()
+ client.setQueryData(key, [{ ...profile, unknownBusinessField: true }])
+ expect(getCanonicalCommunityMessageResources(client, [messageResourceFixture()])).toBeUndefined()
+ client.setQueryData(key, [profile])
+ expect(getCanonicalCommunityMessageResources(client, [messageResourceFixture()])?.profiles).toEqual([profile])
+ } finally { await registry.cleanup(); client.clear() }
+ })
+
+ it("reads and validates only the requested channel across accepted snapshot changes", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const messages = Array.from({ length: 1000 }, (_, index) => messageResourceFixture({ id: `outside-${index}`, channelId: "other" }))
+ messages.push(messageResourceFixture())
+ await writeCommunityCollectionRows(registry, "messages", messages, row => row.id)
+ const parse = vi.spyOn(messageSchema, "safeParse")
+ try {
+ const first = getCanonicalCommunityMessages(client, "c1")
+ expect(parse).toHaveBeenCalledTimes(1)
+ expect(first.map(row => row.id)).toEqual(["m1"])
+ parse.mockClear()
+ expect(getCanonicalCommunityMessages(client, "c1")).toEqual(first)
+ await writeCommunityCollectionRows(registry, "messages", [...messages, messageResourceFixture({ id: "another", channelId: "other" })], row => row.id)
+ expect(getCanonicalCommunityMessages(client, "c1")).toEqual(first)
+ expect(parse).not.toHaveBeenCalled()
+ } finally { parse.mockRestore() }
+ })
+
+ it("keeps coverage on accepted rows while a real optimistic message transaction is pending", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const message = messageResourceFixture()
+ await writeCommunityCollectionRows(registry, "messages", [message], row => row.id)
+ let release!: () => void
+ const pending = new Promise<void>(done => { release = done })
+ const transaction = registry.dbClient.createTransaction({ mutationFn: () => pending })
+ transaction.mutate(() => registry.collections.messages.update(message.id, row => { row.content = "Optimistic" }))
+ try {
+ expect(registry.collections.messages.get(message.id)?.content).toBe("Optimistic")
+ expect(getCanonicalCommunityMessages(client, "c1")[0]?.content).toBe(message.content)
+ await writeCommunityCollectionRows(registry, "messages", [{ ...message, content: "Confirmed" }], row => row.id)
+ expect(getCanonicalCommunityMessages(client, "c1")[0]?.content).toBe("Confirmed")
+ } finally {
+ release()
+ await transaction.when("settled")
+ }
+ })
+
+ it("limits profile validation to the message graph as unrelated profiles grow", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const profiles = Array.from({ length: 1000 }, (_, index) => profileResourceFixture({ id: `unrelated-${index}` }))
+ profiles.push(profileResourceFixture({ id: "author" }))
+ await writeCommunityCollectionRows(registry, "profiles", profiles, row => row.id)
+ await writeCommunityCollectionRows(registry, "messages", [messageResourceFixture({ authorId: "author" })], row => row.id)
+ const parse = vi.spyOn(profileSchema, "safeParse")
+ try {
+ expect(getCanonicalCommunityMessageResources(client, [registry.collections.messages.get("m1")], {})?.profiles).toHaveLength(1)
+ expect(parse).not.toHaveBeenCalled()
+ } finally { parse.mockRestore() }
+ })
+
+ it("reuses one window graph and does not parse unrelated account profiles", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const profiles = Array.from({ length: 1000 }, (_, index) => profileResourceFixture({ id: `unrelated-${index}` }))
+ profiles.push(profileResourceFixture({ id: "author" }))
+ await writeCommunityCollectionRows(registry, "profiles", profiles, row => row.id)
+ await writeCommunityCollectionRows(registry, "messages", [messageResourceFixture({ authorId: "author" })], row => row.id)
+ const window = {}
+ const rows = () => [registry.collections.messages.get("m1")]
+ const parse = vi.spyOn(profileSchema, "safeParse")
+ try {
+ const first = getCanonicalCommunityMessageResources(client, rows(), window)
+ expect(first?.profiles.map(row => row.id)).toEqual(["author"])
+ expect(getCanonicalCommunityMessageResources(client, rows(), window)).toBe(first)
+ await writeCommunityCollectionRows(registry, "profiles", [...profiles, profileResourceFixture({ id: "another-unrelated" })], row => row.id)
+ expect(getCanonicalCommunityMessageResources(client, rows(), window)).toBe(first)
+ expect(parse).not.toHaveBeenCalled()
+ } finally { parse.mockRestore() }
+ })
+
+ it("rechecks the actual message and profile dependencies, including deletion", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const profile = profileResourceFixture({ id: "author" })
+ const message = messageResourceFixture({ authorId: profile.id })
+ await writeCommunityCollectionRows(registry, "profiles", [profile], row => row.id)
+ await writeCommunityCollectionRows(registry, "messages", [message], row => row.id)
+ const window = {}
+ const read = () => getCanonicalCommunityMessageResources(client, [registry.collections.messages.get(message.id)], window)
+ const first = read()
+ await writeCommunityCollectionRows(registry, "profiles", [{ ...profile, name: "Updated" }], row => row.id)
+ expect(read()).not.toBe(first)
+ expect(read()?.profiles[0]?.name).toBe("Updated")
+ await writeCommunityCollectionRows(registry, "messages", [{ ...message, content: "Edited" }], row => row.id)
+ expect(read()?.messages[0]?.content).toBe("Edited")
+ await writeCommunityCollectionRows(registry, "profiles", [], row => row.id)
+ expect(read()).toBeUndefined()
+ await writeCommunityCollectionRows(registry, "profiles", [profile], row => row.id)
+ expect(read()?.profiles[0]?.name).toBe(profile.name)
+ await writeCommunityCollectionRows(registry, "messages", [], row => row.id)
+ expect(read()).toBeUndefined()
+ })
+
+ it("keeps malformed and missing profiles incomplete while allowing an empty graph", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const message = messageResourceFixture({ authorId: "missing" })
+ expect(getCanonicalCommunityMessageResources(client, [message], {})).toBeUndefined()
+ expect(getCanonicalCommunityMessageResources(client, [{ id: "partial" }], {})).toBeUndefined()
+ expect(getCanonicalCommunityMessageResources(client, [], {})).toEqual({ messages: [], profiles: [] })
+ const profile = profileResourceFixture({ id: "missing" })
+ await writeCommunityCollectionRows(registry, "profiles", [profile], row => row.id)
+ expect(getCanonicalCommunityMessageResources(client, [message], {})?.profiles).toEqual([profile])
+ registry.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 }))
+ expect(getCanonicalCommunityMessageResources(client, [message], {})).toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/community-db/resources.ts b/src/web/src/lib/community-db/resources.ts
new file mode 100644
index 000000000..429d2602e
--- /dev/null
+++ b/src/web/src/lib/community-db/resources.ts
@@ -0,0 +1,98 @@
+import { hasVirtualProps } from "@tanstack/react-db"
+import { CommunityMessageResourceSchema, CommunityResourceProfileSchema, communityMessageProfileIds, type CommunityMessageResource, type CommunityResourceProfile } from "@alook/shared"
+import type { z } from "zod"
+import { communityKeys } from "@/lib/query-keys"
+import type { CommunityDbRegistry } from "./collections"
+import { messageSchema as canonicalMessageSchema, profileSchema as canonicalProfileSchema, type MessageRow, type ProfileRow } from "./schema"
+import { communityRowData } from "./write"
+
+const messageSchema = CommunityMessageResourceSchema.strip()
+const profileSchema = CommunityResourceProfileSchema.strip()
+type Resources = { messages: CommunityMessageResource[]; profiles: CommunityResourceProfile[] }
+type ResourceRead = { messages: readonly unknown[]; profiles: readonly unknown[]; additionalProfiles: readonly string[]; value: Resources }
+type ResourceReads = {
+ messages: WeakMap<object, CommunityMessageResource | null>
+ profiles: WeakMap<object, CommunityResourceProfile | null>
+ canonicalMessages: WeakMap<object, MessageRow | null>
+ canonicalProfiles: WeakMap<object, ProfileRow | null>
+ messageScopes: WeakMap<readonly unknown[], Map<string, number[]>>
+ windows: WeakMap<object, ResourceRead>
+}
+const resourceReads = new WeakMap<CommunityDbRegistry, ResourceReads>()
+
+function readsFor(registry: CommunityDbRegistry) {
+ let reads = resourceReads.get(registry)
+ if (!reads) {
+ reads = { messages: new WeakMap(), profiles: new WeakMap(), canonicalMessages: new WeakMap(), canonicalProfiles: new WeakMap(), messageScopes: new WeakMap(), windows: new WeakMap() }
+ resourceReads.set(registry, reads)
+ }
+ return reads
+}
+
+function readResource<T extends object>(schema: z.ZodType<T>, cache: WeakMap<object, T | null>, row: unknown, canonicalSource = false): T | undefined {
+ const immutable = row !== null && typeof row === "object" && (canonicalSource || hasVirtualProps(row))
+ if (immutable && cache.has(row)) return cache.get(row) ?? undefined
+ const parsed = schema.safeParse(communityRowData(row))
+ const value = parsed.success ? parsed.data : undefined
+ if (immutable) cache.set(row, value ?? null)
+ return value
+}
+
+function profileRow(registry: CommunityDbRegistry, id: string): unknown {
+ if (registry.collections.profiles.status === "ready") return registry.collections.profiles.get(id)
+ const rows = registry.queryClient.getQueryData<CommunityResourceProfile[]>(communityKeys.communityDbCollection(registry.scopeId, "profiles"))
+ const row = Array.isArray(rows) ? rows.find(row => row?.id === id) : undefined
+ return readResource(canonicalProfileSchema, readsFor(registry).canonicalProfiles, row, true)
+}
+
+function sameRows(left: readonly unknown[], right: readonly unknown[]) {
+ return left.length === right.length && left.every((row, index) => row === right[index])
+}
+
+export function canonicalMessageResource(registry: CommunityDbRegistry, row: unknown) {
+ return readResource(messageSchema, readsFor(registry).messages, row)
+}
+
+export function canonicalChannelMessages(registry: CommunityDbRegistry, channelId: string): MessageRow[] {
+ if (!registry.runtime.lifecycle.get().active) return []
+ const data = registry.queryClient.getQueryData<unknown[]>(communityKeys.communityDbCollection(registry.scopeId, "messages"))
+ if (data !== undefined && !Array.isArray(data)) return []
+ const rows = data ?? [...registry.collections.messages.values()]
+ const reads = readsFor(registry)
+ let scopes = reads.messageScopes.get(rows)
+ if (!scopes) {
+ scopes = new Map()
+ for (let index = 0; index < rows.length; index++) {
+ const row = rows[index]
+ if (!row || typeof row !== "object" || !("channelId" in row) || typeof row.channelId !== "string") continue
+ const positions = scopes.get(row.channelId) ?? []
+ positions.push(index)
+ scopes.set(row.channelId, positions)
+ }
+ reads.messageScopes.set(rows, scopes)
+ }
+ return (scopes.get(channelId) ?? []).flatMap(index => {
+ const row = readResource(canonicalMessageSchema, reads.canonicalMessages, rows[index], true)
+ return row ? [row] : []
+ })
+}
+
+export function canonicalMessageResources(registry: CommunityDbRegistry, messages: readonly unknown[], window: object = messages, additionalProfiles: readonly string[] = []): Resources | undefined {
+ if (!registry.runtime.lifecycle.get().active) return
+ const reads = readsFor(registry)
+ const previous = reads.windows.get(window)
+ if (previous && sameRows(messages, previous.messages) && sameRows(additionalProfiles, previous.additionalProfiles)
+ && previous.value.profiles.every((profile, index) => profileRow(registry, profile.id) === previous.profiles[index])) return previous.value
+ const parsed = messages.map(row => readResource(messageSchema, reads.messages, row))
+ if (parsed.some(row => !row)) return
+ const resources = parsed as CommunityMessageResource[]
+ const ids = [...new Set([...communityMessageProfileIds(resources), ...additionalProfiles])]
+ const profileRows = ids.map(id => profileRow(registry, id))
+ const profiles = profileRows.map(row => readResource(profileSchema, reads.profiles, row, true))
+ if (profiles.some(row => !row)) return
+ const value = { messages: resources, profiles: profiles as CommunityResourceProfile[] }
+ if ([...messages, ...profileRows].every(row => row !== null && typeof row === "object" && hasVirtualProps(row))) {
+ reads.windows.set(window, { messages: [...messages], profiles: profileRows, additionalProfiles: [...additionalProfiles], value })
+ }
+ return value
+}
diff --git a/src/web/src/lib/community-db/restore.test.ts b/src/web/src/lib/community-db/restore.test.ts
index 7f207a1e0..61d9d7cc6 100644
--- a/src/web/src/lib/community-db/restore.test.ts
+++ b/src/web/src/lib/community-db/restore.test.ts
@@ -71,7 +71,7 @@ describe("canonical disk input precedence", () => {
it("preserves a WS patch that arrived before its disk row and a current message over old disk", async () => {
const { client, registry } = owner()
- publishCommunityMessages(client, { profiles: messageProfilesFixture([message("current", "c1", "RSC")]), channelId: "c1", messages: [message("current", "c1", "RSC")], proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ await publishCommunityMessages(client, { profiles: messageProfilesFixture([message("current", "c1", "RSC")]), channelId: "c1", messages: [message("current", "c1", "RSC")], proof: { token: captureCommunityLiveSnapshotToken(client) } })
projectCommunityWsEventToDb(client, { type: "community:reaction.add", serverId: "s1", channelId: "c1", messageId: "pending", emoji: "👍", userId: "peer" })
await restoreCommunityCollections(registry, input({ messages: [message("current"), message("pending"), message("uncovered", "other")] }))
const rows = client.getQueryData<Array<ReturnType<typeof message>>>(communityKeys.communityDbCollection("viewer", "messages"))!
@@ -95,11 +95,11 @@ describe("canonical disk input precedence", () => {
it("preserves authoritative empty scopes and still restores an unrelated server", async () => {
const { client, registry } = owner()
- publishCommunityLiveSnapshot(client, {
+ await publishCommunityLiveSnapshot(client, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture({ id: "s1", name: "Fresh", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "folders", data: { folders: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "folders", data: { folders: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
const disk = input({
servers: [server("s1"), server("s2")],
categories: [{ id: "old-category", serverId: "s1", name: "Old", position: 0, private: false, creatorId: null, pending: false }],
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index e59f7c15c..d0096a23d 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -162,7 +162,7 @@ describe("community DB sync", () => {
restoreAttentionScopeOptimisticSnapshot(db, first)
expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBe(3)
const next = clearAttentionScopeOptimistically(db, "dm", 5)
- publishCommunityConversationReadState(db.queryClient, { channelId: "dm", lastReadMessageId: "m5", lastReadAt: "2026-10-27T00:00:05.000Z", lastReadSeq: 5 }, 2, { token: captureCommunityLiveSnapshotToken(db.queryClient) }, "advance")
+ await publishCommunityConversationReadState(db.queryClient, { channelId: "dm", lastReadMessageId: "m5", lastReadAt: "2026-10-27T00:00:05.000Z", lastReadSeq: 5 }, 2, { token: captureCommunityLiveSnapshotToken(db.queryClient) }, "advance")
seed(1)
await commitAttentionScopeOptimisticSnapshot(db, next)
expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBe(1)
@@ -170,19 +170,19 @@ describe("community DB sync", () => {
it("keeps unloaded and partial member data unknown but prunes a fresh complete roster without requiring profiles", async () => {
const db = await registry()
- publishCommunityChannelMetadata(db.queryClient, {
+ await publishCommunityChannelMetadata(db.queryClient, {
metadata: channelResourceFixture({ id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBeUndefined()
applyTypingIndicator(db.queryClient, "ch:c1", "unknown", null)
applyTypingIndicator(db.queryClient, "ch:c1", "kept", null)
- publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mv", userId: "viewer", role: "member" }], { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ await publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mv", userId: "viewer", role: "member" }], { token: captureCommunityLiveSnapshotToken(db.queryClient) })
projectCommunityWsEventToDb(db.queryClient, { type: "community:member.update", serverId: "s1", memberId: "mu", userId: "unknown", changes: { role: "admin" } })
expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBeUndefined()
expect(db.runtime.ui.get().typingByScope.get("ch:c1")).toEqual(new Map([["unknown", null], ["kept", null]]))
const members = [{ channelId: "c1", userId: "kept", relation: "access" as const, source: "explicit", isCreator: false, role: null, memberId: null }]
- publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "c1", "access", members, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ await publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "c1", "access", members, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
db.queryClient.setQueryData(communityKeys.channelMembers("c1", "access"), { serverId: "s1", relation: "access", members })
expect(db.runtime.ui.get().typingByScope.get("ch:c1")).toEqual(new Map([["kept", null]]))
expect(db.runtime.ui.get().typingTimers.has("ch:c1|unknown")).toBe(false)
@@ -198,7 +198,7 @@ describe("community DB sync", () => {
applyTypingIndicator(db.queryClient, "ch:thread", "peer", "Peer")
setCanonicalCommunityChannelMember(db.queryClient, "thread", "peer", "notify", false, { event: true })
const members = [{ channelId: "thread", userId: "peer", relation: "notify" as const, source: "spoke", isCreator: false, role: null, memberId: null }]
- publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "thread", "notify", members, { token })
+ await publishCommunityChannelMembersSnapshot(db.queryClient, "s1", "thread", "notify", members, { token })
db.queryClient.setQueryData(communityKeys.channelMembers("thread", "notify"), { serverId: "s1", relation: "notify", members })
expect(db.collections.channelMemberships.has("thread:peer:notify")).toBe(false)
expect(getCanonicalCommunityTypingMembership(db.queryClient, "thread", "peer")).toBe(false)
@@ -214,13 +214,13 @@ describe("community DB sync", () => {
ingestServerDetail(db, serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "public-category", name: "Public", private: false, channels: [{ id: "c1", name: "Forum", type: "forum", active: false, unread: false }] }] }))
for (const [id, serverId, type] of [["c1", "s1", "forum"], ["c2", "s2", "text"], ["dm1", null, "dm"]] as const) {
- publishCommunityChannelMetadata(db.queryClient, {
+ await publishCommunityChannelMetadata(db.queryClient, {
metadata: channelResourceFixture({ id, serverId, type, name: id, parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
applyTypingIndicator(db.queryClient, `${type === "dm" ? "dm" : "ch"}:${id}`, "peer", null)
}
- publishCommunityChannelMetadata(db.queryClient, {
+ await publishCommunityChannelMetadata(db.queryClient, {
metadata: channelResourceFixture({ id: "child", serverId: "s1", type: "thread", name: "Child", parentChannelId: "c1", parentMessageId: "opener", creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
@@ -228,7 +228,7 @@ describe("community DB sync", () => {
applyTypingIndicator(db.queryClient, "ch:child", "peer", null)
const beforeLeave = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, { type: "community:member.leave", serverId: "s1", userId: "peer" })
- publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mp", userId: "peer", role: "member" }], { token: beforeLeave })
+ await publishCommunityMembersSnapshot(db.queryClient, "s1", [{ id: "mp", userId: "peer", role: "member" }], { token: beforeLeave })
expect(db.runtime.ui.get().typingByScope.has("ch:c1")).toBe(false)
expect(db.runtime.ui.get().typingTimers.has("ch:c1|peer")).toBe(false)
expect(db.runtime.ui.get().typingByScope.has("ch:child")).toBe(false)
@@ -248,7 +248,7 @@ describe("community DB sync", () => {
const db = await registry()
if (visibility === "private") ingestServerDetail(db, serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "private-category", name: "Private", private: true, channels: [{ id: "c1", name: "Channel", type: "text", active: false, unread: false }] }] }))
- else publishCommunityChannelMetadata(db.queryClient, {
+ else await publishCommunityChannelMetadata(db.queryClient, {
metadata: channelResourceFixture({ id: "c1", serverId: "s1", categoryId: "unloaded-category", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
@@ -267,7 +267,7 @@ describe("community DB sync", () => {
projectCommunityWsEventToDb(db.queryClient, { type: "community:server.update", serverId: "s1", changes: { name } })
publishCommunityServerFields(db.queryClient, "s1", { name: "old-confirmation", description: "confirmed" }, { token, signal: undefined })
expect(db.collections.servers.get("s1")).toMatchObject({ name, description: "confirmed" })
- publishCommunityLiveSnapshotWithProof(db.queryClient, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [original] }, "viewer") }, proof: { kind: "structural", token, signal: undefined } })
+ await publishCommunityLiveSnapshotWithProof(db.queryClient, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [original] }, "viewer") }, proof: { kind: "structural", token, signal: undefined } })
expect(db.collections.servers.get("s1")).toMatchObject({ name, description: "confirmed" })
})
@@ -442,7 +442,7 @@ describe("community DB sync", () => {
}],
}))
- expect(publishCommunityChannelDirectory(db.queryClient, {
+ expect(await publishCommunityChannelDirectory(db.queryClient, {
resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "forum1", serverId: "s1", categoryId: "cat1", type: "forum", name: "Forum renamed" })]),
directory: [{
id: "s1",
@@ -464,7 +464,7 @@ describe("community DB sync", () => {
it("uses explicit full resource type for a new directory channel", async () => {
const db = await registry()
- expect(publishCommunityChannelDirectory(db.queryClient, {
+ expect(await publishCommunityChannelDirectory(db.queryClient, {
resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1", type: "text", name: "General" })]),
directory: [{
id: "s1",
@@ -492,7 +492,7 @@ describe("community DB sync", () => {
const resources = resourceBundleFixture({ viewerId: "viewer", servers: [current, added], serverMemberships: [
{ serverId: "s1", userId: "viewer", memberId: "member-1", role: "admin" }, { serverId: "s2", userId: "viewer", memberId: "member-2", role: "member" }] })
const summaries = resources.servers.map(({ id, name, discriminator }) => ({ id, name, discriminator }))
- if (source === "directory") publishCommunityChannelDirectory(db.queryClient, { resources, directory: summaries.map(server => ({ ...server, channels: [] })), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ if (source === "directory") await publishCommunityChannelDirectory(db.queryClient, { resources, directory: summaries.map(server => ({ ...server, channels: [] })), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
else ingestAttentionSnapshot(db, AccountAttentionSnapshotSchema.parse({ resources, scopes: [], items: [], limit: 100, truncated: false, included: { servers: summaries, channels: [], dms: [], profiles: [], messages: [] } }))
expect(db.collections.servers.get("s1")).toMatchObject(current)
expect(db.collections.servers.get("s2")).toMatchObject(added)
@@ -573,9 +573,9 @@ describe("community DB sync", () => {
expect(publishCommunityDmSummary(db.queryClient, dm)).toBe("missing-resource")
expect(db.collections.channels.has(dm.id)).toBe(false)
const channel = channelResourceFixture({ id: dm.id, type: "dm", serverId: null, name: null })
- publishConversationEntry(db.queryClient, { channelId: dm.id, serverId: null }, conversationEntryFromChannel(channel), { token: captureCommunityLiveSnapshotToken(db.queryClient, dm.id) })
+ await publishConversationEntry(db.queryClient, { channelId: dm.id, serverId: null }, conversationEntryFromChannel(channel), { token: captureCommunityLiveSnapshotToken(db.queryClient, dm.id) })
expect(publishCommunityDmSummary(db.queryClient, dm)).toBe("published")
- publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ await publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: { kind: "dms", data: { conversations: ([]).map(row => dmListRowFixture(row, "viewer")) } },
proof: { kind: "structural", token, signal: undefined },
})
@@ -604,7 +604,7 @@ describe("community DB sync", () => {
messageId: "m1",
emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
- publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
+ await publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
channelId: "c1",
messages: messageSeedFixture("c1", [staleMessage]),
proof: { token, signal: undefined },
@@ -630,7 +630,7 @@ describe("community DB sync", () => {
...message,
reactions: [{ emoji: "👍", count: 2, me: true, userIds: ["peer", "viewer"] }],
}))
- publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
+ await publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
channelId: "c1",
messages: messageSeedFixture("c1", [staleMessage]),
proof: { token, signal: undefined },
@@ -651,7 +651,7 @@ describe("community DB sync", () => {
messageId: "m1",
emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
- publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ await publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
id: "m1",
type: "chat",
seq: 1,
@@ -676,7 +676,7 @@ describe("community DB sync", () => {
communityKeys.communityDbCollection("viewer", "messages"),
[],
)
- publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ await publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
id: "m1",
type: "chat",
seq: 1,
@@ -720,7 +720,7 @@ describe("community DB sync", () => {
communityKeys.communityDbCollection("viewer", "messages"),
[],
)
- publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ await publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
id: "m1",
type: "chat",
seq: 1,
@@ -786,7 +786,7 @@ describe("community DB sync", () => {
channelId: "c1",
changes: { name: "fresh channel" },
} as CommunityWsEvent)
- publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ await publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture(detail) },
proof: { kind: "structural", token, signal: undefined },
})
@@ -808,7 +808,7 @@ describe("community DB sync", () => {
serverId: "s1",
changes: { name: "Fresh server" },
} as CommunityWsEvent)
- publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ await publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: {
kind: "server-detail",
data: serverDirectoryFixture({
@@ -847,7 +847,7 @@ describe("community DB sync", () => {
channelId: "c1",
changes: { name: "fresh channel" },
} as CommunityWsEvent)
- publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ await publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: { kind: "server-detail", data: serverDirectoryFixture(detail) },
proof: { kind: "structural", token, signal: undefined },
})
@@ -913,7 +913,7 @@ describe("community DB sync", () => {
it("rejects a superseded read-state freshness proof before replacement", async () => {
const db = await registry()
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "read-state",
data: {
revision: 1,
@@ -925,7 +925,7 @@ describe("community DB sync", () => {
})
const token = captureCommunityLiveSnapshotToken(db.queryClient)
- expect(publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ expect(await publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: {
kind: "read-state",
data: {
@@ -1111,26 +1111,26 @@ describe("community DB sync", () => {
}],
}))
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
data: serverRailResponseFixture({ servers: [server("merge-s1"), server("merge-s2")] }, "viewer"),
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "server-detail",
data: detail(["merge-c1", "merge-c2"]),
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
data: { conversations: ([dm("merge-dm1", "peer1"), dm("merge-dm2", "peer2")]).map(row => dmListRowFixture(row, "viewer")) },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
data: { folders: [
{ id: "merge-f1", name: "One", position: 0, servers: [] },
{ id: "merge-f2", name: "Two", position: 1, servers: [] },
] },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "read-state",
data: {
revision: 1,
@@ -1140,7 +1140,7 @@ describe("community DB sync", () => {
],
},
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "notification-settings",
data: {
raw: [
@@ -1232,19 +1232,19 @@ describe("community DB sync", () => {
}],
}))
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
data: serverRailResponseFixture({ servers: [server("live-s1"), server("live-s2")] }, "viewer"),
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "server-detail",
data: detail(["live-c1", "live-c2"]),
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
data: { conversations: ([dm("live-dm1", "peer1"), dm("live-dm2", "peer2")]).map(row => dmListRowFixture(row, "viewer")) },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
data: { folders: [
{
@@ -1261,7 +1261,7 @@ describe("community DB sync", () => {
},
] },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "read-state",
data: {
revision: 1,
@@ -1271,7 +1271,7 @@ describe("community DB sync", () => {
],
},
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "notification-settings",
data: {
raw: [
@@ -1283,15 +1283,15 @@ describe("community DB sync", () => {
},
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "server-detail",
data: detail(["live-c1"]),
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
data: { conversations: ([dm("live-dm1", "peer1")]).map(row => dmListRowFixture(row, "viewer")) },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
data: { folders: [{
id: "live-f1",
@@ -1300,7 +1300,7 @@ describe("community DB sync", () => {
servers: [{ id: "live-s1", name: "Live one", initial: "L", icon: null }],
}] },
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "read-state",
data: {
revision: 2,
@@ -1312,7 +1312,7 @@ describe("community DB sync", () => {
}],
},
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "notification-settings",
data: {
raw: [{ serverId: "live-s1", level: "nothing" }],
@@ -1320,7 +1320,7 @@ describe("community DB sync", () => {
channel: {},
},
})
- publishCommunityLiveSnapshot(db.queryClient, {
+ await publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
data: serverRailResponseFixture({ servers: [server("live-s1")] }, "viewer"),
})
@@ -1452,7 +1452,7 @@ describe("community DB sync", () => {
expect(db.collections.categories.get("cat1")).toMatchObject({ serverId: "s1" })
expect(db.collections.channels.get("c1")).toMatchObject({ serverId: "s1", categoryId: "cat1" })
expect(db.collections.channelMemberships.get("c1:viewer:access")).toBeUndefined()
- publishCommunityChannelMetadata(db.queryClient, { metadata: CommunityChannelResourceSchema.strip().parse(db.collections.channels.get("c1")), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ await publishCommunityChannelMetadata(db.queryClient, { metadata: CommunityChannelResourceSchema.strip().parse(db.collections.channels.get("c1")), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
expect(db.collections.channelMemberships.get("c1:viewer:access")).toMatchObject({ relation: "access", source: "explicit" })
expect(db.collections.channels.get("dm1")).toMatchObject({ type: "dm", serverId: null })
expect(db.collections.channelMemberships.get("dm1:viewer:access")).toBeDefined()
@@ -1492,21 +1492,21 @@ describe("community DB sync", () => {
it("orders an entry pointer and full account snapshots by server revision while permitting deletion rollback", async () => {
const db = await registry()
const point = (seq: number) => ({ channelId: "c1", lastReadMessageId: seq ? `m${seq}` : null, lastReadAt: seq ? `at${seq}` : null, lastReadSeq: seq })
- const publish = (seq: number, revision: number) => publishCommunityConversationReadState(db.queryClient, point(seq), revision, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
- expect(publish(10, 5)).toBe("published")
+ const publish = async (seq: number, revision: number) => await publishCommunityConversationReadState(db.queryClient, point(seq), revision, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ expect(await publish(10, 5)).toBe("published")
expect(db.collections.readStateClock.get("account")).toBeUndefined()
ingestReadStateSnapshot(db, { revision: 4, readStates: [{ ...point(20), lastReadAt: "at20" }] })
expect(db.collections.readStateClock.get("account")?.revision).toBe(4)
expect(db.collections.readStates.get("c1")).toMatchObject({ lastReadSeq: 10, observedRevision: 5 })
ingestReadStateSnapshot(db, { revision: 6, readStates: [{ ...point(8), lastReadAt: "at8" }] })
expect(db.collections.readStates.get("c1")).toMatchObject({ lastReadSeq: 8, observedRevision: 6 })
- expect(publish(10, 5)).toBe("superseded")
- expect(publish(0, 7)).toBe("published")
+ expect(await publish(10, 5)).toBe("superseded")
+ expect(await publish(0, 7)).toBe("published")
ingestReadStateSnapshot(db, { revision: 6, readStates: [] })
expect(db.collections.readStates.get("c1")).toMatchObject({ lastReadMessageId: null, lastReadSeq: 0, observedRevision: 7 })
ingestReadStateSnapshot(db, { revision: 8, readStates: [] })
expect(db.collections.readStates.get("c1")).toBeUndefined()
- expect(publish(20, 7)).toBe("superseded")
+ expect(await publish(20, 7)).toBe("superseded")
expect(db.collections.readStates.get("c1")).toBeUndefined()
})
@@ -1520,7 +1520,7 @@ describe("community DB sync", () => {
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")
+ expect(await 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)
@@ -1553,7 +1553,7 @@ describe("community DB sync", () => {
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 } })
+ await 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()
@@ -1570,7 +1570,7 @@ describe("community DB sync", () => {
})
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 } })
+ await 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)
@@ -1588,7 +1588,7 @@ describe("community DB sync", () => {
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 } })
+ await 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()
@@ -1630,7 +1630,7 @@ describe("community DB sync", () => {
})
const token = captureCommunityLiveSnapshotToken(db.queryClient)
- expect(publishAccountAttentionSnapshot(db.queryClient, {
+ expect(await publishAccountAttentionSnapshot(db.queryClient, {
snapshot: { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token, signal: undefined },
})).toBe("published")
@@ -1766,7 +1766,7 @@ describe("community DB sync", () => {
(entry) => entry.sourceId !== "keep",
)
const token = captureCommunityLiveSnapshotToken(db.queryClient)
- expect(publishAccountAttentionSnapshot(db.queryClient, {
+ expect(await publishAccountAttentionSnapshot(db.queryClient, {
snapshot,
proof: { token, signal: undefined },
})).toBe("published")
@@ -1802,7 +1802,7 @@ describe("community DB sync", () => {
const before = clearAttentionOptimistically(db)
const beforeToken = captureCommunityLiveSnapshotToken(db.queryClient)
- publishAccountAttentionSnapshot(db.queryClient, {
+ await publishAccountAttentionSnapshot(db.queryClient, {
snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(), scopes: [scope], items: [], limit: 100, truncated: false },
proof: { token: beforeToken, signal: undefined },
})
@@ -1812,7 +1812,7 @@ describe("community DB sync", () => {
ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }), scopes: [scope], items: [], limit: 100, truncated: false })
const duringToken = captureCommunityLiveSnapshotToken(db.queryClient)
const during = clearAttentionOptimistically(db)
- publishAccountAttentionSnapshot(db.queryClient, {
+ await publishAccountAttentionSnapshot(db.queryClient, {
snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(), scopes: [scope], items: [], limit: 100, truncated: false },
proof: { token: duringToken, signal: undefined },
})
@@ -1993,7 +1993,7 @@ describe("community DB sync", () => {
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] },
}
const reconcileToken = captureCommunityLiveSnapshotToken(db.queryClient)
- publishAccountAttentionSnapshot(db.queryClient, {
+ await publishAccountAttentionSnapshot(db.queryClient, {
snapshot: newerSnapshot,
proof: { token: reconcileToken },
})
@@ -2126,7 +2126,7 @@ describe("community DB sync", () => {
createdAt: `2026-09-27T01:0${seq}:00.000Z`,
}))
const reconcileToken = captureCommunityLiveSnapshotToken(db.queryClient)
- publishAccountAttentionSnapshot(db.queryClient, { snapshot: { resources: resourceBundleFixture(),
+ await publishAccountAttentionSnapshot(db.queryClient, { snapshot: { resources: resourceBundleFixture(),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -2230,7 +2230,7 @@ describe("community DB sync", () => {
const profile = { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 1 }
const page = normalizeThreadResources("c1", { ...value.forumFeed, included: { ...value.forumFeed!.included,
members: [{ channelId: "t1", userId: "peer", relation: "notify", source: "spoke", isCreator: false, role: "member", memberId: "member-peer" }], profiles: [profile] } })
- publishCommunityForumFeed(db.queryClient, "c1", page, { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") })
+ await publishCommunityForumFeed(db.queryClient, "c1", page, { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") })
expect(db.collections.channelMemberships.get("t1:peer:notify")).toMatchObject({ id: "t1:peer:notify", channelId: "t1", userId: "peer", relation: "notify", source: "spoke" })
expect(db.collections.channelMemberships.get("t1:peer:notify")).not.toHaveProperty("role")
expect(db.collections.serverMemberships.get("s1:peer")).toMatchObject({ serverId: "s1", userId: "peer", memberId: "member-peer", role: "member" })
@@ -2243,7 +2243,7 @@ describe("community DB sync", () => {
const profile = { id: "peer", name: "Original Name", discriminator: "0042", avatar: null, avatarVersion: 7 }
const channel = channelResourceFixture({ id: "c1", type: "forum" })
const child = channelResourceFixture({ id: "t1", type: "thread", parentChannelId: channel.id, parentMessageId: "m1" })
- publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture()], [channel, child], [], [profile]), { token: captureCommunityLiveSnapshotToken(db.queryClient, channel.id) })
+ await publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture()], [channel, child], [], [profile]), { token: captureCommunityLiveSnapshotToken(db.queryClient, channel.id) })
const collections = ["profiles", "channels", "channelMemberships", "serverMemberships", "messages"] as const
const before = new Map(collections.map(name => [name, db.queryClient.getQueryData(communityKeys.communityDbCollection(db.scopeId, name))]))
const { avatar: _avatar, ...incomplete } = profile
@@ -2273,14 +2273,14 @@ describe("community DB sync", () => {
const proof = { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }
if (surface === "bundle") {
const resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [message], [profile])
- publishCommunityResourceBundle(db.queryClient, resources, proof)
+ await publishCommunityResourceBundle(db.queryClient, resources, proof)
} else if (surface === "dm-entry") {
const value = dmConversationEntryFixture()
- publishConversationEntry(db.queryClient, { channelId: "c1", serverId: null }, { ...value, peer: profile, profiles: [profile], messages: [message] }, proof)
+ await publishConversationEntry(db.queryClient, { channelId: "c1", serverId: null }, { ...value, peer: profile, profiles: [profile], messages: [message] }, proof)
} else {
const value = forumConversationEntryFixture()
const page = normalizeThreadResources("c1", { ...value.forumFeed, included: { ...value.forumFeed!.included, messages: [message], profiles: [profile] } })
- publishCommunityForumFeed(db.queryClient, "c1", page, proof)
+ await publishCommunityForumFeed(db.queryClient, "c1", page, proof)
}
expect(db.collections.profiles.get(profile.id)).toMatchObject({ ...profile,
avatar: hintVersion > profile.avatarVersion ? "hint.png" : profile.avatar, avatarVersion: Math.max(profile.avatarVersion, hintVersion),
@@ -3191,8 +3191,8 @@ describe("forum archive channel semantics", () => {
const message = messageResourceFixture({ id: "opener", channelId: "forum", content: "Post", thread: { id: "post", name: "Post", messageCount: 1, tags: ["archived"], participants: [] } })
ingestMessages(db, "forum", [message])
expect(db.collections.channels.get("post")).toBeUndefined()
- publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "forum", serverId: "s1", type: "forum" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
- publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "post", serverId: "s1", type: "thread", parentChannelId: "forum", parentMessageId: "opener" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ await publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "forum", serverId: "s1", type: "forum" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ await publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "post", serverId: "s1", type: "thread", parentChannelId: "forum", parentMessageId: "opener" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
ingestMessages(db, "forum", [message])
expect(db.collections.channels.get("post")).toMatchObject({ archived: false, tags: ["archived"] })
publishCommunityChannelFields(db.queryClient, "post", { archived: true }, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
@@ -3219,7 +3219,7 @@ describe("current message reference windows", () => {
const db = await registry()
const channel = channelResourceFixture({ id: "dm", type: "dm", serverId: null })
const message = messageResourceFixture({ id: "message", channelId: channel.id })
- publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [], [channel], [message]), { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined }, [{ id: message.id, channelId: channel.id }])
+ await publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [], [channel], [message]), { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined }, [{ id: message.id, channelId: channel.id }])
expect(db.collections.messages.get(message.id)).toMatchObject(message)
})
})
@@ -3228,7 +3228,7 @@ it.each(["warm", "cold", "normal"])("retains newer profile and status domains wh
const { encodeCommunityBrowserEvent, decodeCommunityBrowserEvent } = await import("@alook/shared")
const db = await registry()
const oldProfile = profileResourceFixture({ id: "late-author", name: "Before", aboutMe: "Before about", bannerColor: null, statusEmoji: "old", statusText: "Before status" })
- if (order === "warm") publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [oldProfile] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ if (order === "warm") await publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [oldProfile] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
const delayed = encodeCommunityBrowserEvent({ type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "late-create", authorId: oldProfile.id, authorName: oldProfile.name, authorAvatarVersion: oldProfile.avatarVersion }), profiles: [oldProfile] })
if (!delayed.ok) throw new Error(JSON.stringify(delayed))
if (order === "normal") projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "late-create", authorId: oldProfile.id, authorName: oldProfile.name, authorAvatarVersion: oldProfile.avatarVersion }), profiles: [oldProfile] })
@@ -3250,7 +3250,7 @@ it("does not let a message dependency seed fence an already in-flight valid HTTP
const profile = profileResourceFixture({ id: "seed-http", name: "Message snapshot", statusEmoji: null, statusText: "" })
projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "seed-http-message", authorId: profile.id, authorName: profile.name, authorAvatarVersion: 0 }), profiles: [profile] })
expect(beginCommunityProfileSeed(db).revision).toBe(before)
- publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [{ ...profile, name: "Current HTTP", aboutMe: "Actual current read", statusEmoji: "🎧", statusText: "Current" }] }), { token })
+ await publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [{ ...profile, name: "Current HTTP", aboutMe: "Actual current read", statusEmoji: "🎧", statusText: "Current" }] }), { token })
expect(db.collections.profiles.get(profile.id)).toMatchObject({ name: "Current HTTP", aboutMe: "Actual current read", statusEmoji: "🎧", statusText: "Current" })
})
@@ -3275,7 +3275,7 @@ it.each([
])("canonicalizes actual approval image values through the message writer ($image, current=$currentVersion)", async ({ image, currentVersion, expected, expectedVersion }) => {
const db = await registry()
const other = profileResourceFixture({ id: "other", name: "Current Other", avatar: "/current.png", avatarVersion: currentVersion })
- publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [other] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ await publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [other] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
const author = profileResourceFixture({ id: "approval-bot", name: "Bot" })
projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", profiles: [author], message: messageResourceFixture({ id: "approval-image", authorId: author.id, authorName: author.name, authorAvatarVersion: 0,
approval: { friendshipId: "friendship", status: "pending", waitingOn: "you", otherProfile: { id: other.id, name: "Card label", discriminator: "0042", image, avatarVersion: 2 }, botProfile: { id: author.id, name: author.name, discriminator: author.discriminator, image: null, avatarVersion: 0 } } }) })
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index c05e0aa2c..a02ff1c67 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -51,13 +51,19 @@ type CommunityDbRegistry,
} from "./collections"
import { channelMembershipKey, canonicalChannelMembershipRow, channelLocalSchema, canonicalChannelRow, folderItemKey, messageSchema, notificationSettingKey, serverMembershipKey, serverMembershipSchema, serverSchema, communityCollectionSchemas, type CommunityCollectionRows, type CategoryRow, type AttentionItemRow, type AttentionScopeRow, type ChannelMembershipRow, type ChannelRow, type FolderItemRow, type FolderRow, type MessageRow, type ProfileRow, type FriendshipRow, type NotificationSettingRow, type ReadStateClockRow, type ReadStateRow, type ServerMembershipRow, type ServerRow } from "./schema"
import type { z } from "zod"
-import { communityRowData, writeCommunityCollectionRows } from "./write"
+import { communityRowData, writeCommunityCollectionRows, writeCommunityCollectionChanges, readCommunityCollectionRow, withCommunityCollectionWrites, afterCommunityCollectionWrites, parseCommunityCollectionRows } from "./write"
+import { canonicalChannelMessages, canonicalMessageResources } from "./resources"
import type { CommunityRestoredCollections } from "@/lib/query-persister"
import { normalizeThreadResources, type CommunityThreadResources } from "@/hooks/community/forum-feed-window"
type CollectionName = keyof CommunityDbRegistry["collections"]
type SnapshotIngestMode = "authoritative" | "merge"
+export function completeCommunityPublication<T>(owner: QueryClient | CommunityDbRegistry, publish: () => T) {
+ const registry = "collections" in owner ? owner : getCommunityDbRegistry(owner)
+ return registry ? withCommunityCollectionWrites(registry, publish) : publish()
+}
+
type CanonicalRevisionState = {
revision: number
entityRevisions: Map<string, number>
@@ -300,6 +306,11 @@ function withCanonicalWriteContext<T>(
}
}
+function afterCanonicalWrites(registry: CommunityDbRegistry, publish: () => void | Promise<unknown>) {
+ const context = canonicalWriteContexts.get(registry.queryClient)
+ return afterCommunityCollectionWrites(registry, () => context ? withCanonicalWriteContext(registry.queryClient, context, publish) : publish())
+}
+
function collectionSchema<N extends CollectionName>(name: N) {
return communityCollectionSchemas[name] as unknown as z.ZodType<CommunityCollectionRows[N]>
}
@@ -319,6 +330,24 @@ function collectionKey<N extends CollectionName>(registry: CommunityDbRegistry,
return (row: CommunityCollectionRows[N]) => collection.getKeyFromItem(row)
}
+function reconcileDirectoryChanges<N extends CollectionName>(registry: CommunityDbRegistry, name: N, before: readonly CommunityCollectionRows[N][], after: readonly CommunityCollectionRows[N][]) {
+ if (name !== "channels" && name !== "categories") return
+ const scope = (row: CommunityCollectionRows[N]) => {
+ const value = row as CommunityCollectionRows["channels"] | CommunityCollectionRows["categories"]
+ return !value.pending && (name === "categories" || (value as CommunityCollectionRows["channels"]).parentChannelId === null) ? value.serverId : null
+ }
+ const previous = new Map(before.map(row => [(row as { id: string }).id, scope(row)]))
+ const next = new Map(after.map(row => [(row as { id: string }).id, scope(row)]))
+ const affected = new Set<string>()
+ for (const id of new Set([...previous.keys(), ...next.keys()])) {
+ const oldScope = previous.get(id), newScope = next.get(id)
+ if (oldScope === newScope) continue
+ if (oldScope) affected.add(oldScope)
+ if (newScope) affected.add(newScope)
+ }
+ for (const serverId of affected) afterCommunityCollectionWrites(registry, () => reconcileExistingServerDirectoryWindows(registry, new Set([serverId])), `directory:${serverId}`)
+}
+
function replaceRows<N extends CollectionName>(
registry: CommunityDbRegistry,
name: N,
@@ -333,7 +362,7 @@ function replaceRows<N extends CollectionName>(
}
const schema = collectionSchema(name)
const getKey = collectionKey(registry, name)
- const parsedIncoming = incoming.map((row) => schema.parse(communityRowData(row)))
+ const parsedIncoming = parseCommunityCollectionRows(registry, name, incoming)
const current = collectionRows(registry, name)
const nextByKey = new Map(current.flatMap((row) => {
const key = getKey(row)
@@ -361,7 +390,8 @@ function replaceRows<N extends CollectionName>(
const next = [...nextByKey.values()]
writeCommunityCollectionRows(registry, name, next, getKey)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
- if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
+ const touched = new Set([...current.filter(owns).map(getKey), ...parsedIncoming.map(getKey)])
+ reconcileDirectoryChanges(registry, name, current.filter(row => touched.has(getKey(row))), next.filter(row => touched.has(getKey(row))))
recordEventWrites(registry, name, [
...current.filter(owns).map(getKey),
...parsedIncoming.map(getKey),
@@ -375,7 +405,32 @@ function upsertRows<N extends CollectionName>(
incoming: CommunityCollectionRows[N][],
eventFields?: readonly string[],
) {
- replaceRows(registry, name, incoming, () => false, eventFields)
+ const schema = collectionSchema(name), getKey = collectionKey(registry, name)
+ const parsed = parseCommunityCollectionRows(registry, name, incoming)
+ const before = new Map<string, CommunityCollectionRows[N]>(), next = new Map<string, CommunityCollectionRows[N]>()
+ for (const row of parsed) {
+ const key = getKey(row)
+ const previous = next.get(key) ?? readCommunityCollectionRow(registry, name, key)
+ if (previous && !before.has(key)) before.set(key, previous)
+ if (!isProtectedFromQueryWrite(registry, name, key)) {
+ next.set(key, row)
+ clearPendingOperations(registry, name, [key])
+ } else if (previous) {
+ const context = canonicalWriteContexts.get(registry.queryClient)
+ const revisions = canonicalRevisionState(registry.queryClient).fieldRevisions.get(canonicalEntityKey(name, key))
+ if (context?.kind === "query" && !Array.from(revisions?.values() ?? []).some(revision => revision > context.requestRevision)) next.set(key, row)
+ else next.set(key, previous)
+ clearPendingOperations(registry, name, [key])
+ } else {
+ const merged = mergePendingOperationsIntoQueryRow(registry, name, key, schema, row)
+ if (merged) next.set(key, merged)
+ }
+ }
+ writeCommunityCollectionChanges(registry, name, [...next.values()])
+ if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
+ reconcileDirectoryChanges(registry, name, [...before.values()], [...next.values()])
+ recordEventWrites(registry, name, parsed.map(getKey), eventFields)
+ if (name === "channelMemberships" || name === "serverMemberships") pruneCanonicalTypingMembership(registry)
}
export function discardCommunityRestoreReplacements(registry: CommunityDbRegistry) {
@@ -464,27 +519,32 @@ function patchRows<N extends CollectionName>(
matches: (row: CommunityCollectionRows[N]) => boolean,
eventKeys?: Iterable<string>,
eventFields?: readonly string[],
+ candidateKeys?: readonly string[],
) {
- const schema = collectionSchema(name)
const getKey = collectionKey(registry, name)
- const current = collectionRows(registry, name)
+ const keys = eventKeys ? [...eventKeys] : undefined
+ const candidates = candidateKeys ?? keys
+ const current = candidates ? candidates.flatMap(key => { const row = readCommunityCollectionRow(registry, name, key); return row ? [row] : [] }) : collectionRows(registry, name)
let changed = false
const changedKeys: string[] = []
- const next = current.map((row) => {
- if (!matches(row)) return row
+ const before: CommunityCollectionRows[N][] = [], after: CommunityCollectionRows[N][] = []
+ for (const row of current) {
+ if (!matches(row)) continue
const key = getKey(row)
- if (isProtectedFromQueryWrite(registry, name, key)) return row
+ if (isProtectedFromQueryWrite(registry, name, key)) continue
changed = true
changedKeys.push(key)
- return schema.parse(patch(row))
- })
+ const updated = parseCommunityCollectionRows(registry, name, [patch(row)])[0]!
+ before.push(row)
+ after.push(updated)
+ }
if (changed) {
- writeCommunityCollectionRows(registry, name, next, getKey)
+ writeCommunityCollectionChanges(registry, name, after)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
- if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
+ reconcileDirectoryChanges(registry, name, before, after)
}
- if (eventKeys) {
- recordEventPatches(registry, name, eventKeys, patch, new Set(changedKeys), eventFields)
+ if (keys) {
+ recordEventPatches(registry, name, keys, patch, new Set(changedKeys), eventFields)
}
else recordEventWrites(registry, name, changedKeys, eventFields)
return changed
@@ -495,20 +555,22 @@ function deleteRows<N extends CollectionName>(
name: N,
remove: (row: CommunityCollectionRows[N]) => boolean,
eventKeys?: Iterable<string>,
+ candidateKeys?: readonly string[],
) {
const getKey = collectionKey(registry, name)
- const current = collectionRows(registry, name)
+ const current = candidateKeys ? candidateKeys.flatMap(key => { const row = readCommunityCollectionRow(registry, name, key); return row ? [row] : [] }) : collectionRows(registry, name)
const removedKeys: string[] = []
- const next = current.filter((row) => {
- if (!remove(row)) return true
+ const removed: CommunityCollectionRows[N][] = []
+ for (const row of current) {
+ if (!remove(row)) continue
const key = getKey(row)
- if (isProtectedFromQueryWrite(registry, name, key)) return true
+ if (isProtectedFromQueryWrite(registry, name, key)) continue
removedKeys.push(key)
- return false
- })
- writeCommunityCollectionRows(registry, name, next, getKey)
+ removed.push(row)
+ }
+ writeCommunityCollectionChanges(registry, name, [], removedKeys)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
- if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
+ reconcileDirectoryChanges(registry, name, removed, [])
if (eventKeys) recordEventDeletes(registry, name, eventKeys)
else recordEventWrites(registry, name, removedKeys)
if (name === "channelMemberships" || name === "serverMemberships") pruneCanonicalTypingMembership(registry)
@@ -718,7 +780,7 @@ export function ingestServerDetail(
upsertRows(registry, "servers", [detail.server])
replaceRows(registry, "categories", categories, row => row.serverId === serverId)
replaceRows(registry, "channels", channels, row => row.serverId === serverId && row.parentChannelId === null)
- recordServerDirectoryWindow(registry, serverId)
+ afterCommunityCollectionWrites(registry, () => { recordServerDirectoryWindow(registry, serverId) }, `directory:${serverId}`)
})
}
@@ -859,39 +921,29 @@ export function publishCommunityServerRailCommit(queryClient: QueryClient, proje
}
function effectiveMessageResource(registry: CommunityDbRegistry, resource: CommunityMessageResource) {
- const previous = registry.collections.messages.status === "ready" ? registry.collections.messages.get(resource.id)
- : registry.queryClient.getQueryData<MessageRow[]>(communityKeys.communityDbCollection(registry.scopeId, "messages"))?.find(message => message.id === resource.id)
+ const previous = readCommunityCollectionRow(registry, "messages", resource.id)
const retainReply = previous?.channelId === resource.channelId
&& previous.authorId === resource.authorId && previous.clientNonce === resource.clientNonce
&& previous.replyToId === resource.replyToId && resource.replyToId !== null && !("replyTo" in resource)
- return messageSchema.parse({ ...resource, ...(retainReply && previous.replyTo ? { replyTo: previous.replyTo } : {}) })
+ return retainReply && previous.replyTo ? messageSchema.parse({ ...resource, replyTo: previous.replyTo }) : resource
}
-export function getCanonicalCommunityMessageResources(queryClient: QueryClient, messages: readonly unknown[]) {
+export function getCanonicalCommunityMessageResources(queryClient: QueryClient, messages: readonly unknown[], window?: object, additionalProfiles?: readonly string[]) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry) return
- const parsed = CommunityMessageResourceSchema.strip().array().safeParse(messages)
- if (!parsed.success) return
- const currentProfiles = new Map(collectionRows(registry, "profiles").map(profile => [profile.id, profile]))
- const profiles = communityMessageProfileIds(parsed.data).flatMap(id => {
- const profile = CommunityResourceProfileSchema.strip().safeParse(currentProfiles.get(id))
- return profile.success ? [profile.data] : []
- })
- const graph = CommunityMessageResourcesSchema.safeParse({ messages: parsed.data, profiles })
- return graph.success ? graph.data : undefined
+ return canonicalMessageResources(registry, messages, window, additionalProfiles)
}
export function validateCommunityMessagePublication(registry: CommunityDbRegistry, messages: readonly unknown[], profiles: readonly CommunityResourceProfile[]) {
const graph = CommunityMessageResourcesSchema.parse({ messages, profiles })
const retained = graph.messages.map(message => effectiveMessageResource(registry, message))
- const currentProfiles = new Map(collectionRows(registry, "profiles").map(profile => [profile.id, profile]))
const available = new Map(communityMessageProfileIds(retained).flatMap(id => {
- const profile = CommunityResourceProfileSchema.strip().safeParse(currentProfiles.get(id))
+ const profile = CommunityResourceProfileSchema.strip().safeParse(readCommunityCollectionRow(registry, "profiles", id))
return profile.success ? [[id, profile.data] as const] : []
}))
for (const profile of graph.profiles) available.set(profile.id, profile)
- if (!CommunityMessageResourcesSchema.safeParse({ messages: retained, profiles: [...available.values()] }).success) throw new Error("Retained message profile resource missing")
- return graph
+ if (communityMessageProfileIds(retained).some(id => !available.has(id))) throw new Error("Retained message profile resource missing")
+ return { messages: retained, profiles: graph.profiles }
}
export function ingestMessages(
@@ -900,27 +952,36 @@ export function ingestMessages(
messages: readonly unknown[],
profiles: readonly CommunityResourceProfile[] = [],
) {
- const fullProfiles = new Map(profiles.map(profile => { const parsed = CommunityResourceProfileSchema.parse(profile); return [parsed.id, parsed] as const }))
+ const verifiedProfiles = profiles.map(profile => CommunityResourceProfileSchema.parse(profile))
const resources = messages.map(message => {
const resource = CommunityMessageResourceSchema.parse(message)
if (resource.channelId !== channelId) throw new Error("Message channel mismatch")
return resource
})
- const rows = resources.map(resource => effectiveMessageResource(registry, resource))
+ return ingestMessageResources(registry, resources.map(resource => effectiveMessageResource(registry, resource)), verifiedProfiles)
+}
+
+function ingestMessageResources(registry: CommunityDbRegistry, resources: readonly CommunityMessageResource[], profiles: readonly CommunityResourceProfile[]) {
+ const fullProfiles = new Map(profiles.map(profile => [profile.id, profile]))
+ const rows = [...resources]
upsertRows(registry, "messages", rows)
+ afterCanonicalWrites(registry, () => {
+ const threads = new Map<string, CommunityCollectionRows["channels"]>()
for (const resource of resources) {
const thread = resource.thread
- const previous = thread && registry.collections.channels.get(thread.id)
+ const previous = thread && (threads.get(thread.id) ?? readCommunityCollectionRow(registry, "channels", thread.id))
if (!thread || !previous || !CommunityChannelResourceSchema.strip().safeParse(previous).success) continue
- upsertRows(registry, "channels", [canonicalChannelRow({ ...previous,
+ threads.set(thread.id, canonicalChannelRow({ ...previous,
name: thread.name, messageCount: thread.messageCount,
...(thread.lastReplyAt === undefined ? {} : { lastMessageAt: thread.lastReplyAt }),
...(thread.tags === undefined ? {} : { tags: thread.tags }),
...(thread.preview === undefined ? {} : { preview: thread.preview }),
...(thread.participantCount === undefined ? {} : { participantCount: thread.participantCount }),
- })])
+ }))
}
- writeCanonicalProfilePatches(registry, messageProfilePatches(resources).filter(patch => {
+ if (threads.size) upsertRows(registry, "channels", [...threads.values()])
+ })
+ const publishProfiles = () => writeCanonicalProfilePatches(registry, messageProfilePatches(resources).filter(patch => {
const previous = registry.collections.profiles.get(patch.id)
return previous !== undefined && CommunityResourceProfileSchema.strip().safeParse(previous).success
}).map(patch => {
@@ -931,6 +992,7 @@ export function ingestMessages(
if (hints.avatar && hints.avatar.avatarVersion <= full.avatarVersion) delete hints.avatar
return hints
}), canonicalWriteContexts.get(registry.queryClient)?.kind === "event")
+ afterCanonicalWrites(registry, publishProfiles)
}
export function ingestReadStateSnapshot(
@@ -953,7 +1015,7 @@ export function ingestReadStateSnapshot(
notifyManager.batch(() => {
replaceRows(registry, "readStates", readStates, () => true)
replaceRows(registry, "readStateClock", [clock], () => true)
- projectConfirmedAttention(registry, changedReads)
+ afterCanonicalWrites(registry, () => projectConfirmedAttention(registry, changedReads))
})
}
@@ -970,7 +1032,7 @@ export function publishCommunityConversationReadState(
if (clock > revision || (current?.observedRevision ?? -1) > revision
|| (mode === "snapshot" ? (current?.observedRevision ?? -1) === revision : (current?.lastReadSeq ?? -1) >= readState.lastReadSeq)) return "superseded" as const
upsertRows(registry, "readStates", [{ ...readState, observedRevision: revision }])
- projectConfirmedAttention(registry, new Set([readState.channelId]))
+ afterCanonicalWrites(registry, () => projectConfirmedAttention(registry, new Set([readState.channelId])))
return "published" as const
})
}
@@ -1537,10 +1599,22 @@ export function publishCommunityMembersSnapshot(queryClient: QueryClient, server
})
}
-function withCommunityQueryProof<T>(queryClient: QueryClient, proof: CommunityFreshQueryProof, publish: (registry: CommunityDbRegistry) => T): T {
+function withCommunityQueryProof<T>(queryClient: QueryClient, proof: CommunityFreshQueryProof, publish: (registry: CommunityDbRegistry) => T) {
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
+ const assertOwner = () => {
+ const registry = getCommunityDbRegistry(queryClient), state = registry?.runtime.ws.get()
+ if (proof.signal?.aborted || registry !== proof.token.registry || !registry?.runtime.lifecycle.get().active
+ || registry.runtime.lifecycle.get().generation !== proof.token.ownerGeneration
+ || state?.profileViewerId !== proof.token.viewerId || state.profileAccountEpoch !== proof.token.accountEpoch) throw new DOMException("Retired community publication", "AbortError")
+ if (proof.token.channelId) assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
+ }
try {
- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => publish(proof.token.registry!))
+ const result = withCommunityCollectionWrites(proof.token.registry!, () => withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => publish(proof.token.registry!)), assertOwner)
+ return result instanceof Promise ? result.catch((error: unknown) => {
+ assertOwner()
+ if (error instanceof ZodError) throw requestBusinessSchemaUpdate()
+ throw error
+ }) : result
} catch (error) { if (error instanceof ZodError) throw requestBusinessSchemaUpdate(); throw error }
}
@@ -1573,7 +1647,7 @@ export function publishCommunityMemberRemoval(queryClient: QueryClient, memberKe
const registry = proof.token.registry!
if (!collectionRows(registry, "serverMemberships").some((row) => row.id === memberKey && row.memberId === memberId)) return false
return withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
- deleteRows(registry, "serverMemberships", (row) => row.id === memberKey && row.memberId === memberId, [memberKey])
+ deleteRows(registry, "serverMemberships", (row) => row.id === memberKey && row.memberId === memberId, [memberKey], [memberKey])
return true
})
}
@@ -1608,22 +1682,24 @@ export function assertCommunityLiveSnapshotTokenCurrent(
token: CommunityLiveSnapshotToken,
signal: AbortSignal | undefined,
) {
+ assertCommunityLiveSnapshotOwnerCurrent(queryClient, token, signal)
const state = getCommunityRuntime(queryClient).ws.get()
if (
- signal?.aborted
- || !token.registry?.runtime.lifecycle.get().active
- || token.registry.runtime.lifecycle.get().generation !== token.ownerGeneration
- || state.profileViewerId !== token.viewerId
- || state.profileAccountEpoch !== token.accountEpoch
- || state.accessEpoch !== token.accessEpoch
+ state.accessEpoch !== token.accessEpoch
|| (token.channelId && token.channelLineage
? [token.channelId, token.channelLineage.parentChannelId].some((id) => id && (state.channelAccessScopes.get(id)?.generation ?? 0) !== (token.channelScopes.get(id)?.generation ?? 0))
: [...state.channelAccessScopes].some(([id, scope]) => scope.generation !== (token.channelScopes.get(id)?.generation ?? 0)))
- || queryClient !== token.queryClient
- || getCommunityDbRegistry(queryClient) !== token.registry
) throw new DOMException("Stale community live snapshot", "AbortError")
}
+export function assertCommunityLiveSnapshotOwnerCurrent(queryClient: QueryClient, token: CommunityLiveSnapshotToken, signal: AbortSignal | undefined) {
+ const state = getCommunityRuntime(queryClient).ws.get()
+ if (signal?.aborted || !token.registry?.runtime.lifecycle.get().active
+ || token.registry.runtime.lifecycle.get().generation !== token.ownerGeneration
+ || state.profileViewerId !== token.viewerId || state.profileAccountEpoch !== token.accountEpoch
+ || queryClient !== token.queryClient || getCommunityDbRegistry(queryClient) !== token.registry) throw new DOMException("Stale community live snapshot", "AbortError")
+}
+
export function beginCommunityCommandRevision(queryClient: QueryClient, token: CommunityLiveSnapshotToken): CommunityLiveSnapshotToken {
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
return { ...token, canonicalRevision: canonicalRevisionState(queryClient).revision }
@@ -1705,8 +1781,10 @@ export function publishCommunityMessages(
if (graph.messages.some(message => message.channelId !== publication.channelId)) throw new Error("Message channel mismatch")
notifyManager.batch(() => {
ingestResourceProfiles(registry, graph.profiles, publication.proof)
- if (!getCanonicalCommunityMessageResources(queryClient, graph.messages.map(message => effectiveMessageResource(registry, message)))) throw new Error("Message profile publication incomplete")
- ingestMessages(registry, publication.channelId, graph.messages, graph.profiles)
+ ingestMessageResources(registry, graph.messages, graph.profiles)
+ afterCommunityCollectionWrites(registry, () => {
+ if (!getCanonicalCommunityMessageResources(queryClient, graph.messages)) throw new Error("Message profile publication incomplete")
+ })
})
return "published" as const
})
@@ -1724,16 +1802,12 @@ export function publishCommunityEmbeddedMessages(
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
const graph = validateCommunityMessagePublication(registry, publication.entries.map(entry => entry.message), publication.profiles)
if (publication.entries.some(entry => entry.channelId !== entry.message.channelId)) throw new Error("Message channel mismatch")
- const byChannel = new Map<string, Array<MessageInput | CommunityMessageResource>>()
- for (const { channelId, message } of publication.entries) {
- byChannel.set(channelId, [...(byChannel.get(channelId) ?? []), message])
- }
notifyManager.batch(() => {
ingestResourceProfiles(registry, graph.profiles, publication.proof)
- if (!getCanonicalCommunityMessageResources(queryClient, graph.messages.map(message => effectiveMessageResource(registry, message)))) throw new Error("Message profile publication incomplete")
- for (const [channelId, messages] of byChannel) {
- ingestMessages(registry, channelId, messages, graph.profiles)
- }
+ ingestMessageResources(registry, graph.messages, graph.profiles)
+ afterCommunityCollectionWrites(registry, () => {
+ if (!getCanonicalCommunityMessageResources(queryClient, graph.messages)) throw new Error("Message profile publication incomplete")
+ })
})
return "published" as const
})
@@ -1863,6 +1937,7 @@ export function patchCanonicalCommunityChannel(
"channels",
patch,
(row) => row.id === channelId,
+ undefined, undefined, [channelId],
))
}
@@ -2006,7 +2081,7 @@ export function publishCommunityNotificationSetting(queryClient: QueryClient, ta
const registry = proof.token.registry!, id = notificationSettingKey(target)
if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("notificationSettings", id)) ?? 0) > proof.token.canonicalRevision) return false
return withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
- if (level === null) deleteRows(registry, "notificationSettings", (row) => row.id === id, [id])
+ if (level === null) deleteRows(registry, "notificationSettings", (row) => row.id === id, [id], [id])
else upsertRows(registry, "notificationSettings", [{ id, ...target, level }])
return true
})
@@ -2045,7 +2120,7 @@ export function publishCommunityFriendDecision(queryClient: QueryClient, friends
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
const registry = proof.token.registry!
if (action === "accept") publishConfirmedFields(queryClient, "friendships", friendshipId, { kind: "accepted" as const, needsOwnerApproval: null }, proof)
- else if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("friendships", friendshipId)) ?? 0) <= proof.token.canonicalRevision) withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "friendships", (row) => row.id === friendshipId, [friendshipId]))
+ else if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("friendships", friendshipId)) ?? 0) <= proof.token.canonicalRevision) withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "friendships", (row) => row.id === friendshipId, [friendshipId], [friendshipId]))
withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.sourceId === friendshipId))
removeSettledCommunityFriendCommands(queryClient, [friendshipId])
}
@@ -2090,30 +2165,35 @@ function publishCreatedTreeRow<N extends "channels" | "categories">(
) {
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
const registry = proof.token.registry!
- const existing = collectionRows(registry, name).find((current) => current.id === row.id)
+ const existing = readCommunityCollectionRow(registry, name, row.id)
if (!existing) withCommunityQueryProof(queryClient, proof, (owner) => upsertRows(owner, name, [row]))
- if (collectionRows(registry, name).some((current) => current.id === row.id)) {
+ afterCanonicalWrites(registry, () => {
+ if (readCommunityCollectionRow(registry, name, row.id)) {
withCanonicalWriteContext(queryClient, { kind: "event" }, () => recordEventWrites(registry, name, [row.id]))
}
+ })
}
export function publishCommunityCreatedChannel(queryClient: QueryClient, input: Parameters<typeof canonicalChannelRow>[0], proof: CommunityFreshQueryProof) {
+ return withCommunityQueryProof(queryClient, proof, (registry) => {
const row = canonicalChannelRow(input, proof.token.registry!.collections.channels.get(input.id))
publishCreatedTreeRow(queryClient, "channels", row, proof)
- const registry = proof.token.registry!
- if (!registry.accountId || !collectionRows(registry, "channels").some((current) => current.id === row.id)) return
+ afterCanonicalWrites(registry, () => {
+ if (!registry.accountId || !readCommunityCollectionRow(registry, "channels", row.id)) return
withCanonicalWriteContext(queryClient, { kind: "event" }, () => upsertRows(
registry, "channelMemberships", [canonicalChannelMembershipRow(row.id, registry.accountId!, "access", { source: "inherited" })],
))
+ })
+ })
}
export function publishCommunityCreatedCategory(queryClient: QueryClient, row: CategoryRow, proof: CommunityFreshQueryProof) {
- publishCreatedTreeRow(queryClient, "categories", row, proof)
+ return withCommunityQueryProof(queryClient, proof, () => publishCreatedTreeRow(queryClient, "categories", row, proof))
}
export function publishCommunityDeletedCategory(queryClient: QueryClient, categoryId: string, proof: CommunityFreshQueryProof) {
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
- withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(proof.token.registry!, "categories", (row) => row.id === categoryId, [categoryId]))
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(proof.token.registry!, "categories", (row) => row.id === categoryId, [categoryId], [categoryId]))
}
export function publishCommunityServerMembershipRemoval(queryClient: QueryClient, serverId: string, proof: CommunityFreshQueryProof) {
@@ -2137,6 +2217,7 @@ export function patchCanonicalCommunityMessage(
"messages",
patch,
(row) => row.id === messageId,
+ undefined, undefined, [messageId],
)
))
}
@@ -2181,7 +2262,7 @@ export function setCanonicalCommunityChannelMember(queryClient: QueryClient, cha
const id = channelMembershipKey(channelId, userId, relation)
const write = () => {
if (!present) {
- deleteRows(registry, "channelMemberships", (row) => row.id === id, [id])
+ deleteRows(registry, "channelMemberships", (row) => row.id === id, [id], [id])
if (userId === registry.accountId && relation === "notify") retireCommunityNotificationScope(registry, channelId)
return true
}
@@ -2221,9 +2302,9 @@ export function getCanonicalCommunityChannelMemberships(queryClient: QueryClient
: []
}
-export function getCanonicalCommunityMessages(queryClient: QueryClient) {
+export function getCanonicalCommunityMessages(queryClient: QueryClient, channelId?: string) {
const registry = getCommunityDbRegistry(queryClient)
- return registry ? collectionRows(registry, "messages") : []
+ return registry ? channelId === undefined ? collectionRows(registry, "messages") : canonicalChannelMessages(registry, channelId) : []
}
export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: string) {
@@ -2353,7 +2434,7 @@ export function purgeCommunityChannel(registry: CommunityDbRegistry, channelId:
export function purgeCommunityForumPost(registry: CommunityDbRegistry, unit: { childChannelId: string; openerMessageId: string; serverId?: string }, options?: { queries?: ReadonlySet<Query>; assertView?: () => void }) {
withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {
if (registry.collections.channels.has(unit.childChannelId) || !registry.runtime.ws.actions.isChannelAccessRevoked(unit.childChannelId, unit.serverId)) retireCommunityChannelReading(registry, unit.childChannelId, { reason: "resource-deleted", serverId: unit.serverId, ...options })
- deleteRows(registry, "messages", (row) => row.id === unit.openerMessageId, [unit.openerMessageId])
+ deleteRows(registry, "messages", (row) => row.id === unit.openerMessageId, [unit.openerMessageId], [unit.openerMessageId])
deleteRows(registry, "attentionItems", (row) => row.childChannelId === unit.childChannelId || row.messageId === unit.openerMessageId)
}))
}
diff --git a/src/web/src/lib/community-db/write.ts b/src/web/src/lib/community-db/write.ts
index f1fe85c0e..db7416a61 100644
--- a/src/web/src/lib/community-db/write.ts
+++ b/src/web/src/lib/community-db/write.ts
@@ -4,6 +4,145 @@ import { communityKeys } from "@/lib/query-keys"
import type { CommunityDbRegistry } from "./collections"
import { communityCollectionSchemas, type CommunityCollectionName, type CommunityCollectionRows } from "@alook/shared"
+const acceptedViews = new WeakMap<CommunityDbRegistry, {
+ indexes: WeakMap<readonly unknown[], Map<CommunityCollectionName, Map<string, unknown>>>
+ rows: WeakMap<object, Map<CommunityCollectionName, object | null>>
+}>()
+type AfterWrite = () => void | Promise<unknown>
+type WriteScope = { completions: Promise<void>[]; after: Map<object | string, AfterWrite>; validated: Map<CommunityCollectionName, WeakSet<object>> }
+const writeScopes = new WeakMap<CommunityDbRegistry, WriteScope>()
+
+export function withCommunityCollectionWrites<T>(registry: CommunityDbRegistry, publish: () => T, assertCurrent?: () => void): T | Promise<T> {
+ if (writeScopes.has(registry)) return publish()
+ const generation = registry.runtime.lifecycle.get().generation
+ const accountEpoch = registry.runtime.ws.get().profileAccountEpoch
+ const guard = assertCurrent ?? (() => {
+ if (!registry.runtime.lifecycle.get().active || registry.runtime.lifecycle.get().generation !== generation
+ || registry.runtime.ws.get().profileAccountEpoch !== accountEpoch) throw new DOMException("Retired community owner", "AbortError")
+ })
+ const scope: WriteScope = { completions: [], after: new Map(), validated: new Map() }
+ writeScopes.set(registry, scope)
+ let result: T
+ try { result = publish() }
+ catch (error) { void Promise.allSettled(scope.completions); throw error }
+ finally { writeScopes.delete(registry) }
+ const finish = () => {
+ guard()
+ let completion: Promise<unknown> | undefined
+ for (const after of scope.after.values()) {
+ const publish = () => { guard(); return after() }
+ if (completion) completion = completion.then(publish)
+ else {
+ const next = publish()
+ if (next instanceof Promise) completion = next
+ }
+ }
+ return completion ? completion.then(() => { guard(); return result }) : result
+ }
+ return scope.completions.length ? Promise.all(scope.completions).then(finish) : finish()
+}
+
+export function afterCommunityCollectionWrites(registry: CommunityDbRegistry, publish: AfterWrite, key: object | string = publish) {
+ const scope = writeScopes.get(registry)
+ if (scope) scope.after.set(key, () => withCommunityCollectionWrites(registry, publish))
+ else return publish()
+}
+
+function trackWrite(registry: CommunityDbRegistry, completion: Promise<void>) {
+ const scope = writeScopes.get(registry)
+ if (scope) { scope.completions.push(completion); void completion.catch(() => undefined) }
+ return completion
+}
+
+export function parseCommunityCollectionRows<N extends CommunityCollectionName>(registry: CommunityDbRegistry, name: N, rows: readonly unknown[]): CommunityCollectionRows[N][] {
+ const scope = writeScopes.get(registry)
+ let validated = scope?.validated.get(name)
+ if (scope && !validated) { validated = new WeakSet(); scope.validated.set(name, validated) }
+ return rows.map(row => {
+ if (registry.collections[name].status === "ready" && row !== null && typeof row === "object" && validated?.has(row)) return row as CommunityCollectionRows[N]
+ const parsed = communityCollectionSchemas[name].parse(communityRowData(row)) as CommunityCollectionRows[N]
+ validated?.add(parsed)
+ return parsed
+ })
+}
+
+export function readCommunityCollectionRow<N extends CommunityCollectionName>(registry: CommunityDbRegistry, name: N, key: string): CommunityCollectionRows[N] | undefined {
+ if (!registry.runtime.lifecycle.get().active) return
+ let view = acceptedViews.get(registry)
+ if (!view) { view = { indexes: new WeakMap(), rows: new WeakMap() }; acceptedViews.set(registry, view) }
+ const rows = registry.queryClient.getQueryData<readonly unknown[]>(communityKeys.communityDbCollection(registry.scopeId, name))
+ const collection = registry.collections[name]
+ let row: unknown
+ if (rows) {
+ let indexes = view.indexes.get(rows)
+ if (!indexes) { indexes = new Map(); view.indexes.set(rows, indexes) }
+ let index = indexes.get(name)
+ if (!index) {
+ const getKey = (row: unknown) => (collection.getKeyFromItem as (row: unknown) => string).call(collection, row)
+ index = new Map(rows.filter(value => value !== null && typeof value === "object").map(value => [getKey(value), value]))
+ indexes.set(name, index)
+ }
+ row = index.get(key)
+ } else row = collection.get(key)
+ if (row === null || typeof row !== "object") return
+ let verified = view.rows.get(row)
+ if (!verified) { verified = new Map(); view.rows.set(row, verified) }
+ if (!verified.has(name)) {
+ const parsed = communityCollectionSchemas[name].safeParse(communityRowData(row))
+ verified.set(name, parsed.success ? parsed.data : null)
+ }
+ return (verified.get(name) ?? undefined) as CommunityCollectionRows[N] | undefined
+}
+
+function changedRow(previous: unknown, next: object) {
+ if (previous === undefined) return next
+ const previousData = communityRowData(previous)
+ const entries = previousData !== null && typeof previousData === "object" ? Object.entries(previousData) : []
+ const fields = Object.fromEntries(entries.filter(([, value]) => value !== undefined))
+ const nextFields = Object.fromEntries(Object.entries(next).filter(([, value]) => value !== undefined))
+ if (replaceEqualDeep(fields, nextFields) === fields) return
+ return { ...Object.fromEntries(entries.filter(([key]) => !(key in next)).map(([key]) => [key, undefined])), ...next }
+}
+
+export function writeCommunityCollectionChanges<N extends CommunityCollectionName>(registry: CommunityDbRegistry, name: N, incoming: readonly unknown[], removed: readonly string[] = []) {
+ if (!registry.runtime.lifecycle.get().active) throw new DOMException("Retired community owner", "AbortError")
+ type Row = CommunityCollectionRows[N]
+ const verified = parseCommunityCollectionRows(registry, name, incoming)
+ const collection = registry.collections[name] as {
+ status: string
+ getKeyFromItem: (row: Row) => string
+ utils: { writeBatch: (callback: () => void) => Promise<void>; writeDelete: (keys: string[]) => void; writeUpsert: (rows: Row[]) => void }
+ }
+ const getKey = (row: Row) => collection.getKeyFromItem(row)
+ const keys = verified.map(getKey)
+ if ([...keys, ...removed].some(key => typeof key !== "string" || key.length === 0) || new Set(keys).size !== keys.length
+ || removed.some(key => keys.includes(key))) throw new Error("Invalid canonical row identity")
+ const changed = verified.flatMap(row => {
+ const next = changedRow(readCommunityCollectionRow(registry, name, getKey(row)), row)
+ return next ? [next as Row] : []
+ })
+ const deletes = [...new Set(removed)].filter(key => readCommunityCollectionRow(registry, name, key) !== undefined)
+ if (!changed.length && !deletes.length) return
+ if (collection.status !== "ready") {
+ const queryKey = communityKeys.communityDbCollection(registry.scopeId, name)
+ const previous = registry.queryClient.getQueryData<Row[]>(queryKey) ?? []
+ const replacements = new Map(changed.map(row => [getKey(row), row]))
+ const deleted = new Set(deletes)
+ const next = previous.flatMap(row => {
+ const key = getKey(row)
+ const replacement = replacements.get(key)
+ replacements.delete(key)
+ return deleted.has(key) ? [] : [replacement ?? row]
+ })
+ registry.queryClient.setQueryData(queryKey, [...next, ...replacements.values()])
+ return
+ }
+ return trackWrite(registry, collection.utils.writeBatch(() => {
+ if (deletes.length) collection.utils.writeDelete(deletes)
+ if (changed.length) collection.utils.writeUpsert(changed)
+ }))
+}
+
export function communityRowData(row: unknown) {
return row !== null && typeof row === "object" && hasVirtualProps(row)
? Object.fromEntries(Object.entries(row).filter(([key]) => !["$hasPendingWrites", "$synced", "$origin", "$key", "$collectionId"].includes(key)))
@@ -17,8 +156,9 @@ export function writeCommunityCollectionRows<N extends CommunityCollectionName>(
getKey: (row: CommunityCollectionRows[N]) => string,
options?: { updatedAt: number },
) {
+ if (!registry.runtime.lifecycle.get().active) throw new DOMException("Retired community owner", "AbortError")
type Row = CommunityCollectionRows[N]
- const verified = rows.map(row => communityCollectionSchemas[name].parse(communityRowData(row))) as Row[]
+ const verified = parseCommunityCollectionRows(registry, name, rows)
const keys = verified.map(getKey)
if (keys.some(key => typeof key !== "string" || key.length === 0) || new Set(keys).size !== keys.length) throw new Error("Invalid canonical row identity")
const collection = registry.collections[name] as {
@@ -59,8 +199,8 @@ export function writeCommunityCollectionRows<N extends CommunityCollectionName>(
if (removed.length === 0 && changed.length === 0) {
return
}
- return collection.utils.writeBatch(() => {
+ return trackWrite(registry, collection.utils.writeBatch(() => {
if (removed.length > 0) collection.utils.writeDelete(removed)
if (changed.length > 0) collection.utils.writeUpsert(changed)
- })
+ }))
}
diff --git a/src/web/src/lib/community/account-cache-lifecycle.ts b/src/web/src/lib/community/account-cache-lifecycle.ts
index 515c3be26..ee3253b50 100644
--- a/src/web/src/lib/community/account-cache-lifecycle.ts
+++ b/src/web/src/lib/community/account-cache-lifecycle.ts
@@ -29,10 +29,11 @@ export async function loadCommunityRequest<T>(
load: (options: ApiRequestOptions) => Promise<T>,
token: CommunityLiveSnapshotToken,
signal?: AbortSignal,
+ assertCurrent?: () => void,
): Promise<T> {
const registry = token.registry
if (!registry) throw new DOMException("Missing community profile owner", "AbortError")
- const assertActive = () => assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal)
+ const assertActive = assertCurrent ?? (() => assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal))
await registry.ready
assertActive()
await registry.collections.profiles.preload()
@@ -51,10 +52,11 @@ export function apiFetchCommunity<T>(
path: string,
options: ApiRequestOptions | undefined,
token: CommunityLiveSnapshotToken,
+ assertCurrent?: () => void,
): Promise<T> {
const observation = options?.observation ?? commandObservation(token) ?? { page: currentPageObservation(), reason: "unknown" }
return loadCommunityRequest((origin) => apiFetch<T>(path, {
...options, ...origin, observation, signal: options?.signal,
assertActive: () => { origin.assertActive?.(); options?.assertActive?.() },
- }), token, options?.signal ?? undefined)
+ }), token, options?.signal ?? undefined, assertCurrent)
}
diff --git a/src/web/src/lib/community/channel-ref-access.test.ts b/src/web/src/lib/community/channel-ref-access.test.ts
new file mode 100644
index 000000000..7bfa001fc
--- /dev/null
+++ b/src/web/src/lib/community/channel-ref-access.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { createCommunityWsStore } from "@/stores/community/ws-store"
+import { channelRefAccessQualification, channelRefTargetAffected } from "./channel-ref"
+
+afterEach(() => vi.restoreAllMocks())
+const target = { server: { id: "server", name: "Studio" }, channel: { id: "child", name: "Thread", parentChannelId: "parent" } }
+
+it("shares unknown scope sorting and does not enumerate scopes for a known target", () => {
+ const ws = createCommunityWsStore("viewer")
+ for (let i = 0; i < 1000; i++) ws.actions.beginChannelMembershipChange("other", `other-${i}`)
+ const state = ws.get(), iterate = vi.spyOn(state.channelAccessScopes, Symbol.iterator)
+ const known = channelRefAccessQualification(state, target)
+ for (let i = 0; i < 100; i++) expect(channelRefAccessQualification(state, target)).toBe(known)
+ expect(iterate).not.toHaveBeenCalled()
+ const unknown = channelRefAccessQualification(state)
+ for (let i = 0; i < 100; i++) expect(channelRefAccessQualification(state)).toBe(unknown)
+ expect(iterate).toHaveBeenCalledTimes(1)
+})
+
+it("uses target, parent and server generations and resets them with the account owner", () => {
+ const ws = createCommunityWsStore("viewer")
+ const known = channelRefAccessQualification(ws.get(), target), unknown = channelRefAccessQualification(ws.get())
+ ws.actions.revokeServerAccess("other")
+ expect(channelRefAccessQualification(ws.get(), target)).toBe(known)
+ expect(channelRefAccessQualification(ws.get())).not.toBe(unknown)
+ ws.actions.revokeChannelAccess("server", "parent")
+ expect(channelRefAccessQualification(ws.get(), target)).not.toBe(known)
+ ws.actions.rememberChannelAccess("server", "child", "parent")
+ const restored = channelRefAccessQualification(ws.get(), target)
+ ws.actions.revokeServerAccess("server")
+ expect(channelRefAccessQualification(ws.get(), target)).not.toBe(restored)
+ ws.actions.grantServerAccess("server")
+ expect(channelRefAccessQualification(ws.get(), target)).not.toBe(restored)
+ ws.actions.activateProfileAccount("other-viewer")
+ expect(ws.get().serverAccessGenerations.size).toBe(0)
+ expect(channelRefAccessQualification(ws.get(), target)).not.toBe(known)
+})
+
+it("limits known invalidation to the actual scope and keeps unknown targets conservative", () => {
+ expect(channelRefTargetAffected(target, { channelId: "other" })).toBe(false)
+ expect(channelRefTargetAffected(target, { channelId: "parent" })).toBe(true)
+ expect(channelRefTargetAffected(target, { channelId: "child" })).toBe(true)
+ expect(channelRefTargetAffected(target, { serverId: "other" })).toBe(false)
+ expect(channelRefTargetAffected(target, { serverId: "server" })).toBe(true)
+ expect(channelRefTargetAffected(undefined, { channelId: "other" })).toBe(true)
+ expect(channelRefTargetAffected(target)).toBe(true)
+})
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index 46fe2d39f..e50736121 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -1,10 +1,45 @@
import { DM_SERVER, formatRef, parseNameAndTag, parseRef } from "@alook/shared"
+import type { CommunityWsStoreState } from "@/stores/community/ws-store"
export type ChannelRefTarget = {
server: { id: string; name: string }
channel: { id: string; name: string; parentChannelId: string | null }
}
+const referenceScopes = new WeakMap<CommunityWsStoreState["channelAccessScopes"], string>()
+const referenceServers = new WeakMap<CommunityWsStoreState["revokedServerIds"], string>()
+export type ChannelRefAccessState = Pick<CommunityWsStoreState, "profileAccountEpoch" | "accessEpoch" | "serverAccessGenerations" | "revokedServerIds" | "channelAccessScopes">
+
+export function channelRefAccessQualification(state: ChannelRefAccessState, target?: ChannelRefTarget) {
+ if (target) {
+ const scope = (id: string, parentId: string | null) => {
+ const value = state.channelAccessScopes.get(id)
+ return [id, value?.generation ?? 0, value?.revoked ?? false, value?.serverId ?? target.server.id, value?.parentChannelId ?? parentId]
+ }
+ return JSON.stringify([state.profileAccountEpoch, state.serverAccessGenerations.get(target.server.id) ?? 0,
+ state.revokedServerIds.has(target.server.id), scope(target.channel.id, target.channel.parentChannelId),
+ target.channel.parentChannelId ? scope(target.channel.parentChannelId, null) : null])
+ }
+ let scopes = referenceScopes.get(state.channelAccessScopes)
+ if (scopes === undefined) {
+ scopes = JSON.stringify([...state.channelAccessScopes].filter(([, scope]) => scope.generation > 0 || scope.revoked)
+ .sort(([left], [right]) => left.localeCompare(right)).map(([id, scope]) => [id, scope.generation, scope.revoked]))
+ referenceScopes.set(state.channelAccessScopes, scopes)
+ }
+ let servers = referenceServers.get(state.revokedServerIds)
+ if (servers === undefined) {
+ servers = JSON.stringify([...state.revokedServerIds].sort())
+ referenceServers.set(state.revokedServerIds, servers)
+ }
+ return JSON.stringify([state.profileAccountEpoch, state.accessEpoch, scopes, servers])
+}
+
+export function channelRefTargetAffected(target: ChannelRefTarget | undefined, scope?: { serverId?: string | null; channelId?: string }) {
+ return !scope || !target || (scope.channelId
+ ? target.channel.id === scope.channelId || target.channel.parentChannelId === scope.channelId
+ : target.server.id === scope.serverId)
+}
+
export function parseChannelRefDestination(ref: string) {
try {
const parsed = parseRef(ref)
diff --git a/src/web/src/lib/community/conversation-entry.server.ts b/src/web/src/lib/community/conversation-entry.server.ts
index 9f60f7cdb..0c76f29ef 100644
--- a/src/web/src/lib/community/conversation-entry.server.ts
+++ b/src/web/src/lib/community/conversation-entry.server.ts
@@ -1,6 +1,6 @@
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, communityChannelResourceFromStorage, CommunityConversationEntryReadSchema, CommunityThreadsReadSchema, CommunityMessageResourceSchema, queries, withD1Retry, type CommunityConversationEntryRead, type Database } from "@alook/shared"
-import { readCommunityResourceProfiles } from "./resource-profiles.server"
+import { createCommunityResourceProfileReader, type CommunityResourceProfileReader } from "./resource-profiles.server"
import { readCommunityMessageWindow } from "./message-window.server"
import { communityMessagesReadFromPage } from "./read-contract"
import type { DoorTarget } from "./message-door"
@@ -26,17 +26,18 @@ export async function readCommunityConversationEntry(db: Database, input: Conver
const channelId = target.target.channelId
if (channel.id !== channelId) throw new Error("Conversation entry target mismatch")
if (channel.archived) return { ok: false, status: 403, error: "channel is archived" }
+ const readProfiles = createCommunityResourceProfileReader(db)
const [read, canSend, peer, opener, parent] = await Promise.all([
- readEntryWindow(db, input),
+ readEntryWindow(db, input, readProfiles),
target.access.surface === "dm"
? queries.communityFriendship.areFriends(db, viewerId, target.access.dm.otherUserId)
: Promise.resolve(true),
- target.access.surface === "dm" ? readPeer(db, target.access.dm.otherUserId) : Promise.resolve(null),
+ target.access.surface === "dm" ? readPeer(db, target.access.dm.otherUserId, readProfiles) : Promise.resolve(null),
channel.parentChannelId && channel.parentMessageId ? readOpener(db, viewerId, channel.parentChannelId, channel.parentMessageId) : Promise.resolve(undefined),
channel.parentChannelId ? readParent(db, viewerId, channel.parentChannelId) : Promise.resolve(undefined),
])
if (!read.ok) return read
- const openerProfiles = opener ? await readCommunityMessageProfiles(db, [opener]) : []
+ const openerProfiles = opener ? await readCommunityMessageProfiles(db, [opener], readProfiles) : []
const profiles = [...new Map([...read.page.profiles, ...openerProfiles].map(profile => [profile.id, profile])).values()]
return { ok: true, entry: CommunityConversationEntryReadSchema.parse({
...communityMessagesReadFromPage(channelId, read.page), profiles, viewerId, channel, peer,
@@ -49,7 +50,7 @@ export async function readCommunityConversationEntry(db: Database, input: Conver
}) }
}
-async function readEntryWindow(db: Database, { viewerId, target, window, preferTail, tag }: ConversationEntryInput) {
+async function readEntryWindow(db: Database, { viewerId, target, window, preferTail, tag }: ConversationEntryInput, readProfiles: CommunityResourceProfileReader) {
const channelId = target.target.channelId
const { readState: row, revision } = await withD1Retry(() => queries.communityReadState.getChannelReadStateSnapshot(db, { userId: viewerId, channelId }), {
route: "community/messages:entry-read-state",
@@ -70,20 +71,20 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
reason: window.anchorId ? "explicit_anchor" : anchorId ? "read_pointer" : "tail", anchorMessageId: anchorId ?? null,
}
let result = await readCommunityMessageWindow(db, {
- viewerId, target, window: { ...window, anchorId }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag,
+ viewerId, target, window: { ...window, anchorId }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag, readProfiles,
})
if (!result.ok && !window.anchorId && anchorId) {
selection = { reason: "read_pointer_missing", anchorMessageId: null }
result = await readCommunityMessageWindow(db, {
- viewerId, target, window: { ...window, anchorId: undefined }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag,
+ viewerId, target, window: { ...window, anchorId: undefined }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag, readProfiles,
})
}
if (!result.ok) return { ...result, ...(window.anchorId ? { details: [COMMUNITY_CONVERSATION_ANCHOR_MISSING] } : {}) }
return { ok: true as const, page: result.page, readState, revision, selection }
}
-async function readPeer(db: Database, peerId: string) {
- const [peer] = await withD1Retry(() => readCommunityResourceProfiles(db, [peerId]), { route: "community/messages:entry-peer" })
+async function readPeer(db: Database, peerId: string, readProfiles: CommunityResourceProfileReader) {
+ const [peer] = await withD1Retry(() => readProfiles([peerId]), { route: "community/messages:entry-peer" })
if (!peer) throw new Error("Conversation peer resource missing")
return peer
}
diff --git a/src/web/src/lib/community/conversation-entry.test.ts b/src/web/src/lib/community/conversation-entry.test.ts
index e6e4534af..cc84239e0 100644
--- a/src/web/src/lib/community/conversation-entry.test.ts
+++ b/src/web/src/lib/community/conversation-entry.test.ts
@@ -19,6 +19,21 @@ beforeEach(() => { load.mockReset() })
import { conversationEntryFixture as entry, conversationEntryTarget as target, dmConversationEntryFixture, forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"
describe("conversation entry canonical publication", () => {
+ it("shares the qualified display and landing window through unrelated profile changes", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const value = entry()
+ await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const scope = getQualifiedConversationScope(client, target)!
+ const first = findConversationDisplayWindow(client, target, scope)
+ expect(first).toBeDefined()
+ expect(findConversationEntryWindow(client, target, scope, value.readState)).toBe(first)
+ const profiles = [...registry.collections.profiles.values(), profileResourceFixture({ id: "unrelated" })]
+ await writeCommunityCollectionRows(registry, "profiles", profiles, row => row.id)
+ expect(findConversationDisplayWindow(client, target, scope)).toBe(first)
+ await writeCommunityCollectionRows(registry, "profiles", [], row => row.id)
+ expect(findConversationDisplayWindow(client, target, scope)).toBeUndefined()
+ })
+
it("does not backfill entry phases when observation becomes eligible after that request began", async () => {
const { client } = await createCommunityQueryOwner()
const events: Array<{ name: string }> = []
@@ -59,7 +74,7 @@ describe("conversation entry canonical publication", () => {
value.parent = { ...entry().channel, id: "parent" }
value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }
}
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
const before = client.getQueryData(resource.windowKey)
const channels = communityKeys.communityDbCollection("viewer", "channels")
if (condition === "retired") registry.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 }))
@@ -98,7 +113,7 @@ describe("conversation entry canonical publication", () => {
}
const destination = { channelId: "c1", serverId: value.channel.serverId }
const options = conversationEntryOptions(client, destination)
- const resource = publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
client.setQueryData(options.queryKey, resource)
client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
const scope = getQualifiedConversationScope(client, destination)
@@ -112,7 +127,7 @@ describe("conversation entry canonical publication", () => {
it("rejects residual entities without viewer access and retires the same cache on an account change", async () => {
const { client, registry } = await createCommunityQueryOwner()
- publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ await publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(getQualifiedConversationScope(client, target)).toBeDefined()
const key = communityKeys.communityDbCollection("viewer", "channelMemberships")
const rows = client.getQueryData(key)
@@ -127,7 +142,7 @@ describe("conversation entry canonical publication", () => {
it("keeps a real cached display window distinct from an uncovered target and an isolated canonical entity", async () => {
const { client, registry } = await createCommunityQueryOwner()
const value = entry()
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
const scope = getQualifiedConversationScope(client, target)!
const selected = { ...target, anchorMessageId: "elsewhere" }
expect(findConversationDisplayWindow(client, selected, scope)?.key).toEqual(resource.windowKey)
@@ -194,7 +209,7 @@ describe("conversation entry canonical publication", () => {
it.each(["child-missing", "child-type", "child-server", "child-parent", "opener-missing", "opener-channel"] as const)("rejects a cached Forum display window with %s without refreshing its qualification", async invalid => {
const { client, registry } = await createCommunityQueryOwner()
const value = forumConversationEntryFixture()
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
const scope = getQualifiedConversationScope(client, target)!
expect(findConversationDisplayWindow(client, target, scope)?.key).toEqual(resource.windowKey)
if (invalid === "child-missing") await registry.collections.channels.utils.writeDelete("t1")
@@ -223,7 +238,7 @@ describe("conversation entry canonical publication", () => {
if (state === "failed-query") await expect(client.query({ queryKey: key, queryFn: () => Promise.reject(new Error("first read failed")), retry: false, select: undefined })).rejects.toThrow("first read failed")
if (state === "empty-pages") client.setQueryData(key, { pages: [], pageParams: [] })
if (state === "mismatched-params") client.setQueryData(key, { pages: [forum ? { threads: [] } : { messages: [] }], pageParams: [] })
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(client.getQueryData<{ pages: unknown[] }>(key)?.pages).toHaveLength(1)
expect(findConversationEntryWindow(client, target, resource, value.readState)?.key).toEqual(key)
}
@@ -235,7 +250,7 @@ describe("conversation entry canonical publication", () => {
const previous = { pages: [{ threads: [], nextCursor: "older" }, { threads: [], nextCursor: null }], pageParams: [null, "older"] }
client.setQueryData(key, previous)
const value = forumConversationEntryFixture()
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(client.getQueryData(key)).toBe(previous)
expect(findConversationEntryWindow(client, target, resource, value.readState)?.key).toEqual(key)
})
@@ -257,24 +272,24 @@ describe("conversation entry canonical publication", () => {
const token = captureCommunityLiveSnapshotToken(client, "c1")
const { writeCommunityProfilePatches } = await import("./profile-seed")
writeCommunityProfilePatches([{ id: "peer", identityAbout: { name: "Current", discriminator: "0042" }, avatar: { avatar: "new-avatar", avatarVersion: 8 } }], registry, { event: true })
- publishConversationEntry(client, { channelId: "c1", serverId: null }, dmConversationEntryFixture(), { token })
+ await publishConversationEntry(client, { channelId: "c1", serverId: null }, dmConversationEntryFixture(), { token })
expect(registry.collections.profiles.get("peer")).toMatchObject({ name: "Current", avatar: "new-avatar", avatarVersion: 8 })
})
it("keeps a freshly verified DM when an older full directory response omits it", async () => {
const { client, registry } = await createCommunityQueryOwner()
const previous = captureCommunityLiveSnapshotToken(client)
- publishConversationEntry(client, { channelId: "c1", serverId: null }, dmConversationEntryFixture(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [] } }, proof: { kind: "structural", token: previous, signal: undefined } })
+ await publishConversationEntry(client, { channelId: "c1", serverId: null }, dmConversationEntryFixture(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [] } }, proof: { kind: "structural", token: previous, signal: undefined } })
expect(registry.collections.channels.get("c1")).toMatchObject({ type: "dm" })
expect(registry.collections.channelMemberships.get("c1:peer:access")).toBeDefined()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
expect(registry.collections.channels.get("c1")).toBeUndefined()
})
it("keeps a structural directory from creating a second reading-proof cache", async () => {
const { client, registry } = await createCommunityQueryOwner()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "dm", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ await publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "dm", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
expect(registry.collections.channels.has("dm")).toBe(true)
expect(client.getQueryData(communityKeys.channelMeta(null, "dm"))).toBeUndefined()
expect(client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("dm") })).toEqual([])
@@ -319,13 +334,13 @@ describe("conversation entry canonical publication", () => {
pageParams: [{ mode: "anchor", anchor: "m1" }, { mode: "older", cursor: "old" }],
}
client.setQueryData(key, previous)
- publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ await publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(client.getQueryData(key)).toBe(previous)
})
it("keeps an explicit missing anchor local to its window and does not retire readable history", async () => {
const { client, registry } = await createCommunityQueryOwner()
- publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ await publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })
const missing = new ApiError("anchor not found", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING])
load.mockRejectedValue(missing)
await expect(client.query({ ...conversationEntryOptions(client, { ...target, anchorMessageId: "missing" }), select: undefined })).rejects.toBe(missing)
@@ -392,7 +407,7 @@ describe("conversation entry canonical publication", () => {
it("finds its canonical window after channel transport query eviction", async () => {
const { client, registry } = await createCommunityQueryOwner()
const value = entry()
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
client.removeQueries({ queryKey: communityKeys.communityDbCollection(registry.scopeId, "channels"), exact: true })
expect(registry.collections.channels.get("c1")).toMatchObject(value.channel)
expect(findConversationEntryWindow(client, target, resource, value.readState)?.key).toEqual(resource.windowKey)
@@ -403,7 +418,7 @@ describe("conversation entry canonical publication", () => {
const value = entry()
value.readState = { channelId: "c1", lastReadMessageId: "missing", lastReadAt: "at", lastReadSeq: 10 }
value.selection = { reason: "read_pointer_missing", anchorMessageId: null }
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(findConversationEntryWindow(client, target, resource, value.readState)?.initial).toEqual({ mode: "newest" })
expect(findConversationEntryWindow(client, target, resource, { ...value.readState, lastReadMessageId: "newer" })).toBeUndefined()
expect(findConversationEntryWindow(client, { ...target, anchorMessageId: "explicit" }, resource, value.readState)).toBeUndefined()
@@ -446,7 +461,7 @@ it.each(["main", "opener"] as const)("validates the effective retained %s reply
expect(client.getQueryCache().getAll().map(query => [query.queryKey, query.state.data])).toEqual(queries)
const prior = profileResourceFixture({ id: "prior-author", name: "Prior author" })
writeCommunityProfilePatches([communityUserProfilePatch(prior.id, prior)], registry)
- const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(registry.collections.messages.get(original.id)?.replyTo).toEqual(retainedReply)
expect(findConversationEntryWindow(client, target, resource, value.readState)).toBeDefined()
})
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index ce19a3773..4e027207d 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -1,15 +1,17 @@
+import { completeCommunityPublication } from "@/lib/community-db/sync"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { reconcileConversationLanding } from "@/hooks/community/community-ws/reconnect-messages"
import { channelHref } from "./community-route"
import { actionAttributes, currentPageObservation, navigationForHref } from "@/lib/observability/context"
import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"
-import { hashKey, notifyManager, queryOptions, type QueryClient, type QueryKey } from "@tanstack/react-query"
-import { COMMUNITY_CONTRACT_HEADER, CommunityConversationEntryReadSchema, CommunityResourceProfileSchema, type CommunityConversationEntryRead, type CommunityReadStateResource } from "@alook/shared"
+import { hashKey, notifyManager, queryOptions, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
+import { COMMUNITY_CONTRACT_HEADER, CommunityConversationEntryReadSchema, type CommunityConversationEntryRead, type CommunityReadStateResource, type CommunityMessageResources } from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { communityRequestOptions } from "./account-cache-lifecycle"
import { isChannelMetadataTokenCurrent } from "./conversation-qualification"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { withCommunityCollectionWrites, afterCommunityCollectionWrites } from "@/lib/community-db/write"
import { channelMembershipKey, type ReadStateRow } from "@/lib/community-db/schema"
import { ApiError, CommunityApiError } from "@/lib/errors"
import {
@@ -46,6 +48,17 @@ export type ConversationEntryResource = {
export type ConversationWindowScope = Pick<ConversationEntryResource, "channelId" | "proof">
& Partial<Pick<ConversationEntryResource, "windowKey" | "readStateAtEntry" | "selection">>
+type ConversationDisplayWindow = { key: QueryKey; initial: InitialMessageWindow; tag: string | null; resources?: CommunityMessageResources }
+const qualifiedWindows = new WeakMap<Query, { resources: CommunityMessageResources; window: ConversationDisplayWindow }>()
+
+function qualifiedWindow(query: Query, initial: InitialMessageWindow, tag: string | null, resources: CommunityMessageResources): ConversationDisplayWindow {
+ const previous = qualifiedWindows.get(query)
+ if (previous?.resources === resources) return previous.window
+ const window = { key: query.queryKey, initial, tag, resources }
+ qualifiedWindows.set(query, { resources, window })
+ return window
+}
+
export function assessConversationScope(client: QueryClient, target: ConversationEntryTarget) {
const registry = getCommunityDbRegistry(client)
if (!registry?.accountId || registry.sessionViewer() !== registry.accountId || registry.runtime.ws.get().profileViewerId !== registry.accountId) return { reason: "account_unknown" as const }
@@ -80,7 +93,7 @@ export function publishConversationEntry(
value: CommunityConversationEntryRead,
proof: CommunityFreshQueryProof,
source: "rsc" | "network" = "network",
-): ConversationEntryResource {
+): ConversationEntryResource | Promise<ConversationEntryResource> {
assertCommunityLiveSnapshotTokenCurrent(client, proof.token, proof.signal)
const entry = CommunityConversationEntryReadSchema.parse(value)
const channel = entry.channel
@@ -96,6 +109,7 @@ export function publishConversationEntry(
const initialWindow: InitialMessageWindow = entry.selection.anchorMessageId ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }
const windowKey = entry.forumFeed ? communityKeys.forumFeed(target.channelId, target.tag ?? null) : communityKeys.channelMessagesWindow(target.channelId, initialWindow, target.tag)
const qualified = { ...proof.token, channelLineage: { parentChannelId: parent } }
+ return withCommunityCollectionWrites(registry, () => {
notifyManager.batch(() => {
if (channel.serverId) registry.runtime.ws.actions.grantServerAccess(channel.serverId)
registry.runtime.ws.actions.rememberChannelAccess(channel.serverId, channel.id, parent ?? undefined)
@@ -107,22 +121,27 @@ export function publishConversationEntry(
publishCommunityMessages(client, { channelId: channel.id, messages: entry.messages, profiles: entry.profiles, proof })
if (entry.opener) {
publishCommunityMessages(client, { channelId: entry.opener.channelId, messages: [entry.opener], profiles: entry.profiles, proof })
- client.setQueryData(communityKeys.message(entry.opener.id), entry.opener.id)
+ afterCommunityCollectionWrites(registry, () => { client.setQueryData(communityKeys.message(entry.opener!.id), entry.opener!.id) })
}
publishCommunityConversationReadState(client, entry.readState, entry.readStateRevision, proof)
confirmCommunityConversationPresence(client, channel.id, proof)
if (entry.forumFeed) {
const page = normalizeThreadResources(channel.id, entry.forumFeed)
publishCommunityForumFeed(client, channel.id, page, proof)
+ afterCommunityCollectionWrites(registry, () => {
if (!conversationDisplayWindows(client, target, { channelId: channel.id, proof: qualified, windowKey })?.some(window => hashKey(window.key) === hashKey(windowKey))) client.setQueryData(windowKey, { pages: [forumFeedWindow(page)], pageParams: [null] })
+ })
}
else {
+ afterCommunityCollectionWrites(registry, () => {
if (conversationDisplayWindows(client, target, { channelId: channel.id, proof: qualified, windowKey })?.some(window => hashKey(window.key) === hashKey(windowKey))) return
const page = messageWindowPage({ ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, profiles: entry.profiles })
client.setQueryData<MessageWindowData>(windowKey, { pages: [page], pageParams: [initialWindow as MessagesPageParam] })
+ })
}
})
return { channelId: channel.id, source, initialWindow, windowKey, readStateAtEntry: entry.readState, readStateRevision: entry.readStateRevision, selection: entry.selection, access: entry.access, proof: qualified }
+ }, () => assertCommunityLiveSnapshotTokenCurrent(client, proof.token, proof.signal))
}
export function getQualifiedConversationEntry(client: QueryClient, channelId: string) {
@@ -149,7 +168,8 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
const messages = registry.collections.messages
if (channel.type === "forum" && !target.anchorMessageId) {
const key = communityKeys.forumFeed(channel.id, target.tag ?? null)
- const feed = client.getQueryData<{ pages: ForumFeedPage[]; pageParams: Array<string | null> }>(key)
+ const query = client.getQueryCache().find({ queryKey: key, exact: true })
+ const feed = query?.state.data as { pages: ForumFeedPage[]; pageParams: Array<string | null> } | undefined
if (!Array.isArray(feed?.pages) || !feed.pages.length || !Array.isArray(feed.pageParams) || feed.pages.length !== feed.pageParams.length) return
const byId = registry.collections.channels
if (feed.pages.some(page => !Array.isArray(page?.threads) || page.threads.some(thread => {
@@ -158,14 +178,15 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
const opener = thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined
return !child || child.pending || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id
|| !opener || opener.channelId !== channel.id || child.parentMessageId !== opener.id
- || !Array.isArray(thread.participantIds) || thread.participantIds.some(id => !CommunityResourceProfileSchema.strip().safeParse(registry.collections.profiles.get(id)).success)
+ || !Array.isArray(thread.participantIds) || thread.participantIds.some(id => typeof id !== "string" || !id)
}))) return
const retained = feed.pages.flatMap(page => page.threads.flatMap(thread => {
const child = byId.get(thread.id)
return [thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined, child?.firstMessageId ? messages.get(child.firstMessageId) : undefined].filter(message => message !== undefined)
}))
- if (!getCanonicalCommunityMessageResources(client, retained)) return
- return [{ key, initial: { mode: "newest" as const }, tag: target.tag ?? null }]
+ const resources = getCanonicalCommunityMessageResources(client, retained, feed, feed.pages.flatMap(page => page.threads.flatMap(thread => thread.participantIds)))
+ if (!query || !resources) return
+ return [qualifiedWindow(query, { mode: "newest" }, target.tag ?? null, resources)]
}
const windows = client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(target.channelId) })
.sort((left, right) => Number(hashKey(right.queryKey) === hashKey(resource.windowKey ?? [])) - Number(hashKey(left.queryKey) === hashKey(resource.windowKey ?? [])) || right.state.dataUpdatedAt - left.state.dataUpdatedAt)
@@ -176,8 +197,9 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
if (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page?.messages) || page.messages.some(message => typeof message?.id !== "string" || !message.id))) return []
const ids = data.pages.flatMap((page) => page.messages.map((message) => message.id))
if (ids.some(id => messages.get(id)?.channelId !== target.channelId)) return []
- if (!getCanonicalCommunityMessageResources(client, ids.map(id => messages.get(id)))) return []
- return [{ key: window.queryKey, initial: identity.initial, tag: identity.tag }]
+ const resources = getCanonicalCommunityMessageResources(client, ids.map(id => messages.get(id)), data)
+ if (!resources) return []
+ return [qualifiedWindow(window, identity.initial, identity.tag, resources)]
})
}
@@ -249,7 +271,7 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }
const windowKey = communityKeys.channelMessagesWindow(target.channelId, initial, target.tag)
const hadWindow = !!client.getQueryData<MessageWindowData>(windowKey)?.pages.length
- const resource = publishConversationEntry(client, target, entry, { token, signal })
+ const resource = await publishConversationEntry(client, target, entry, { token, signal })
record("validated")
record("published")
if (hadWindow && !entry.forumFeed) {
@@ -266,8 +288,8 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
&& !!original && client.getQueryCache().get(original.queryHash) === original
record(!current || error instanceof Error && error.name === "AbortError" ? "cancelled" : "error")
assert()
- if (error instanceof ApiError && (error.status === 403 || error.status === 404) && !isConversationAnchorMissingError(error)) retireCommunityChannelReading(token.registry!, target.channelId, { reason: "read-denied", serverId: target.serverId, preserveQuery: original,
- ...(error instanceof CommunityApiError ? { denialCode: error.code } : {}) })
+ if (error instanceof ApiError && (error.status === 403 || error.status === 404) && !isConversationAnchorMissingError(error)) await completeCommunityPublication(token.registry!, () => retireCommunityChannelReading(token.registry!, target.channelId, { reason: "read-denied", serverId: target.serverId, preserveQuery: original,
+ ...(error instanceof CommunityApiError ? { denialCode: error.code } : {}) }))
throw error
}
},
diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.ts
index 2473c4073..66b6f3990 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -104,11 +104,11 @@ async function createClient() {
owners.push(registry)
return client
}
-function seedCanonicalDirectory(queryClient: QueryClient, options: { channels?: boolean } = {}) {
+async function seedCanonicalDirectory(queryClient: QueryClient, options: { channels?: boolean } = {}) {
const registry = getCommunityDbRegistry(queryClient)!
ingestServers(registry, serverRailResponseFixture({ servers: serverRows }, (registry)!.accountId))
if (options.channels !== false) {
- for (const channel of channelRows) publishCommunityCreatedChannel(queryClient, channel, { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
+ for (const channel of channelRows) await publishCommunityCreatedChannel(queryClient, channel, { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
}
}
afterEach(async () => {
@@ -238,7 +238,7 @@ describe("desktop system notification candidates", () => {
it("resolves a cold channel name before formatting the desktop copy", async () => {
const queryClient = await createClient()
- seedCanonicalDirectory(queryClient, { channels: false })
+ await seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "channel_1",
serverId: "server_1",
@@ -292,7 +292,7 @@ describe("desktop system notification candidates", () => {
it("resolves cold thread and parent channel names before formatting the desktop copy", async () => {
const queryClient = await createClient()
- seedCanonicalDirectory(queryClient, { channels: false })
+ await seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockResolvedValueOnce(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "thread_1",
serverId: "server_1",
@@ -330,7 +330,7 @@ describe("desktop system notification candidates", () => {
it("uses complete current-account collections without metadata I/O", async () => {
const queryClient = await createClient()
- seedCanonicalDirectory(queryClient)
+ await seedCanonicalDirectory(queryClient)
await expect(resolveDesktopSystemNotificationCandidate(
create,
bump,
@@ -354,7 +354,7 @@ describe("desktop system notification candidates", () => {
it("keeps safe fallback copy when cold metadata resolution fails", async () => {
const queryClient = await createClient()
- seedCanonicalDirectory(queryClient, { channels: false })
+ await seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockRejectedValue(new Error("metadata unavailable"))
await expect(resolveDesktopSystemNotificationCandidate(
create,
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index b59233062..6abc93b6e 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -2,6 +2,7 @@ import { queries, withD1Retry, CommunityChannelResourceSchema, CommunityMessageT
import type { getDb } from "@/lib/db"
import { loadApiMessageContext, mapMessageForApi, readCommunityMessageProfiles } from "@/lib/community/message-payload"
import { canonicalUserImage } from "@/lib/community/storage"
+import type { CommunityResourceProfileReader } from "./resource-profiles.server"
// Message enrichment shared by the channel messages route, the channel
// bootstrap route, and the DM messages route (previously three near-identical
@@ -22,6 +23,7 @@ export async function enrichMessages(
userId: string,
scope: MessageScope,
items: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string }>,
+ readProfiles?: CommunityResourceProfileReader,
): Promise<{ messages: CommunityMessageResource[]; profiles: CommunityResourceProfile[]; latestSeq: number }> {
const isDm = scope.isDm === true
const messageIds = items.map((m) => m.id)
@@ -113,5 +115,5 @@ export async function enrichMessages(
approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
}, scope.contract, scope.channelId),
)
- return { messages, profiles: await readCommunityMessageProfiles(db, messages), latestSeq }
+ return { messages, profiles: await readCommunityMessageProfiles(db, messages, readProfiles), latestSeq }
}
diff --git a/src/web/src/lib/community/forum-sidebar-window.ts b/src/web/src/lib/community/forum-sidebar-window.ts
index 0aeb78ad9..17e934f09 100644
--- a/src/web/src/lib/community/forum-sidebar-window.ts
+++ b/src/web/src/lib/community/forum-sidebar-window.ts
@@ -1,7 +1,7 @@
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { readServerDirectoryWindow, type ServerDirectoryWindow } from "./server-directory-window"
import { z } from "zod"
-import { projectForumSidebar, supportsSidebarThreads } from "./forum-sidebar"
+import { projectForumSidebar, supportsSidebarThreads, type ForumSidebarThread } from "./forum-sidebar"
import type { CommunityCollectionRows } from "@/lib/community-db/schema"
const referenceSchema = z.object({ id: z.string().min(1), parentChannelId: z.string().min(1), parentMessageId: z.string().min(1) })
@@ -39,7 +39,7 @@ export function readForumSidebarWindowResult(data: unknown) {
}
export function forumSidebarWindowComplete(
- window: ForumSidebarWindow, rows: ForumSidebarWindowRows, accountId: string | null, serverId: string, retainId?: string | null, serverNowMs = Date.now(),
+ window: ForumSidebarWindow, rows: ForumSidebarWindowRows, accountId: string | null, serverId: string, retainId?: string | null, serverNowMs = Date.now(), visibleThreads?: readonly ForumSidebarThread[],
) {
const directory = readServerDirectoryWindow(rows.directory)
if (window.accountId !== accountId || window.serverId !== serverId
@@ -48,7 +48,7 @@ export function forumSidebarWindowComplete(
const parents = rows.channels.filter(row => row.serverId === serverId && supportsSidebarThreads(row.type))
if (window.parents.some(id => !directory.channelIds.includes(id) || !parents.some(row => row.id === id))
|| parents.some(row => !window.parents.includes(row.id))) return false
- const visible = projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, accountId, serverId,
+ const visible = visibleThreads ?? projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, accountId, serverId,
retainId ?? (window.retained?.disposition === "eligible" ? window.retained.id : null), serverNowMs).threads
const references = [...window.base, ...(window.retained?.disposition === "eligible" ? [window.retained.reference] : []), ...visible]
if (!references.every(reference => rows.channels.some(row => row.id === reference.id && row.serverId === serverId
diff --git a/src/web/src/lib/community/forum-sidebar.ts b/src/web/src/lib/community/forum-sidebar.ts
index 5a6d4e1e2..c50b419eb 100644
--- a/src/web/src/lib/community/forum-sidebar.ts
+++ b/src/web/src/lib/community/forum-sidebar.ts
@@ -15,6 +15,39 @@ export function supportsSidebarThreads(type: string | null | undefined) {
export const FORUM_SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000
+type AttentionProjection = {
+ servers: Map<string, { unread: boolean; mentions: number }>
+ channels: Map<string, Set<string>>
+ parents: Map<string, Set<string>>
+ scopes: Set<string>
+}
+const attentionProjections = new WeakMap<readonly AttentionScopeRow[], AttentionProjection>()
+
+export function projectCommunityAttention(attention: readonly AttentionScopeRow[]) {
+ const previous = attentionProjections.get(attention)
+ if (previous) return previous
+ const result: AttentionProjection = { servers: new Map(), channels: new Map(), parents: new Map(), scopes: new Set() }
+ for (const scope of attention) {
+ const unread = scope.ordinaryUnread || scope.attentionCount > 0
+ if (unread) result.scopes.add(scope.scopeId)
+ if (!scope.serverId) continue
+ const server = result.servers.get(scope.serverId) ?? { unread: false, mentions: 0 }
+ server.unread ||= scope.ordinaryUnread
+ server.mentions += scope.attentionCount
+ result.servers.set(scope.serverId, server)
+ if (!unread) continue
+ const channels = result.channels.get(scope.serverId) ?? new Set<string>()
+ channels.add(scope.channelId)
+ if (scope.parentChannelId) channels.add(scope.parentChannelId)
+ result.channels.set(scope.serverId, channels)
+ const parents = result.parents.get(scope.serverId) ?? new Set<string>()
+ parents.add(scope.parentChannelId ?? scope.channelId)
+ result.parents.set(scope.serverId, parents)
+ }
+ attentionProjections.set(attention, result)
+ return result
+}
+
export function viewerNotifyChannelIds(memberships: readonly ChannelMembershipRow[], viewerId: string | null) {
return new Set(memberships.filter((row) => row.relation === "notify" && row.userId === viewerId).map((row) => row.channelId))
}
@@ -48,11 +81,11 @@ export function forumSidebarCandidates(
}).sort(compareForumSidebarThreads)
}
-export function projectForumSidebar(
+export function projectForumSidebarStructure(
channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],
- viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number, attention: readonly AttentionScopeRow[] = [],
+ viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number,
) {
- const candidates = forumSidebarCandidates(channels, memberships, messages, viewerId, serverId, attention)
+ const candidates = forumSidebarCandidates(channels, memberships, messages, viewerId, serverId)
.filter((thread) => thread.id === retainId || !Number.isFinite(Date.parse(thread.expiresAt)) || Date.parse(thread.expiresAt) > serverNowMs)
const byParent = new Map<string, ForumSidebarThread[]>()
for (const thread of candidates) {
@@ -65,9 +98,19 @@ export function projectForumSidebar(
if (!retained || siblings.slice(0, 5).some((thread) => thread.id === retainId)) return siblings.slice(0, 5)
return [...siblings.filter((thread) => thread.id !== retainId).slice(0, 4), retained].sort(compareForumSidebarThreads)
})
- const parentUnread: Record<string, boolean> = Object.fromEntries(channels.filter(channel => channel.serverId === serverId && channel.type !== "thread").map(channel => [channel.id, false]))
- for (const scope of attention) {
- if (scope.serverId === serverId && (scope.ordinaryUnread || scope.attentionCount > 0)) parentUnread[scope.parentChannelId ?? scope.channelId] = true
- }
- return { threads, parentUnread }
+ return { threads, parentIds: channels.filter(channel => channel.serverId === serverId && channel.type !== "thread").map(channel => channel.id) }
+}
+
+export function applyForumSidebarAttention(structure: ReturnType<typeof projectForumSidebarStructure>, serverId: string, attention: readonly AttentionScopeRow[]) {
+ const projected = projectCommunityAttention(attention)
+ const parentUnread: Record<string, boolean> = Object.fromEntries(structure.parentIds.map(id => [id, false]))
+ for (const id of projected.parents.get(serverId) ?? []) parentUnread[id] = true
+ return { threads: structure.threads.map(thread => projected.scopes.has(thread.id) ? { ...thread, unread: true } : thread), parentUnread }
+}
+
+export function projectForumSidebar(
+ channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],
+ viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number, attention: readonly AttentionScopeRow[] = [],
+) {
+ return applyForumSidebarAttention(projectForumSidebarStructure(channels, memberships, messages, viewerId, serverId, retainId, serverNowMs), serverId, attention)
}
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 686afc84a..91cf3db4b 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -17,7 +17,7 @@
import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, communityMessageProfileIds, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment } from "@alook/shared"
import type { BotCreationPayload, FriendApprovalPayload } from "@alook/shared"
-import { readCommunityResourceProfiles } from "./resource-profiles.server"
+import { readCommunityResourceProfiles, type CommunityResourceProfileReader } from "./resource-profiles.server"
import { canonicalUserImage } from "@/lib/community/storage"
import { projectMessageWireType } from "@/lib/community/message-wire-type"
import { groupAttachments, groupReactions } from "./messages"
@@ -162,8 +162,8 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract
}
-export async function readCommunityMessageProfiles(db: Database, messages: readonly CommunityMessageResource[]) {
- const profiles = await readCommunityResourceProfiles(db, communityMessageProfileIds(messages))
+export async function readCommunityMessageProfiles(db: Database, messages: readonly CommunityMessageResource[], readProfiles: CommunityResourceProfileReader = ids => readCommunityResourceProfiles(db, ids)) {
+ const profiles = await readProfiles(communityMessageProfileIds(messages))
CommunityMessageResourcesSchema.parse({ messages, profiles })
return profiles
}
diff --git a/src/web/src/lib/community/message-read.profile.dom.test.tsx b/src/web/src/lib/community/message-read.profile.dom.test.tsx
index 3e3c7e150..852e7f198 100644
--- a/src/web/src/lib/community/message-read.profile.dom.test.tsx
+++ b/src/web/src/lib/community/message-read.profile.dom.test.tsx
@@ -47,7 +47,7 @@ it.each(["messages", "entry", "committed-ws"].flatMap(scenario => [false, true].
fixtures.response = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body)
const { client, registry } = await createCommunityQueryOwner("viewer")
const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["channel"] })
- await act(async () => { publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) }) })
+ await act(async () => { await publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) }) })
expect(registry.collections.profiles.get("former")).toBeUndefined()
function Consumer() {
useCanonicalCommunityProfile("former")
@@ -69,7 +69,7 @@ it.each(["messages", "entry", "committed-ws"].flatMap(scenario => [false, true].
const entry = await readCommunityConversationEntry(db, { viewerId: "viewer", target: target.value, window: parseCommunityMessageWindow(new URLSearchParams()), preferTail: true })
if (!entry.ok) throw new Error(JSON.stringify(entry))
wireProfiles = entry.entry.profiles
- await act(async () => { publishConversationEntry(client, { serverId: "server", channelId: "channel" }, entry.entry, { token: captureCommunityLiveSnapshotToken(client, "channel") }) })
+ await act(async () => { await publishConversationEntry(client, { serverId: "server", channelId: "channel" }, entry.entry, { token: captureCommunityLiveSnapshotToken(client, "channel") }) })
} else {
const plan = await planCommittedMessage(db, "message")
const encoded = encodeCommunityBrowserEvent(plan.messageEvent)
@@ -116,7 +116,7 @@ it.each(["initial", "two-hop"])("carries the actual SQL approval author through
expect(sqlite.prepare("SELECT status,needs_owner_approval AS owner FROM community_friendship WHERE id=?").get(request.friendship.id)).toMatchObject({ status: "pending", owner: viewer })
const { client, registry } = await createCommunityQueryOwner(viewer)
const structure = await readCommunityResourceBundle(db, viewer, { channelIds: [event.channelId] })
- publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ await publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
expect(registry.collections.profiles.get(author)).toBeUndefined()
function Consumer() {
useCanonicalCommunityProfile(author)
@@ -155,7 +155,7 @@ it.each([false, true])("keeps current actual DB profile facts on first native co
if (!encoded.ok) throw new Error(JSON.stringify(encoded))
const { client, registry } = await createCommunityQueryOwner("viewer")
const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["channel"], ...(warm ? { profileIds: ["former"] } : {}) })
- publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ await publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
const frames: string[] = []
function Consumer() {
useCanonicalCommunityProfile("former")
diff --git a/src/web/src/lib/community/message-window.server.ts b/src/web/src/lib/community/message-window.server.ts
index f8fa2633d..12335a761 100644
--- a/src/web/src/lib/community/message-window.server.ts
+++ b/src/web/src/lib/community/message-window.server.ts
@@ -3,6 +3,7 @@ import { buildAnchorResponse, buildPaginatedResponse, buildSinceResponse, type p
import { enrichMessages } from "./enrich-messages"
import type { DoorTarget } from "./message-door"
import type { MessagePage } from "./read-contract"
+import type { CommunityResourceProfileReader } from "./resource-profiles.server"
export async function readCommunityMessageWindow(db: Database, input: {
viewerId: string
@@ -10,6 +11,7 @@ export async function readCommunityMessageWindow(db: Database, input: {
window: ReturnType<typeof parseCommunityMessageWindow>
contract: CommunityContract
tag?: string
+ readProfiles?: CommunityResourceProfileReader
}): 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
@@ -25,19 +27,19 @@ export async function readCommunityMessageWindow(db: Database, input: {
const { items, ...page } = buildAnchorResponse(around.older, around.newer, {
hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer,
})
- const enriched = await enrichMessages(db, viewerId, scope, items)
+ const enriched = await enrichMessages(db, viewerId, scope, items, input.readProfiles)
return { ok: true, page: { ...page, ...enriched, surfaceReceipt } }
}
if (since) {
const rows = await queries.communityMessage.listMessagesSince(db, { channelId, since, limit: pageSize, tag })
const { items, ...page } = buildSinceResponse(rows, pageSize)
- const enriched = await enrichMessages(db, viewerId, scope, items)
+ const enriched = await enrichMessages(db, viewerId, scope, items, input.readProfiles)
return { ok: true, page: { ...page, ...enriched, surfaceReceipt } }
}
const rows = await queries.communityMessage.listMessages(db, { channelId, cursor, limit: pageSize + 1, tag })
const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)
- const enriched = await enrichMessages(db, viewerId, scope, items.slice().reverse())
+ const enriched = await enrichMessages(db, viewerId, scope, items.slice().reverse(), input.readProfiles)
return { ok: true, page: { ...enriched, hasMore, cursor: nextCursor, surfaceReceipt } }
}
diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.ts
index f5ca60e63..2f9d7a173 100644
--- a/src/web/src/lib/community/message-window.ts
+++ b/src/web/src/lib/community/message-window.ts
@@ -86,7 +86,7 @@ export const channelMessagesQueryFn =
role: pageParam.mode === "older" || pageParam.mode === "newer" ? "pagination" : "window", windowMode: pageParam.mode,
} }, publicationToken)
{
- const result = publishCommunityMessages(originalClient, {
+ const result = await publishCommunityMessages(originalClient, {
channelId,
messages: page.messages,
profiles: page.profiles,
diff --git a/src/web/src/lib/community/navigation-metadata.dom.test.tsx b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
index 447ba13e0..7401d1533 100644
--- a/src/web/src/lib/community/navigation-metadata.dom.test.tsx
+++ b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
@@ -84,7 +84,7 @@ describe("native navigation warming and DM consumer mounting", () => {
entry.selection = { reason: "read_pointer", anchorMessageId: "m28" }
entry.page.latestSeq = 28
} else {
- publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ await publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
}
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
@@ -111,7 +111,7 @@ describe("native navigation warming and DM consumer mounting", () => {
it.each(["account", "channel"] as const)("still cancels warming and rejects late data after %s retirement", async kind => {
const owner = await createCommunityQueryOwner()
const entry = dmConversationEntryFixture()
- publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ await publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
const warming = prepareNavigationMetadata(owner.client, "/c/me/c1", "foreground")
diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.ts
index bb99897e0..2ae1b051b 100644
--- a/src/web/src/lib/community/profile-seed.ts
+++ b/src/web/src/lib/community/profile-seed.ts
@@ -6,13 +6,12 @@ import type {
import type { MessageInput } from "@/lib/community/models/message"
import { canonicalCommunityUserImage, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
-import { communityKeys } from "@/lib/query-keys"
import {
type CommunityDbRegistry,
} from "@/lib/community-db/collections"
import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"
-import { writeCommunityCollectionRows } from "@/lib/community-db/write"
-import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { readCommunityCollectionRow, writeCommunityCollectionChanges, withCommunityCollectionWrites } from "@/lib/community-db/write"
+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
type ProfileFieldRevisions = {
@@ -65,8 +64,7 @@ export function retireCommunityProfile(userId: string, registry: CommunityDbRegi
pendingFieldsByUserId.delete(userId)
store.setState(() => ({ ...previous, revision, fieldsByUserId, deletedByUserId, pendingFieldsByUserId }))
registry.runtime.ws.actions.forgetPresence(userId)
- const rows = registry.queryClient.getQueryData<ProfileRow[]>(communityKeys.communityDbCollection(registry.scopeId, "profiles")) ?? [...registry.collections.profiles.values()]
- writeCommunityCollectionRows(registry, "profiles", rows.filter(row => row.id !== userId), row => row.id)
+ return writeCommunityCollectionChanges(registry, "profiles", [], [userId])
}
export function beginCommunityProfileSeed(
@@ -171,10 +169,7 @@ export function writeCommunityProfilePatches(
) {
if (!registry || patches.length === 0 || !registry.runtime.lifecycle.get().active) return
if (options?.snapshot && options.snapshot.registry !== registry) return
- const queryKey = communityKeys.communityDbCollection(registry.scopeId, "profiles")
- const cached = registry.queryClient.getQueryData<ProfileRow[]>(queryKey)
- ?? Array.from(registry.collections.profiles.values())
- const profiles = new Map(cached.map((profile) => [profile.id, profile]))
+ const profiles = new Map<string, ProfileRow>()
const revisionStore = revisionState(registry)
const previous = revisionStore.get()
const pendingOwner = JSON.stringify([registry.runtime.ws.get().profileAccountEpoch, registry.runtime.lifecycle.get().generation])
@@ -185,7 +180,7 @@ export function writeCommunityProfilePatches(
for (const patch of patches) {
const deletedAt = revisions.deletedByUserId.get(patch.id)
if (deletedAt !== undefined && (options?.resourceSeed || guardedRevision !== undefined && guardedRevision < deletedAt)) continue
- const current = profiles.get(patch.id)
+ const current = profiles.get(patch.id) ?? readCommunityCollectionRow(registry, "profiles", patch.id)
const known = { ...current, ...revisions.pendingFieldsByUserId.get(patch.id) }
const seedFields = <T extends object>(fields: T | undefined): T | undefined => {
if (!fields || !options?.resourceSeed) return fields
@@ -242,7 +237,7 @@ export function writeCommunityProfilePatches(
if (advanced && writeRevision !== null) revisions.revision = writeRevision
revisionStore.setState(() => revisions)
const rows = [...profiles.values()]
- writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.id)
+ return writeCommunityCollectionChanges(registry, "profiles", rows)
}
export async function loadAndSeedProfiles<T>(
@@ -260,19 +255,21 @@ export async function loadAndSeedProfiles<T>(
if (token.registry !== registry) throw new DOMException("Mismatched community profile owner", "AbortError")
const data = await loadCommunityRequest(load, token, signal)
const projected = patches(data)
- writeCommunityProfilePatches(projected, profileSnapshot.registry, {
+ await writeCommunityProfilePatches(projected, profileSnapshot.registry, {
snapshot: profileSnapshot,
})
+ assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal)
const presence = projected.flatMap((patch) => (
patch.presence === undefined
? []
: [{ id: patch.id, presence: patch.presence }]
))
if (presence.length > 0) {
- overlay.seedPresence(
+ await withCommunityCollectionWrites(registry, () => overlay.seedPresence(
overlaySnapshot,
presence.map((patch) => [patch.id, patch.presence] as const),
- )
+ ))
+ assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal)
}
return data
}
diff --git a/src/web/src/lib/community/resource-profiles.server.test.ts b/src/web/src/lib/community/resource-profiles.server.test.ts
new file mode 100644
index 000000000..136d106c0
--- /dev/null
+++ b/src/web/src/lib/community/resource-profiles.server.test.ts
@@ -0,0 +1,32 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { queries, type Database } from "@alook/shared"
+import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { createCommunityResourceProfileReader } from "./resource-profiles.server"
+
+afterEach(() => vi.restoreAllMocks())
+
+it("shares overlapping in-flight IDs within one authorized request and keeps other requests separate", async () => {
+ const load = vi.spyOn(queries.communityUserProfile, "getResourceProfiles").mockImplementation(async (_db, ids) => ids.map(id => profileResourceFixture({ id })))
+ const db = {} as Database
+ const read = createCommunityResourceProfileReader(db)
+ const first = read(["peer"]), second = read(["peer", "author", "peer"])
+ expect(await first).toMatchObject([{ id: "peer" }])
+ expect(await second).toMatchObject([{ id: "peer" }, { id: "author" }])
+ await read(["peer", "author"])
+ expect(load.mock.calls.map(([, ids]) => ids)).toEqual([["peer"], ["author"]])
+ await createCommunityResourceProfileReader(db)(["peer"])
+ expect(load).toHaveBeenCalledTimes(3)
+})
+
+it("releases rejected reads for the existing retry and never returns an unrequested profile", async () => {
+ const error = new Error("D1 unavailable")
+ const load = vi.spyOn(queries.communityUserProfile, "getResourceProfiles")
+ .mockRejectedValueOnce(error)
+ .mockResolvedValueOnce([profileResourceFixture({ id: "peer" }), profileResourceFixture({ id: "unrequested" })])
+ const read = createCommunityResourceProfileReader({} as Database)
+ await expect(read(["peer"])).rejects.toBe(error)
+ expect(await read(["peer", "missing"])).toMatchObject([{ id: "peer" }])
+ expect(await read(["missing"])).toEqual([])
+ expect(await read([])).toEqual([])
+ expect(load.mock.calls.map(([, ids]) => ids)).toEqual([["peer"], ["peer", "missing"]])
+})
diff --git a/src/web/src/lib/community/resource-profiles.server.ts b/src/web/src/lib/community/resource-profiles.server.ts
index 62e46c382..b036d1e01 100644
--- a/src/web/src/lib/community/resource-profiles.server.ts
+++ b/src/web/src/lib/community/resource-profiles.server.ts
@@ -1,5 +1,24 @@
-import { queries, type Database } from "@alook/shared"
+import { queries, type Database, type CommunityResourceProfile } from "@alook/shared"
+
+export type CommunityResourceProfileReader = (userIds: readonly string[]) => Promise<CommunityResourceProfile[]>
export function readCommunityResourceProfiles(db: Database, userIds: readonly string[]) {
return queries.communityUserProfile.getResourceProfiles(db, userIds)
}
+
+export function createCommunityResourceProfileReader(db: Database): CommunityResourceProfileReader {
+ const pending = new Map<string, Promise<CommunityResourceProfile | undefined>>()
+ return async userIds => {
+ const ids = [...new Set(userIds)], missing = ids.filter(id => !pending.has(id))
+ if (missing.length) {
+ const batch = readCommunityResourceProfiles(db, missing).then(profiles => new Map(profiles.map(profile => [profile.id, profile])))
+ for (const id of missing) {
+ const value = batch.then(profiles => profiles.get(id))
+ pending.set(id, value)
+ void value.catch(() => { if (pending.get(id) === value) pending.delete(id) })
+ }
+ }
+ const profiles = await Promise.all(ids.map(id => pending.get(id)!))
+ return profiles.filter(profile => profile !== undefined)
+ }
+}
diff --git a/src/web/src/lib/community/server-directory-window.ts b/src/web/src/lib/community/server-directory-window.ts
index 615f5a995..d340baff4 100644
--- a/src/web/src/lib/community/server-directory-window.ts
+++ b/src/web/src/lib/community/server-directory-window.ts
@@ -2,6 +2,7 @@ import { z } from "zod"
import { BUSINESS_SCHEMA_VERSION, CommunityChannelResourceSchema, categorySchema, serverSchema, type CommunityCollectionRows } from "@alook/shared"
import type { CommunityDbRegistry } from "@/lib/community-db/collections"
import { communityKeys } from "@/lib/query-keys"
+import { readCommunityCollectionRow } from "@/lib/community-db/write"
export const ServerDirectorySnapshotSchema = z.strictObject({
server: serverSchema,
@@ -30,10 +31,13 @@ export function serverDirectoryWindowComplete(window: ServerDirectoryWindow, row
categories: readonly CommunityCollectionRows["categories"][]
channels: readonly CommunityCollectionRows["channels"][]
}, accountId: string | null, serverId: string) {
+ const categories = new Map(rows.categories.map(row => [row.id, row]))
+ const channels = new Map(rows.channels.map(row => [row.id, row]))
+ const categoryIds = new Set(window.categoryIds)
return window.accountId === accountId && window.serverId === serverId && rows.servers.some(row => row.id === serverId)
- && window.categoryIds.every(id => rows.categories.some(row => row.id === id && row.serverId === serverId && !row.pending))
- && window.channelIds.every(id => rows.channels.some(row => row.id === id && row.serverId === serverId && row.parentChannelId === null && !row.pending
- && (row.categoryId === null || window.categoryIds.includes(row.categoryId))))
+ && window.categoryIds.every(id => { const row = categories.get(id); return row?.serverId === serverId && !row.pending })
+ && window.channelIds.every(id => { const row = channels.get(id); return row?.serverId === serverId && row.parentChannelId === null && !row.pending
+ && (row.categoryId === null || categoryIds.has(row.categoryId)) })
}
function directoryRows(registry: CommunityDbRegistry) {
@@ -47,7 +51,14 @@ function directoryRows(registry: CommunityDbRegistry) {
export function getServerDirectoryWindow(registry: CommunityDbRegistry | null | undefined, serverId: string) {
if (!registry) return
const window = readServerDirectoryWindow(registry.queryClient.getQueryData(communityKeys.server(serverId)))
- return window && serverDirectoryWindowComplete(window, directoryRows(registry), registry.accountId, serverId) ? window : undefined
+ if (!window) return
+ const server = readCommunityCollectionRow(registry, "servers", serverId)
+ const rows = {
+ servers: server ? [server] : [],
+ categories: window.categoryIds.flatMap(id => { const row = readCommunityCollectionRow(registry, "categories", id); return row ? [row] : [] }),
+ channels: window.channelIds.flatMap(id => { const row = readCommunityCollectionRow(registry, "channels", id); return row ? [row] : [] }),
+ }
+ return serverDirectoryWindowComplete(window, rows, registry.accountId, serverId) ? window : undefined
}
export function recordServerDirectoryWindow(registry: CommunityDbRegistry, serverId: string) {
@@ -58,14 +69,20 @@ export function recordServerDirectoryWindow(registry: CommunityDbRegistry, serve
categoryIds: rows.categories.filter(row => row.serverId === serverId && !row.pending).map(row => row.id),
channelIds: rows.channels.filter(row => row.serverId === serverId && row.parentChannelId === null && !row.pending).map(row => row.id),
})
+ const current = registry.queryClient.getQueryData<ServerDirectoryWindow>(communityKeys.server(serverId))
+ const previous = readServerDirectoryWindow(current)
+ if (previous?.accountId === window.accountId && previous.serverId === serverId
+ && previous.categoryIds.length === window.categoryIds.length && previous.channelIds.length === window.channelIds.length) {
+ const categories = new Set(previous.categoryIds), channels = new Set(previous.channelIds)
+ if (window.categoryIds.every(id => categories.has(id)) && window.channelIds.every(id => channels.has(id))) return current
+ }
registry.queryClient.setQueryData(communityKeys.server(serverId), window)
return window
}
-export function reconcileExistingServerDirectoryWindows(registry: CommunityDbRegistry) {
- for (const query of registry.queryClient.getQueryCache().findAll({ queryKey: communityKeys.servers() })) {
- if (!isServerDirectoryWindowKey(query.queryKey)) continue
- const window = readServerDirectoryWindow(query.state.data)
- if (window?.accountId === registry.accountId) recordServerDirectoryWindow(registry, window.serverId)
+export function reconcileExistingServerDirectoryWindows(registry: CommunityDbRegistry, serverIds: ReadonlySet<string>) {
+ for (const serverId of serverIds) {
+ const window = readServerDirectoryWindow(registry.queryClient.getQueryData(communityKeys.server(serverId)))
+ if (window?.accountId === registry.accountId && window.serverId === serverId) recordServerDirectoryWindow(registry, serverId)
}
}
diff --git a/src/web/src/lib/community/thread-read.profile.dom.test.tsx b/src/web/src/lib/community/thread-read.profile.dom.test.tsx
index 0010fa34f..77d5ae362 100644
--- a/src/web/src/lib/community/thread-read.profile.dom.test.tsx
+++ b/src/web/src/lib/community/thread-read.profile.dom.test.tsx
@@ -48,8 +48,8 @@ it.each(["same-channel", "foreign-channel"])("renders the real cold post author
expect(registry.collections.friendships.size).toBe(0)
const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["forum", "post"] })
await act(async () => {
- publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
- publishCommunityForumFeed(client, "forum", page, { token: captureCommunityLiveSnapshotToken(client) })
+ await publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ await publishCommunityForumFeed(client, "forum", page, { token: captureCommunityLiveSnapshotToken(client) })
})
function Harness() {
const channels = useCanonicalChannelsById()
diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.ts
index 1bb23557a..02d56906e 100644
--- a/src/web/src/stores/community/ws-store.ts
+++ b/src/web/src/stores/community/ws-store.ts
@@ -33,8 +33,9 @@ type ChannelAccessScope = {
denialCode?: CommunityApiError["code"]
}
-type CommunityWsStoreState = {
+export type CommunityWsStoreState = {
accessEpoch: number
+ serverAccessGenerations: Map<string, number>
channelAccessScopes: Map<string, ChannelAccessScope>
revokedServerIds: Set<string>
beginChannelMembershipChange: (serverId: string | null, channelId: string, options?: { preserveRevocation: boolean }) => number
@@ -82,10 +83,11 @@ const initialState = (): Pick<
"profileViewerId" | "profileAccountEpoch" | "presenceRevision"
| "presenceByUserId" | "presenceRevisionsByUserId"
| "seenMessageIds" | "seenDeliveryOperations"
- | "accessEpoch" | "accessConnected" | "channelAccessScopes" | "revokedServerIds"
+ | "accessEpoch" | "accessConnected" | "channelAccessScopes" | "revokedServerIds" | "serverAccessGenerations"
| "connectionStatus" | "reconnectNow"
> => ({
accessEpoch: 0,
+ serverAccessGenerations: new Map(),
channelAccessScopes: new Map(),
revokedServerIds: new Set(),
accessConnected: false,
@@ -160,6 +162,7 @@ export function createCommunityWsStore(viewerId: string | null, publishPresence?
profileAccountEpoch,
accessEpoch: state.accessEpoch + 1,
channelAccessScopes: new Map(),
+ serverAccessGenerations: new Map(),
revokedServerIds: new Set(),
presenceRevision: 0,
presenceByUserId: new Map(),
@@ -287,7 +290,9 @@ export function createCommunityWsStore(viewerId: string | null, publishPresence?
revokeServerAccess: (serverId) => {
const revokedServerIds = new Set(get().revokedServerIds).add(serverId)
- setState((state) => ({ ...state, ...{ revokedServerIds, accessEpoch: get().accessEpoch + 1 } }))
+ const serverAccessGenerations = new Map(get().serverAccessGenerations)
+ serverAccessGenerations.set(serverId, (serverAccessGenerations.get(serverId) ?? 0) + 1)
+ setState((state) => ({ ...state, ...{ revokedServerIds, serverAccessGenerations, accessEpoch: get().accessEpoch + 1 } }))
},
grantServerAccess: (serverId) => {
diff --git a/src/web/src/test/conversation-entry-fixtures.ts b/src/web/src/test/conversation-entry-fixtures.ts
index 68f4729b9..82f1e559e 100644
--- a/src/web/src/test/conversation-entry-fixtures.ts
+++ b/src/web/src/test/conversation-entry-fixtures.ts
@@ -54,7 +54,7 @@ export async function seedConversationEntry(client: import("@tanstack/react-quer
const { publishConversationEntry, conversationEntryOptions } = await import("@/lib/community/conversation-entry")
const { captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
const options = conversationEntryOptions(client, target)
- const resource = publishConversationEntry(client, target, entry, { token: captureCommunityLiveSnapshotToken(client, target.channelId), signal: undefined })
+ const resource = await publishConversationEntry(client, target, entry, { token: captureCommunityLiveSnapshotToken(client, target.channelId), signal: undefined })
client.setQueryData(options.queryKey, resource)
return { ...options, resource }
}
diff --git a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
index 9b8699985..ad00e3a8e 100644
--- a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
+++ b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
@@ -127,10 +127,12 @@ async function historyEvents(page: Page): Promise<HistoryEvent[]> {
).__communityHistoryEvents ?? [])
}
-async function sidebarFrames(page: Page): Promise<SidebarFrame[]> {
- return page.evaluate(() => (
+async function sidebarFrames(page: Page, targetScope: string): Promise<SidebarFrame[]> {
+ const read = () => page.evaluate(() => (
window as typeof window & { __communitySidebarFrames?: SidebarFrame[] }
).__communitySidebarFrames ?? [])
+ await expect.poll(async () => (await read()).some(frame => frame.scope === targetScope && !frame.skeleton)).toBe(true)
+ return read()
}
function expectAtomicTargetFrames(
@@ -272,7 +274,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
.toBeVisible({ timeout: 30_000 })
await expect(page.getByTestId(tid.channelRow(channelB))).toBeVisible({ timeout: 30_000 })
expectAtomicTargetFrames(
- await sidebarFrames(page),
+ await sidebarFrames(page, `server:${serverB}`),
`server:${serverB}`,
channelB,
[channelA],
@@ -308,7 +310,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
`community:lastChannel:${serverC}`)).toBe(rememberedC)
const rememberedCHeading = await firstCMain.getByRole("heading").innerText()
await expect(firstCMain.getByRole("heading", { name: rememberedCHeading, exact: true })).toBeVisible()
- const coldFrames = await sidebarFrames(page)
+ const coldFrames = await sidebarFrames(page, `server:${serverC}`)
const coldPendingFrames = coldFrames.filter((frame) => frame.pendingServer === serverC)
expect(coldPendingFrames.length).toBeGreaterThan(0)
expect(coldPendingFrames.every((frame) => frame.ownerId === null && frame.rows.length === 0))
@@ -348,7 +350,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await expect.poll(() => page.evaluate((key) => localStorage.getItem(key),
`community:lastChannel:${serverC}`)).toBe(rememberedC)
expectAtomicTargetFrames(
- await sidebarFrames(page),
+ await sidebarFrames(page, `server:${serverC}`),
`server:${serverC}`,
channelC,
[channelA, channelB],
@@ -394,7 +396,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverD}`))
.toBe(true)
await expect(page.getByTestId(tid.channelRow(channelD))).toBeVisible({ timeout: 30_000 })
- const mobileColdFrames = await sidebarFrames(page)
+ const mobileColdFrames = await sidebarFrames(page, `server:${serverD}`)
expectAtomicTargetFrames(
mobileColdFrames,
`server:${serverD}`,
@@ -421,7 +423,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await coldF.release()
await expectDesktopServerDetail(page, serverF)
await expect(page.getByTestId(tid.channelRow(channelF))).toBeVisible({ timeout: 30_000 })
- const supersededFrames = await sidebarFrames(page)
+ const supersededFrames = await sidebarFrames(page, `server:${serverF}`)
expect(supersededFrames.some((frame) => frame.scope === `server:${serverE}`)).toBe(false)
expectAtomicTargetFrames(
supersededFrames,
diff --git a/src/web/src/test/e2e-ui/perf/perf-capture-types.ts b/src/web/src/test/e2e-ui/perf/perf-capture-types.ts
index 9ceefef0e..8fb59ea26 100644
--- a/src/web/src/test/e2e-ui/perf/perf-capture-types.ts
+++ b/src/web/src/test/e2e-ui/perf/perf-capture-types.ts
@@ -5,6 +5,8 @@
export type CacheState = "cold" | "memory-warm" | "disk-warm"
export type SwitchKind = "server" | "channel"
+export type PerfTarget = { serverId: string; channelId?: string; messageScrollerId: string }
+export type PerfStableTarget = { contentStableTs: number; contentChannelId: string; contentKind: "messages" | "empty" }
/** One `/api/community/*` request, from the in-page resource observer. */
export interface CapturedResource {
@@ -42,10 +44,13 @@ export interface CapturedSwitch {
clickTs: number
/** performance.now() when the first skeleton for the target appeared. */
skeletonTs: number | null
- /** performance.now() when the first message row painted. */
+ /** performance.now() when qualified target messages or a loaded empty state became visible. */
paintedTs: number | null
- /** performance.now() of the last ResizeObserver settle on the list. */
+ /** performance.now() when qualified target content satisfies the geometry stability condition. */
contentStableTs: number | null
+ contentChannelId?: string | null
+ contentKind?: "messages" | "empty" | null
+ resizes?: number[]
resources: CapturedResource[]
commits: CapturedCommit[]
/** fiber-unmount events during the switch, by component name. */
@@ -79,9 +84,11 @@ declare global {
__PERF_RESOURCES__?: Array<{ name: string; startTime: number; responseEnd: number }>
__PERF_SHIFTS__?: Array<{ ts: number; value: number; hadRecentInput: boolean }>
__PERF_RESIZES__?: number[]
+ __PERF_RESOURCE_OBSERVER__?: PerformanceObserver
+ __PERF_LAYOUT_OBSERVER__?: PerformanceObserver
__PERF_RESIZE_OBSERVER__?: ResizeObserver
- __PERF_ATTACH_RESIZE__?: () => boolean
- __PERF_WAIT_FOR_STABLE_RESIZE__?: () => Promise<void>
+ __PERF_ATTACH_RESIZE__?: (target: PerfTarget) => boolean
+ __PERF_WAIT_FOR_STABLE_RESIZE__?: (target: PerfTarget) => Promise<PerfStableTarget>
__PERF_SKELETON_TS__?: number | null
__PERF_PAINTED_TS__?: number | null
__PERF_WARM_RELOAD__?: { customBootstrapSeen: boolean; skeletonSeen: boolean }
diff --git a/src/web/src/test/e2e-ui/perf/switch.perf.ts b/src/web/src/test/e2e-ui/perf/switch.perf.ts
index b017d4296..adf4acc5a 100644
--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts
+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts
@@ -43,6 +43,8 @@ import type {
CapturedWarmReload,
CapturedSwitch,
SwitchKind,
+ PerfTarget,
+ PerfStableTarget,
} from "./perf-capture-types"
const BASE_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000"
@@ -81,11 +83,53 @@ async function authenticateAs(context: BrowserContext, email: string): Promise<v
}
}
+function samplePerfTarget(target: PerfTarget) {
+ const path = location.pathname.split("/")
+ if (path.length !== 5 || path[1] !== "c" || path[2] !== "channels" || decodeURIComponent(path[3]) !== target.serverId) return false
+ const channelId = decodeURIComponent(path[4])
+ if (!channelId || target.channelId !== undefined && channelId !== target.channelId) return false
+ const visible = (element: HTMLElement) => {
+ const style = getComputedStyle(element)
+ return !element.closest('[hidden], [inert], [aria-hidden="true"]') && element.getClientRects().length > 0 && style.display !== "none" && style.visibility !== "hidden"
+ }
+ const surfaces = [...document.querySelectorAll<HTMLElement>('[data-slot="community-conversation-surface"]')]
+ .filter(surface => surface.dataset.channelId === channelId && visible(surface))
+ if (surfaces.length !== 1) return false
+ const surface = surfaces[0]
+ const root = surface.querySelector<HTMLElement>(`[data-testid="${target.messageScrollerId}"]`)
+ if (!root || !visible(root)) return false
+ const skeleton = root.querySelector('[data-slot="skeleton"]')
+ if (skeleton && window.__PERF_SKELETON_TS__ == null) window.__PERF_SKELETON_TS__ = performance.now()
+ const content = root.querySelector<HTMLElement>("[data-message-list-content]")
+ if (!content || !visible(content) || skeleton || surface.getAttribute("aria-busy") === "true" || root.getAttribute("aria-busy") === "true") return false
+ const bounds = root.getBoundingClientRect()
+ const rows = [...content.querySelectorAll<HTMLElement>("[data-msg-id]")]
+ const inViewport = (element: HTMLElement) => {
+ const rect = element.getBoundingClientRect(), style = getComputedStyle(element)
+ return element.getClientRects().length > 0 && style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0
+ && rect.bottom > bounds.top && rect.top < bounds.bottom && rect.right > bounds.left && rect.left < bounds.right
+ }
+ const painted = rows.some(row => visible(row) && inViewport(row))
+ const emptyTail = content.querySelector<HTMLElement>("[data-message-empty-tail]")
+ const empty = rows.length === 0 && content.dataset.initialPositionPhase === "revealed" && !content.querySelector('[role="alert"]')
+ && emptyTail !== null && inViewport(emptyTail)
+ if (!painted && !empty) return false
+ if (window.__PERF_PAINTED_TS__ == null) window.__PERF_PAINTED_TS__ = performance.now()
+ return { root, content, channelId, contentKind: painted ? "messages" as const : "empty" as const }
+}
+
// In-page instrumentation installed before each measured switch. Reads the
// react-scan ring buffer + performance marks + resource timings + a
// ResizeObserver on the message scroll container, all on the browser clock.
const INPAGE_SETUP = `
(() => {
+ const readTarget = (${samplePerfTarget.toString()});
+ window.__PERF_RESOURCE_OBSERVER__?.disconnect();
+ window.__PERF_LAYOUT_OBSERVER__?.disconnect();
+ window.__PERF_RESIZE_OBSERVER__?.disconnect();
+ let observedRoot = null;
+ let observedContent = null;
+ let resizeStart = 0;
window.__PERF_RESOURCES__ = [];
window.__PERF_SHIFTS__ = [];
window.__PERF_RESIZES__ = [];
@@ -97,6 +141,7 @@ const INPAGE_SETUP = `
}
});
ro.observe({ type: 'resource', buffered: true });
+ window.__PERF_RESOURCE_OBSERVER__ = ro;
const lo = new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
// KEEP hadRecentInput entries — the click-triggered reflow is exactly what
@@ -105,44 +150,59 @@ const INPAGE_SETUP = `
}
});
try { lo.observe({ type: 'layout-shift', buffered: true }); } catch (_) {}
+ window.__PERF_LAYOUT_OBSERVER__ = lo;
// Attach a ResizeObserver to the message scroll container. The container is
// persistent, but on a cold switch it may be re-created (React swaps the
// subtree), so a once-only global guard would leave the observer watching a
// detached node and never fire again — hence NO cross-switch guard here, and
// we disconnect the prior observer before re-observing the current root.
- window.__PERF_ATTACH_RESIZE__ = () => {
- const root = document.querySelector('[data-testid="${tid.messageScroller}"]');
- if (!root) return false;
+ window.__PERF_ATTACH_RESIZE__ = (target) => {
+ const sample = readTarget(target);
+ if (!sample) return false;
if (window.__PERF_RESIZE_OBSERVER__) window.__PERF_RESIZE_OBSERVER__.disconnect();
+ observedRoot = sample.root;
+ observedContent = sample.content;
+ resizeStart = window.__PERF_RESIZES__.length;
const rz = new ResizeObserver(() => { window.__PERF_RESIZES__.push(performance.now()); });
- rz.observe(root);
- if (root.firstElementChild) rz.observe(root.firstElementChild);
+ rz.observe(observedRoot);
+ rz.observe(observedContent);
window.__PERF_RESIZE_OBSERVER__ = rz;
return true;
};
- window.__PERF_WAIT_FOR_STABLE_RESIZE__ = () => new Promise((resolve, reject) => {
+ window.__PERF_WAIT_FOR_STABLE_RESIZE__ = (target) => new Promise((resolve, reject) => {
+ let previousRoot = null;
+ let previousContent = null;
let previous = '';
let unchangedFrames = 0;
let observedFrames = 0;
const sample = () => {
observedFrames += 1;
- const root = document.querySelector('[data-testid="${tid.messageScroller}"]');
- const content = root?.firstElementChild;
- if (!root || !content) {
+ const targetSample = readTarget(target);
+ if (!targetSample) {
+ previous = '';
+ unchangedFrames = 0;
if (observedFrames >= 120) {
- reject(new Error('target message scroller did not mount'));
+ reject(new Error('target message content did not become visible'));
return;
}
requestAnimationFrame(sample);
return;
}
+ const { root, content, channelId, contentKind } = targetSample;
+ if (observedRoot !== root || observedContent !== content) window.__PERF_ATTACH_RESIZE__(target);
+ if (previousRoot !== root || previousContent !== content) {
+ previous = '';
+ unchangedFrames = 0;
+ }
+ previousRoot = root;
+ previousContent = content;
const rootRect = root.getBoundingClientRect();
const contentRect = content.getBoundingClientRect();
const current = [rootRect.width, rootRect.height, contentRect.width, contentRect.height, root.scrollHeight].join(':');
unchangedFrames = current === previous ? unchangedFrames + 1 : 0;
previous = current;
- if (window.__PERF_RESIZES__.length > 0 && unchangedFrames >= 1) {
- resolve();
+ if (window.__PERF_RESIZES__.length > resizeStart && unchangedFrames >= 1) {
+ resolve({ contentStableTs: performance.now(), contentChannelId: channelId, contentKind });
return;
}
if (observedFrames >= 120) {
@@ -161,6 +221,9 @@ interface DrainedSwitch {
skeletonTs: number | null
paintedTs: number | null
contentStableTs: number | null
+ contentChannelId: string | null
+ contentKind: "messages" | "empty" | null
+ resizes: number[]
resources: CapturedSwitch["resources"]
commits: CapturedSwitch["commits"]
unmounts: string[]
@@ -168,9 +231,9 @@ interface DrainedSwitch {
degraded: boolean
}
-async function drainSwitch(page: Page, sinceTs: number, markName: string): Promise<DrainedSwitch> {
+async function drainSwitch(page: Page, sinceTs: number, markName: string, stable: PerfStableTarget | null): Promise<DrainedSwitch> {
return page.evaluate(
- ({ sinceTs, markName }) => {
+ ({ sinceTs, markName, stable }) => {
const marks = performance.getEntriesByName(markName, "mark")
const clickTs = marks.length ? marks[marks.length - 1].startTime : sinceTs
@@ -214,13 +277,16 @@ async function drainSwitch(page: Page, sinceTs: number, markName: string): Promi
const resources = (window.__PERF_RESOURCES__ || []).filter((r) => r.startTime >= clickTs)
const layoutShifts = (window.__PERF_SHIFTS__ || []).filter((s) => s.ts >= clickTs)
const resizes = (window.__PERF_RESIZES__ || []).filter((t) => t >= clickTs)
- const contentStableTs = resizes.length ? resizes[resizes.length - 1] : null
+ const contentStableTs = stable?.contentStableTs ?? null
return {
clickTs,
skeletonTs: window.__PERF_SKELETON_TS__ ?? null,
paintedTs: window.__PERF_PAINTED_TS__ ?? null,
contentStableTs,
+ contentChannelId: stable?.contentChannelId ?? null,
+ contentKind: stable?.contentKind ?? null,
+ resizes,
resources,
commits,
unmounts,
@@ -228,7 +294,7 @@ async function drainSwitch(page: Page, sinceTs: number, markName: string): Promi
degraded: window.__ALOOK_PERF_DEGRADED__ === true,
}
},
- { sinceTs, markName },
+ { sinceTs, markName, stable },
)
}
@@ -255,7 +321,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {
)
// Prove the react-scan hook registered early enough: commit events must
// actually arrive (not merely that hooks are "available").
- await page.waitForFunction(() => Array.isArray(window.__ALOOK_PERF__) && window.__ALOOK_PERF__.length > 0, {
+ await page.waitForFunction(() => Array.isArray(window.__ALOOK_PERF__) && window.__ALOOK_PERF__.length > 0, undefined, {
timeout: 20_000,
})
const degraded = await page.evaluate(() => window.__ALOOK_PERF_DEGRADED__ === true)
@@ -267,7 +333,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {
if (page.url() !== firstLeaf) {
await page.goto(firstLeaf, { waitUntil: "commit" })
}
- await page.waitForSelector("[data-msg-id]", { timeout: 20_000 }).catch(() => {})
+ await page.waitForSelector("[data-msg-id]", { timeout: 20_000 })
const captured: CapturedSwitch[] = []
const warmReloadCapture: { current?: CapturedWarmReload } = {}
@@ -279,61 +345,36 @@ test("community switch perceived-latency capture", async ({ browser }) => {
cacheState: CacheState,
navigate: () => Promise<void>,
): Promise<void> {
+ const target: PerfTarget = { serverId: kind === "server" ? targetId : targetServer.id,
+ ...(kind === "channel" ? { channelId: targetId } : {}), messageScrollerId: tid.messageScroller }
await page.evaluate(INPAGE_SETUP)
- await page.evaluate(() => {
+ await page.evaluate(target => {
window.__PERF_SKELETON_TS__ = null
window.__PERF_PAINTED_TS__ = null
- window.__PERF_ATTACH_RESIZE__?.()
- })
+ if (!window.__PERF_ATTACH_RESIZE__) throw new Error("Missing perf resize collector")
+ window.__PERF_ATTACH_RESIZE__(target)
+ }, target)
const markName = `alook:switch:${kind}:${targetId}`
const t0 = await page.evaluate(() => performance.now())
-
- await navigate()
-
- // Record skeleton + painted anchors as they appear. Both are captured in
- // ONE polling loop so whichever DOM state shows first stamps its own
- // timestamp: the message-list loading state renders `[data-slot=skeleton]`
- // in the scroll container, then swaps to `[data-msg-id]` rows once loaded.
- // A memory/disk-warm switch can paint rows with no skeleton frame at all,
- // so skeleton stays null there (correctly — there was no loading spell).
- await page
- .waitForFunction(
- () => {
- // Scope the skeleton probe to the message scroll container — a bare
- // `[data-slot=skeleton]` also matches sidebar/member-list skeletons
- // elsewhere on the page (and leftovers from the prior switch), which
- // stamped a bogus 16ms skeleton on memory-warm switches that have no
- // loading spell at all.
- if (
- window.__PERF_SKELETON_TS__ == null &&
- document.querySelector(`[data-testid="${tid.messageScroller}"] [data-slot='skeleton']`)
- ) {
- window.__PERF_SKELETON_TS__ = performance.now()
- }
- const painted = document.querySelector("[data-msg-id]")
- if (painted && window.__PERF_PAINTED_TS__ == null) {
- window.__PERF_PAINTED_TS__ = performance.now()
- }
- return window.__PERF_PAINTED_TS__ != null
- },
- { timeout: 25_000 },
- )
- .catch(() => {})
-
- // Re-attach the ResizeObserver to the CURRENT scroll container. Attaching
- // once before navigate() misses cold switches where React re-creates the
- // container after the click, leaving the pre-switch observer on a detached
- // node — the bug that left contentStableTs perpetually null.
- await page.evaluate(() => window.__PERF_ATTACH_RESIZE__?.())
-
- await page.evaluate(() => window.__PERF_WAIT_FOR_STABLE_RESIZE__?.())
-
- const drained = await drainSwitch(page, t0, markName)
- captured.push({ kind, targetId, cacheState, ...drained })
- // Write incrementally so a timed-out / interrupted run still yields a
- // usable capture the report generator can consume (dev-build latency can
- // blow any single wall-clock budget — see the harness header).
- flushCapture()
+ const capture = async (stable: PerfStableTarget | null) => {
+ const drained = await drainSwitch(page, t0, markName, stable)
+ captured.push({ kind, targetId, cacheState, ...drained })
+ flushCapture()
+ }
+ let stable: PerfStableTarget
+ try {
+ await navigate()
+ const painted = await page.waitForFunction(samplePerfTarget, target, { timeout: 25_000 })
+ await painted.dispose()
+ stable = await page.evaluate(async target => {
+ if (!window.__PERF_ATTACH_RESIZE__ || !window.__PERF_WAIT_FOR_STABLE_RESIZE__) throw new Error("Missing perf stability sampler")
+ if (!window.__PERF_ATTACH_RESIZE__(target)) throw new Error("Target content disappeared before stability sampling")
+ return window.__PERF_WAIT_FOR_STABLE_RESIZE__(target)
+ }, target)
+ } catch (error) {
+ try { await capture(null) } finally { throw error }
+ }
+ await capture(stable)
}
function flushCapture(): void {
@@ -409,7 +450,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {
inspect()
})
await page.reload({ waitUntil: "commit" })
- await page.waitForSelector("[data-msg-id]", { timeout: 20_000 }).catch(() => {})
+ await page.waitForSelector("[data-msg-id]", { timeout: 20_000 })
warmReloadCapture.current = await page.evaluate(() => {
const latestMark = (name: string) => {
const marks = performance.getEntriesByName(name, "mark")